Removed depcrecated PageModel

pull/28/head
Jens Pelzetter 2022-03-22 19:25:35 +01:00
parent d11c4922ea
commit 8f380e40ec
94 changed files with 39 additions and 13795 deletions

View File

@ -1,60 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import org.libreccm.pagemodel.AbstractComponentModelJsonConverter;
import java.util.Objects;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
public abstract class AbstractContentItemComponentJsonConverter
extends AbstractComponentModelJsonConverter {
private static final String MODE = "mode";
protected void convertContentItemComponentPropertiesToJson(
final ContentItemComponent component,
final JsonObjectBuilder objectBuilder) {
Objects.requireNonNull(component);
Objects.requireNonNull(objectBuilder);
objectBuilder.add(MODE, component.getMode());
}
protected void readContentItemComponentPropertiesFromJson(
final JsonObject jsonObject, final ContentItemComponent component) {
Objects.requireNonNull(jsonObject);
Objects.requireNonNull(component);
if (!jsonObject.isNull(MODE)) {
component.setMode(jsonObject.getString(MODE));
}
}
}

View File

@ -1,203 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import com.arsdigita.kernel.KernelConfig;
import org.libreccm.configuration.ConfigurationManager;
import org.libreccm.security.PermissionChecker;
import org.librecms.contentsection.ContentItem;
import org.librecms.contentsection.ContentItemL10NManager;
import org.librecms.contentsection.ContentItemManager;
import org.librecms.contentsection.privileges.ItemPrivileges;
import org.librecms.pagemodel.contentitems.AbstractContentItemRenderer;
import org.librecms.pagemodel.contentitems.ContentItemRenderers;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import static org.librecms.pages.PagesConstants.*;
import org.libreccm.pagemodel.ComponentRenderer;
import org.librecms.pagemodel.contentitems.ContentItemRenderer;
import java.util.Collections;
/**
*
* Abstract base class for rendering an {@link ContentItemComponent} which
* provides some logic useful for most implementations of
* {@link ContentItemComponentRenderer}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
* @param <T>
*/
@Deprecated
public abstract class AbstractContentItemComponentRenderer<T extends ContentItemComponent>
implements ComponentRenderer<T> {
@Inject
private ConfigurationManager confManager;
@Inject
private ContentItemRenderers contentItemRenderers;
@Inject
private ContentItemL10NManager iteml10nManager;
@Inject
private ContentItemManager itemManager;
@Inject
private PermissionChecker permissionChecker;
/**
* Retrieves the content item to render.
*
* @param componentModel The {@link ComponentModel} which is rendered.
* @param parameters Additional parameters.
*
* @return The {@link ContentItem} to render.
*/
protected abstract ContentItem getContentItem(
T componentModel, final Map<String, Object> parameters);
/**
* Renders the provided {@link ContentItemComponent} and the
* {@link ContentItem} retrieved by
* {@link #getContentItem(org.librecms.pagemodel.ContentItemComponent, java.util.Map)}.
*
* The {@link ContentItem} is rendered using an appropriate implementation
* of {@link ContentItemRenderer}. This method use the draft version of the
* item there is an parameters {@code showDraftItem} in the
* {@code parameters} map with the value {@code true}. If
* {@code showDraftItem} is set to {@code true} and the current user is not
* permitted to new the draft version of the item an
* {@link WebApplicationException} with the correct HTTP response code is
* thrown.
*
* Likewise of the current user is not permitted to view the view version of
* the item an {@link WebApplicationException} with the correct HTTP
* response code is thrown.
*
* @param componentModel The {@link ComponentModel} to render.
* @param parameters Additional parameters.
*
* @return The rendered component.
*/
@Transactional(Transactional.TxType.REQUIRED)
@Override
public Map<String, Object> renderComponent(
final T componentModel,
final Map<String, Object> parameters) {
Objects.requireNonNull(componentModel);
Objects.requireNonNull(parameters);
final ContentItem contentItem = getContentItem(componentModel,
parameters);
if (contentItem == null) {
return Collections.emptyMap();
}
if (Boolean.TRUE.equals(parameters.get("showDraftItem"))) {
final ContentItem draftItem = itemManager
.getDraftVersion(contentItem, contentItem.getClass());
if (permissionChecker.isPermitted(ItemPrivileges.PREVIEW, draftItem)) {
final Map<String, Object> result = generateItem(componentModel,
parameters,
draftItem);
result.put("showDraftItem", Boolean.TRUE);
return result;
} else {
throw new WebApplicationException(
"You are not permitted to view the draft version of this item.",
Response.Status.UNAUTHORIZED);
}
} else {
final ContentItem liveItem = itemManager
.getLiveVersion(contentItem, contentItem.getClass())
.orElseThrow(() -> new NotFoundException(
"This content item does not "
+ "have a live version."));
if (permissionChecker.isPermitted(ItemPrivileges.VIEW_PUBLISHED,
liveItem)) {
return generateItem(componentModel,
parameters,
liveItem);
} else {
throw new WebApplicationException(
"You are not permitted to view the live version of "
+ "this item.",
Response.Status.UNAUTHORIZED);
}
}
}
/**
* A helper method for rendering the {@link ContentItem}. There should be no
* need to overwrite this method, but maybe there are scenarios where this
* is necessary.
*
* @param componentModel The component model to render.
* @param parameters Additional parameters.
* @param item The item to render.
*
* @return The rendered content item.
*/
protected Map<String, Object> generateItem(
final T componentModel,
final Map<String, Object> parameters,
final ContentItem item) {
final Locale language;
if (parameters.containsKey("language")) {
language = new Locale((String) parameters.get(PARAMETER_LANGUAGE));
} else {
final KernelConfig kernelConfig = confManager
.findConfiguration(KernelConfig.class);
language = kernelConfig.getDefaultLocale();
}
if (iteml10nManager.hasLanguage(item, language)) {
final AbstractContentItemRenderer renderer = contentItemRenderers
.findRenderer(item.getClass(), componentModel.getMode());
return renderer.render(item, language);
} else {
throw new NotFoundException("Requested language is not available.");
}
}
}

View File

@ -1,43 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import javax.persistence.Entity;
import javax.persistence.Table;
import static org.librecms.CmsConstants.*;
/**
* A component for showing a content item which is assigned to a category.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Entity
@Table(name = "CATEGORIZED_ITEM_COMPONENTS", schema = DB_SCHEMA)
public class CategorizedItemComponent extends ContentItemComponent {
private static final long serialVersionUID = 6366311513244770272L;
@Override
public boolean canEqual(final Object obj) {
return obj instanceof CategorizedItemComponent;
}
}

View File

@ -1,80 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import org.libreccm.pagemodel.ComponentModel;
import org.libreccm.pagemodel.ConvertsComponentModel;
import java.util.Objects;
import javax.enterprise.context.RequestScoped;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@ConvertsComponentModel(componentModel = CategorizedItemComponent.class)
public class CategorizedItemComponentJsonBuilder
extends AbstractContentItemComponentJsonConverter {
@Override
public JsonObject toJson(final ComponentModel componentModel) {
Objects.requireNonNull(componentModel);
final JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
if (!(componentModel instanceof CategorizedItemComponent)) {
throw new IllegalArgumentException(
"This converter only processes CategorizedItemComponents.");
}
final CategorizedItemComponent component
= (CategorizedItemComponent) componentModel;
convertBasePropertiesToJson(component, objectBuilder);
convertContentItemComponentPropertiesToJson(component, objectBuilder);
return objectBuilder.build();
}
@Override
public void fromJson(final JsonObject jsonObject,
final ComponentModel componentModel) {
Objects.requireNonNull(jsonObject);
if (!(componentModel instanceof CategorizedItemComponent)) {
throw new IllegalArgumentException(
"This converter only processes CategorizedItemComponents.");
}
final CategorizedItemComponent component
= (CategorizedItemComponent) componentModel;
readBasePropertiesFromJson(jsonObject, component);
readContentItemComponentPropertiesFromJson(jsonObject, component);
}
}

View File

@ -1,130 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import org.libreccm.categorization.Categorization;
import org.libreccm.categorization.Category;
import org.libreccm.categorization.CategoryRepository;
import org.libreccm.core.CcmObject;
import org.librecms.contentsection.ContentItem;
import org.librecms.contentsection.ContentItemVersion;
import java.util.Map;
import java.util.Objects;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Root;
import javax.ws.rs.NotFoundException;
import static org.librecms.pages.PagesConstants.*;
import org.libreccm.pagemodel.RendersComponent;
/**
* Renderer for the {@link CategorizedItemComponent}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@RendersComponent(componentModel = CategorizedItemComponent.class)
public class CategorizedItemComponentRenderer
extends AbstractContentItemComponentRenderer<CategorizedItemComponent> {
@Inject
private CategoryRepository categoryRepo;
@Inject
private EntityManager entityManager;
@Override
protected ContentItem getContentItem(
final CategorizedItemComponent componentModel,
final Map<String, Object> parameters) {
Objects.requireNonNull(componentModel);
Objects.requireNonNull(parameters);
if (!parameters.containsKey(PARAMETER_CATEGORY)) {
throw new IllegalArgumentException(String
.format("The parameters map passed to this component does "
+ "not include the parameter \"%s\"",
PARAMETER_CATEGORY));
}
if (!parameters.containsKey(PARAMETER_ITEMNAME)) {
throw new IllegalArgumentException(String
.format("The parameters map passed to this component does "
+ "not include the parameter \"%s\"",
PARAMETER_ITEMNAME));
}
if (!(parameters.get(PARAMETER_CATEGORY) instanceof Category)) {
throw new IllegalArgumentException(String
.format("The parameters map passed to this GreetingItem "
+ "component contains the parameter \"category\", but the "
+ "parameter is not of type \"%s\" but of type \"%s\".",
Category.class.getName(),
parameters.get(PARAMETER_CATEGORY).getClass().getName()));
}
final Category category = categoryRepo
.findById(((CcmObject) parameters.get(PARAMETER_CATEGORY))
.getObjectId())
.orElseThrow(() -> new IllegalArgumentException(String.format(
"No category with ID %d in the database.",
((CcmObject) parameters.get(PARAMETER_CATEGORY)).getObjectId())));
final String itemName = (String) parameters.get(PARAMETER_ITEMNAME);
final CriteriaBuilder builder = entityManager.getCriteriaBuilder();
final CriteriaQuery<ContentItem> criteriaQuery = builder
.createQuery(ContentItem.class);
final Root<ContentItem> from = criteriaQuery.from(ContentItem.class);
final Join<ContentItem, Categorization> join = from
.join("categories");
final TypedQuery<ContentItem> query = entityManager
.createQuery(criteriaQuery
.select(from)
.where(builder.and(
builder.equal(from.get("displayName"), itemName),
builder.equal(from.get("version"), ContentItemVersion.DRAFT),
builder.equal(join.get("category"), category)
)));
try {
return query.getSingleResult();
} catch (NoResultException ex) {
throw new NotFoundException(String
.format("No ContentItem with name \"%s\" in Category \"%s\".",
itemName,
Objects.toString(category)));
}
}
}

View File

@ -1,98 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import org.libreccm.pagemodel.ComponentModel;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import static org.librecms.CmsConstants.*;
/**
* A component which shows the category tree. Depending on the parameters set
* either the complete category tree is shown or the sub tree of the current
* category.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Entity
@Table(name = "CATEGORY_TREE_COMPONENTS", schema = DB_SCHEMA)
public class CategoryTreeComponent extends ComponentModel {
private static final long serialVersionUID = 9142791033478189003L;
@Column(name = "SHOW_FULL_TREE")
private boolean showFullTree;
public boolean isShowFullTree() {
return showFullTree;
}
public void setShowFullTree(final boolean showFullTree) {
this.showFullTree = showFullTree;
}
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 61 * hash + (showFullTree ? 1 : 0);
return hash;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof CategoryTreeComponent)) {
return false;
}
final CategoryTreeComponent other = (CategoryTreeComponent) obj;
if (!other.canEqual(this)) {
return false;
}
return showFullTree == other.isShowFullTree();
}
@Override
public boolean canEqual(final Object obj) {
return obj instanceof CategoryTreeComponent;
}
@Override
public String toString(final String data) {
return super.toString(String.format(", showFullTree = %b%s",
showFullTree,
data));
}
}

View File

@ -1,91 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import org.libreccm.pagemodel.AbstractComponentModelJsonConverter;
import org.libreccm.pagemodel.ComponentModel;
import org.libreccm.pagemodel.ConvertsComponentModel;
import java.util.Objects;
import javax.enterprise.context.RequestScoped;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@ConvertsComponentModel(componentModel = CategoryTreeComponent.class)
public class CategoryTreeComponentJsonConverter
extends AbstractComponentModelJsonConverter {
private static final String SHOW_FULL_TREE = "showFullTree";
@Override
public JsonObject toJson(final ComponentModel componentModel) {
Objects.requireNonNull(componentModel);
if (!(componentModel instanceof CategoryTreeComponent)) {
throw new IllegalArgumentException(
"This converter only processes CategoryTreeComponents.");
}
final CategoryTreeComponent categoryTree
= (CategoryTreeComponent) componentModel;
final JsonObjectBuilder builder = Json.createObjectBuilder();
convertBasePropertiesToJson(categoryTree, builder);
builder.add(SHOW_FULL_TREE, categoryTree.isShowFullTree());
return builder.build();
}
@Override
public void fromJson(final JsonObject jsonObject,
final ComponentModel componentModel) {
Objects.requireNonNull(jsonObject);
if (!(componentModel instanceof CategoryTreeComponent)) {
throw new IllegalArgumentException(
"This converter only processes CategoryTreeComponents.");
}
final CategoryTreeComponent categoryTree
= (CategoryTreeComponent) componentModel;
if (!(componentModel instanceof CategoryTreeComponent)) {
throw new IllegalArgumentException(
"This converter only processes CategoryTreeComponents.");
}
readBasePropertiesFromJson(jsonObject, categoryTree);
if (jsonObject.containsKey(SHOW_FULL_TREE)) {
categoryTree.setShowFullTree(jsonObject.getBoolean(SHOW_FULL_TREE));
}
}
}

View File

@ -1,191 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import com.arsdigita.kernel.KernelConfig;
import org.libreccm.categorization.Category;
import org.libreccm.categorization.CategoryManager;
import org.libreccm.categorization.CategoryRepository;
import org.libreccm.configuration.ConfigurationManager;
import org.libreccm.core.CcmObject;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;
import static org.librecms.pages.PagesConstants.*;
import org.libreccm.pagemodel.ComponentRenderer;
import org.libreccm.pagemodel.RendersComponent;
/**
* Renderer for the {@link CategoryTreeComponent}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@RendersComponent(componentModel = CategoryTreeComponent.class)
public class CategoryTreeComponentRenderer
implements ComponentRenderer<CategoryTreeComponent> {
@Inject
private CategoryManager categoryManager;
@Inject
private CategoryRepository categoryRepo;
@Inject
private ConfigurationManager confManager;
@Transactional(Transactional.TxType.REQUIRED)
@Override
public Map<String, Object> renderComponent(
final CategoryTreeComponent componentModel,
final Map<String, Object> parameters) {
Objects.requireNonNull(componentModel);
Objects.requireNonNull(parameters);
if (!parameters.containsKey(PARAMETER_CATEGORY)) {
throw new IllegalArgumentException(
"The parameters map passed to this CategoryTree component does "
+ "not include the parameter \"category\"");
}
if (!(parameters.get(PARAMETER_CATEGORY) instanceof Category)) {
throw new IllegalArgumentException(String
.format("The parameters map passed to this CategoryTree "
+ "component contains the parameter \"category\", but the "
+ "parameter is not of type \"%s\" but of type \"%s\".",
Category.class.getName(),
parameters.get(PARAMETER_CATEGORY).getClass().getName()));
}
final Category category = categoryRepo
.findById(((CcmObject) parameters.get(PARAMETER_CATEGORY))
.getObjectId())
.orElseThrow(() -> new IllegalArgumentException(String.format(
"No category with ID %d in the database.",
((CcmObject) parameters.get(PARAMETER_CATEGORY)).getObjectId())));
final Locale language;
if (parameters.containsKey(PARAMETER_LANGUAGE)) {
language = new Locale((String) parameters.get(PARAMETER_LANGUAGE));
} else {
final KernelConfig kernelConfig = confManager
.findConfiguration(KernelConfig.class);
language = kernelConfig.getDefaultLocale();
}
final Map<String, Object> result = new HashMap<>();
if (componentModel.isShowFullTree()) {
final Category rootCategory = findRootCategory(category);
result.put("categoryId", Long.toString(rootCategory.getObjectId()));
result.put("uuid", rootCategory.getUuid());
result.put("categoryName", rootCategory.getName());
result.put("categoryPath",
categoryManager.getCategoryPath(rootCategory));
result.put("categoryTitle",
rootCategory.getTitle().getValue(language));
result.put("selected", rootCategory.equals(category));
final List<Map<String, Object>> subCategories = rootCategory
.getSubCategories()
.stream()
.map(current -> generateCategoryWithTree(current,
category,
language))
.collect(Collectors.toList());
result.put("subCategories", subCategories);
} else {
result.put("categoryName", category.getName());
result.put("categoryPath",
categoryManager.getCategoryPath(category));
result.put("categoryTitle", category.getTitle().getValue(language));
final List<Map<String, Object>> subCategories = category
.getSubCategories()
.stream()
.map(current -> generateCategory(current, language))
.collect(Collectors.toList());
result.put("subCategories", subCategories);
}
return result;
}
protected Map<String, Object> generateCategory(final Category category,
final Locale language) {
final Map<String, Object> result = new HashMap<>();
result.put("categoryId", Long.toString(category.getObjectId()));
result.put("uuid", category.getUuid());
result.put("categoryName", category.getName());
result.put("categoryPath", categoryManager.getCategoryPath(category));
result.put("categoryTitle", category.getTitle().getValue(language));
return result;
}
protected Map<String, Object> generateCategoryWithTree(
final Category category,
final Category selectedCategory,
final Locale language) {
final Map<String, Object> result = new HashMap<>();
result.put("categoryId", Long.toString(category.getObjectId()));
result.put("uuid", category.getUuid());
result.put("categoryName", category.getName());
result.put("categoryPath", categoryManager.getCategoryPath(category));
result.put("categoryTitle", category.getTitle().getValue(language));
result.put("selected", selectedCategory.equals(category));
if (!category.getSubCategories().isEmpty()) {
final List<Map<String, Object>> subCategories = category
.getSubCategories()
.stream()
.map(current -> generateCategoryWithTree(current,
selectedCategory,
language))
.collect(Collectors.toList());
result.put("subCategories", subCategories);
}
return result;
}
protected Category findRootCategory(final Category category) {
if (category.getParentCategory() == null) {
return category;
} else {
return findRootCategory(category.getParentCategory());
}
}
}

View File

@ -1,98 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import org.libreccm.pagemodel.ComponentModel;
import org.libreccm.pagemodel.PageModel;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import static org.librecms.CmsConstants.*;
/**
* Basic {@link PageModel} component for displaying a content item. This class
* is not indented for direct use. The subclasses should be used instead.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Entity
@Table(name = "CONTENT_ITEM_COMPONENTS", schema = DB_SCHEMA)
public class ContentItemComponent extends ComponentModel {
private static final long serialVersionUID = 4904530823926147281L;
@Column(name = "MODE")
private String mode;
public String getMode() {
return mode;
}
public void setMode(final String mode) {
this.mode = mode;
}
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 13 * hash + Objects.hashCode(mode);
return hash;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof ContentItemComponent)) {
return false;
}
final ContentItemComponent other = (ContentItemComponent) obj;
if (!other.canEqual(this)) {
return false;
}
return Objects.equals(mode, other.getMode());
}
@Override
public boolean canEqual(final Object obj) {
return obj instanceof ContentItemComponent;
}
@Override
public String toString(final String data) {
return super.toString(String
.format(", mode = \"%s\"",
Objects.toString(mode),
data));
}
}

View File

@ -1,98 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import org.librecms.contentsection.ContentItem;
import java.util.Objects;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import static org.librecms.CmsConstants.*;
/**
* Component for showing a specific {@link ContentItem}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Entity
@Table(name = "FIXED_CONTENT_ITEM_COMPONENTS", schema = DB_SCHEMA)
public class FixedContentItemComponent extends ContentItemComponent {
private static final long serialVersionUID = -4518031021801472455L;
@OneToOne
@JoinColumn(name = "CONTENT_ITEM_ID")
private ContentItem contentItem;
public ContentItem getContentItem() {
return contentItem;
}
public void setContentItem(final ContentItem contentItem) {
this.contentItem = contentItem;
}
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 41 * hash + Objects.hashCode(contentItem);
return hash;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof FixedContentItemComponent)) {
return false;
}
final FixedContentItemComponent other = (FixedContentItemComponent) obj;
if (!other.canEqual(this)) {
return false;
}
return Objects.equals(contentItem, other.getContentItem());
}
@Override
public boolean canEqual(final Object obj) {
return obj instanceof FixedContentItemComponent;
}
@Override
public String toString(final String data) {
return super.toString(String.format(", contentItem = %s%s",
Objects.toString(contentItem),
data));
}
}

View File

@ -1,105 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import org.libreccm.core.UnexpectedErrorException;
import org.libreccm.pagemodel.ComponentModel;
import org.libreccm.pagemodel.ConvertsComponentModel;
import org.librecms.contentsection.ContentItemRepository;
import java.util.Objects;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@ConvertsComponentModel(componentModel = FixedContentItemComponent.class)
public class FixedContentItemComponentJsonConverter
extends AbstractContentItemComponentJsonConverter {
private static final String CONTENT_ITEM = "contentItem";
@Inject
private ContentItemRepository itemRepo;
@Override
public JsonObject toJson(final ComponentModel componentModel) {
Objects.requireNonNull(componentModel);
if (!(componentModel instanceof FixedContentItemComponent)) {
throw new IllegalArgumentException(
"This converter only processes FixedContentItemComponents.");
}
final FixedContentItemComponent component
= (FixedContentItemComponent) componentModel;
final JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
convertBasePropertiesToJson(component, objectBuilder);
convertContentItemComponentPropertiesToJson(component, objectBuilder);
if (component.getContentItem() != null) {
objectBuilder.add(CONTENT_ITEM,
component.getContentItem().getUuid());
}
return objectBuilder.build();
}
@Override
public void fromJson(final JsonObject jsonObject,
final ComponentModel componentModel) {
Objects.requireNonNull(jsonObject);
if (!(componentModel instanceof FixedContentItemComponent)) {
throw new IllegalArgumentException(
"This converter only processes FixedContentItemComponents.");
}
final FixedContentItemComponent component
= (FixedContentItemComponent) componentModel;
readBasePropertiesFromJson(jsonObject, component);
readContentItemComponentPropertiesFromJson(jsonObject, component);
if (!jsonObject.isNull(CONTENT_ITEM)) {
final String uuid = jsonObject.getString(CONTENT_ITEM);
component
.setContentItem(itemRepo
.findByUuid(uuid)
.orElseThrow(() -> new UnexpectedErrorException(
String.format("No ContentItem with UUID \"%s\" exists.",
uuid))));
}
}
}

View File

@ -1,66 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import org.librecms.contentsection.ContentItem;
import org.librecms.contentsection.ContentItemRepository;
import java.util.Map;
import java.util.Objects;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.NotFoundException;
import org.libreccm.pagemodel.RendersComponent;
/**
* Renderer for the {@link FixedContentItemComponent}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@RendersComponent(componentModel = FixedContentItemComponent.class)
public class FixedContentItemComponentRenderer
extends AbstractContentItemComponentRenderer<FixedContentItemComponent> {
@Inject
private ContentItemRepository itemRepo;
@Override
protected ContentItem getContentItem(
final FixedContentItemComponent componentModel,
final Map<String, Object> parameters) {
Objects.requireNonNull(componentModel);
Objects.requireNonNull(parameters);
if (componentModel.getContentItem() == null) {
throw new NotFoundException("No ContentItem configured.");
}
return itemRepo
.findById(componentModel.getContentItem().getObjectId())
.orElseThrow(() -> new IllegalArgumentException(String
.format("No ContentItem with ID %d in the database.",
componentModel.getContentItem().getObjectId())));
}
}

View File

@ -1,47 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import org.libreccm.categorization.Category;
import org.libreccm.pagemodel.PageModel;
import javax.persistence.Entity;
import javax.persistence.Table;
import static org.librecms.CmsConstants.*;
/**
* A {@link PageModel} component model for displaying the Greeting/Index item of
* a {@link Category}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Entity
@Table(name = "GREETING_ITEM_COMPONENTS", schema = DB_SCHEMA)
public class GreetingItemComponent extends ContentItemComponent {
private static final long serialVersionUID = 592400386436077481L;
@Override
public boolean canEqual(final Object obj) {
return obj instanceof GreetingItemComponent;
}
}

View File

@ -1,80 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import org.libreccm.pagemodel.ComponentModel;
import org.libreccm.pagemodel.ConvertsComponentModel;
import java.util.Objects;
import javax.enterprise.context.RequestScoped;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@ConvertsComponentModel(componentModel = GreetingItemComponent.class)
public class GreetingItemComponentJsonConverter
extends AbstractContentItemComponentJsonConverter {
@Override
public JsonObject toJson(final ComponentModel componentModel) {
Objects.requireNonNull(componentModel);
if (!(componentModel instanceof GreetingItemComponent)) {
throw new IllegalArgumentException(
"This converter only processes GreetingItemComponents.");
}
final GreetingItemComponent component
= (GreetingItemComponent) componentModel;
final JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
convertBasePropertiesToJson(component, objectBuilder);
convertContentItemComponentPropertiesToJson(component, objectBuilder);
return objectBuilder.build();
}
@Override
public void fromJson(final JsonObject jsonObject,
final ComponentModel componentModel) {
Objects.requireNonNull(jsonObject);
if (!(componentModel instanceof GreetingItemComponent)) {
throw new IllegalArgumentException(
"This converter only processes GreetingItemComponents.");
}
final GreetingItemComponent component
= (GreetingItemComponent) componentModel;
readBasePropertiesFromJson(jsonObject, component);
readContentItemComponentPropertiesFromJson(jsonObject, component);
}
}

View File

@ -1,140 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.libreccm.categorization.Category;
import org.libreccm.categorization.CategoryManager;
import org.libreccm.categorization.CategoryRepository;
import org.libreccm.core.CcmObject;
import org.librecms.contentsection.ContentItem;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import static org.librecms.pages.PagesConstants.*;
import org.libreccm.pagemodel.RendersComponent;
import org.librecms.contentsection.ContentItemVersion;
/**
* Renderer for the {@link GreetingItemComponent}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@RendersComponent(componentModel = GreetingItemComponent.class)
public class GreetingItemComponentRenderer
extends AbstractContentItemComponentRenderer<GreetingItemComponent> {
private static final Logger LOGGER = LogManager
.getLogger(GreetingItemComponentRenderer.class);
@Inject
private CategoryRepository categoryRepo;
@Inject
private CategoryManager categoryManager;
@Override
protected ContentItem getContentItem(
final GreetingItemComponent componentModel,
final Map<String, Object> parameters) {
Objects.requireNonNull(componentModel);
Objects.requireNonNull(parameters);
if (!parameters.containsKey(PARAMETER_CATEGORY)) {
throw new IllegalArgumentException(
"The parameters map passed to this GreetingItem component does "
+ "not include the parameter \"category\"");
}
if (!(parameters.get(PARAMETER_CATEGORY) instanceof Category)) {
throw new IllegalArgumentException(String
.format("The parameters map passed to this GreetingItem "
+ "component contains the parameter \"category\", but the "
+ "parameter is not of type \"%s\" but of type \"%s\".",
Category.class.getName(),
parameters.get(PARAMETER_CATEGORY).getClass().getName()));
}
final Optional<Category> catResult = categoryRepo.findById(
((CcmObject) parameters.get(PARAMETER_CATEGORY)).getObjectId()
);
final Category category = catResult.orElseThrow(
() -> new IllegalArgumentException(
String.format(
"No category with ID %d in the database.",
((CcmObject) parameters.get(PARAMETER_CATEGORY))
.getObjectId()
)
)
);
// final Category category = categoryRepo
// .findById(((CcmObject) parameters.get(PARAMETER_CATEGORY))
// .getObjectId())
// .orElseThrow(() -> new IllegalArgumentException(String.format(
// "No category with ID %d in the database.",
// ((CcmObject) parameters.get(PARAMETER_CATEGORY)).getObjectId())));
final Optional<CcmObject> indexObj = categoryManager
.getIndexObject(category)
.stream()
.filter(object -> object instanceof ContentItem)
.filter(item -> {
return ((ContentItem) item)
.getVersion() == ContentItemVersion.LIVE;
})
.findFirst();
if (indexObj.isPresent()) {
if (indexObj.get() instanceof ContentItem) {
return (ContentItem) indexObj.get();
} else {
// throw new NotFoundException(String
// .format(
// "The index item %s of category %s does not have "
// + "a live version.",
// Objects.toString(indexObj),
// Objects.toString(category)));
LOGGER.debug("The index item {} of category {} does not have "
+ "a live version.",
Objects.toString(indexObj),
Objects.toString(category));
return null;
}
} else {
LOGGER.debug("The category {} does not have a index item.",
Objects.toString(category));
return null;
// throw new NotFoundException(String
// .format("The category %s does not have a index item.",
// Objects.toString(category)));
}
}
}

View File

@ -1,182 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import org.libreccm.pagemodel.ComponentModel;
import org.librecms.contentsection.ContentItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import static org.librecms.CmsConstants.*;
/**
* A component for displaying the list of {@link ContentItem}s assigned to a
* Category.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Entity
@Table(name = "ITEM_LIST_COMPONENTS", schema = DB_SCHEMA)
public class ItemListComponent extends ComponentModel {
private static final long serialVersionUID = -8058080493341203684L;
/**
* Should the list show also items assigned to sub categories?
*/
@Column(name = "DESCINDING")
private boolean descending;
/**
* Include only items of the specified type into the list. This must be a
* subtype of {@link ContentItem}.
*/
@Column(name = "LIMIT_TO_TYPE")
private String limitToType;
/**
* Maximum number of items shown on one page.
*/
@Column(name = "PAGE_SIZE")
private int pageSize;
/**
* Order the list by this properties. Warning: All items must have the
* properties listed here, otherwise an error will occur!
*/
@ElementCollection
@CollectionTable(name = "ITEM_LIST_ORDER",
schema = DB_SCHEMA,
joinColumns = {
@JoinColumn(name = "ITEM_LIST_ID")
})
@Column(name = "LIST_ORDER")
private List<String> listOrder;
public ItemListComponent() {
listOrder = new ArrayList<>();
}
public boolean isDescending() {
return descending;
}
public void setDescending(final boolean descending) {
this.descending = descending;
}
public String getLimitToType() {
return limitToType;
}
public void setLimitToType(final String limitToType) {
this.limitToType = limitToType;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(final int pageSize) {
this.pageSize = pageSize;
}
public List<String> getListOrder() {
return Collections.unmodifiableList(listOrder);
}
public void addListOrder(final String order) {
listOrder.add(order);
}
public void removeListOrder(final String order) {
listOrder.remove(order);
}
public void setListOrder(final List<String> listOrder) {
this.listOrder = new ArrayList<>(listOrder);
}
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 41 * hash + (descending ? 1 : 0);
hash = 41 * hash + Objects.hashCode(limitToType);
hash = 41 * hash + Objects.hashCode(listOrder);
return hash;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof ItemListComponent)) {
return false;
}
final ItemListComponent other = (ItemListComponent) obj;
if (!other.canEqual(this)) {
return false;
}
if (descending != other.isDescending()) {
return false;
}
if (!Objects.equals(limitToType, other.getLimitToType())) {
return false;
}
return Objects.equals(listOrder, other.getListOrder());
}
@Override
public boolean canEqual(final Object obj) {
return obj instanceof ItemListComponent;
}
@Override
public String toString(final String data) {
return super.toString(String.format(", descending = %b, "
+ "limitToTypes = %s, "
+ "listOrder = %s%s",
descending,
limitToType,
Objects.toString(listOrder),
data));
}
}

View File

@ -1,119 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import org.libreccm.pagemodel.AbstractComponentModelJsonConverter;
import org.libreccm.pagemodel.ComponentModel;
import org.libreccm.pagemodel.ConvertsComponentModel;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.enterprise.context.RequestScoped;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@ConvertsComponentModel(componentModel = ItemListComponent.class)
public class ItemListComponentJsonConverter
extends AbstractComponentModelJsonConverter {
private static final String LIST_ORDER = "listOrder";
private static final String PAGE_SIZE = "pageSize";
private static final String LIMIT_TO_TYPE = "limitToType";
private static final String DESCENDING = "descending";
@Override
public JsonObject toJson(final ComponentModel componentModel) {
Objects.requireNonNull(componentModel);
if (!(componentModel instanceof ItemListComponent)) {
throw new IllegalArgumentException(
"This implementation does only handle ItemListComponents.");
}
final ItemListComponent itemList = (ItemListComponent) componentModel;
final JsonObjectBuilder builder = Json.createObjectBuilder();
convertBasePropertiesToJson(itemList, builder);
builder.add(DESCENDING, itemList.isDescending());
builder.add(LIMIT_TO_TYPE, itemList.getLimitToType());
builder.add(PAGE_SIZE, itemList.getPageSize());
final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
if (itemList.getListOrder() != null) {
itemList
.getListOrder()
.stream()
.forEach(value -> arrayBuilder.add(value));
}
builder.add(LIST_ORDER, arrayBuilder.build());
return builder.build();
}
@Override
public void fromJson(final JsonObject jsonObject,
final ComponentModel componentModel) {
Objects.requireNonNull(jsonObject);
if (!(componentModel instanceof ItemListComponent)) {
throw new IllegalArgumentException(
"This implementation does only handle ItemListComponents.");
}
final ItemListComponent itemList = (ItemListComponent) componentModel;
readBasePropertiesFromJson(jsonObject, itemList);
if (!jsonObject.isNull(DESCENDING)) {
itemList.setDescending(jsonObject.getBoolean(DESCENDING));
}
if (!jsonObject.isNull(LIMIT_TO_TYPE)) {
itemList.setLimitToType(jsonObject.getString(LIMIT_TO_TYPE));
}
if (!jsonObject.isNull(PAGE_SIZE)) {
itemList.setPageSize(jsonObject.getInt(PAGE_SIZE));
}
if (!jsonObject.isNull(LIST_ORDER)) {
itemList.setListOrder(
jsonObject
.getJsonArray(LIST_ORDER)
.stream()
.map(value -> value.toString())
.collect(Collectors.toList()));
}
}
}

View File

@ -1,387 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel;
import com.arsdigita.kernel.KernelConfig;
import org.libreccm.categorization.Categorization;
import org.libreccm.categorization.Category;
import org.libreccm.configuration.ConfigurationManager;
import org.libreccm.core.UnexpectedErrorException;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import org.libreccm.pagemodel.ComponentRenderer;
import org.librecms.contentsection.ContentItem;
import org.librecms.pagemodel.contentitems.AbstractContentItemRenderer;
import org.librecms.pagemodel.contentitems.ContentItemRenderers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import static org.librecms.pages.PagesConstants.*;
import org.libreccm.pagemodel.RendersComponent;
import org.libreccm.security.Permission;
import org.libreccm.security.PermissionChecker;
import org.libreccm.security.Role;
import org.libreccm.security.RoleManager;
import org.libreccm.security.Shiro;
import org.libreccm.security.User;
import org.libreccm.security.UserRepository;
import org.librecms.contentsection.ContentItemVersion;
import org.librecms.contentsection.privileges.ItemPrivileges;
import java.util.Optional;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
/**
* Renderer for the {@link ItemListComponent}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@RendersComponent(componentModel = ItemListComponent.class)
public class ItemListComponentRenderer
implements ComponentRenderer<ItemListComponent> {
@Inject
private ConfigurationManager confManager;
@Inject
private ContentItemRenderers itemRenderers;
@Inject
private EntityManager entityManager;
@Inject
private HttpServletRequest request;
@Inject
private PermissionChecker permissionChecker;
@Inject
private RoleManager roleManager;
@Inject
private Shiro shiro;
@Inject
private UserRepository userRepository;
@Override
public Map<String, Object> renderComponent(
final ItemListComponent componentModel,
final Map<String, Object> parameters) {
Objects.requireNonNull(componentModel);
Objects.requireNonNull(parameters);
if (!parameters.containsKey(PARAMETER_CATEGORY)) {
throw new IllegalArgumentException(
"The parameters map passed to this GreetingItem component does "
+ "not include the parameter \"category\"");
}
if (!(parameters.get(PARAMETER_CATEGORY) instanceof Category)) {
throw new IllegalArgumentException(String
.format("The parameters map passed to this GreetingItem "
+ "component contains the parameter \"category\", but the "
+ "parameter is not of type \"%s\" but of type \"%s\".",
Category.class.getName(),
parameters.get(PARAMETER_CATEGORY).getClass().getName()));
}
final Category category = (Category) parameters.get(PARAMETER_CATEGORY);
final Locale language;
if (parameters.containsKey(PARAMETER_LANGUAGE)) {
language = new Locale((String) parameters.get(PARAMETER_LANGUAGE));
} else {
final KernelConfig kernelConfig = confManager
.findConfiguration(KernelConfig.class);
language = kernelConfig.getDefaultLocale();
}
final List<Category> categories = new ArrayList<>();
if (componentModel.isDescending()) {
categories.addAll(collectCategories(category));
}
categories.add(category);
final Class<? extends ContentItem> limitToType = getLimitToType(
componentModel);
final List<? extends ContentItem> items = findItems(
limitToType,
categories,
componentModel.getListOrder(),
componentModel.getPageSize());
final Map<String, Object> result = new HashMap<>();
result.put("items",
items
.stream()
.map(item -> renderItem(item, language))
.collect(Collectors.toList()));
return result;
}
private List<Category> collectCategories(final Category category) {
if (category.getSubCategories().isEmpty()) {
return Collections.emptyList();
} else {
final List<Category> categories = new ArrayList<>();
for (final Category subCategory : category.getSubCategories()) {
categories.add(subCategory);
categories.addAll(collectCategories(subCategory));
}
return categories;
}
}
private List<? extends ContentItem> findItems(
final Class<? extends ContentItem> limitToType,
final List<Category> categories,
final List<String> listOrder,
final int pageSize) {
final CriteriaBuilder criteriaBuilder = entityManager
.getCriteriaBuilder();
final CriteriaQuery<? extends ContentItem> criteriaQuery
= criteriaBuilder
.createQuery(limitToType);
final Root<? extends ContentItem> from = criteriaQuery
.from(limitToType);
final Join<? extends ContentItem, Categorization> catJoin = from
.join("categories");
final Join<? extends ContentItem, Permission> permissionsJoin = from
.join("permissions", JoinType.LEFT);
final Optional<User> user = shiro.getUser();
final List<Role> roles;
if (user.isPresent()) {
final User theUser = userRepository
.findById(user.get().getPartyId())
.orElseThrow(() -> new IllegalArgumentException(String
.format(
"No user with id %d in the database. "
+ "Where did that ID come from?",
user.get().getPartyId())));
roles = roleManager.findAllRolesForUser(theUser);
} else {
final Optional<User> publicUser;
final KernelConfig kernelConfig = confManager
.findConfiguration(KernelConfig.class);
final String principal = (String) shiro
.getPublicUser()
.getPrincipal();
if (kernelConfig.emailIsPrimaryIdentifier()) {
publicUser = userRepository.findByEmailAddress(principal);
} else {
publicUser = userRepository.findByName(principal);
}
if (publicUser.isPresent()) {
roles = roleManager.findAllRolesForUser(publicUser.get());
} else {
roles = Collections.emptyList();
}
}
final boolean isSystemUser = shiro.isSystemUser();
final boolean isAdmin = permissionChecker.isPermitted("*");
final Predicate permissionsCheck;
if (roles.isEmpty()) {
permissionsCheck = criteriaBuilder
.or(
criteriaBuilder.equal(criteriaBuilder.literal(true),
isSystemUser),
criteriaBuilder.equal(criteriaBuilder.literal(true),
isAdmin)
);
} else {
permissionsCheck = criteriaBuilder
.or(
criteriaBuilder
.and(
criteriaBuilder.in(permissionsJoin.get("grantee"))
.value(roles),
criteriaBuilder
.equal(
permissionsJoin.get("grantedPrivilege"),
criteriaBuilder.selectCase()
.when(
criteriaBuilder.equal(
from.get("version"),
ContentItemVersion.DRAFT),
ItemPrivileges.PREVIEW)
.otherwise(
ItemPrivileges.VIEW_PUBLISHED))
),
criteriaBuilder
.equal(criteriaBuilder.literal(true),
isSystemUser),
criteriaBuilder
.equal(criteriaBuilder.literal(true),
isAdmin)
);
}
criteriaQuery.distinct(true).where(criteriaBuilder
.and(catJoin.get("category").in(categories),
criteriaBuilder.equal(catJoin.get("indexObject"), false),
criteriaBuilder.equal(catJoin.get("type"), ""),
criteriaBuilder.equal(from.get("version"),
ContentItemVersion.LIVE),
permissionsCheck
// criteriaBuilder.or(
// criteriaBuilder.and(
// criteriaBuilder
// .in(permissionsJoin.get("grantee"))
// .value(roles),
// criteriaBuilder.equal(
// permissionsJoin.get("grantedPrivilege"),
// criteriaBuilder.selectCase()
// .when(
// criteriaBuilder
// .equal(from.get("version"),
// ContentItemVersion.DRAFT),
// ItemPrivileges.PREVIEW)
// .otherwise(ItemPrivileges.VIEW_PUBLISHED))
// ),
// criteriaBuilder
// .equal(criteriaBuilder.literal(true),
// isSystemUser),
// criteriaBuilder
// .equal(criteriaBuilder.literal(true),
// isAdmin)
// )
)
);
criteriaQuery
.orderBy(listOrder
.stream()
.map(order -> createOrder(order, from, criteriaBuilder))
.collect(Collectors.toList()));
return entityManager
.createQuery(criteriaQuery)
.setFirstResult(getOffset(pageSize))
.setMaxResults(pageSize)
.getResultList();
}
private Class<? extends ContentItem> getLimitToType(
final ItemListComponent componentModel) {
final String className = componentModel.getLimitToType();
if (className == null
|| className.matches("\\s*")) {
return ContentItem.class;
} else {
final Class<?> clazz;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException ex) {
throw new UnexpectedErrorException(ex);
}
if (ContentItem.class.isAssignableFrom(clazz)) {
@SuppressWarnings("unchecked")
final Class<? extends ContentItem> type
= (Class<? extends ContentItem>) clazz;
return type;
} else {
throw new UnexpectedErrorException(String
.format(
"The type \"%s\" set in ItemList is not a subtype of "
+ "\"%s\".",
clazz.getName(),
ContentItem.class.getName()));
}
}
}
private Order createOrder(final String order,
final Root<? extends ContentItem> from,
final CriteriaBuilder criteriaBuilder) {
if (order.endsWith(" ASC")) {
final String colName = order
.substring(0, order.length() - " ASC".length());
return (criteriaBuilder.asc(from.get(colName)));
} else if (order.endsWith(" DESC")) {
final String colName = order
.substring(0, order.length() - " DESC".length());
return criteriaBuilder.desc(from.get(colName));
} else {
return criteriaBuilder.asc(from.get(order));
}
}
private int getOffset(final int pageSize) {
if (request.getParameterMap().containsKey("page")) {
final String value = request.getParameter("page");
if (value.matches("\\d*")) {
final int page = Integer.valueOf(value);
return page * pageSize;
} else {
return 0;
}
} else {
return 0;
}
}
private Map<String, Object> renderItem(final ContentItem item,
final Locale language) {
final AbstractContentItemRenderer renderer = itemRenderers
.findRenderer(item.getClass());
return renderer.render(item, language);
}
}

View File

@ -1,84 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.contentsection.Asset;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* Abstract base class for rendering {@link Asset}s.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
public abstract class AbstractAssetRenderer {
/**
* Basic implementation rendering the common properties of an asset. For
* rendering the specific properties of the asset this method calls
* {@link #renderAsset(org.librecms.contentsection.Asset, java.util.Locale, java.util.Map)}.
*
* The common properties put into {@code result} are:
*
* <pre>
* {
* "objectId": {@link Asset#getObjectId()}
* "uuid": {@link Asset#getUuid()}
* "displayName": {@link Asset#getDisplayName()}
* "title": {@link Asset#getTitle()}
* }
* </pre>
*
* @param asset The {@link Asset} to render.
* @param language The current language.
*
* @return The rendered asset.
*/
public Map<String, Object> render(final Asset asset,
final Locale language) {
final Map<String, Object> result = new HashMap<>();
result.put("objectId", asset.getObjectId());
result.put("uuid", asset.getUuid());
result.put("displayName", asset.getDisplayName());
result.put("title", asset.getTitle().getValue(language));
renderAsset(asset, language, result);
return result;
}
/**
* Renders the special properties of an specific asset type. If the provided
* asset is not of the correct type for the renderer this an implementation
* of this method should return without doing anything.
*
* @param asset The {@link Asset} to render.
* @param language The current language.
* @param result The map in which the rendered properties are stored.
*/
protected abstract void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result);
}

View File

@ -1,46 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.contentsection.Asset;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
/**
* Annotation for marking asset renderers.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,
ElementType.FIELD,
ElementType.PARAMETER,
ElementType.TYPE})
public @interface AssetRenderer {
Class<? extends Asset> renders();
}

View File

@ -1,114 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.librecms.contentsection.Asset;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Inject;
/**
* Provides access to all available implementations of
* {@link AbstractAssetRenderer}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
public class AssetRenderers {
private static final Logger LOGGER = LogManager
.getLogger(AssetRenderers.class);
@Inject
@Any
private Instance<AbstractAssetRenderer> renderers;
/**
* Tries to find an implementation of {@link AbstractAssetRenderer} for the
* provided asset type. If no renderer is found for the provided
* {@code assetType} an noop implementation of {@link AbstractAssetRenderer}
* is returned. This means that only the common properties of the asset are
* rendered.
*
* @param assetType The asset type.
*
* @return An renderer for the provided asset type.
*/
public AbstractAssetRenderer findRenderer(
final Class<? extends Asset> assetType) {
LOGGER.debug("Trying to find renderer for asset type \"{}\"...",
assetType.getName());
final AssetRendererLiteral literal = new AssetRendererLiteral(assetType);
final Instance<AbstractAssetRenderer> instance = renderers
.select(literal);
if (instance.isUnsatisfied()) {
LOGGER.warn("No renderer for asset type \"{}\". "
+ "Returning default renderer.",
assetType.getName());
return new AbstractAssetRenderer() {
@Override
protected void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result) {
//Nothing here.
}
};
} else {
return instance.iterator().next();
}
}
private class AssetRendererLiteral
extends AnnotationLiteral<AssetRenderer>
implements AssetRenderer {
private static final long serialVersionUID = 2635180159989399554L;
private final Class<? extends Asset> renders;
public AssetRendererLiteral(final Class<? extends Asset> renders) {
this.renders = renders;
}
@Override
public Class<? extends Asset> renders() {
return renders;
}
}
}

View File

@ -1,82 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.assets.AudioAsset;
import org.librecms.assets.LegalMetadata;
import org.librecms.contentsection.Asset;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
/**
* Renderer for {@link AudioAsset}s.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@AssetRenderer(renders = AudioAsset.class)
public class AudioAssetRenderer extends BinaryAssetRenderer {
@Inject
@AssetRenderer(renders = LegalMetadata.class)
private AbstractAssetRenderer legalMetadataRenderer;
/**
* Renders to provided {@link AudioAsset}. The following properties are put
* into {@code result}:
*
* <pre>
* {
* "legamMetadata": {@link AudioAsset#getLegalMetadata()}.
* }
* </pre>
*
* The associated {@link LegalMetadata} asset is rendered using
* {@link LegalMetadataRenderer} and the result is put {@code result} under
* the key {@code legalMetadata}.
*
* @param asset The asset to render.
* @param language The current language.
* @param result The map into which the result is placed.
*/
@Override
protected void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result) {
super.renderAsset(asset, language, result);
final AudioAsset audioAsset;
if (asset instanceof AudioAsset) {
audioAsset = (AudioAsset) asset;
} else {
return;
}
result.put("legalMetadata",
legalMetadataRenderer.render(audioAsset.getLegalMetadata(),
language));
}
}

View File

@ -1,78 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.assets.BinaryAsset;
import org.librecms.contentsection.Asset;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
/**
* A renderer for {@link BinaryAsset}s. Please note that the binary data is
* usually not included into the render result. Instead an URL to a service
* which provides the binary data is included. For more details see the
* documentation of the specific renderers.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
public class BinaryAssetRenderer extends AbstractAssetRenderer {
/**
* Renders the common properties of all {@link BinaryAssets}. These are the
* following properties:
*
* <pre>
* {
* "description": {@link BinaryAsset#getDescription()}
* "fileName": {@link BinaryAsset#getFileName()}
* "mimeType": {@link BinaryAsset#getMimeType()}
* "size": {@link BinaryAsset#getSize()}.
* }
* </pre>
*
* The mime type is converted to a string using
* {@link Objects#toString(java.lang.Object)}.
*
* @param asset The asset to render.
* @param language The current language.
* @param result The map into which the result is put.
*/
@Override
protected void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result) {
final BinaryAsset binaryAsset;
if (asset instanceof BinaryAsset) {
binaryAsset = (BinaryAsset) asset;
} else {
return;
}
result.put("description",
binaryAsset.getDescription().getValue(language));
result.put("fileName", binaryAsset.getFileName());
result.put("mimeType", Objects.toString(binaryAsset.getMimeType()));
result.put("size", binaryAsset.getSize());
}
}

View File

@ -1,71 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.contentsection.Asset;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import org.librecms.assets.Bookmark;
/**
* Renderer for {@link Bookmark} assets.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@AssetRenderer(renders = Bookmark.class)
public class BookmarkRenderer extends AbstractAssetRenderer {
/**
* Renders the provided {@link BookmarkAsset}. The following properties
* are put into {@code result}:
*
* <pre>
* {
* "description": {@link Bookmark#getDescription()}
* "url": {@link Bookmark#getUrl()}.
* }
* </pre>
*
* @param asset The asset to render.
* @param language The current language.
* @param result The map into which the result is placed.
*/
@Override
protected void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result) {
final Bookmark bookmark;
if (asset instanceof Bookmark) {
bookmark = (Bookmark) asset;
} else {
return;
}
result.put("description", bookmark.getDescription().getValue(language));
result.put("url", bookmark.getUrl());
}
}

View File

@ -1,90 +0,0 @@
/*
* Copyright (C) 2019 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.assets.ContactEntry;
import org.librecms.assets.ContactableEntity;
import org.librecms.assets.Organization;
import org.librecms.assets.PostalAddress;
import org.librecms.contentsection.Asset;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
public class ContactableEntityRenderer extends AbstractAssetRenderer {
@Inject
private AssetRenderers assetRenderers;
@Override
protected void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result) {
final ContactableEntity contactable;
if (asset instanceof ContactableEntity) {
contactable = (ContactableEntity) asset;
} else {
return;
}
final Map<String, String> contactEntries = buildContactEntries(
contactable);
result.put("contactEntries", contactEntries);
if (contactable.getPostalAddress() != null) {
final AbstractAssetRenderer postalAddressRenderer = assetRenderers
.findRenderer(PostalAddress.class);
final PostalAddress postalAddress = contactable.getPostalAddress();
result.put("postalAddress",
postalAddressRenderer.render(postalAddress, language));
}
}
private Map<String, String> buildContactEntries(
final ContactableEntity contactable) {
return contactable
.getContactEntries()
.stream()
.map(this::buildContactEntry)
.collect(Collectors.toMap(entry -> entry[0], entry -> entry[1]));
}
private String[] buildContactEntry(final ContactEntry entry) {
final String key = entry.getKey().getEntryKey();
final String value = entry.getValue();
return new String[]{key, value};
}
}

View File

@ -1,85 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.assets.ExternalAudioAsset;
import org.librecms.assets.LegalMetadata;
import org.librecms.contentsection.Asset;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
/**
* Renderer for {@link ExternalAudioAsset}s.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@AssetRenderer(renders = ExternalAudioAsset.class)
public class ExternalAudioAssetRenderer extends BookmarkRenderer {
@Inject
@AssetRenderer(renders = LegalMetadata.class)
private AbstractAssetRenderer legalMetadataRenderer;
/**
* Renders the provided {@link ExternalVideoAsset}. In addition to the data
* put into {@code result} by the {@link BookmarkRenderer} the following
* properties are put into the map:
*
* <pre>
* {
* "legalMetadata": {@link ExternalVideoAsset#getLegalMetadata()}
* }
* </pre>
*
* The associated {@link LegalMetadata} asset is rendered using the
* {@link LegalMetadata} and the result is put into the map under the key
* {@code legalMetadata}.
*
* @param asset The asset to render.
* @param language The current language
* @param result The map into which the result is put.
*/
@Override
protected void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result) {
super.renderAsset(asset, language, result);
final ExternalAudioAsset externalAudioAsset;
if (asset instanceof ExternalAudioAsset) {
externalAudioAsset = (ExternalAudioAsset) asset;
} else {
return;
}
result.put("legalMetadata",
legalMetadataRenderer
.render(externalAudioAsset.getLegalMetadata(),
language));
}
}

View File

@ -1,83 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.assets.ExternalVideoAsset;
import org.librecms.assets.LegalMetadata;
import org.librecms.contentsection.Asset;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
/**
* Renderer for {@link ExternalVideoAsset}s.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@AssetRenderer(renders = ExternalVideoAsset.class)
public class ExternalVideoAssetRenderer extends BookmarkRenderer {
@Inject
@AssetRenderer(renders = LegalMetadata.class)
private AbstractAssetRenderer legalMetadataRenderer;
/**
* Renders the provided {@link ExternalVideoAsset}. In addition to the data
* put into {@code result} by the {@link BookmarkRenderer} the following
* properties are put into the map:
*
* <pre>
* {
* "legalMetadata": {@link ExternalVideoAsset#getLegalMetadata()}
* }
* </pre>
*
* The associated {@link LegalMetadata} asset is rendered using the
* {@link LegalMetadata} and the result is put into the map under the key
* {@code legalMetadata}.
*
* @param asset The asset to render.
* @param language The current language
* @param result The map into which the result is put.
*/
@Override
protected void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result) {
super.renderAsset(asset, language, result);
final ExternalVideoAsset externalVideoAsset;
if (asset instanceof ExternalVideoAsset) {
externalVideoAsset = (ExternalVideoAsset) asset;
} else {
return;
}
result.put("legalMetadata",
legalMetadataRenderer
.render(externalVideoAsset.getLegalMetadata(), language));
}
}

View File

@ -1,56 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.assets.FileAsset;
import org.librecms.contentsection.Asset;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
/**
* Renderer for {@link FileAsset}s.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@AssetRenderer(renders = FileAsset.class)
public class FileAssetRenderer extends BinaryAssetRenderer {
/**
* Renders the provided {@link FileAsset}. No additional data.
*
* @param asset
* @param locale
* @param result
*/
@Override
protected void renderAsset(final Asset asset,
final Locale locale,
final Map<String, Object> result) {
super.renderAsset(asset, locale, result);
//Nothing more yet
}
}

View File

@ -1,88 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.assets.Image;
import org.librecms.assets.LegalMetadata;
import org.librecms.contentsection.Asset;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
/**
* Renderer for {@link ImageRenderer}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@AssetRenderer(renders = Image.class)
@RequestScoped
public class ImageRenderer extends BinaryAssetRenderer {
@Inject
@AssetRenderer(renders = LegalMetadata.class)
private AbstractAssetRenderer legalMetadataRenderer;
/**
* Renders the provided {@link ImageAsset}. The following data is put into
* the map:
*
* <pre>
* {
* "width": {@link Image#getWidth()}
* "height": {@link Image#getHeight()}
* "legalMetadata": {@link LegalMetadataRenderer#render(org.librecms.contentsection.Asset, java.util.Locale)} using {@link Image#getLegalMetadata()}.
* }
* </pre>
*
* The associated {@link LegalMetadata} asset is rendered using
* {@link LegalMetadataRenderer} and the result is put into map under the
* key {@code legalMetadata}.
*
* @param asset The asset to render.
* @param language The current language.
* @param result The map into which the result is put.
*/
@Override
protected void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result) {
super.renderAsset(asset, language, result);
final Image image;
if (asset instanceof Image) {
image = (Image) asset;
} else {
return;
}
result.put("width", image.getWidth());
result.put("height", image.getHeight());
if (image.getLegalMetadata() != null) {
result.put("legalMetadata",
legalMetadataRenderer.render(image.getLegalMetadata(),
language));
}
}
}

View File

@ -1,76 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.assets.LegalMetadata;
import org.librecms.contentsection.Asset;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
/**
* Renderer for {@link LegalMetadata} assets.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@AssetRenderer(renders = LegalMetadata.class)
public class LegalMetadataRenderer extends AbstractAssetRenderer {
/**
* Render the provided {@link LegalMetadata} asset. The following properties
* are added to the {@code result} map:
*
* <pre>
* "rightsHolder": {@link LegalMetadata#getRightsHolder()}
* "rights": {@link LegalMetadata#getRights()}
* "publisher": {@link LegalMetadata#getPublisher()}
* "creator": {@link LegalMetadata#getCreator()}
* "contributors": {@link LegalMetadata#getContributors()}
* </pre>
*
* @param asset The asset to renderer.
* @param language The current language.
* @param result The map into which the result is placed.
*/
@Override
protected void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result) {
final LegalMetadata legalMetadata;
if (asset instanceof LegalMetadata) {
legalMetadata = (LegalMetadata) asset;
} else {
return;
}
result.put("rightsHolder", legalMetadata.getRightsHolder());
result.put("rights", legalMetadata.getRights().getValue(language));
result.put("publisher", legalMetadata.getPublisher());
result.put("creator", legalMetadata.getCreator());
result.put("contributors",
new ArrayList<>(legalMetadata.getContributors()));
}
}

View File

@ -1,55 +0,0 @@
/*
* Copyright (C) 2019 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.assets.Organization;
import org.librecms.contentsection.Asset;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@AssetRenderer(renders = Organization.class)
public class OrganizationRenderer extends ContactableEntityRenderer {
@Override
protected void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result) {
super.renderAsset(asset, language, result);
final Organization organization;
if (asset instanceof Organization) {
organization = (Organization) asset;
} else {
return;
}
result.put("organizationName", organization.getName());
}
}

View File

@ -1,86 +0,0 @@
/*
* Copyright (C) 2019 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.assets.Person;
import org.librecms.assets.PersonName;
import org.librecms.contentsection.Asset;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@AssetRenderer(renders = Person.class)
public class PersonRenderer extends ContactableEntityRenderer {
@Override
protected void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result) {
super.renderAsset(asset, language, result);
final Person person;
if (asset instanceof Person) {
person = (Person) asset;
} else {
return;
}
final PersonName personName = person.getPersonName();
if (personName != null) {
if (personName.getSurname() != null
&& !personName.getSurname().isEmpty()) {
result.put("surname", personName.getSurname());
}
if (personName.getGivenName() != null
&& !personName.getGivenName().isEmpty()) {
result.put("givenName", personName.getGivenName());
}
if (personName.getPrefix() != null
&& !personName.getPrefix().isEmpty()) {
result.put("prefix", personName.getPrefix());
}
if (personName.getSuffix() != null
&& !personName.getSuffix().isEmpty()) {
result.put("suffix", personName.getSuffix());
}
}
if (person.getBirthdate() != null) {
result.put("birthdate", person.getBirthdate());
}
}
}

View File

@ -1,57 +0,0 @@
/*
* Copyright (C) 2019 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.assets.PostalAddress;
import org.librecms.contentsection.Asset;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@AssetRenderer(renders = PostalAddress.class)
public class PostalAddressRenderer extends AbstractAssetRenderer {
@Override
protected void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result) {
final PostalAddress postalAddress;
if (asset instanceof PostalAddress) {
postalAddress = (PostalAddress) asset;
} else {
return;
}
result.put("address", postalAddress.getAddress());
result.put("city", postalAddress.getCity());
result.put("isoCountryCode", postalAddress.getIsoCountryCode());
result.put("postalCode", postalAddress.getPostalCode());
result.put("state", postalAddress.getState());
}
}

View File

@ -1,118 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.assets.Bookmark;
import org.librecms.assets.RelatedLink;
import org.librecms.contentsection.Asset;
import org.librecms.contentsection.ContentItem;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
/**
* Renderer for {@link RelatedLink} assets.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@AssetRenderer(renders = RelatedLink.class)
public class RelatedLinkRenderer extends AbstractAssetRenderer {
@Inject
@AssetRenderer(renders = Bookmark.class)
private AbstractAssetRenderer bookmarkRenderer;
/**
* Render the provided {@link RelatedLink}.
*
* Depending on the type of the {@link RelatedLink} (internal or external)
* different properties are placed into {@code result}.
*
* For internal links: An entry with the key {@code targetItem} and a map
* containing the following properties of the target item:
*
* <pre>
* {
* "objectId": {@link ContentItem#getObjectId()}
* "itemUuid": {@link ContentItem#getItemUuid()}
* "displayName": {@link ContentItem#getDisplayName()}
* "name": {@link ContentItem#getName()}
* "title": {@link ContentItem#getTitle()}
* "description": {@link ContentItem#getDescription()}
* }
* </pre>
*
* For external links an {@link RelatedLink} uses a association with a
* {@link Bookmark}. The {@code Bookmark} is rendered using the
* {@link BookmarkRenderer}. The result is put into {@code result} with the
* key {@code bookmark}.
*
*
* @param asset The asset to render.
* @param language The current language.
* @param result The map is which to result is stored.
*/
@Override
protected void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result) {
final RelatedLink relatedLink;
if (asset instanceof RelatedLink) {
relatedLink = (RelatedLink) asset;
} else {
return;
}
if (relatedLink.getTargetItem() != null) {
result.put("targetItem",
renderTargetItem(relatedLink.getTargetItem(),
language));
}
if (relatedLink.getBookmark() != null) {
result.put("bookmark",
bookmarkRenderer.render(relatedLink.getBookmark(),
language));
}
}
protected Map<String, Object> renderTargetItem(final ContentItem targetItem,
final Locale language) {
final Map<String, Object> result = new HashMap<>();
result.put("objectId", targetItem.getObjectId());
result.put("itemUuid", targetItem.getItemUuid());
result.put("displayName", targetItem.getDisplayName());
result.put("name", targetItem.getName().getValue(language));
result.put("title", targetItem.getTitle().getValue(language));
result.put("description",
targetItem.getDescription().getValue(language));
return result;
}
}

View File

@ -1,68 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.assets.SideNote;
import org.librecms.contentsection.Asset;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
/**
* Renderer for {@link SideNote} assets.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@AssetRenderer(renders = SideNote.class)
public class SideNoteRenderer extends AbstractAssetRenderer {
/**
* Renderer to provided {@link SideNote}. The only property put into
* {@code result} by this renderer is {@code text}:
*
* <pre>
* {
* "text": {@link SideNote#getText()}
* }
* </pre>
*
* @param asset The {@link SideNote} to render.
* @param language The current language.
* @param result The into which the result is placed.
*/
@Override
protected void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result) {
final SideNote siteNote;
if (asset instanceof SideNote) {
siteNote = (SideNote) asset;
} else {
return;
}
result.put("text", siteNote.getText().getValue(language));
}
}

View File

@ -1,82 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.assets;
import org.librecms.assets.LegalMetadata;
import org.librecms.assets.VideoAsset;
import org.librecms.contentsection.Asset;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
/**
* Renderer for {@link VideoAsset}s.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@AssetRenderer(renders = VideoAsset.class)
public class VideoAssetRenderer extends BinaryAssetRenderer {
@Inject
@AssetRenderer(renders = LegalMetadata.class)
private AbstractAssetRenderer legalMetadataRenderer;
/**
* Renders the provided {@link VideoAsset}. The following properties a put
* into {@code result}:
*
* <pre>
* {
* width: {@link VideoAsset#getWidth()}
* height: {@link VideoAsset#getHeight()}
* legalMetadata: {@link VideoAsset#getLegalMetadata()}
* }
* </pre>
*
* @param asset The asset to render.
* @param language The current language.
* @param result The map into which the result is put.
*/
@Override
protected void renderAsset(final Asset asset,
final Locale language,
final Map<String, Object> result) {
super.renderAsset(asset, language, result);
final VideoAsset videoAsset;
if (asset instanceof VideoAsset) {
videoAsset = (VideoAsset) asset;
} else {
return;
}
result.put("width", videoAsset.getWidth());
result.put("height", videoAsset.getHeight());
result.put("legalMetadata",
legalMetadataRenderer.render(videoAsset.getLegalMetadata(),
language));
}
}

View File

@ -1,248 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.contentitems;
import org.libreccm.messaging.Attachment;
import org.librecms.contentsection.Asset;
import org.librecms.pagemodel.assets.AbstractAssetRenderer;
import org.librecms.contentsection.AttachmentList;
import org.librecms.contentsection.ContentItem;
import org.librecms.contentsection.ContentType;
import org.librecms.contentsection.ItemAttachment;
import org.librecms.contentsection.rs.ContentItems;
import org.librecms.pagemodel.assets.AssetRenderers;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Base class for the renderers for {@link ContentItems}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
public abstract class AbstractContentItemRenderer implements Serializable {
private static final long serialVersionUID = 1290408390406469580L;
// private final AssetRenderers assetRenderers;
//
// public AbstractContentItemRenderer(final AssetRenderers assetRenderers) {
// this.assetRenderers = assetRenderers;
// }
/**
* This method should be called to render a {@link ContentItem}. The method
* puts the common properties for {@link ContentItem}s into {@code result}
* and than calls
* {@link #renderItem(org.librecms.contentsection.ContentItem, java.util.Locale, java.util.Map)}
* to put the special properties of provided item into {@code result}.
*
* The common properties put into {@code result} are:
*
* <pre>
* {
* "objectId": {@link ContentItem#getObjectId()}
* "uuid": {@link ContentItem#getUuid()}
* "displayName": {@link ContentItem#getDisplayName()}
* "itemUuid": {@link ContentItem#getItemUuid()}
* "name": {@link ContentItem#getName()}
* "title": {@link ContentItem#getTitle()}
* "contentType": {@link ContentItem#getContentType()}
* "description": {@link ContentItem#getDescription()}
* "creationDate": {@link ContentItem#getCreationDate()}
* "lastModified": {@link ContentItem#getLastModified()}
* "creationUserName": {@link ContentItem#getCreationUserName()}
* "lastModifyingUserName": {@link ContentItem#getLastModifyingUserName()}
* "attachments": {@link ContentItem#getAttachments()}.
* }
* </pre>
*
* The value of {@link ContentItem#getContentType} is rendered by
* {@link #renderContentType(org.librecms.contentsection.ContentType, java.util.Locale)}.
*
* The value of {@link ContentItem#getAttachments()} is rendered using
* {@link #renderAttachmentList(org.librecms.contentsection.AttachmentList, java.util.Locale)}.
*
* @param item The item to render.
* @param language The current language.
*
* @return A map with the data of the provided {@link ContentItem}.
*/
public Map<String, Object> render(final ContentItem item,
final Locale language) {
final Map<String, Object> result = new HashMap<>();
result.put("objectId", item.getObjectId());
result.put("uuid", item.getUuid());
result.put("displayName", item.getDisplayName());
result.put("itemUuid", item.getItemUuid());
result.put("name", item.getName().getValue(language));
result.put("title", item.getTitle().getValue(language));
result.put("contentType", renderContentType(item.getContentType(),
language));
result.put("description", item.getDescription().getValue(language));
result.put("version", item.getVersion().toString());
result.put("creationDate", item.getCreationDate());
result.put("lastModified", item.getLastModified());
result.put("creationUserName", item.getCreationUserName());
result.put("lastModifyingUserName", item.getLastModifyingUserName());
result.put("attachments",
item
.getAttachments()
.stream()
.map(list -> renderAttachmentList(list, language))
.collect(Collectors.toList()));
renderItem(item, language, result);
return result;
}
protected abstract void renderItem(final ContentItem item,
final Locale language,
final Map<String, Object> result);
protected abstract AssetRenderers getAssetRenderers();
/**
* Renders the {@link ContentType} of an {@link ContentItem}. The generated
* map contains the following values:
*
* <pre>
* {
* "objectId": {@link ContentType#getObjectId()}
* "uuid": {@link ContentType#getUuid()}
* "displayName": {@link ContentType#getDisplayName()}
* "label": {@link ContentType#getLabel()}
* }
* </pre>
*
* @param contentType The {@link ContentType} to render.
* @param language The current language.
*
* @return A map with the properties of the {@link ContentType}.
*/
protected Map<String, Object> renderContentType(
final ContentType contentType, final Locale language) {
final Map<String, Object> result = new HashMap<>();
result.put("objectId", contentType.getObjectId());
result.put("uuid", contentType.getUuid());
result.put("displayName", contentType.getDisplayName());
result.put("label", contentType.getLabel().getValue(language));
return result;
}
/**
* Renders a {@link AttachmentList} and all {@link ItemAttachment}s. in the
* list. The map contains the following values:
*
* <pre>
* {
* "listId": {@link AttachmentList#getListId()}
* "uuid": {@link AttachmentList#getUuid()}
* "name": {@link AttachmentList#getName()}
* "order": {@link AttachmentList#getListOrder()}
* "title": {@link AttachmentList#getTitle()}
* "description": {@link AttachmentList#getDescription()}
* "attachments": {@link AttachmentList#getAttachments()}
* }
* </pre>
*
* The attachments of the list are rendered using
* {@link #renderAttachment(org.librecms.contentsection.ItemAttachment, java.util.Locale)}.
*
* @param attachmentList The {@link AttachmentList} to render.
* @param language The current language.
*
* @return A map containing the data of the {@link AttachmentList} and its
* {@link Attachment}s.
*/
protected Map<String, Object> renderAttachmentList(
final AttachmentList attachmentList,
final Locale language) {
final Map<String, Object> result = new HashMap<>();
result.put("listId", attachmentList.getListId());
result.put("uuid", attachmentList.getUuid());
result.put("name", attachmentList.getName());
result.put("order", attachmentList.getListOrder());
result.put("title", attachmentList.getTitle().getValue(language));
result.put("description",
attachmentList.getDescription().getValue(language));
result.put("attachments",
attachmentList
.getAttachments()
.stream()
.map(attachment -> renderAttachment(attachment, language))
.collect(Collectors.toList()));
return result;
}
/**
* Renders an {@link ItemAttachment}. The generated map contains the
* following values:
*
* <pre>
* {
* "attachmentId": {@link ItemAttachment#getAttachmentId()}
* "uuid": {@link ItemAttachment#getUuid()}
* "sortKey": {@link ItemAttachment#getSortKey()}
* "asset": {@link ItemAttachment#getAsset()}
* }
* </pre>
*
* The associated {@link Asset} is rendered using the appropriate
* {@link AbstractAssetRenderer} implementation. The
* {@link AbstractAssetRenderer} to use is retrieved using
* {@link AssetRenderers#findRenderer(java.lang.Class)}.
*
* @param attachment The {@link ItemAttachment} to render.
* @param language The current language.
*
* @return A map with the data of the {@link ItemAttachment}.
*/
protected Map<String, Object> renderAttachment(
final ItemAttachment<?> attachment,
final Locale language) {
final Map<String, Object> result = new HashMap<>();
result.put("attachmentId", attachment.getAttachmentId());
result.put("uuid", attachment.getUuid());
result.put("sortKey", attachment.getSortKey());
final AbstractAssetRenderer renderer = getAssetRenderers()
.findRenderer(attachment.getAsset().getClass());
result.put("asset", renderer.render(attachment.getAsset(), language));
return result;
}
}

View File

@ -1,85 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.contentitems;
import org.librecms.contentsection.ContentItem;
import org.librecms.contenttypes.Article;
import org.librecms.pagemodel.assets.AssetRenderers;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
/**
* Renderer for {@link Article} items.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@ContentItemRenderer(renders = Article.class)
@RequestScoped
public class ArticleRenderer extends AbstractContentItemRenderer {
private static final long serialVersionUID = 8355183377902033759L;
@Inject
private AssetRenderers assetRenderers;
// @Inject
// public ArticleRenderer(final AssetRenderers assetRenderers) {
// super(assetRenderers);
// }
/**
* Render the provided {@link Article}. The following values are put into
* the map:
*
* <pre>
* {
* "text": {@link Article#getText()}
* }
* </pre>
*
* @param item The item to render.
* @param language The current language.
* @param result The map into which the result is placed.
*/
@Override
protected void renderItem(
final ContentItem item,
final Locale language,
final Map<String, Object> result
) {
final Article article;
if (item instanceof Article) {
article = (Article) item;
} else {
return;
}
result.put("text", article.getText().getValue(language));
}
@Override
public AssetRenderers getAssetRenderers() {
return assetRenderers;
}
}

View File

@ -1,54 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.contentitems;
import org.librecms.contentsection.ContentItem;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
/**
* Qualifier annotation for implementations of
* {@link AbstractContentItemRenderer}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,
ElementType.FIELD,
ElementType.PARAMETER,
ElementType.TYPE})
public @interface ContentItemRenderer {
/**
* The type of Item which can be rendered by the annotated content item
* renderer.
*
* @return
*/
Class<? extends ContentItem> renders();
String mode() default "--DEFAULT--";
}

View File

@ -1,169 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.contentitems;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.librecms.contentsection.ContentItem;
import org.librecms.contenttypes.Article;
import org.librecms.pagemodel.assets.AssetRenderers;
import java.io.Serializable;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Inject;
/**
* Provides access to all available implementations of
* {@link AbstractContentItemRenderer}.
*
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
public class ContentItemRenderers implements Serializable {
private static final long serialVersionUID = 4038159486301146385L;
private static final Logger LOGGER = LogManager
.getLogger(ContentItemRenderers.class);
@Inject
private AssetRenderers assetRenderers;
@Inject
@Any
private Instance<AbstractContentItemRenderer> renderers;
/**
* Tries to find the renderer for provided type and the default mode.
*
* @param itemType The type for which the renderer is retrieved.
*
* @return The renderer for the provided type.
*/
public AbstractContentItemRenderer findRenderer(
final Class<? extends ContentItem> itemType) {
LOGGER.debug("Trying to find default renderer for item type \"{}\"...",
itemType.getName());
return findRenderer(itemType, "--DEFAULT--");
}
/**
* Tries to find the renderer for provided type and the provided mode. If a
* appropriate renderer is found an default renderer with an empty
* implementation of
* {@link AbstractContentItemRenderer#renderItem(org.librecms.contentsection.ContentItem, java.util.Locale, java.util.Map)}
* is returned.
*
* @param itemType The type for which the renderer is retrieved.
* @param mode The render mode.
*
* @return The renderer for the provided type.
*/
public AbstractContentItemRenderer findRenderer(
final Class<? extends ContentItem> itemType, final String mode) {
LOGGER.debug("Trying to find default renderer for item type \"{}\""
+ "and mode \"{}\"...",
itemType.getName(),
mode);
final ContentItemRendererLiteral literal
= new ContentItemRendererLiteral(
itemType, mode);
final Instance<AbstractContentItemRenderer> instance = renderers
.select(literal);
if (instance.isUnsatisfied()) {
if ("--DEFAULT--".equals(mode)) {
LOGGER.warn("No renderer for item type \"{}\" and mode "
+ "\"--DEFAULT--\". Returning default renderer.",
itemType.getName());
return new AbstractContentItemRenderer() {
private static final long serialVersionUID
= -4679445070846896396L;
@Override
public void renderItem(final ContentItem item,
final Locale language,
final Map<String, Object> result) {
//Nothing here.
}
@Override
public AssetRenderers getAssetRenderers() {
return assetRenderers;
}
};
} else {
LOGGER.warn("No renderer for item type \"{}\" and mode "
+ "\"{}\". Trying to find renderer for "
+ "mode \"--DEFAULT--\".",
itemType.getName(),
mode);
return findRenderer(itemType);
}
} else {
return instance.iterator().next();
}
}
private class ContentItemRendererLiteral
extends AnnotationLiteral<ContentItemRenderer>
implements ContentItemRenderer {
private static final long serialVersionUID = 6104170621944116228L;
private final Class<? extends ContentItem> renders;
private final String mode;
public ContentItemRendererLiteral(
final Class<? extends ContentItem> renders,
final String mode) {
this.renders = renders;
this.mode = mode;
}
@Override
public Class<? extends ContentItem> renders() {
return renders;
}
@Override
public String mode() {
return mode;
}
}
}

View File

@ -1,102 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.contentitems;
import org.librecms.contentsection.ContentItem;
import org.librecms.contenttypes.Event;
import org.librecms.pagemodel.assets.AssetRenderers;
import java.util.Locale;
import java.util.Map;
import javax.inject.Inject;
/**
* Renderer for {@link Event} items.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@ContentItemRenderer(renders = Event.class)
public class EventRenderer extends AbstractContentItemRenderer {
private static final long serialVersionUID = -3517404651544429745L;
@Inject
private AssetRenderers assetRenderers;
// @Inject
// public EventRenderer(final AssetRenderers assetRenderers) {
// super(assetRenderers);
// }
/**
* Render the provided {@link Event}. The following values are put into
* {@code result}:
*
* <pre>
* {
* "text": {@link Event#getText()}
* "startDate": {@link Event#getStartDate()}
* "endDate": {@link Event#getEndDate()}
* "eventDate": {@link Event#getEventType()}
* "location": {@link Event#getLocation()}
* "mainContributor": {@link Event#getMainContributor()}
* "eventType": {@link Event#getEventType()}
* "mapLink": {@link Event#getMapLink()}
* "cost": {@link Event#getCost()}
* }
* </pre>
*
* @param item The item to render.
* @param language The current language.
* @param result The map into which the result is placed.
*/
@Override
public void renderItem(final ContentItem item,
final Locale language,
final Map<String, Object> result) {
final Event event;
if (item instanceof Event) {
event = (Event) item;
} else {
return;
}
result.put("text", event.getText().getValue(language));
result.put("startDate", event.getStartDate());
result.put("endDate", event.getEndDate());
result.put("eventDate", event.getEventDate().getValue(language));
result.put("location", event.getLocation().getValue(language));
result.put("mainContributor",
event.getMainContributor().getValue(language));
result.put("eventType", event.getEventType().getValue(language));
result.put("mapLink", event.getMapLink());
result.put("cost", event.getCost().getValue(language));
}
@Override
protected AssetRenderers getAssetRenderers() {
return assetRenderers;
}
}

View File

@ -1,133 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.contentitems;
import org.librecms.contentsection.ContentItem;
import org.librecms.contenttypes.MultiPartArticle;
import org.librecms.contenttypes.MultiPartArticleSection;
import org.librecms.pagemodel.assets.AssetRenderers;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import javax.inject.Inject;
/**
* Renderer for {@link MultiPartArticle} items.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@ContentItemRenderer(renders = MultiPartArticle.class)
public class MultiPartArticleRenderer extends AbstractContentItemRenderer {
private static final long serialVersionUID = -4298383182795585868L;
@Inject
private AssetRenderers assetRenderers;
// @Inject
// public MultiPartArticleRenderer(final AssetRenderers assetRenderers) {
// super(assetRenderers);
// }
/**
* Renders the provided {@link MultiPartArticle}. The following values are
* put into {@code result}:
*
* <pre>
* {
* "summary": {@link MultiPartArticle#getSummary()}
* "sections": {@link MultiPartArticle#getSections()}
* }
* </pre>
*
* The value of {@code sections} is a list containing a {@link Map}
* generated by
* {@link #renderSection(org.librecms.contenttypes.MultiPartArticleSection, java.util.Locale)}
* for each section.
*
* @param item The item to render.
* @param language The current language.
* @param result The map into which the result is placed.
*/
@Override
public void renderItem(final ContentItem item,
final Locale language,
final Map<String, Object> result) {
final MultiPartArticle article;
if (item instanceof MultiPartArticle) {
article = (MultiPartArticle) item;
} else {
return;
}
result.put("summary", article.getSummary().getValue(language));
result.put("sections",
article
.getSections()
.stream()
.map(section -> renderSection(section, language))
.collect(Collectors.toList()));
}
/**
* Renders a {@link MultiPartArticleSection}. The generated map contains the
* following values:
*
* <pre>
* {
* "sectionId": {@link MultiPartArticleSection#getSectionId()}
* "title": {@link MultiPartArticleSection#getTitle()}
* "rank": {@link MultiPartArticleSection#getRank()}
* "pageBreak": {@link MultiPartArticleSection#isPageBreak()}
* "text": {@link MultiPartArticleSection#getText()}
* }
* </pre>
*
* @param section The section to render.
* @param language The current language.
*
* @return A map with the data of the section.
*/
protected Map<String, Object> renderSection(
final MultiPartArticleSection section, final Locale language) {
final Map<String, Object> result = new HashMap<>();
result.put("sectionId", section.getSectionId());
result.put("title", section.getTitle().getValue(language));
result.put("rank", section.getRank());
result.put("pageBreak", section.isPageBreak());
result.put("text", section.getText().getValue(language));
return result;
}
@Override
protected AssetRenderers getAssetRenderers() {
return assetRenderers;
}
}

View File

@ -1,86 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pagemodel.contentitems;
import org.librecms.contentsection.ContentItem;
import org.librecms.contenttypes.News;
import org.librecms.pagemodel.assets.AssetRenderers;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
/**
* Renderer for {@link News} items.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@ContentItemRenderer(renders = News.class)
@RequestScoped
public class NewsRenderer extends AbstractContentItemRenderer {
private static final long serialVersionUID = -493301428054148505L;
@Inject
private AssetRenderers assetRenderers;
// @Inject
// public NewsRenderer(final AssetRenderers assetRenderers) {
// super(assetRenderers);
// }
/**
* Renders the provided {@link News} item. The following values are put into
* {@code result}:
*
* <pre>
* {
* "text": {@link News#getText()}
* "releaseDate": {@link News#getReleaseDate()}
* }
* </pre>
*
* @param item The item to render.
* @param language The current language.
* @param result The map into which the result is placed.
*/
@Override
public void renderItem(final ContentItem item,
final Locale language,
final Map<String, Object> result) {
final News news;
if (item instanceof News) {
news = (News) item;
} else {
return;
}
result.put("text", news.getText().getValue(language));
result.put("releaseDate", news.getReleaseDate());
}
@Override
protected AssetRenderers getAssetRenderers() {
return assetRenderers;
}
}

View File

@ -1,58 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pages;
import org.libreccm.categorization.Category;
import org.libreccm.pagemodel.AbstractPageRenderer;
import org.libreccm.pagemodel.PageRenderer;
import java.util.HashMap;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
/**
* Implementation of {@link PageRenderer} for CMS pages.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@RequestScoped
public class CmsPageRenderer extends AbstractPageRenderer {
@Override
public Map<String, Object> renderPage(final Map<String, Object> parameters) {
final Map<String, Object> result = new HashMap<>();
result.put("application", Pages.class.getName());
if (parameters.containsKey(PagesRouter.SITE_INFO)) {
result.put(
PagesRouter.SITE_INFO, parameters.get(PagesRouter.SITE_INFO)
);
}
if (parameters.containsKey(PagesRouter.PAGE_PATH)) {
result.put(
PagesRouter.PAGE_PATH, parameters.get(PagesRouter.PAGE_PATH)
);
}
return result;
}
}

View File

@ -1,929 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.pages;
import com.arsdigita.kernel.KernelConfig;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.libreccm.categorization.Category;
import org.libreccm.categorization.CategoryManager;
import org.libreccm.categorization.CategoryRepository;
import org.libreccm.configuration.ConfigurationManager;
import org.libreccm.l10n.GlobalizationHelper;
import org.libreccm.pagemodel.PageModel;
import org.libreccm.pagemodel.PageModelManager;
import org.libreccm.pagemodel.PageModelVersion;
import org.libreccm.sites.Site;
import org.libreccm.sites.SiteRepository;
import org.libreccm.theming.ThemeInfo;
import org.libreccm.theming.ThemeVersion;
import org.libreccm.theming.Themes;
import org.librecms.contentsection.ContentItemVersion;
import java.net.URI;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import static org.librecms.pages.PagesConstants.*;
/**
* JAX-RS class providing access to the pages.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated // to be replaced by PagesController
@RequestScoped
@Path("/")
public class PagesRouter {
protected static final String PAGE_PATH = "pagePath";
protected static final String PAGE_PATH_CATEGORY_ID = "categoryId";
protected static final String PAGE_PATH_CATEGORY_NAME = "categoryName";
protected static final String PAGE_PATH_CATEGORY_TITLE = "categoryTitle";
protected static final String PAGE_PATH_CATEGORY_UUID = "uuid";
protected static final String SITE_INFO = "siteInfo";
protected static final String SITE_INFO_NAME = "name";
protected static final String SITE_INFO_DOMAIN = "domain";
protected static final String SITE_INFO_HOST = "host";
protected static final String SITE_INFO_LANGS = "supportedLanguages";
@Inject
private CategoryManager categoryManager;
@Inject
private CategoryRepository categoryRepo;
@Inject
private ConfigurationManager confManager;
@Inject
private GlobalizationHelper globalizationHelper;
@Inject
private CmsPageRenderer pageBuilder;
@Inject
private PagesRepository pagesRepo;
@Inject
private PageManager pageManager;
@Inject
private PageModelManager pageModelManager;
@Inject
private SiteRepository siteRepo;
@Inject
private Themes themes;
private Locale defaultLocale;
@PostConstruct
private void init() {
final KernelConfig kernelConfig = confManager
.findConfiguration(KernelConfig.class);
defaultLocale = kernelConfig.getDefaultLocale();
}
@GET
@Path("/")
@Transactional(Transactional.TxType.REQUIRED)
public Response redirectToIndexPage(@Context final UriInfo uriInfo) {
final String domain = uriInfo.getBaseUri().getHost();
final Pages pages = getPages(domain);
final Category category = getCategory(domain, pages, "/");
final String language = determineLanguage(category);
final String indexPage = String.format("/index.%s.html", language);
final URI uri = uriInfo.getBaseUriBuilder().path(indexPage).build();
return Response.temporaryRedirect(uri).build();
}
@GET
@Path("/{name:[\\w\\-]+}")
@Transactional(Transactional.TxType.REQUIRED)
public Response getRootPage(
@Context final UriInfo uriInfo,
@PathParam("name") final String itemName) {
final String domain = uriInfo.getBaseUri().getHost();
final Pages pages = getPages(domain);
final Category category = getCategory(domain, pages, "/");
final String language = determineLanguage(category);
final String itemPage = String.format("/%s.%s.html", itemName, language);
final URI uri = uriInfo.getBaseUriBuilder().path(itemPage).build();
return Response.temporaryRedirect(uri).build();
}
@GET
@Path("/{name:[\\w\\-]+}.html")
@Transactional(Transactional.TxType.REQUIRED)
public Response getRootPageAsHtml(
@Context final UriInfo uriInfo,
@PathParam("name") final String itemName) {
final String domain = uriInfo.getBaseUri().getHost();
final Pages pages = getPages(domain);
final Category category = getCategory(domain, pages, "/");
final String language = determineLanguage(category);
final String itemPage = String.format("/%s.%s.html", itemName, language);
final String path = uriInfo
.getPath()
.replace(String.format("%s.html", itemName), itemPage);
final URI uri = uriInfo.getBaseUriBuilder().path(path).build();
return Response.temporaryRedirect(uri).build();
}
@GET
@Path("/{name:[\\w\\-]+}.{lang:\\w+}.html")
@Produces("text/html")
@Transactional(Transactional.TxType.REQUIRED)
public String getRootPageAsHtml(
@Context
final UriInfo uriInfo,
@PathParam("name")
final String itemName,
@PathParam("lang")
final String language,
@QueryParam("theme")
@DefaultValue("--DEFAULT--")
final String theme,
@QueryParam("preview")
@DefaultValue("")
final String preview) {
final Versions versions = generateFromPreviewParam(preview);
final Map<String, Object> result;
if ("index".equals(itemName)) {
result = getCategoryIndexPage(uriInfo,
"/",
language,
versions.getPageModelVersion());
} else {
result = getCategoryItemPage(uriInfo,
"/",
itemName,
language,
versions.getPageModelVersion());
}
final Site site = getSite(uriInfo);
final ThemeInfo themeInfo = getTheme(site,
theme,
versions.getThemeVersion());
return themes.process(result, themeInfo);
}
@GET
@Path("/{name:[\\w\\-]+}.{lang:\\w+}.json")
@Produces("application/json")
@Transactional(Transactional.TxType.REQUIRED)
public String getRootPageAsJson(
@Context
final UriInfo uriInfo,
@PathParam("name")
final String itemName,
@PathParam("lang")
final String language,
@QueryParam("preview")
@DefaultValue("")
final String preview) {
final Versions versions = generateFromPreviewParam(preview);
final ObjectMapper mapper = new ObjectMapper();
final Map<String, Object> result;
if ("index".equals(itemName)) {
result = getCategoryIndexPage(uriInfo,
"/",
language,
versions.getPageModelVersion());
} else {
result = getCategoryItemPage(uriInfo,
"/",
itemName,
language,
versions.getPageModelVersion());
}
try {
final String json = mapper.writeValueAsString(result);
return json;
} catch (JsonProcessingException ex) {
throw new WebApplicationException(ex);
}
}
@GET
@Path("/{name:[\\w\\-]+}.{lang:\\w+}.xml")
@Produces("text/xml")
@Transactional(Transactional.TxType.REQUIRED)
public String getRootPageAsXml(
@Context
final UriInfo uriInfo,
@PathParam("name")
final String itemName,
@PathParam("lang")
final String language,
@QueryParam("preview")
@DefaultValue("")
final String preview) {
final Versions versions = generateFromPreviewParam(preview);
final JacksonXmlModule xmlModule = new JacksonXmlModule();
final ObjectMapper mapper = new XmlMapper(xmlModule);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
final Map<String, Object> result;
if ("index".equals(itemName)) {
result = getCategoryIndexPage(uriInfo,
"/",
language,
versions.getPageModelVersion());
} else {
result = getCategoryItemPage(uriInfo,
"/",
itemName,
language,
versions.getPageModelVersion());
}
try {
final String html = mapper
.writer()
.withRootName("page")
.writeValueAsString(result);
return html;
} catch (JsonProcessingException ex) {
throw new WebApplicationException(ex);
}
}
/**
* Retrieve the item page for a category and the content item associated
* with the category and identified by {@code itemName}.
*
* Redirects to
* {@link #getPageAsHtml(javax.ws.rs.core.UriInfo, java.lang.String, java.lang.String)}.
*
* @param uriInfo
* @param page
* @param itemName
*
* @return
*/
@GET
@Path("/{page:[\\w\\-/]+}/{name:[\\w\\-]+}")
@Transactional(Transactional.TxType.REQUIRED)
public Response getPage(
@Context final UriInfo uriInfo,
@PathParam("page") final String page,
@PathParam("name") final String itemName) {
final String domain = uriInfo.getBaseUri().getHost();
final Pages pages = getPages(domain);
final Category category = getCategory(domain, pages, page);
final String language = determineLanguage(category);
final String redirectTo;
if (uriInfo.getPath().endsWith("/")) {
redirectTo = String.format("%sindex.%s.html",
uriInfo.getPath(),
language);
} else {
final String itemPath = String.format("%s.%s.html",
itemName,
language);
redirectTo = uriInfo.getPath().replace(itemName, itemPath);
}
final URI uri = uriInfo.getBaseUriBuilder().path(redirectTo).build();
return Response.temporaryRedirect(uri).build();
}
/**
* Retrieve the item page for a category and the content item associated
* with the category and identified by {@code itemName}. Redirects to
* {@link #getPageAsHtml(javax.ws.rs.core.UriInfo, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)}.
*
* @param uriInfo
* @param page
* @param itemName
*
* @return
*/
@GET
@Path("/{page:[\\w\\-/]+}/{name:[\\w\\-]+}.html")
@Transactional(Transactional.TxType.REQUIRED)
public Response getPageAsHtml(
@Context final UriInfo uriInfo,
@PathParam("page") final String page,
@PathParam("name") final String itemName) {
final String domain = uriInfo.getBaseUri().getHost();
final Pages pages = getPages(domain);
final Category category = getCategory(domain, pages, page);
final String language = determineLanguage(category);
final String redirectTo;
if (uriInfo.getPath().endsWith("/")) {
redirectTo = String.format("%sindex.%s.html",
uriInfo.getPath(),
language);
} else {
final String itemPath = String.format("%s.%s.html",
itemName,
language);
redirectTo = uriInfo.getPath().replace(itemName, itemPath);
}
final URI uri = uriInfo.getBaseUriBuilder().path(redirectTo).build();
return Response.temporaryRedirect(uri).build();
}
/**
* Retrieve the item page as HTML for a category and the content item
* associated with the category and identified by {@code itemName}.
*
* @param uriInfo
* @param page
* @param itemName
* @param language
* @param theme
* @param preview
*
* @return
*/
@GET
@Path("/{page:[\\w\\-/]+}/{name:[\\w\\-]+}.{lang:\\w+}.html")
@Produces("text/html")
@Transactional(Transactional.TxType.REQUIRED)
public String getPageAsHtml(
@Context
final UriInfo uriInfo,
@PathParam("page")
final String page,
@PathParam("name")
final String itemName,
@PathParam("lang")
final String language,
@QueryParam("theme")
@DefaultValue("--DEFAULT--")
final String theme,
@QueryParam("preview")
@DefaultValue("")
final String preview) {
final Versions versions = generateFromPreviewParam(preview);
final Map<String, Object> result;
if ("index".equals(itemName)) {
result = getCategoryIndexPage(uriInfo,
page,
language,
versions.getPageModelVersion());
} else {
result = getCategoryItemPage(uriInfo,
page,
itemName,
language,
versions.getPageModelVersion());
}
final Site site = getSite(uriInfo);
final ThemeInfo themeInfo = getTheme(site,
theme,
versions.getThemeVersion());
return themes.process(result, themeInfo);
}
/**
* Retrieve the item page as JSON for a category and the content item
* associated with the category and identified by {@code itemName}.
*
* @param uriInfo
* @param page
* @param itemName
* @param language
* @param preview
*
* @return
*/
@GET
@Path("/{page:[\\w\\-/]+}/{name:[\\w\\-]+}.{lang:\\w+}.json")
@Produces("application/json")
@Transactional(Transactional.TxType.REQUIRED)
public String getPageAsJson(
@Context
final UriInfo uriInfo,
@PathParam("page")
final String page,
@PathParam("name")
final String itemName,
@PathParam("lang")
final String language,
@QueryParam("preview")
@DefaultValue("")
final String preview) {
final Versions versions = generateFromPreviewParam(preview);
final ObjectMapper mapper = new ObjectMapper();
final Map<String, Object> result;
if ("index".equals(itemName)) {
result = getCategoryIndexPage(uriInfo,
page,
language,
versions.getPageModelVersion());
} else {
result = getCategoryItemPage(uriInfo,
page,
itemName,
language,
versions.getPageModelVersion());
}
try {
final String json = mapper.writeValueAsString(result);
return json;
} catch (JsonProcessingException ex) {
throw new WebApplicationException(ex);
}
}
/**
* Retrieve the item page as XML for a category and the content item
* associated with the category and identified by {@code itemName}.
*
* @param uriInfo
* @param page
* @param itemName
* @param language
* @param preview
*
* @return
*/
@GET
@Path("/{page:[\\w\\-/]+}/{name:[\\w\\-]+}.{lang:\\w+}.xml")
@Produces("text/xml")
@Transactional(Transactional.TxType.REQUIRED)
public String getPageAsXml(
@Context
final UriInfo uriInfo,
@PathParam("page")
final String page,
@PathParam("name")
final String itemName,
@PathParam("lang")
final String language,
@QueryParam("preview")
@DefaultValue("")
final String preview) {
final Versions versions = generateFromPreviewParam(preview);
final JacksonXmlModule xmlModule = new JacksonXmlModule();
final ObjectMapper mapper = new XmlMapper(xmlModule);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
final Map<String, Object> result;
if ("index".equals(itemName)) {
result = getCategoryIndexPage(uriInfo,
page,
language,
versions.getPageModelVersion());
} else {
result = getCategoryItemPage(uriInfo,
page,
itemName,
language,
versions.getPageModelVersion());
}
try {
final String html = mapper
.writer()
.withRootName("page")
.writeValueAsString(result);
return html;
} catch (JsonProcessingException ex) {
throw new WebApplicationException(ex);
}
}
private Site getSite(final UriInfo uriInfo) {
Objects.requireNonNull(uriInfo);
final String domain = uriInfo.getBaseUri().getHost();
final Site site;
if (siteRepo.hasSiteForDomain(domain)) {
site = siteRepo.findByDomain(domain).get();
} else {
site = siteRepo
.findDefaultSite()
.orElseThrow(() -> new NotFoundException(
"No matching Site and no default Site."));
}
return site;
}
private Pages getPages(final String domain) {
return pagesRepo
.findPagesForSite(domain)
.orElseThrow(() -> new NotFoundException(String
.format("No Pages for domain \"%s\" available.",
domain)));
}
private Category getCategory(final String domain,
final Pages pages,
final String pagePath) {
return categoryRepo
.findByPath(pages.getCategoryDomain(), pagePath)
.orElseThrow(() -> new NotFoundException(String.format(
"No Page for path \"%s\" in site \"%s\"",
pagePath,
domain)));
}
private String determineLanguage(final Category category) {
final Locale negoiatedLocale = globalizationHelper
.getNegotiatedLocale();
final String language;
if (category.getTitle().hasValue(negoiatedLocale)) {
language = negoiatedLocale.toString();
} else if (category.getTitle().hasValue(defaultLocale)) {
language = defaultLocale.toString();
} else {
throw new NotFoundException();
}
return language;
}
private ThemeInfo getTheme(final Site site,
final String theme,
final ThemeVersion themeVersion) {
if ("--DEFAULT--".equals(theme)) {
return themes
.getTheme(site.getDefaultTheme(), themeVersion)
.orElseThrow(() -> new WebApplicationException(
String.format("The configured default theme \"%s\" for "
+ "site \"%s\" is not available.",
site.getDefaultTheme(),
site.getDomainOfSite()),
Response.Status.INTERNAL_SERVER_ERROR));
} else {
return themes.getTheme(theme, themeVersion)
.orElseThrow(() -> new WebApplicationException(
String.format("The theme \"%s\" is not available.",
theme),
Response.Status.BAD_REQUEST));
}
}
private Page getPage(final UriInfo uriInfo,
final String pagePath,
final String language,
final Map<String, Object> parameters) {
Objects.requireNonNull(uriInfo);
Objects.requireNonNull(pagePath);
Objects.requireNonNull(parameters);
final KernelConfig kernelConfig = confManager
.findConfiguration(KernelConfig.class);
final String domain = uriInfo.getBaseUri().getHost();
final Pages pages = getPages(domain);
final Map<String, Object> siteInfo = new HashMap<>();
siteInfo.put(SITE_INFO_HOST, uriInfo.getBaseUri().getHost());
siteInfo.put(SITE_INFO_DOMAIN, pages.getSite().getDomainOfSite());
siteInfo.put(SITE_INFO_NAME, pages.getSite().getDisplayName());
siteInfo.put(
SITE_INFO_LANGS,
kernelConfig.getSupportedLanguages().stream().sorted().collect(
Collectors.toList()
)
);
parameters.put(SITE_INFO, siteInfo);
final Category category = getCategory(domain, pages, pagePath);
final Locale locale = new Locale(language);
// disabled. Needs to be decided if the available languages of the
// index item or of the category are
// used to decide if a NotFoundException is thrown.
// if (!category.getTitle().hasValue(locale)) {
// throw new NotFoundException();
// }
globalizationHelper.setSelectedLocale(locale);
parameters.put(PAGE_PATH, buildPageCategoriesPath(category, locale));
parameters.put(PARAMETER_CATEGORY, category);
return pageManager.findPageForCategory(category);
}
private Map<String, Object> buildPage(
final PageModel pageModel,
final Map<String, Object> parameters) {
Objects.requireNonNull(pageModel);
Objects.requireNonNull(parameters);
final Map<String, Object> result;
if (pageModel == null) {
result = pageBuilder.renderPage(parameters);
} else {
result = pageBuilder.renderPage(pageModel, parameters);
}
return result;
}
private Map<String, Object> getCategoryIndexPage(
final UriInfo uriInfo,
final String pagePath,
final String language,
final PageModelVersion pageModelVersion) {
final Map<String, Object> parameters = new HashMap<>();
final Page page = getPage(uriInfo,
pagePath,
language,
parameters);
// final PageModel pageModel;
// if (pageModelVersion == PageModelVersion.DRAFT) {
// pageModel = pageModelManager
// .getDraftVersion(page.getIndexPageModel());
// } else {
// pageModel = pageModelManager
// .getLiveVersion(page.getIndexPageModel())
// .orElseThrow(() -> new NotFoundException(String
// .format("The PageModel for the index page of the category"
// + "\"%s\" is not available as live version.",
// pagePath)));
// }
//
// parameters.put(PARAMETER_LANGUAGE, language);
//
// return buildPage(pageModel, parameters);
throw new UnsupportedOperationException();
}
private Map<String, Object> getCategoryItemPage(
final UriInfo uriInfo,
final String pagePath,
final String itemName,
final String language,
final PageModelVersion pageModelVersion) {
final Map<String, Object> parameters = new HashMap<>();
final Page page = PagesRouter.this.getPage(uriInfo, pagePath, language,
parameters);
// final PageModel pageModel;
// if (pageModelVersion == PageModelVersion.DRAFT) {
// pageModel = pageModelManager.getDraftVersion(page
// .getItemPageModel());
// } else {
// pageModel = pageModelManager
// .getLiveVersion(page.getItemPageModel())
// .orElseThrow(() -> new NotFoundException(String
// .format("The PageModel for the index page of the category"
// + "\"%s\" is not available as live version.",
// pagePath)));
// }
//
// parameters.put(PARAMETER_ITEMNAME, itemName);
// parameters.put(PARAMETER_LANGUAGE, language);
//
// return buildPage(pageModel, parameters);
throw new UnsupportedOperationException();
}
private List<Map<String, Object>> buildPageCategoriesPath(
final Category category, Locale language
) {
final List<Category> categoriesInPath = categoryManager
.getCategoriesInPath(category);
return categoriesInPath
.stream()
.map(cat -> buildPathCategoriesPathEntry(category, language))
.collect(Collectors.toList());
}
private Map<String, Object> buildPathCategoriesPathEntry(
final Category category, Locale language
) {
final Map<String, Object> result = new HashMap<>();
result.put(PAGE_PATH_CATEGORY_ID, Long.toString(category.getObjectId()));
result.put(PAGE_PATH_CATEGORY_UUID, category.getUuid());
result.put(PAGE_PATH_CATEGORY_NAME, category.getName());
result.put(
PAGE_PATH_CATEGORY_TITLE, category.getTitle().getValue(language)
);
return result;
}
/**
* Parse the value of the {@code preview} query parameter.
*
* @param value The value of the {@code preview} query parameter to parse.
*
* @return If the provided value is {@code all} a {@link Versions} object
* with all versions set to the draft versions is created and
* returned. If the provided value is {@code null} or empty a
* {@link Versions} object with fields set the the live versions is
* returned. Otherwise the values is split into tokens (separated by
* commas). The values of the returned {@link Versions} depend on
* presence of certain tokens. At the moment to following tokens are
* recognised:
* <dl>
* <dt>{@code content}</dt>
* <dd>{@link Versions#contentVersion} is set to
* {@link ContentItemVersion#DRAFT}</dd>
* <dt>{@code pagemodel}</dt>
* <dd>{@link Versions#pageModelVersion} is set to
* {@link PageModelVersion#DRAFT}</dd>
* <dt>{@code theme}</dt>
* <dd>{@link Versions#themeVersion} is set to
* {@link ThemeVersion#DRAFT}.</dd>
* </dl>
*
*/
private Versions generateFromPreviewParam(final String value) {
if (value == null || value.isEmpty() || value.matches("\\s*")) {
return new Versions(ContentItemVersion.LIVE,
PageModelVersion.LIVE,
ThemeVersion.LIVE);
} else if ("all".equals(value.toLowerCase(Locale.ROOT))) {
return new Versions(ContentItemVersion.DRAFT,
PageModelVersion.DRAFT,
ThemeVersion.DRAFT);
} else {
final Set<String> values = new HashSet<>();
Collections.addAll(values,
value.toLowerCase(Locale.ROOT).split(","));
final Versions result = new Versions();
if (values.contains("content")) {
result.setContentVersion(ContentItemVersion.DRAFT);
}
if (values.contains("pagemodel")) {
result.setPageModelVersion(PageModelVersion.DRAFT);
}
if (values.contains("theme")) {
result.setThemeVersion(ThemeVersion.DRAFT);
}
return result;
}
}
/**
* Encapsulate the result of converting the value of the {@code preview}
* query parameter.
*/
private class Versions {
/**
* Version of content to use
*/
private ContentItemVersion contentVersion;
/**
* Version of {@link PageModel} to use.
*/
private PageModelVersion pageModelVersion;
/**
* Version of theme to use.
*/
private ThemeVersion themeVersion;
/**
* Creates a new {@code Versions} object with all fields set to
* {@code live} versions.
*/
public Versions() {
this.contentVersion = ContentItemVersion.LIVE;
this.pageModelVersion = PageModelVersion.LIVE;
this.themeVersion = ThemeVersion.LIVE;
}
/**
* Create a new {@code Versions} object with the provided parameters.
*
* @param contentVersion
* @param pageModelVersion
* @param themeVersion
*/
public Versions(final ContentItemVersion contentVersion,
final PageModelVersion pageModelVersion,
final ThemeVersion themeVersion) {
this.contentVersion = contentVersion;
this.pageModelVersion = pageModelVersion;
this.themeVersion = themeVersion;
}
public ContentItemVersion getContentVersion() {
return contentVersion;
}
public void setContentVersion(final ContentItemVersion contentVersion) {
this.contentVersion = contentVersion;
}
public PageModelVersion getPageModelVersion() {
return pageModelVersion;
}
public void setPageModelVersion(final PageModelVersion pageModelVersion) {
this.pageModelVersion = pageModelVersion;
}
public ThemeVersion getThemeVersion() {
return themeVersion;
}
public void setThemeVersion(final ThemeVersion themeVersion) {
this.themeVersion = themeVersion;
}
}
}

View File

@ -28,7 +28,6 @@ import org.librecms.contentsection.ContentItem;
import org.librecms.contentsection.ContentItemVersion;
import org.librecms.contentsection.ItemAttachment;
import org.librecms.pages.PagesController;
import org.librecms.pages.PagesRouter;
import org.librecms.pages.PagesService;
import java.time.ZoneId;
@ -50,9 +49,8 @@ import javax.ws.rs.core.Response;
/**
* Retrieves a categorized content item for the current category. To work, the
* {@link #itemName} property MUST be initalized by the using application (for
* example {@link PagesRouter}. The value for {@link #itemName} is usually
* determined from the requested URL.
* {@link #itemName} property MUST be initalized by the using application. The
* value for {@link #itemName} is usually determined from the requested URL.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/

View File

@ -0,0 +1,8 @@
drop table CCM_CMS.CATEGORY_TREE_COMPONENTS;
drop table CCM_CMS.FIXED_CONTENT_ITEM_COMPONENTS;
drop table CCM_CMS.GREETING_ITEM_COMPONENTS;
drop table CCM_CMS.CATEGORIZED_ITEM_COMPONENTS;
drop table CCM_CMS.CONTENT_ITEM_COMPONENTS;
drop table CCM_CMS.ITEM_LIST_ORDER;
drop table CCM_CMS.ITEM_LIST_COMPONENTS;

View File

@ -0,0 +1,8 @@
drop table CCM_CMS.CATEGORY_TREE_COMPONENTS;
drop table CCM_CMS.FIXED_CONTENT_ITEM_COMPONENTS;
drop table CCM_CMS.GREETING_ITEM_COMPONENTS;
drop table CCM_CMS.CATEGORIZED_ITEM_COMPONENTS;
drop table CCM_CMS.CONTENT_ITEM_COMPONENTS;
drop table CCM_CMS.ITEM_LIST_ORDER;
drop table CCM_CMS.ITEM_LIST_COMPONENTS;

View File

@ -20,9 +20,6 @@ package org.libreccm.modules;
import org.libreccm.configuration.Configuration;
import org.libreccm.configuration.ConfigurationManager;
import org.libreccm.pagemodel.ComponentModel;
import org.libreccm.pagemodel.PageModel;
import org.libreccm.pagemodel.PageModelComponentModel;
import org.libreccm.web.ApplicationType;
import java.lang.annotation.Retention;
@ -92,14 +89,4 @@ public @interface Module {
*/
Class<?>[] configurations() default {};
/**
* Components for use in {@link PageModel}s provided by the annotated
* module.
*
* @return An array containing all {@link ComponentModel}s provided by the
* annotated module.
*/
@Deprecated
PageModelComponentModel[] pageModelComponentModels() default {};
}

View File

@ -1,111 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import java.util.Objects;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
/**
* Converter for the basic properties of a {
*
* @ComponentModel}. Can be used as base for implementations.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
public abstract class AbstractComponentModelJsonConverter
implements ComponentModelJsonConverter {
/**
* Converts the basic properties of a {@link ComponentModel} to JSON.
*
* @param componentModel The {@link ComponentModel}.
* @param objectBuilder The {@link JsonObjectBuilder} to use.
*/
protected void convertBasePropertiesToJson(
final ComponentModel componentModel,
final JsonObjectBuilder objectBuilder) {
Objects.requireNonNull(componentModel);
Objects.requireNonNull(objectBuilder);
objectBuilder
.add("componentModelId",
Long.toString(componentModel.getComponentModelId()))
.add("uuid", componentModel.getUuid())
.add("modelUuid", componentModel.getModelUuid())
.add("key", componentModel.getKey())
.add("type", componentModel.getClass().getName());
if (componentModel.getIdAttribute() != null) {
objectBuilder.add("idAttribute",
componentModel.getIdAttribute());
}
if (componentModel.getClassAttribute() != null) {
objectBuilder.add("classAttribute",
componentModel.getClassAttribute());
}
if (componentModel.getStyleAttribute() != null) {
objectBuilder.add("styleAttribute",
componentModel.getStyleAttribute());
}
}
/**
* Read the basic properties of a {@link ComponentModel} from a
* {@link JsonObject}.
*
* @param jsonObject The {@link JsonObject}.
* @param componentModel The {@link ComponentModel}.
*/
protected void readBasePropertiesFromJson(
final JsonObject jsonObject, final ComponentModel componentModel) {
Objects.requireNonNull(jsonObject);
Objects.requireNonNull(componentModel);
//UUIDs are solely managed by the server!
// if (jsonObject.containsKey("uuid")) {
// componentModel.setUuid(jsonObject.getString("uuid"));
// }
// if (jsonObject.containsKey("modelUuid")) {
// componentModel.setModelUuid(jsonObject.getString("modelUuid"));
// }
componentModel.setKey(jsonObject.getString("key"));
if (jsonObject.getString("idAttribute", null) != null) {
componentModel.setIdAttribute(jsonObject.getString("idAttribute"));
}
if (jsonObject.getString("classAttribute", null) != null) {
componentModel
.setClassAttribute(jsonObject.getString("classAttribute"));
}
if (jsonObject.getString("styleAttribute", null) != null) {
componentModel
.setStyleAttribute(jsonObject.getString("styleAttribute"));
}
}
}

View File

@ -1,186 +0,0 @@
/*
* Copyright (C) 2016 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import com.arsdigita.ui.UI;
import com.arsdigita.web.URL;
import org.apache.shiro.subject.Subject;
import org.libreccm.security.Shiro;
import org.libreccm.security.User;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
/**
* An abstract base class for implementations of the {@link PageRenderer}
* interface providing some functionality needed by all implementations of the
* {@link PageRenderer} interface.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*
*/
@Deprecated
public abstract class AbstractPageRenderer implements PageRenderer {
@Inject
private ComponentRendererManager componentRendererManager;
@Inject
private HttpServletRequest request;
@Inject
private Shiro shiro;
/**
* Renders a {@code Page} based on a {@link PageModel}. This implementation
* first calls {@link #renderPage()} to create the page object. After that
* all {@link ComponentModel}s of the {@link PageModel} are processed and
* the component objects created by the {@link ComponentRenderer}s are added
* to the page.
*
* @param pageModel The {@link PageModel} to render.
* @param parameters Parameters provided by application which wants to
* render a {@link PageModel}. The parameters are passed
* the {@link ComponentRenderer}s.
*
* @return A map containing the results from rendering the components of the
* page model.
*/
@Override
public Map<String, Object> renderPage(final PageModel pageModel,
final Map<String, Object> parameters) {
final Map<String, Object> page = renderPage(parameters);
final Map<String, Object> currentUserData = new HashMap<>();
if (shiro.getUser().isPresent()) {
final User currentUser = shiro.getUser().get();
final Subject currentSubject = shiro.getSubject();
currentUserData.put(
"authenticated", currentSubject.isAuthenticated()
);
currentUserData.put("username", currentUser.getName());
currentUserData.put(
"email", currentUser.getPrimaryEmailAddress().toString()
);
currentUserData.put("familyName", currentUser.getFamilyName());
currentUserData.put("givenName", currentUser.getGivenName());
currentUserData.put(
"workspaceUrl",
URL.there(request, UI.getWorkspaceURL()).toString()
);
currentUserData.put(
"loginUrl",
URL.there(request, "/login").toString()
);
currentUserData.put(
"logoutUrl",
URL.there(
request,
"register/logout"
)
);
currentUserData.put(
"changePasswordUrl",
URL.there(
request,
"register/change-password"
)
);
} else {
currentUserData.put("authenticated", false);
}
page.put("currentUser", currentUserData);
for (final ContainerModel containerModel : pageModel.getContainers()) {
final Map<String, Object> container = renderContainer(
containerModel, parameters);
page.put(containerModel.getKey(), container);
}
return page;
}
protected Map<String, Object> renderContainer(
final ContainerModel containerModel,
final Map<String, Object> parameters) {
final Map<String, Object> container = new HashMap<>();
container.put("key", containerModel.getKey());
if (containerModel.getStyles() != null) {
container.put("styles", containerModel.getStyles().toCss());
}
for (final ComponentModel componentModel : containerModel
.getComponents()) {
renderComponent(componentModel,
componentModel.getClass(),
parameters)
.ifPresent(component -> container.put(componentModel.getKey(),
component));
}
return container;
}
/**
* Helper method for rendering the components.
*
* @param <M> Generics variable for the type of rendered
* component
* @param componentModel The {@link ComponentModel} to process.
* @param componentModelClass The class of the {@link ComponentModel}.
* @param parameters Parameters provided by application which wants
* to render a {@link PageModel}. The parameters
* are passed the {@link ComponentRenderer}s.
*
* @return A map containing the results from rendering the components of the
* page model.
*/
protected <M extends ComponentModel> Optional<Object> renderComponent(
final ComponentModel componentModel,
final Class<M> componentModelClass,
final Map<String, Object> parameters) {
final Optional<ComponentRenderer<M>> renderer = componentRendererManager
.findComponentRenderer(componentModelClass);
if (renderer.isPresent()) {
@SuppressWarnings("unchecked")
final M model = (M) componentModel;
return Optional
.of(renderer.get().renderComponent(model, parameters));
} else {
return Optional.empty();
}
}
}

View File

@ -1,265 +0,0 @@
/*
* Copyright (C) 2016 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import org.libreccm.core.CoreConstants;
import org.libreccm.modules.Module;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* Base class for the component models for use in a {@link PageModel}. This
* class is not designed for direct use. Instead the classes for concrete
* components have to be used. A component model must be registered by adding it
* to list of component models provided by a module by adding it the the list
* provided by {@link Module#pageModelComponentModels() } using the
* {@link PageModelComponentModel} annotation.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "PAGE_MODEL_COMPONENT_MODELS", schema = CoreConstants.DB_SCHEMA)
@NamedQueries({
@NamedQuery(name = "ComponentModel.findComponentByContainerAndKey",
query = "SELECT c "
+ "FROM ComponentModel c "
+ "WHERE c.container = :container "
+ "AND c.key = :key")
})
public class ComponentModel implements Serializable {
private static final long serialVersionUID = 8585775139379396806L;
/**
* ID in the database for this instance.
*/
@Id
@Column(name = "COMPONENT_MODEL_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private long componentModelId;
/**
* The UUID of the instance.
*/
@Column(name = "UUID", length = 255, nullable = false)
@NotNull
private String uuid;
/**
* The UUID of the {@code ComponentModel} which is the same for the draft
* and live version.
*/
@Column(name = "MODEL_UUID", length = 255, nullable = false)
@NotNull
private String modelUuid;
@ManyToOne
@JoinColumn(name = "CONTAINER_ID")
private ContainerModel container;
/**
* ID of the component. Must be unique inside a {@link PageModel}.
*/
@Column(name = "ID_ATTRIBUTE", length = 255)
private String idAttribute;
/**
* CSS Style classes to add to the HTML element representing the component
* in the HTML generated from the rendered component model.
*/
@Column(name = "CLASS_ATTRIBUTE", length = 512)
private String classAttribute;
/**
* CSS styles to add to the HTML element representing the component in the
* HTML generated from the rendered component model. Avoid using this as it
* will add inline styles to the HTML.
*/
@Column(name = "STYLE_ATTRIBUTE", length = 1024)
private String styleAttribute;
/**
* Key for identifying the component in a {@link PageModel}. The will be
* used as key in the map generated by
* {@link PageRenderer#renderPage(java.util.Map)} and
* {@link PageRenderer#renderPage(org.libreccm.pagemodel.PageModel, java.util.Map)}.
*/
@Column(name = "COMPONENT_KEY", length = 255)
private String key;
public long getComponentModelId() {
return componentModelId;
}
protected void setComponentModelId(final long componentModelId) {
this.componentModelId = componentModelId;
}
public String getUuid() {
return uuid;
}
public void setUuid(final String uuid) {
this.uuid = uuid;
}
public String getModelUuid() {
return modelUuid;
}
protected void setModelUuid(final String modelUuid) {
this.modelUuid = modelUuid;
}
public ContainerModel getContainer() {
return container;
}
protected void setContainer(final ContainerModel container) {
this.container = container;
}
public String getIdAttribute() {
return idAttribute;
}
public void setIdAttribute(final String idAttribute) {
this.idAttribute = idAttribute;
}
public String getClassAttribute() {
return classAttribute;
}
public void setClassAttribute(final String classAttribute) {
this.classAttribute = classAttribute;
}
public String getStyleAttribute() {
return styleAttribute;
}
public void setStyleAttribute(final String styleAttribute) {
this.styleAttribute = styleAttribute;
}
public String getKey() {
return key;
}
public void setKey(final String key) {
this.key = key;
}
@Override
public int hashCode() {
int hash = 7;
hash
= 53 * hash + (int) (componentModelId ^ (componentModelId >>> 32));
hash = 53 * hash + Objects.hashCode(uuid);
hash = 53 * hash + Objects.hashCode(container);
hash = 53 * hash + Objects.hashCode(idAttribute);
hash = 53 * hash + Objects.hashCode(classAttribute);
hash = 53 * hash + Objects.hashCode(styleAttribute);
hash = 53 * hash + Objects.hashCode(key);
return hash;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof ComponentModel)) {
return false;
}
final ComponentModel other = (ComponentModel) obj;
if (!other.canEqual(this)) {
return false;
}
if (componentModelId != other.getComponentModelId()) {
return false;
}
if (!Objects.equals(idAttribute, other.getIdAttribute())) {
return false;
}
if (!Objects.equals(classAttribute, other.getClassAttribute())) {
return false;
}
if (!Objects.equals(styleAttribute, other.getStyleAttribute())) {
return false;
}
if (!Objects.equals(container, other.getContainer())) {
return false;
}
return Objects.equals(key, other.getKey());
}
public boolean canEqual(final Object obj) {
return obj instanceof ComponentModel;
}
@Override
public final String toString() {
return toString("");
}
public String toString(final String data) {
return String.format("%s{ "
+ "componentModelId = %d, "
+ "container = %s, "
+ "idAttribute = \"%s\", "
+ "classAttribute = \"%s\", "
+ "styleAttribute = \"%s\", "
+ "key = \"%s\""
+ " }",
super.hashCode(),
componentModelId,
container,
idAttribute,
classAttribute,
styleAttribute,
key);
}
}

View File

@ -1,50 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import javax.json.JsonObject;
/**
* Interface which the JSON converters for {@link ComponentModel}s.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
public interface ComponentModelJsonConverter {
/**
* Convert a {@link ComponentModel} to JSON.
*
* @param componentModel The {@link ComponentModel} to convert.
*
* @return The JSON representation of the provided {@link ComponentModel}.
*/
JsonObject toJson(ComponentModel componentModel);
/**
* Read the values of a {@link ComponentModel} from a JSON object and set
* them on the provided component model.
*
* @param jsonObject The JSON object with the values.
* @param componentModel The {@link ComponentModel} on which the values are
* set.
*/
void fromJson(JsonObject jsonObject, ComponentModel componentModel);
}

View File

@ -1,184 +0,0 @@
/*
* Copyright (C) 2016 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import org.libreccm.core.AbstractEntityRepository;
import org.libreccm.core.CoreConstants;
import org.libreccm.security.AuthorizationRequired;
import org.libreccm.security.RequiresPrivilege;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import javax.enterprise.context.RequestScoped;
import javax.transaction.Transactional;
import java.util.UUID;
import javax.persistence.EntityGraph;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
/**
* Repository class for managing {@link ComponentModel} entities.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
public class ComponentModelRepository
extends AbstractEntityRepository<Long, ComponentModel> {
private static final long serialVersionUID = -6358512316472857971L;
@Override
public Class<ComponentModel> getEntityClass() {
return ComponentModel.class;
}
@Override
public String getIdAttributeName() {
return "componentModelId";
}
@Override
public Long getIdOfEntity(final ComponentModel entity) {
return entity.getComponentModelId();
}
@Override
public boolean isNew(final ComponentModel componentModel) {
return componentModel.getComponentModelId() == 0;
}
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
@Transactional(Transactional.TxType.REQUIRED)
@Override
public void save(final ComponentModel componentModel) {
super.save(componentModel);
}
/**
* Initialises a new entity.
*
* @param componentModel The new {@link ComponentModel} entity to
* initialise.
*/
@Override
public void initNewEntity(final ComponentModel componentModel) {
final String uuid = UUID.randomUUID().toString();
componentModel.setUuid(uuid);
if (componentModel.getModelUuid() == null
|| componentModel.getModelUuid().isEmpty()) {
componentModel.setModelUuid(uuid);
}
}
@Transactional(Transactional.TxType.REQUIRED)
public <M extends ComponentModel> Optional<M> findById(
final long modelId, final Class<M> modelClass) {
return Optional.ofNullable(getEntityManager().find(modelClass,
modelId));
}
@Transactional(Transactional.TxType.REQUIRED)
public <M extends ComponentModel> Optional<M> findById(
final long modelId,
final Class<M> modelClass,
final String entityGraphName) {
return Optional.ofNullable(getEntityManager().find(modelClass,
modelId));
}
@Transactional(Transactional.TxType.REQUIRED)
public <M extends ComponentModel> Optional<M> findById(
final long entityId,
final Class<M> modelClass,
final EntityGraph<M> entityGraph) {
Objects.requireNonNull(entityId);
Objects.requireNonNull(entityGraph);
final Map<String, Object> hints = new HashMap<>();
hints.put(FETCH_GRAPH_HINT_KEY, entityGraph);
return Optional.ofNullable(getEntityManager().find(modelClass,
entityId,
hints));
}
@Transactional(Transactional.TxType.REQUIRED)
public <M extends ComponentModel> Optional<M> findById(
final long entityId,
final Class<M> modelClass,
final String... fetchJoins) {
Objects.requireNonNull(entityId);
final CriteriaBuilder builder = getEntityManager()
.getCriteriaBuilder();
final CriteriaQuery<M> criteriaQuery = builder
.createQuery(modelClass);
final Root<M> from = criteriaQuery.from(modelClass);
criteriaQuery.from(getEntityClass());
criteriaQuery.select(from);
for (final String fetchJoin : fetchJoins) {
from.fetch(fetchJoin);
}
criteriaQuery
.where(builder.equal(from.get(getIdAttributeName()), entityId));
final TypedQuery<M> query = getEntityManager()
.createQuery(criteriaQuery);
try {
return Optional.of(query.getSingleResult());
} catch (NoResultException ex) {
return Optional.empty();
}
}
@Transactional(Transactional.TxType.REQUIRED)
public Optional<ComponentModel> findComponentByContainerAndKey(
final ContainerModel containerModel,
final String componentKey) {
final TypedQuery<ComponentModel> query = getEntityManager()
.createNamedQuery("ComponentModel.findComponentByContainerAndKey",
ComponentModel.class);
query.setParameter("container", containerModel);
query.setParameter("key", componentKey);
try {
return Optional.of(query.getSingleResult());
} catch(NoResultException ex) {
return Optional.empty();
}
}
}

View File

@ -1,132 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import org.libreccm.modules.CcmModule;
import org.libreccm.modules.Module;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.ServiceLoader;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
/**
* An Utility class which provides access to all component models available.
*
* This class is an {@link ApplicationScoped} CDI bean. The {@link #init} method
* is called by the CDI container after creating an instance of this class. The
* {@link #init} method retrieves the informations about the available
* {@link ComponentModel}s from the module classes. For exactly from the
* {@link Module#pageModelComponentModels()} property of the {@link Module}
* annotation of the module class.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@ApplicationScoped
public class ComponentModels {
private final List<PageModelComponentModel> availableComponentModels
= new ArrayList<>();
private final Map<String, PageModelComponentModel> componentInfos
= new HashMap<>();
/**
* Creates the list of available {@link ComponentModels}. Called by the CDI
* container.
*/
@PostConstruct
private void init() {
final ServiceLoader<CcmModule> modules = ServiceLoader
.load(CcmModule.class);
for (final CcmModule module : modules) {
final Module moduleData = module
.getClass()
.getAnnotation(Module.class);
final PageModelComponentModel[] componentModels = moduleData
.pageModelComponentModels();
for (final PageModelComponentModel componentModel : componentModels) {
availableComponentModels.add(componentModel);
componentInfos.put(componentModel.modelClass().getName(),
componentModel);
}
}
}
/**
* Get a list of the available {@link ComponentModel}s.
*
* @return A (unmodifiable) list of all available {@link ComponentModel}s.
*/
public List<PageModelComponentModel> findAvailableComponentModels() {
return Collections.unmodifiableList(availableComponentModels);
}
/**
* Get the informations about a specific {@link ComponentModel}
* implementation.
*
* @param clazz The class of the {@link ComponentModel} implementation.
*
* @return An {@link Optional} containing the informations about the
* {@link ComponentModel} implementation. If the class is not a
* {@link ComponentModel} implementation or is an unknown
* implementation an empty {@link Optional} is returned.
*/
public Optional<PageModelComponentModel> getComponentModelInfo(
final Class<? extends ComponentModel> clazz) {
return getComponentModelInfo(clazz.getName());
}
/**
* Get the informations about a specific {@link ComponentModel}
* implementation.
*
* @param className The name of the class of the {@link ComponentModel}
* implementation.
*
* @return An {@link Optional} containing the informations about the
* {@link ComponentModel} implementation. If the class is not a
* {@link ComponentModel} implementation or is an unknown
* implementation an empty {@link Optional} is returned.
*/
public Optional<PageModelComponentModel> getComponentModelInfo(
final String className) {
if (componentInfos.containsKey(className)) {
return Optional.of(componentInfos.get(className));
} else {
return Optional.empty();
}
}
}

View File

@ -1,69 +0,0 @@
/*
* Copyright (C) 2016 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import java.util.Collection;
import java.util.Map;
/**
* A {@code ComponentRenderer} transforms a {@link ComponentModel} into a
* component.
*
* An implementation must be annotation with the {@link RendersComponent}
* qualifier annotation.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
* @param <M> Type of the model the component renderer processes.
*/
@Deprecated
public interface ComponentRenderer<M extends ComponentModel> {
/**
* Renders a {@link ComponentModel}.
*
* The result of the rendering process is a {@link Map} which uses strings
* as key. The values are either Java primitive types or Collections. More
* exactly the values are objects of one the following types:
*
* <ul>
* <li>{@link Double}</li>
* <li>{@link Float}</li>
* <li>{@link Integer}</li>
* <li>{@link Long}</li>
* <li>{@link Short}</li>
* <li>{@link String}</li>
* <li>{@link List}</li>
* <li>{@link Map}</li>
* </ul>
*
* Other subtypes {@link Collection} are might be supported but there is no
* guarantee for that. The values in a collection must be one of the types
* in the list above. Collections might contain multiple types from the list
* above. The keys for a map should always be strings.
*
* @param componentModel The component model to render.
* @param parameters Parameters provided by the calling
* {@link PageRenderer}.
*
* @return A map representing the rendered component.
*/
Map<String, Object> renderComponent(M componentModel,
Map<String, Object> parameters);
}

View File

@ -1,123 +0,0 @@
/*
* Copyright (C) 2016 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Instance;
import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Inject;
import java.util.Iterator;
import java.util.Optional;
import javax.enterprise.inject.Any;
/**
* Provides access to all available implementations of the
* {@link ComponentRenderer} interface.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
public class ComponentRendererManager {
private static final Logger LOGGER = LogManager.getLogger(
ComponentRendererManager.class);
@Inject
@Any
private Instance<ComponentRenderer<?>> componentRenderers;
/**
* Find an implementation of the {@link ComponentRenderer} interface for a
* specific {@link ComponentModel}.
*
* @param <M> Generic variable for the subtype of
* {@link ComponentModel} which is produced by
* the {@link ComponentRenderer} implementation.
* @param componentModelClass The sub class of the {@link ComponentModel}
* for which is processed by the
* {@link ComponentRenderer}.
*
* @return An {@link Optional} containing the implementation of the
* {@link ComponentRenderer} interface for the specified parameters.
* If there is no implementation for the specified parameters an
* empty {@link Optional} is returned.
*/
@SuppressWarnings("unchecked")
public <M extends ComponentModel> Optional<ComponentRenderer<M>> findComponentRenderer(
final Class<M> componentModelClass) {
LOGGER.debug("Trying to find ComponentRenderer for ComponentModel\"{}\""
+ "and type \"{}\"...",
componentModelClass.getName());
final RenderComponentLiteral literal = new RenderComponentLiteral(
componentModelClass);
final Instance<ComponentRenderer<?>> instance = componentRenderers
.select(literal);
if (instance.isUnsatisfied()) {
LOGGER.warn("No ComponentRenderer for component model \"{}\". "
+ "Ignoring component model.",
componentModelClass.getName());
return Optional.empty();
} else if (instance.isAmbiguous()) {
throw new IllegalStateException(String.format(
"Multiple ComponentRenderers for component model \"%s\"available. "
+ "Something is wrong",
componentModelClass.getName()));
} else {
final Iterator<ComponentRenderer<?>> iterator = instance.
iterator();
final ComponentRenderer<?> componentRenderer = iterator.next();
return Optional.of((ComponentRenderer<M>) componentRenderer);
}
}
/**
* Annotation literal for the {@link RendersComponent} annotation.
*/
private static class RenderComponentLiteral
extends AnnotationLiteral<RendersComponent>
implements RendersComponent {
private static final long serialVersionUID = -2601632434295178600L;
private final Class<? extends ComponentModel> componentModel;
public RenderComponentLiteral(
final Class<? extends ComponentModel> componentModel) {
this.componentModel = componentModel;
}
@Override
public Class<? extends ComponentModel> componentModel() {
return componentModel;
}
}
}

View File

@ -1,273 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.libreccm.core.CoreConstants;
import org.libreccm.pagemodel.styles.Styles;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
* A {@code ContainerModel} for grouping {@link ComponentModel}s. Each
* {@link PageModel} contains a least one container. A container also contains
* styles which allow it to provide the theme engine with CSS for aligning the
* components in the container. Please note that theme developers can ignore the
* information.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Entity
@Table(name = "PAGE_MODEL_CONTAINER_MODELS", schema = CoreConstants.DB_SCHEMA)
@NamedQueries({
@NamedQuery(name = "ContainerModel.findByKeyAndPage",
query = "SELECT c FROM ContainerModel c "
+ "WHERE c.key = :key "
+ "AND c.pageModel = :pageModel")
})
@XmlRootElement(name = "container-model")
public class ContainerModel implements Serializable {
private static final long serialVersionUID = -7472858443655353588L;
/**
* ID of the ContainerModel in the database.
*/
@Id
@Column(name = "CONTAINER_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
@XmlElement(name = "container-model-id")
private long containerId;
/**
* The UUID of this version of the container.
*/
@Column(name = "UUID", length = 255, nullable = false)
@NotNull
private String uuid;
/**
* The UUID of the container which is the same in all versions.
*/
@Column(name = "CONTAINER_UUID", length = 255, nullable = false)
@NotNull
private String containerUuid;
/**
* A key for identifying the container inside a {@link PageModel}. May be
* used for the value of the {@code id} or {@code class} attribute in HTML.
* It is recommended the use semantic names.
*/
@Column(name = "CONTAINER_KEY", length = 255)
private String key;
/**
* Styles for this container. This should be limited to CSS which describes
* the layout of the components in the container. Colours etc. are the
* responsibility of the theme. A theme might also alter the styles stored
* here.
*/
@OneToOne
@JoinColumn(name = "STYLE_ID")
@Cascade(CascadeType.ALL)
private Styles styles;
@ManyToOne
@JoinColumn(name = "PAGE_MODEL_ID")
@XmlTransient
private PageModel pageModel;
/**
* The components in this this container.
*/
@OneToMany(mappedBy = "container")
@OrderBy("key ASC")
private List<ComponentModel> components;
public ContainerModel() {
this.styles = new Styles();
this.components = new ArrayList<>();
}
public long getContainerId() {
return containerId;
}
protected void setContainerId(final long containerId) {
this.containerId = containerId;
}
public String getUuid() {
return uuid;
}
public void setUuid(final String uuid) {
this.uuid = uuid;
}
public String getContainerUuid() {
return containerUuid;
}
protected void setContainerUuid(final String containerUuid) {
this.containerUuid = containerUuid;
}
public String getKey() {
return key;
}
public void setKey(final String key) {
this.key = key;
}
public Styles getStyles() {
return styles;
}
protected void setStyles(final Styles styles) {
this.styles = styles;
}
public PageModel getPageModel() {
return pageModel;
}
protected void setPageModel(final PageModel pageModel) {
this.pageModel = pageModel;
}
public List<ComponentModel> getComponents() {
return Collections.unmodifiableList(components);
}
protected void setComponents(final List<ComponentModel> components) {
this.components = new ArrayList<>(components);
}
protected void addComponent(final ComponentModel component) {
components.add(component);
}
protected void removeComponent(final ComponentModel component) {
components.remove(component);
}
protected void clearComponents() {
components.clear();
}
@Override
public int hashCode() {
int hash = 5;
hash = 97 * hash + (int) (containerId ^ (containerId >>> 32));
hash = 97 * hash + Objects.hashCode(uuid);
hash = 97 * hash + Objects.hashCode(containerUuid);
hash = 97 * hash + Objects.hashCode(key);
hash = 97 * hash + Objects.hashCode(styles);
return hash;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof ContainerModel)) {
return false;
}
final ContainerModel other = (ContainerModel) obj;
if (!other.canEqual(this)) {
return false;
}
if (containerId != other.getContainerId()) {
return false;
}
if (!Objects.equals(uuid, other.getUuid())) {
return false;
}
if (!Objects.equals(containerUuid, other.getContainerUuid())) {
return false;
}
if (!Objects.equals(styles, other.getStyles())) {
return false;
}
return Objects.equals(key, other.getKey());
}
public boolean canEqual(final Object obj) {
return obj instanceof ContainerModel;
}
public String toString(final String data) {
return String.format("%s{ "
+ "containerId = %d, "
+ "uuid = %s, "
+ "containerUuid = %s, "
+ "key = \"%s\", "
+ "styles = %s%s"
+ " }",
super.toString(),
containerId,
uuid,
containerUuid,
key,
Objects.toString(styles),
data);
}
@Override
public final String toString() {
return toString("");
}
}

View File

@ -1,145 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.libreccm.modules.CcmModule;
import org.libreccm.modules.Module;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
public class ContainerModelManager implements Serializable {
private static final long serialVersionUID = -2793646505397414050L;
private static final Logger LOGGER = LogManager
.getLogger(ContainerModelManager.class);
@Inject
private ContainerModelRepository containerRepo;
@Inject
private ComponentModelRepository componentModelRepo;
private final Map<String, PageModelComponentModel> components
= new HashMap<>();
/**
* Called by CDI after an instance of this class is created. Initialises the
* {@link #components} by retrieving the data about all available
* {@link ComponentModel}s.
*/
@PostConstruct
private void init() {
LOGGER.debug("Initalising {}...",
ContainerModelManager.class.getName());
final ServiceLoader<CcmModule> modules = ServiceLoader.load(
CcmModule.class);
for (CcmModule module : modules) {
final Module moduleData = module.getClass().getAnnotation(
Module.class);
final PageModelComponentModel[] models = moduleData
.pageModelComponentModels();
for (PageModelComponentModel model : models) {
components.put(model.modelClass().getName(),
model);
}
}
LOGGER.debug("Initalised {}. Found {} ComponentModels.",
ContainerModelManager.class.getName(),
components.size());
}
/**
* Adds a {@link ComponentModel} to a {@link ContainerModel}.
*
* @param container The {@link ContainerModel} to which component model
* is added.
* @param componentModel The {@link ComponentModel} to add.
*/
@Transactional(Transactional.TxType.REQUIRED)
public void addComponentModel(final ContainerModel container,
final ComponentModel componentModel) {
if (container == null) {
throw new IllegalArgumentException(
"Can't add a component model to page model null.");
}
if (componentModel == null) {
throw new IllegalArgumentException(
"Can't add component model null to a page model.");
}
container.addComponent(componentModel);
componentModel.setContainer(container);
containerRepo.save(container);
componentModelRepo.save(componentModel);
}
/**
* Removes a {@link ComponentModel} from a {@link ContainerModel}.
*
* @param container The {@link ContainerModel} from which the
* {@link ComponentModel} is removed.
* @param componentModel The {@link ComponentModel} to remove. The component
* model is also removed from the database.
*/
@Transactional(Transactional.TxType.REQUIRED)
public void removeComponentModel(final ContainerModel container,
final ComponentModel componentModel) {
if (container == null) {
throw new IllegalArgumentException(
"Can't remove a component model from page model null.");
}
if (componentModel == null) {
throw new IllegalArgumentException(
"Can't remove component model null from a page model.");
}
container.removeComponent(componentModel);
componentModel.setContainer(null);
containerRepo.save(container);
componentModelRepo.delete(componentModel);
}
}

View File

@ -1,104 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import org.libreccm.core.AbstractEntityRepository;
import org.libreccm.core.CoreConstants;
import org.libreccm.security.AuthorizationRequired;
import org.libreccm.security.RequiresPrivilege;
import java.util.Optional;
import java.util.UUID;
import javax.enterprise.context.RequestScoped;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
public class ContainerModelRepository
extends AbstractEntityRepository<Long, ContainerModel> {
private static final long serialVersionUID = 6613005988522263867L;
@Override
public Class<ContainerModel> getEntityClass() {
return ContainerModel.class;
}
@Override
public String getIdAttributeName() {
return "containerId";
}
@Override
public Long getIdOfEntity(final ContainerModel container) {
return container.getContainerId();
}
@Override
public boolean isNew(final ContainerModel container) {
return container.getContainerId() == 0;
}
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
@Transactional(Transactional.TxType.REQUIRED)
@Override
public void save(final ContainerModel container) {
super.save(container);
}
@Override
public void initNewEntity(final ContainerModel container) {
final String uuid = UUID.randomUUID().toString();
container.setUuid(uuid);
if (container.getContainerUuid() == null
|| container.getContainerUuid().isEmpty()) {
container.setContainerUuid(uuid);
}
}
@Transactional(Transactional.TxType.REQUIRED)
public Optional<ContainerModel> findContainerByKeyAndPageModel(
final String key, final PageModel pageModel) {
final TypedQuery<ContainerModel> query = getEntityManager()
.createNamedQuery("ContainerModel.findByKeyAndPage",
ContainerModel.class);
query.setParameter("key", key);
query.setParameter("pageModel", pageModel);
try {
return Optional.of(query.getSingleResult());
} catch (NoResultException ex) {
return Optional.empty();
}
}
}

View File

@ -1,43 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,
ElementType.METHOD,
ElementType.PARAMETER,
ElementType.TYPE})
public @interface ConvertsComponentModel {
Class<? extends ComponentModel> componentModel();
}

View File

@ -1,484 +0,0 @@
/*
* Copyright (C) 2016 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import org.libreccm.core.CoreConstants;
import org.libreccm.l10n.LocalizedString;
import org.libreccm.web.CcmApplication;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.persistence.AssociationOverride;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
* A {@link PageModel} is used by a {@link PageRenderer} implementation to
* render a page. The {@code PageModel} specifics which components are used on a
* page.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
* @see PageModelRepository
* @see PageModelManager
* @see PageRenderer
*/
@Deprecated
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "PAGE_MODELS", schema = CoreConstants.DB_SCHEMA)
@NamedQueries({
@NamedQuery(
name = "PageModel.findAllDraftModels",
query = "SELECT p FROM PageModel p "
+ "WHERE p.version = org.libreccm.pagemodel"
+ ".PageModelVersion.DRAFT")
,
@NamedQuery(
name = "PageModel.findAllLiveModels",
query = "SELECT p FROM PageModel p "
+ "WHERE p.version = org.libreccm.pagemodel"
+ ".PageModelVersion.LIVE")
,
@NamedQuery(
name = "PageModel.findDraftVersion",
query = "SELECT p FROM PageModel p "
+ "WHERE p.modelUuid = :uuid "
+ "AND p.version = org.libreccm.pagemodel"
+ ".PageModelVersion.DRAFT")
,
@NamedQuery(
name = "PageModel.hasLiveVersion",
query =
"SELECT (CASE WHEN COUNT(p) > 0 THEN true ELSE "
+ "False END) "
+ "FROM PageModel p "
+ "WHERE p.modelUuid = :uuid "
+ "AND p.version = org.libreccm.pagemodel"
+ ".PageModelVersion.LIVE"
)
,
@NamedQuery(
name = "PageModel.findLiveVersion",
query = "SELECT p FROM PageModel p "
+ "WHERE p.modelUuid = :uuid "
+ "AND p.version = org.libreccm.pagemodel"
+ ".PageModelVersion.LIVE")
,
@NamedQuery(
name = "PageModel.findDraftByApplication",
query = "SELECT p FROM PageModel p "
+ "WHERE p.application = :application "
+ "AND p.version = org.libreccm.pagemodel"
+ ".PageModelVersion.DRAFT"
)
,
@NamedQuery(
name = "PageModel.findDraftByApplicationAndName",
query = "SELECT p FROM PageModel p "
+ "WHERE p.application = :application "
+ "AND p.name = :name "
+ "AND p.version = org.libreccm.pagemodel"
+ ".PageModelVersion.DRAFT"
)
,
@NamedQuery(
name = "PageModel.countDraftByApplicationAndName",
query = "SELECT COUNT(p) FROM PageModel p "
+ "WHERE p.name = :name "
+ "AND p.application = :application "
+ "AND p.version = org.libreccm.pagemodel"
+ ".PageModelVersion.DRAFT"
)
,
@NamedQuery(
name = "PageModel.countDraftByApplication",
query = "SELECT COUNT(p) FROM PageModel p "
+ "WHERE p.application = :application "
+ "AND p.version = org.libreccm.pagemodel"
+ ".PageModelVersion.DRAFT"
)
,
@NamedQuery(
name = "PageModel.findLiveByApplication",
query = "SELECT p FROM PageModel p "
+ "WHERE p.application = :application "
+ "AND p.version = org.libreccm.pagemodel"
+ ".PageModelVersion.LIVE")
,
@NamedQuery(
name = "PageModel.countLiveByApplication",
query = "SELECT COUNT(p) FROM PageModel p "
+ "WHERE p.application = :application "
+ "AND p.version = org.libreccm.pagemodel"
+ ".PageModelVersion.LIVE")
,
@NamedQuery(
name = "PageModel.findLiveByApplicationAndName",
query = "SELECT p FROM PageModel p "
+ "WHERE p.name = :name "
+ "AND p.application = :application "
+ "AND p.version = org.libreccm.pagemodel"
+ ".PageModelVersion.LIVE"
)
,
@NamedQuery(
name = "PageModel.countLiveByApplicationAndName",
query = "SELECT COUNT(p) FROM PageModel p "
+ "WHERE p.name = :name "
+ "AND p.application = :application "
+ "AND p.version = org.libreccm.pagemodel"
+ ".PageModelVersion.LIVE"
)
})
@XmlRootElement(name = "pagemodel")
public class PageModel implements Serializable {
private static final long serialVersionUID = 7252512839926020978L;
/**
* The ID of the entity in the database.
*/
@Id
@Column(name = "PAGE_MODEL_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
@XmlElement(name = "pagemodel-id")
private long pageModelId;
/**
* The UUID of this {@code PageModel}. Please note that this UUID identifies
* the dataset not the model. Therefore the draft and the live version have
* different values for this field.
*/
@Column(name = "UUID", length = 255, nullable = false)
@NotNull
private String uuid;
/**
* The UUID of the model. Same for draft and live versions.
*/
@Column(name = "MODEL_UUID", length = 255, nullable = false)
@NotNull
private String modelUuid;
/**
* The name of this {@code PageModel}. Not localised, for use in URLs.
*/
@Column(name = "NAME", length = 255)
private String name;
/**
* The version of this {@code PageModel}.
*/
@Column(name = "VERSION", length = 255, nullable = false)
@Enumerated(EnumType.STRING)
private PageModelVersion version;
@Column(name = "LAST_MODIFIED")
@Temporal(TemporalType.TIMESTAMP)
private Date lastModified;
/**
* The localised title of this {@code PageModel} (shown in the
* administration UI),
*/
@Embedded
@AssociationOverride(
name = "values",
joinTable = @JoinTable(name = "PAGE_MODEL_TITLES",
schema = CoreConstants.DB_SCHEMA,
joinColumns = {
@JoinColumn(name = "PAGE_MODEL_ID")
}))
private LocalizedString title;
/**
* A description of this {@code PageModel} describing its purpose.
*/
@Embedded
@AssociationOverride(
name = "values",
joinTable = @JoinTable(name = "PAGE_MODEL_DESCRIPTIONS",
schema = CoreConstants.DB_SCHEMA,
joinColumns = {
@JoinColumn(name = "PAGE_MODEL_ID")
}))
private LocalizedString description;
/**
* The application with which this {@code PageModel} is associated.
*/
@ManyToOne
@JoinColumn(name = "APPLICATION_ID")
@XmlTransient
private CcmApplication application;
/**
* The type of this {@code PageModel}.
*/
@Column(name = "TYPE", length = 255, nullable = false)
@NotNull
private String type;
@OneToMany(mappedBy = "pageModel")
@OrderBy("key ASC")
private List<ContainerModel> containers;
public PageModel() {
title = new LocalizedString();
description = new LocalizedString();
containers = new ArrayList<>();
}
public long getPageModelId() {
return pageModelId;
}
protected void setPageModelId(final long pageModelId) {
this.pageModelId = pageModelId;
}
public String getUuid() {
return uuid;
}
public void setUuid(final String uuid) {
this.uuid = uuid;
}
public String getModelUuid() {
return modelUuid;
}
protected void setModelUuid(final String modelUuid) {
this.modelUuid = modelUuid;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public PageModelVersion getVersion() {
return version;
}
protected void setVersion(final PageModelVersion version) {
this.version = version;
}
public Date getLastModified() {
return lastModified;
}
protected void setLastModified(final Date lastModified) {
this.lastModified = new Date(lastModified.getTime());
}
public LocalizedString getTitle() {
return title;
}
protected void setTitle(final LocalizedString title) {
Objects.requireNonNull(title);
this.title = title;
}
public LocalizedString getDescription() {
return description;
}
protected void setDescription(final LocalizedString description) {
Objects.requireNonNull(description);
this.description = description;
}
public CcmApplication getApplication() {
return application;
}
public void setApplication(final CcmApplication application) {
this.application = application;
}
public String getType() {
return type;
}
public void setType(final String type) {
this.type = type;
}
public List<ContainerModel> getContainers() {
return Collections.unmodifiableList(containers);
}
protected void setContainers(final List<ContainerModel> containers) {
this.containers = new ArrayList<>(containers);
}
protected void addContainer(final ContainerModel container) {
containers.add(container);
}
protected void removeContainer(final ContainerModel container) {
containers.remove(container);
}
protected void clearContainers() {
containers.clear();
}
@Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + (int) (pageModelId ^ (pageModelId >>> 32));
hash = 71 * hash + Objects.hashCode(uuid);
hash = 71 * hash + Objects.hashCode(name);
hash = 71 * hash + Objects.hashCode(title);
hash = 71 * hash + Objects.hashCode(description);
hash = 71 * hash + Objects.hashCode(type);
return hash;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof PageModel)) {
return false;
}
final PageModel other = (PageModel) obj;
if (!other.canEqual(this)) {
return false;
}
if (pageModelId != other.getPageModelId()) {
return false;
}
if (!Objects.equals(uuid, other.getUuid())) {
return false;
}
if (!Objects.equals(name, other.getName())) {
return false;
}
if (!Objects.equals(type, other.getType())) {
return false;
}
if (!Objects.equals(title, other.getTitle())) {
return false;
}
return Objects.equals(description, other.getDescription());
}
public boolean canEqual(final Object obj) {
return obj instanceof PageModel;
}
@Override
public final String toString() {
return toString("");
}
public String toString(final String data) {
return String.format("%s{ "
+ "pageModelId = %d, "
+ "uuid = %s, "
+ "name = \"%s\", "
+ "title = %s, "
+ "description = %s, "
+ "type = \"%s\""
+ " }",
super.toString(),
pageModelId,
uuid,
name,
Objects.toString(title),
Objects.toString(description),
type);
}
}

View File

@ -1,80 +0,0 @@
/*
* Copyright (C) 2016 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import com.arsdigita.bebop.Form;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ResourceBundle;
/**
* Used in the description of {@link CcmModule} to specify which
* {@link ComponentModel}s are provided by an module.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface PageModelComponentModel {
/**
* Fully qualified name of a resource bundle providing the title and
* description of the {@link ComponentModel}.
*
* @return The fully qualified name of the {@link ResourceBundle} which
* provides the title and description of the {@link ComponentModel}.
*/
String descBundle() default "";
/**
* Key for the title of the {@link ComponentModel} in the
* {@link ResourceBundle} specified by {@link #descBundle()}.
*
* @return The key for the title of the {@link ComponentModel}.
*/
String titleKey() default "component_model_title";
/**
* Key for the description of the {@link ComponentModel} in the
* {@link ResourceBundle} specified by {@link #descBundle()}.
*
* @return The key for the description of the {@link ComponentModel}.
*/
String descKey() default "component_model_desc";
/**
* The class which provides the {@link ComponentModel}.
*
* @return The class which provides the {@link ComponentModel}.
*/
Class<? extends ComponentModel> modelClass();
/**
* A (Bebop) form for editing the properties of an instance of the
* {@link ComponentModel}.
*
* @return A (Bebop) form for editing the {@code ComponentModel}.
*/
Class<? extends Form> editor();
}

View File

@ -1,609 +0,0 @@
/*
* Copyright (C) 2016 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.libreccm.core.CoreConstants;
import org.libreccm.core.UnexpectedErrorException;
import org.libreccm.modules.CcmModule;
import org.libreccm.modules.Module;
import org.libreccm.pagemodel.styles.CssProperty;
import org.libreccm.pagemodel.styles.MediaQuery;
import org.libreccm.pagemodel.styles.MediaRule;
import org.libreccm.pagemodel.styles.Rule;
import org.libreccm.pagemodel.styles.Styles;
import org.libreccm.security.AuthorizationRequired;
import org.libreccm.security.RequiresPrivilege;
import org.libreccm.web.CcmApplication;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Provides several methods for managing {@link PageModel}s.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
public class PageModelManager {
private static final Logger LOGGER = LogManager.getLogger(
PageModelManager.class);
@Inject
private EntityManager entityManager;
@Inject
private ComponentModelRepository componentModelRepo;
@Inject
private ContainerModelRepository containerModelRepo;
@Inject
private ContainerModelManager containerModelManager;
@Inject
private PageModelRepository pageModelRepo;
private final Map<String, PageModelComponentModel> components
= new HashMap<>();
/**
* Called by CDI after an instance of this class is created. Initialises the
* {@link #components} by retrieving the data about all available {@link
* ComponentModel}s.
*/
@PostConstruct
private void init() {
LOGGER.debug("Initalising {}...", PageModelManager.class.getName());
final ServiceLoader<CcmModule> modules = ServiceLoader.load(
CcmModule.class);
for (CcmModule module : modules) {
final Module moduleData = module.getClass().getAnnotation(
Module.class);
final PageModelComponentModel[] models = moduleData
.pageModelComponentModels();
for (PageModelComponentModel model : models) {
components.put(model.modelClass().getName(),
model);
}
}
LOGGER.debug("Initalised {}. Found {} ComponentModels.",
PageModelManager.class.getName(),
components.size());
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public PageModel createPageModel(final String name,
final CcmApplication application) {
return createPageModel(name, application, "");
}
/**
* Creates a new {@link PageModel} for the provided application. The method
* tries to retrieve the appropriate application by using {@link
* PageModelRepository#findLiveByApplicationAndName(org.libreccm.web
* .CcmApplication,
* java.lang.String)}. Please note that this method will always return the
* <strong>draft</strong> version of the page model.
*
* @param name The name of the new page model. Must be unique for the
* application.
* @param application The application for which the {@link PageModel} is
* created.
* @param type Type of the page model.
*
* @return The new {@link PageModel}.
*/
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public PageModel createPageModel(final String name,
final CcmApplication application,
final String type) {
Objects.requireNonNull(application,
"Can't create a page model for application "
+ "null");
Objects.requireNonNull(name, "Then name of a Pagemodel can't be null.");
if (name.isEmpty()
|| name.matches("\\s*")) {
throw new IllegalArgumentException(
"The name of a PageModel can't be empty.");
}
LOGGER.debug(
"Creating new PageModel with name \"{}\" for application \"{}\" "
+ "and type \"{}\".",
name,
application.getPrimaryUrl(),
type);
final long count = pageModelRepo.countLiveByApplicationAndName(
application,
name);
if (count > 0) {
LOGGER.error("A page model with the name \"{}\" for the "
+ "application \"{}\" already exists.",
name,
application.getPrimaryUrl());
throw new IllegalArgumentException(String.format(
"A page model with the name \"%s\" for the application \"%s\" "
+ "already exists.",
name,
application.getPrimaryUrl()));
}
final PageModel pageModel = new PageModel();
pageModel.setName(name);
pageModel.setApplication(application);
pageModel.setType(type);
pageModel.setVersion(PageModelVersion.DRAFT);
return pageModel;
}
/**
* Retrieves the draft version of a {@link PageModel}. To invoke this method
* the current user needs a permission granting the {@link
* CoreConstants#PRIVILEGE_ADMIN} privilege.
*
* @param pageModel The {@link PageModel} for which the draft version is
* retrieved.
*
* @return The draft version of the provided {@link PageModel}.
*/
@AuthorizationRequired
@Transactional(Transactional.TxType.REQUIRED)
public PageModel getDraftVersion(
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
final PageModel pageModel) {
if (pageModel == null) {
throw new IllegalArgumentException(
"Can't get draft version for page model null.");
}
final TypedQuery<PageModel> query = entityManager.createNamedQuery(
"PageModel.findDraftVersion", PageModel.class);
query.setParameter("uuid", pageModel.getModelUuid());
return query.getSingleResult();
}
/**
* Checks if a {@link PageModel} has a live version.
*
* @param pageModel The {@link PageModel} to check for a live version.
*
* @return {@code true} if there is a live version for the provided {@link
* PageModel}, {@code false} otherwise.
*/
@Transactional(Transactional.TxType.REQUIRED)
public boolean isLive(final PageModel pageModel) {
final TypedQuery<Boolean> query = entityManager.createNamedQuery(
"PageModel.hasLiveVersion", Boolean.class);
query.setParameter("uuid", pageModel.getModelUuid());
return query.getSingleResult();
}
/**
* Retrieves the live version of a {@link PageModel}. This method does not
* require any privileges.
*
* @param pageModel The {@link PageModel} of which the live version is
* retrieved.
*
* @return An {@link Optional} containing the live version of the provided
* {@link PageModel} if there is a live version. Otherwise an empty
* {@link Optional} is returned.
*/
@Transactional(Transactional.TxType.REQUIRED)
public Optional<PageModel> getLiveVersion(final PageModel pageModel) {
if (isLive(pageModel)) {
final TypedQuery<PageModel> query = entityManager.createNamedQuery(
"PageModel.findLiveVersion",
PageModel.class);
query.setParameter("uuid", pageModel.getModelUuid());
return Optional.of(query.getSingleResult());
} else {
return Optional.empty();
}
}
/**
* Publishes the draft version of a {@link PageModel}. If there is already a
* live version of the provided {@link PageModel} the live version is
* updated. If no live version exists a new live version is created.
*
* @param pageModel The {@link PageModel} to publish.
*
* @return The live version of the provided {@link PageModel}.
*/
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
@Transactional(Transactional.TxType.REQUIRED)
public PageModel publish(final PageModel pageModel) {
Objects.requireNonNull(pageModel, "Can't publish PageModel null.");
LOGGER.debug("Publishing PageModel \"{}\"...", pageModel.getName());
final PageModel draftModel = getDraftVersion(pageModel);
final PageModel liveModel;
final boolean isLive;
if (isLive(pageModel)) {
isLive = true;
liveModel = getLiveVersion(draftModel).get();
} else {
liveModel = new PageModel();
isLive = false;
}
liveModel.setName(draftModel.getName());
liveModel.setVersion(PageModelVersion.LIVE);
liveModel.setModelUuid(draftModel.getModelUuid());
for (Map.Entry<Locale, String> entry : draftModel.getTitle().getValues()
.entrySet()) {
liveModel.getTitle().putValue(entry.getKey(), entry.getValue());
}
for (Map.Entry<Locale, String> entry : draftModel.getDescription()
.getValues().entrySet()) {
liveModel.getDescription().putValue(entry.getKey(),
entry.getValue());
}
liveModel.setApplication(draftModel.getApplication());
liveModel.setType(draftModel.getType());
LOGGER.debug("Publishing ContainerModels of PageModel \"{}\"...",
draftModel.getName());
liveModel.clearContainers();
draftModel
.getContainers()
.stream()
.map(this::publishContainerModel)
.forEach(liveContainerModel -> addContainerModel(liveModel,
liveContainerModel));
liveModel.setLastModified(new Date());
pageModelRepo.save(liveModel);
//if (isLive) {
// entityManager.merge(liveModel);
//} else {
// entityManager.persist(liveModel);
//}
LOGGER.debug("Successfully published PageModel \"{}\".",
liveModel.getName());
return liveModel;
}
private ContainerModel publishContainerModel(
final ContainerModel draftModel) {
Objects.requireNonNull(draftModel);
final ContainerModel liveModel = new ContainerModel();
liveModel.setKey(draftModel.getKey());
liveModel.setContainerUuid(draftModel.getContainerUuid());
final Styles draftStyles = draftModel.getStyles();
if (draftStyles != null) {
final Styles liveStyles = new Styles();
liveStyles.setStyleName(draftStyles.getStyleName());
liveStyles.setRules(draftStyles
.getRules()
.stream()
.map(this::publishRule)
.collect(Collectors.toList()));
liveStyles.setMediaRules(draftStyles
.getMediaRules()
.stream()
.map(this::publishMediaRule)
.collect(Collectors.toList()));
}
draftModel
.getComponents()
.stream()
.map(this::publishComponentModel)
.forEach(
liveComponentModel -> containerModelManager
.addComponentModel(liveModel, liveComponentModel));
return liveModel;
}
private MediaRule publishMediaRule(final MediaRule draftMediaRule) {
Objects.requireNonNull(draftMediaRule);
final MediaRule liveMediaRule = new MediaRule();
final MediaQuery liveMediaQuery = new MediaQuery();
liveMediaQuery
.setMaxWidth(draftMediaRule.getMediaQuery().getMaxWidth());
liveMediaQuery
.setMediaType(draftMediaRule.getMediaQuery().getMediaType());
liveMediaQuery
.setMinWidth(draftMediaRule.getMediaQuery().getMinWidth());
liveMediaRule.setRules(draftMediaRule
.getRules()
.stream()
.map(this::publishRule)
.collect(Collectors.toList()));
return liveMediaRule;
}
private Rule publishRule(final Rule draftRule) {
Objects.requireNonNull(draftRule);
final Rule liveRule = new Rule();
liveRule.setSelector(draftRule.getSelector());
liveRule.setProperties(draftRule
.getProperties()
.stream()
.map(this::publishCssProperty)
.collect(Collectors.toList()));
return liveRule;
}
private CssProperty publishCssProperty(final CssProperty draftProperty) {
Objects.requireNonNull(draftProperty);
final CssProperty liveProperty = new CssProperty();
liveProperty.setName(draftProperty.getName());
liveProperty.setValue(draftProperty.getValue());
return liveProperty;
}
/**
* Helper method for coping the {@link ComponentModel}s from the draft
* version to the live version.
*
* @param draftModel The draft version of the {@link ComponentModel} to copy
* to the live version of its {@link PageModel}.
*
* @return The live version of the {@link ComponentModel}.
*/
@SuppressWarnings("unchecked")
private ComponentModel publishComponentModel(final ComponentModel draftModel) {
Objects.requireNonNull(draftModel,
"Can't publish ComponentModel null.");
LOGGER.debug("Publishing ComponentModel \"{}\"...",
draftModel.getKey());
final Class<? extends ComponentModel> clazz = draftModel.getClass();
final ComponentModel liveModel;
try {
liveModel = clazz.newInstance();
} catch (InstantiationException | IllegalAccessException ex) {
throw new UnexpectedErrorException(ex);
}
liveModel.setModelUuid(draftModel.getModelUuid());
final BeanInfo beanInfo;
try {
beanInfo = Introspector.getBeanInfo(clazz);
} catch (IntrospectionException ex) {
throw new UnexpectedErrorException(ex);
}
for (final PropertyDescriptor propertyDescriptor : beanInfo.
getPropertyDescriptors()) {
LOGGER.debug(
"Publishing property \"{}\" of ComponentModel \"{}\"...",
propertyDescriptor.getName(),
draftModel.getKey());
final Class<?> propType = propertyDescriptor.getPropertyType();
final Method readMethod = propertyDescriptor.getReadMethod();
final Method writeMethod = propertyDescriptor.getWriteMethod();
if (propertyIsExcluded(propertyDescriptor.getName())) {
continue;
}
if (writeMethod == null) {
continue;
}
if (propType != null
&& propType.isAssignableFrom(List.class)) {
try {
final List<Object> source = (List<Object>) readMethod
.invoke(draftModel);
final List<Object> target = new ArrayList<>();
target.addAll(source);
writeMethod.invoke(draftModel, target);
} catch (IllegalAccessException
| IllegalArgumentException
| InvocationTargetException ex) {
throw new UnexpectedErrorException(ex);
}
} else if (propType != null
&& propType.isAssignableFrom(Map.class)) {
final Map<Object, Object> source;
final Map<Object, Object> target;
try {
source
= (Map<Object, Object>) readMethod.invoke(draftModel);
target = (Map<Object, Object>) readMethod.invoke(liveModel);
} catch (IllegalAccessException
| IllegalArgumentException
| InvocationTargetException ex) {
throw new UnexpectedErrorException(ex);
}
source.forEach((key, value) -> target.put(key, value));
} else if (propType != null
&& propType.isAssignableFrom(Set.class)) {
final Set<Object> source;
final Set<Object> target;
try {
source = (Set<Object>) readMethod.invoke(draftModel);
target = (Set<Object>) readMethod.invoke(liveModel);
} catch (IllegalAccessException
| IllegalArgumentException
| InvocationTargetException ex) {
throw new UnexpectedErrorException(ex);
}
target.addAll(source);
} else {
final Object value;
try {
value = readMethod.invoke(draftModel);
writeMethod.invoke(liveModel, value);
} catch (IllegalAccessException
| IllegalArgumentException
| InvocationTargetException ex) {
throw new UnexpectedErrorException(ex);
}
}
}
componentModelRepo.save(liveModel);
LOGGER.debug("Successfully published ComponentModel \"{}\".",
liveModel.getKey());
return liveModel;
}
/**
* Helper method to determine if a property is excluded from the publishing
* process.
*
* @param name The name of the property.
*
* @return {@code true} if the property is excluded from the publishing
* process, {@link false} if not.
*/
private boolean propertyIsExcluded(final String name) {
final String[] excluded = new String[]{
"class",
"uuid",
"modelUuid"
};
boolean result = false;
for (final String current : excluded) {
if (current.equals(name)) {
result = true;
break;
}
}
return result;
}
@Transactional(Transactional.TxType.REQUIRED)
public void addContainerModel(final PageModel pageModel,
final ContainerModel container) {
Objects.requireNonNull(pageModel);
Objects.requireNonNull(container);
pageModel.addContainer(container);
container.setPageModel(pageModel);
containerModelRepo.save(container);
pageModelRepo.save(pageModel);
}
@Transactional(Transactional.TxType.REQUIRED)
public void removeContainerModel(final PageModel pageModel,
final ContainerModel container) {
Objects.requireNonNull(pageModel);
Objects.requireNonNull(container);
if (!container.getComponents().isEmpty()) {
throw new IllegalArgumentException("Container is not empty.");
}
pageModel.removeContainer(container);
container.setPageModel(null);
pageModelRepo.save(pageModel);
containerModelRepo.delete(container);
}
}

View File

@ -1,378 +0,0 @@
/*
* Copyright (C) 2016 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import org.libreccm.core.AbstractEntityRepository;
import org.libreccm.core.CoreConstants;
import org.libreccm.security.AuthorizationRequired;
import org.libreccm.security.RequiresPrivilege;
import org.libreccm.web.CcmApplication;
import javax.enterprise.context.RequestScoped;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
/**
* Repository for {@link PageModel}s.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
public class PageModelRepository extends AbstractEntityRepository<Long, PageModel> {
private static final long serialVersionUID = -7240418542790568571L;
@Override
public Class<PageModel> getEntityClass() {
return PageModel.class;
}
@Override
public String getIdAttributeName() {
return "pageModelId";
}
@Override
public Long getIdOfEntity(final PageModel entity) {
return entity.getPageModelId();
}
@Override
public boolean isNew(final PageModel pageModel) {
Objects.requireNonNull(pageModel);
return pageModel.getPageModelId() == 0;
}
/**
* Sets the UUID field of a new {@link PageModel}.
*
* @param pageModel The new {@link PageModel}.
*/
@Override
public void initNewEntity(final PageModel pageModel) {
Objects.requireNonNull(pageModel);
final String uuid = UUID.randomUUID().toString();
pageModel.setUuid(uuid);
if (pageModel.getModelUuid() == null
|| pageModel.getModelUuid().isEmpty()) {
pageModel.setModelUuid(uuid);
}
}
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
@Transactional(Transactional.TxType.REQUIRED)
@Override
public void save(final PageModel pageModel) {
pageModel.setLastModified(new Date());
super.save(pageModel);
}
/**
* Find all draft versions of {@link PageModel}s.
*
* @return A list with all draft versions of {@link PageModel}s.
*/
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
@Transactional(Transactional.TxType.REQUIRED)
public List<PageModel> findAllDraftModels() {
final TypedQuery<PageModel> query = getEntityManager()
.createNamedQuery("PageModel.findAllDraftModels", PageModel.class);
return query.getResultList();
}
/**
* Find all live versions of {@link PageModel}s.
*
* @return A list with all draft versions of {@link PageModel}s.
*/
@Transactional(Transactional.TxType.REQUIRED)
public List<PageModel> findAllLiveModels() {
final TypedQuery<PageModel> query = getEntityManager()
.createNamedQuery("PageModel.findAllLiveModels", PageModel.class);
return query.getResultList();
}
/**
* Finds the draft versions of all {@link PageModel}s for the provided
* application.
*
* @param application The application for which the {@link PageModel}s are
* retrieved.
*
* @return A list of the {@link PageModel}s defined for the provided
* {@code application}.
*/
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public List<PageModel> findDraftByApplication(
final CcmApplication application) {
Objects.requireNonNull(application,
"Can't find page models for application null");
final TypedQuery<PageModel> query = getEntityManager()
.createNamedQuery("PageModel.findDraftByApplication",
PageModel.class);
query.setParameter("application", application);
return query.getResultList();
}
/**
* Counts the {@link PageModel}s (draft version) defined for a application.
*
* @param application The application for which the {@link PageModels}s are
* counted.
*
* @return The number of {@link PageModel}s defined for the provided
* {@code application}.
*/
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public long countByApplication(final CcmApplication application) {
Objects.requireNonNull(application,
"Can't count page models for application null");
final TypedQuery<Long> query = getEntityManager().createNamedQuery(
"PageModel.countDraftByApplication", Long.class);
query.setParameter("application", application);
return query.getSingleResult();
}
/**
* Finds a {@link PageModel} (draft version) by the application and its
* {@code name}.
*
* @param application The application for which the {@link PageModel} is
* defined.
* @param name The name of the {@link PageModel}.
*
* @return An {@link Optional} containing the {@link PageModel} for the
* provided {@code application} with the provided {@code name}. If
* there is no {@link PageModel} matching the criteria an empty
* {@link Optional} is returned.
*/
public Optional<PageModel> findDraftByApplicationAndName(
final CcmApplication application,
final String name) {
Objects.requireNonNull(application,
"Can't find page models for application null");
Objects.requireNonNull(name,
"The name of a page model can't be null or empty.");
if (name.isEmpty() || name.matches("\\s*")) {
throw new IllegalArgumentException(
"The name of a page model can't be null or empty.");
}
final long count = countDraftByApplicationAndName(application, name);
if (count == 0) {
return Optional.empty();
}
final TypedQuery<PageModel> query = getEntityManager().createNamedQuery(
"PageModel.findDraftByApplicationAndName", PageModel.class);
query.setParameter("application", application);
query.setParameter("name", name);
return Optional.of(query.getSingleResult());
}
/**
* Counts the number of {@link PageModel} (draft version) defined for the
* provided application with the provided name.
*
* @param application The application for which the {@link PageModel} is
* defined.
* @param name The name of the {@link PageModel}.
*
* @return The number of {@link PageModel}s matching the criteria. Should be
* 0 or 1.
*/
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public long countDraftByApplicationAndName(final CcmApplication application,
final String name) {
Objects.requireNonNull(application,
"Can't find page models for application null");
Objects.requireNonNull(name,
"The name of a page model can't be null or empty.");
if (name.isEmpty() || name.matches("\\s*")) {
throw new IllegalArgumentException(
"The name of a page model can't be null or empty.");
}
final TypedQuery<Long> query = getEntityManager().createNamedQuery(
"PageModel.countDraftByApplicationAndName", Long.class);
query.setParameter("application", application);
query.setParameter("name", name);
return query.getSingleResult();
}
/**
* Finds the live versions of all {@link PageModel}s for the provided
* application.
*
* @param application The application for which the {@link PageModel}s are
* retrieved.
*
* @return A list of the {@link PageModel}s defined for the provided
* {@code application}.
*/
@Transactional(Transactional.TxType.REQUIRED)
public List<PageModel> findLiveByApplication(
final CcmApplication application) {
Objects.requireNonNull(application,
"Can't find page models for application null");
final TypedQuery<PageModel> query = getEntityManager()
.createNamedQuery("PageModel.findLiveByApplication",
PageModel.class);
query.setParameter("application", application);
return query.getResultList();
}
/**
* Counts the {@link PageModel}s (live version) defined for a application.
*
* @param application The application for which the {@link PageModels}s are
* counted.
*
* @return The number of {@link PageModel}s defined for the provided
* {@code application}.
*/
@Transactional(Transactional.TxType.REQUIRED)
public long countLiveByApplication(final CcmApplication application) {
Objects.requireNonNull(application,
"Can't count page models for application null");
final TypedQuery<Long> query = getEntityManager().createNamedQuery(
"PageModel.countLiveByApplication", Long.class);
query.setParameter("application", application);
return query.getSingleResult();
}
/**
* Finds a {@link PageModel} (live version) by the application and its
* {@code name}.
*
* @param application The application for which the {@link PageModel} is
* defined.
* @param name The name of the {@link PageModel}.
*
* @return An {@link Optional} containing the {@link PageModel} for the
* provided {@code application} with the provided {@code name}. If
* there is no {@link PageModel} matching the criteria an empty
* {@link Optional} is returned.
*/
@Transactional(Transactional.TxType.REQUIRED)
public Optional<PageModel> findLiveByApplicationAndName(
final CcmApplication application,
final String name) {
Objects.requireNonNull(application,
"Can't find page models for application null");
Objects.requireNonNull(name,
"The name of a page model can't be null or empty.");
if (name.isEmpty() || name.matches("\\s*")) {
throw new IllegalArgumentException(
"The name of a page model can't be null or empty.");
}
final long count = countLiveByApplicationAndName(application, name);
if (count == 0) {
return Optional.empty();
}
final TypedQuery<PageModel> query = getEntityManager().createNamedQuery(
"PageModel.findLiveByApplicationAndName", PageModel.class);
query.setParameter("application", application);
query.setParameter("name", name);
return Optional.of(query.getSingleResult());
}
/**
* Counts the number of {@link PageModel} (live version) defined for the
* provided application with the provided name.
*
* @param application The application for which the {@link PageModel} is
* defined.
* @param name The name of the {@link PageModel}.
*
* @return The number of {@link PageModel}s matching the criteria. Should be
* 0 or 1.
*/
@Transactional(Transactional.TxType.REQUIRED)
public long countLiveByApplicationAndName(final CcmApplication application,
final String name) {
Objects.requireNonNull(application,
"Can't find page models for application null");
Objects.requireNonNull(name,
"The name of a page model can't be null or empty.");
if (name.isEmpty() || name.matches("\\s*")) {
throw new IllegalArgumentException(
"The name of a page model can't be null or empty.");
}
final TypedQuery<Long> query = getEntityManager().createNamedQuery(
"PageModel.countLiveByApplicationAndName", Long.class);
query.setParameter("application", application);
query.setParameter("name", name);
return query.getSingleResult();
}
}

View File

@ -1,32 +0,0 @@
/*
* Copyright (C) 2016 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
/**
* Enumeration for the possible values for the version of a {@link PageModel}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
public enum PageModelVersion {
DRAFT,
LIVE
}

View File

@ -1,75 +0,0 @@
/*
* Copyright (C) 2016 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import java.util.Map;
/**
* Interface for page renderers. A page renderer is invoked to render a page of
* specific type. An implementation should be a CDI bean which is annotated with
* the qualifier {@link RendersPageModelType}.
*
* An implementation should add all default components which have to be present
* in page. The {@link PageModel} should only specify
* <strong>additional</strong> components.
*
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
public interface PageRenderer {
/**
* Render a page with the default components for a application. An
* implementation of {@link #renderPage(org.libreccm.pagemodel.PageModel)}
* should use this method for creating the default page.
*
* The result of the rendering process is a map with the values of the
* {@link ComponentModel#key} property as key and the result of rendering
* the component as value.
*
* @param parameters Parameters provided by application which wants to
* render a {@link PageModel}. The parameters are passed
* the {@link ComponentRenderer}s.
*
* @return A page with the default components.
*/
Map<String, Object> renderPage(Map<String, Object> parameters);
/**
* Render a page using the provided {@link PageModel}.
* Implementations should call the implementation of {@link #renderPage()}
* for creating the basic page with the default components.
*
* The result of the rendering process is a map with the values of the
* {@link ComponentModel#key} property as key and the result of rendering
* the component as value.
*
*
* @param pageModel The {@link PageModel} from which the page is generated.
* @param parameters Parameters provided by application which wants to
* render a {@link PageModel}. The parameters are passed
* the {@link ComponentRenderer}s.
*
* @return The page generated from the provided {@link PageModel}.
*/
Map<String, Object> renderPage(PageModel pageModel,
Map<String, Object> parameters);
}

View File

@ -1,41 +0,0 @@
/*
* Copyright (C) 2016 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Specifies which type of components a {@link ComponentRenderer} implementation
* renders.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface RendersComponent {
Class<? extends ComponentModel> componentModel();
}

View File

@ -1,42 +0,0 @@
/*
* Copyright (C) 2017 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
/**
* Specifies which type of {@link PageModel} an implementation of
* {@link PageRenderer} can render.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface RendersPageModelType {
String value();
}

View File

@ -1,43 +0,0 @@
/*
* Copyright (C) 2016 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
/**
* <p>
* The {@code pagemodel} packages provides an abstraction layer between the data
* model of page and its generating components. This layer replaces the JSP
* templates which were used in previous versions of CCM for this purpose.
* </p>
* <p>
* The Page Model system allows it to specify which components are used on a
* page and therefore which information is displayed on a page. It is intended
* to be used for public pages (like the item page of a content item category
* page in ccm-cms module. The Page Model system uses data containers which are
* read by a renderer class.
* </p>
* <p>
* The central interface is the {@link org.libreccm.pagemodel.PageRenderer}
* interface. An implementation of this interface will take a
* {@link org.libreccm.pagemodel.PageModel} and process it and create a page
* from it using the view technology supported by the implementation.
* {@code PageRenderer}s are CDI beans. Implementations can be retrieved using
* the
* {@link org.libreccm.pagemodel.PageRendererManager#findPageRenderer(String, Class)}
* method.
* </p>
*/
package org.libreccm.pagemodel;

View File

@ -1,628 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.rs;
import org.libreccm.core.CoreConstants;
import org.libreccm.pagemodel.ComponentModel;
import org.libreccm.pagemodel.ComponentModelJsonConverter;
import org.libreccm.pagemodel.ComponentModelRepository;
import org.libreccm.pagemodel.ContainerModel;
import org.libreccm.pagemodel.ContainerModelManager;
import org.libreccm.pagemodel.ConvertsComponentModel;
import org.libreccm.pagemodel.PageModel;
import org.libreccm.security.AuthorizationRequired;
import org.libreccm.security.RequiresPrivilege;
import org.libreccm.web.CcmApplication;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonValue;
import javax.transaction.Transactional;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
/**
* Provides RESTful endpoints for retrieving, creating, updating and deleting
* {@link ComponentModel}s of a {@link ContainerModel}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@Path("/")
public class Components {
@Inject
private ComponentModelRepository componentRepo;
@Inject
private ContainerModelManager containerManager;
@Inject
private PageModelsController controller;
@Inject
@Any
private Instance<ComponentModelJsonConverter> jsonConverters;
/**
* Retrieve all {@link ComponentModel} of a {@link ContainerModel}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
*
* @return A JSON array containing the data of all {@link ComponentModel} of
* the {@link ContainerModel}.
*/
@GET
@Path(PageModelsApp.COMPONENTS_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonArray getComponents(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final ContainerModel container = controller.findContainer(app,
pageModel,
containerKey);
final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
container
.getComponents()
.stream()
.map(component -> mapComponentModelToJson(component))
.forEach(arrayBuilder::add);
return arrayBuilder.build();
}
/**
* Retrieves a specific {@link ComponentModel}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
* @param componentKey The key of the {@link ComponentModel}.
*
* @return A JSON object containing the data of the {@link ComponentModel}.
*/
@GET
@Path(PageModelsApp.COMPONENT_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject getComponent(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(PageModelsApp.COMPONENT_KEY) final String componentKey) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(componentKey);
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final ContainerModel container = controller.findContainer(app,
pageModel,
containerKey);
final ComponentModel component = controller
.findComponentModel(app, pageModel, container, componentKey);
return mapComponentModelToJson(component);
}
/**
* Creates or updates a {@link ComponentModel}.
*
* If a {@link ComponentModel} with provided {@code componentKey} already
* exists in the container identified by {@code appPath},
* {@code pageModelName} and {@code containerKey} the {@link ComponentModel}
* is updated with the data from {@code componentModelData}.
*
* Otherwise a new {@link ComponentModel} is created using the data from
* {@code componentModelData}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
* @param componentKey The key of the {@link ComponentModel} to create
* or update.
* @param componentModelData The data for creating or updating the
* {@link ComponentModel}.
*
* @return The new or updated {@link ComponentModel}.
*/
@PUT
@Path(PageModelsApp.COMPONENT_PATH)
@Consumes("application/json; charset=utf-8")
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject putComponent(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(PageModelsApp.COMPONENT_KEY) final String componentKey,
final JsonObject componentModelData) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(componentKey);
Objects.requireNonNull(componentModelData);
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final ContainerModel container = controller.findContainer(app,
pageModel,
containerKey);
final Optional<ComponentModel> result = container
.getComponents()
.stream()
.filter(c -> c.getKey().equals(componentKey))
.findAny();
final ComponentModel componentModel;
if (result.isPresent()) {
componentModel = result.get();
} else {
componentModel = createComponentModel(componentModelData);
componentModel.setKey(componentKey);
containerManager.addComponentModel(container, componentModel);
}
setComponentPropertiesFromJson(componentModelData, componentModel);
componentRepo.save(componentModel);
final ComponentModel saved = controller
.findComponentModel(app, pageModel, container, componentKey);
return mapComponentModelToJson(saved);
}
/**
* Deletes a {@link ComponentModel}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
* @param componentKey The key of the {@link ComponentModel} to delete.
*
*/
@DELETE
@Path(PageModelsApp.COMPONENT_PATH)
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void deleteComponent(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(PageModelsApp.COMPONENT_KEY) final String componentKey) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(componentKey);
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final ContainerModel container = controller.findContainer(app,
pageModel,
containerKey);
final ComponentModel component = controller
.findComponentModel(app, pageModel, container, componentKey);
containerManager.removeComponentModel(container, component);
}
/**
* Helper method for mapping a {@link ComponentModel} to JSON.
*
* @param componentModel The {@link ComponentModel} to map.
*
* @return The JSON representation of the
* {@link ComponentModel} {@code componentModel}.
*/
private JsonObject mapComponentModelToJson(
final ComponentModel componentModel) {
final Class<? extends ComponentModel> clazz = Objects
.requireNonNull(componentModel)
.getClass();
final ComponentModelJsonConverter jsonConverter
= findJsonConverter(clazz)
.orElseThrow(() -> new WebApplicationException(String.format(
"No JSON converter available for component model \"%s\".",
clazz.getName())));
return jsonConverter.toJson(componentModel);
// Objects.requireNonNull(componentModel);
//
// final JsonObjectBuilder objectBuilder = Json
// .createObjectBuilder()
// .add("componentModelId",
// Long.toString(componentModel.getComponentModelId()))
// .add("uuid", componentModel.getUuid())
// .add("modelUuid", componentModel.getModelUuid())
// .add("key", componentModel.getKey())
// .add("type", componentModel.getClass().getName());
//
// if (componentModel.getIdAttribute() != null) {
// objectBuilder.add("idAttribute", componentModel.getIdAttribute());
// }
//
// if (componentModel.getClassAttribute() != null) {
// objectBuilder.add("classAttribute",
// componentModel.getClassAttribute());
// }
//
// if (componentModel.getStyleAttribute() != null) {
// objectBuilder.add("styleAttribute",
// componentModel.getStyleAttribute());
// }
//
// final Class<? extends ComponentModel> clazz = componentModel.getClass();
// final BeanInfo beanInfo;
// try {
// beanInfo = Introspector.getBeanInfo(clazz);
// } catch (IntrospectionException ex) {
// throw new WebApplicationException(ex);
// }
//
// for (final PropertyDescriptor propertyDescriptor
// : beanInfo.getPropertyDescriptors()) {
//
// final Method readMethod = propertyDescriptor.getReadMethod();
// final Object value;
// try {
// value = readMethod.invoke(componentModel);
// } catch (IllegalAccessException
// | InvocationTargetException ex) {
// throw new WebApplicationException(ex);
// }
//
// final String valueStr;
// if (value == null) {
// valueStr = "";
// } else {
// valueStr = value.toString();
// }
//
// objectBuilder.add(propertyDescriptor.getName(), valueStr);
//
// }
//
// return objectBuilder.build();
}
/**
* Creates a new {@link ComponentModel} instance.
*
* Uses reflection and the value of {@code type} property from the JSON
* {@code data} to determine the correct class.
*
* @param data The data from which the new {@link ComponentModel} is
* created.
*
* @return The new {@link ComponentModel}.
*/
private ComponentModel createComponentModel(final JsonObject data) {
Objects.requireNonNull(data);
if (!data.containsKey("type")) {
throw new BadRequestException("The JSON data for creating the "
+ "component has no value for the type of the component to "
+ "create.");
}
final String type = data.getString("type");
final Class<? extends ComponentModel> clazz = findComponentModelClass(
type);
final ComponentModel componentModel;
try {
componentModel = clazz.getConstructor().newInstance();
} catch (IllegalAccessException
| InstantiationException
| InvocationTargetException
| NoSuchMethodException ex) {
throw new WebApplicationException(ex);
}
return componentModel;
}
/**
* Helper method for finding the correct subclass of {@link ComponentModel}
* using the fully qualified name the class.
*
* @param type The fully qualified name of the subclass of
* {@link ComponentModel}.
*
* @return The subclass of {@link ComponentModel}.
*
* @throws BadRequestException If there is no subclass of
* {@link ComponentModel} with the fully
* qualified name provided by the {@code type}
* parameter.
*/
@SuppressWarnings("unchecked")
private Class<? extends ComponentModel> findComponentModelClass(
final String type) {
Objects.requireNonNull(type);;
try {
final Class<?> clazz = Class.forName(type);
if (ComponentModel.class.isAssignableFrom(clazz)) {
return (Class<? extends ComponentModel>) clazz;
} else {
throw new BadRequestException(String.format(
"The type \"%s\" is not a subclass of \"%s\".",
type,
ComponentModel.class.getName()));
}
} catch (ClassNotFoundException ex) {
throw new BadRequestException(String.format(
"The component model type \"%s\" "
+ "does not exist.",
type));
}
}
/**
* Helper method for setting the properties of a {@link ComponentModel} from
* the JSON data.
*
* @param data The JSON data.
* @param componentModel The {@link ComponentModel}.
*/
private void setComponentPropertiesFromJson(
final JsonObject data,
final ComponentModel componentModel) {
final Class<? extends ComponentModel> clazz = Objects
.requireNonNull(componentModel)
.getClass();
final ComponentModelJsonConverter jsonConverter
= findJsonConverter(clazz)
.orElseThrow(() -> new WebApplicationException(String.format(
"No JSON converter available for component model \"%s\".",
clazz.getName())));
jsonConverter.fromJson(data, componentModel);
// final BeanInfo beanInfo;
// try {
// beanInfo = Introspector.getBeanInfo(componentModel.getClass());
// } catch (IntrospectionException ex) {
// throw new WebApplicationException(ex);
// }
//
// Arrays
// .stream(beanInfo.getPropertyDescriptors())
// .forEach(
// propertyDesc -> setComponentPropertyFromJson(componentModel,
// propertyDesc,
// data));
}
/**
* Helper emthod for setting a property of a {@link ComponentModel} using a
* value from JSON data.
*
* @param componentModel The {@link ComponentModel}
* @param propertyDesc The {@link PropertyDescriptor} for the property to
* set.
* @param data The JSON data containing the new value of the
* property.
*/
private void setComponentPropertyFromJson(
final ComponentModel componentModel,
final PropertyDescriptor propertyDesc,
final JsonObject data) {
// Ignore key and type (handled by other methods).
if ("key".equals(propertyDesc.getName())
|| "type".equals(propertyDesc.getName())) {
return;
}
if (data.containsKey(propertyDesc.getName())) {
final Method writeMethod = propertyDesc.getWriteMethod();
final Class<?> propertyType = propertyDesc.getPropertyType();
if (writeMethod != null) {
try {
// final String value = data.getString(propertyDesc.getName());
final JsonValue value = data.get(propertyDesc.getName());
// final JsonValue.ValueType valueType = value.getValueType();
if (propertyType == Boolean.TYPE) {
writeMethod.invoke(
componentModel,
Boolean.parseBoolean(value.toString()));
} else if (propertyType == Double.TYPE) {
writeMethod.invoke(
componentModel,
Double.parseDouble(value.toString()));
} else if (propertyType == Float.TYPE) {
writeMethod.invoke(componentModel,
Float.parseFloat(value.toString()));
} else if (propertyType == Integer.TYPE) {
writeMethod.invoke(componentModel,
Integer.parseInt(value.toString()));
} else if (propertyType == Long.TYPE) {
writeMethod.invoke(componentModel,
Long.parseLong(value.toString()));
} else if (propertyType == String.class) {
writeMethod.invoke(componentModel, value.toString());
} else if (propertyType == List.class) {
final JsonValue valueObj = data
.get(propertyDesc.getName());
if (valueObj.getValueType()
== JsonValue.ValueType.ARRAY) {
final JsonArray dataArray = data
.getJsonArray(propertyDesc.getName());
final List<String> values = dataArray
.stream()
.map(jsonValue -> jsonValue.toString())
.collect(Collectors.toList());
writeMethod.invoke(componentModel, values);
} else {
String valueStr = value.toString();
if (valueStr.startsWith("[")) {
valueStr = valueStr.substring(1);
}
if (valueStr.endsWith("]")) {
valueStr = valueStr
.substring(valueStr.length() - 1);
}
final String[] tokens = valueStr.split(",");
final List<String> values = Arrays
.stream(tokens)
.map(token -> token.trim())
.collect(Collectors.toList());
writeMethod.invoke(componentModel, values);
}
} else {
throw new IllegalArgumentException(
"Unsupported property type.");
}
} catch (IllegalAccessException
| InvocationTargetException ex) {
throw new WebApplicationException(ex);
}
}
}
}
private Optional<ComponentModelJsonConverter>
findJsonConverter(
final Class<? extends ComponentModel> componentModelClass) {
final ConvertsComponentModelLiteral literal
= new ConvertsComponentModelLiteral(
componentModelClass);
final Instance<ComponentModelJsonConverter> instance = jsonConverters
.select(literal);
if (instance.isUnsatisfied()) {
return Optional.empty();
} else if (instance.isAmbiguous()) {
throw new IllegalStateException(String.format(
"Multiple JSONConverter for \"%s\".",
componentModelClass.getName()));
} else {
final Iterator<ComponentModelJsonConverter> iterator = instance
.iterator();
@SuppressWarnings("unchecked")
final ComponentModelJsonConverter converter = iterator.next();
return Optional.of(converter);
}
}
private static class ConvertsComponentModelLiteral
extends AnnotationLiteral<ConvertsComponentModel>
implements ConvertsComponentModel {
private static final long serialVersionUID = 1L;
private final Class<? extends ComponentModel> componentModel;
public ConvertsComponentModelLiteral(
final Class<? extends ComponentModel> componentModel) {
this.componentModel = componentModel;
}
@Override
public Class<? extends ComponentModel> componentModel() {
return componentModel;
}
}
}

View File

@ -1,253 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.rs;
import org.libreccm.core.CoreConstants;
import org.libreccm.pagemodel.ContainerModel;
import org.libreccm.pagemodel.ContainerModelRepository;
import org.libreccm.pagemodel.PageModel;
import org.libreccm.pagemodel.PageModelManager;
import org.libreccm.security.AuthorizationRequired;
import org.libreccm.security.RequiresPrivilege;
import org.libreccm.web.CcmApplication;
import java.util.Optional;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
/**
* Provides RESTful endpoints for managing the {@link ContainerModel}s of a
* {@link PageModel}
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@Path("/")
public class Containers {
@Inject
private PageModelsController controller;
@Inject
private ContainerModelRepository containerModelRepo;
@Inject
private PageModelManager pageModelManager;
/**
* Retrieves all {@link ContainerModel}s of a {@link PageModel}.
*
* @param appPath The primary URL of the {@link CcmApplication} to
* which the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} of which the
* containers are retrieved.
*
* @return A JSON array containing the data of all {@link ContainerModel}s
* of the {@link PageModel} identified by {@code pageModelName} of
* the {@link CcmApplication} with the primary URL {@code appPath}.
*/
@GET
@Path(PageModelsApp.CONTAINERS_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonArray getContainers(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName) {
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
pageModel
.getContainers()
.stream()
.map(containerModel -> mapContainerModelToJson(containerModel))
.forEach(arrayBuilder::add);
return arrayBuilder.build();
}
/**
* Retrieve a specific {@link ContainerModel}.
*
* @param appPath The primary URL of the {@link CcmApplication} to
* which the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param containerKey The value of the {@link ContainerModel#key} property
* of the {@link ContainerModel} to retrieve.
*
* @return A JSON object containing the data of the {@link PageModel}.
*/
@GET
@Path(PageModelsApp.CONTAINER_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject getContainer(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey) {
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final ContainerModel container = controller.findContainer(app,
pageModel,
containerKey);
return mapContainerModelToJson(container);
}
/**
* Creates or updates a {@link ContainerModel}. If there is already a
* {@link ContainerModel} for the container identified by the provided
* {@code containerKey}, {@code pageModelName} and {@code appPath} the
* {@link ContainerModel} is updated with the data from the
* {@link JsonObject} {@code containerModelData}.
*
* If there is no such {@link ContainerModel} a new {@link ContainerModel}
* is created using the data provided by {@code containerModelData}.
*
* @param appPath The path of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key identifying the {@link ContainerModel}.
* @param containerModelData The data for updating or creating the
* {@link ContainerModel}.
*
* @return The new or updated {@link ContainerModel}.
*/
@PUT
@Path(PageModelsApp.CONTAINER_PATH)
@Consumes("application/json; charset=utf-8")
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject putContainer(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
final JsonObject containerModelData) {
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final Optional<ContainerModel> result = pageModel
.getContainers()
.stream()
.filter(model -> model.getKey().equals(containerKey))
.findAny();
final ContainerModel containerModel;
if (result.isPresent()) {
containerModel = result.get();
result.get().setKey(containerKey);
containerModelRepo.save(result.get());
} else {
containerModel = new ContainerModel();
containerModel.setKey(containerKey);
pageModelManager.addContainerModel(pageModel, containerModel);
}
return mapContainerModelToJson(containerModel);
}
/**
* Deletes the {@link ContainerModel} identified by the provided parameters.
*
* @param appPath The path of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key identifying the {@link ContainerModel} to
* delete.
*/
@DELETE
@Path(PageModelsApp.CONTAINER_PATH)
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void deleteContainer(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey) {
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final ContainerModel container = controller.findContainer(app,
pageModel,
containerKey);
pageModelManager.removeContainerModel(pageModel, container);
}
/**
* Helper method for mapping a {@link ContainerModel} to JSON:
*
* @param containerModel The {@link ContainerModel} to map.
*
* @return A {@link JsonObject} containing the data of the
* {@link ContainerModel}.
*/
private JsonObject mapContainerModelToJson(
final ContainerModel containerModel) {
return Json
.createObjectBuilder()
.add("containerId", Long.toString(containerModel.getContainerId()))
.add("uuid", containerModel.getUuid())
.add("containerUuid", containerModel.getContainerUuid())
.add("key", containerModel.getKey())
.build();
}
}

View File

@ -1,383 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.rs;
import com.arsdigita.kernel.KernelConfig;
import org.libreccm.configuration.ConfigurationManager;
import org.libreccm.core.CoreConstants;
import org.libreccm.l10n.GlobalizationHelper;
import org.libreccm.pagemodel.ComponentModel;
import org.libreccm.pagemodel.ContainerModel;
import org.libreccm.pagemodel.PageModel;
import org.libreccm.pagemodel.PageModelManager;
import org.libreccm.pagemodel.PageModelRepository;
import org.libreccm.security.AuthorizationRequired;
import org.libreccm.security.RequiresPrivilege;
import org.libreccm.web.CcmApplication;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Provides RESTful endpoints for retrieving, creating, updating and deleting
* {@link PageModels}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@Path("/")
public class PageModels {
@Inject
private PageModelsController controller;
@Inject
private PageModelManager pageModelManager;
@Inject
private PageModelRepository pageModelRepo;
@Inject
private GlobalizationHelper globalizationHelper;
@Inject
private ConfigurationManager confManager;
/**
* Retrieves all {@link PageModel}s available for an {@link
* CcmApplication}.
*
* @param appPath The path of the {@code app}.
*
* @return A JSON array with the data of all {@link PageModel}s of the
* {@link CcmApplication} {@code app}.
*
* @throws NotFoundException If there is no {@link CcmApplication} with the
* primary URL {@code appPath} an {@link
* NotFoundException} thrown resulting in 404
* response.
*/
@GET
@Path(PageModelsApp.PAGE_MODELS_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonArray getAllPageModels(
@PathParam(PageModelsApp.APP_NAME) String appPath) {
Objects.requireNonNull(appPath);
final CcmApplication app = controller
.findCcmApplication(String.format("/%s/", appPath));
final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
pageModelRepo
.findDraftByApplication(app)
.stream()
.map(this::mapPageModelToJson)
.forEach(arrayBuilder::add);
return arrayBuilder.build();
}
/**
* Retrieves a specific {@link PageModel}.
*
* @param appPath The path ({@link CcmApplication#primaryUrl} of the
* {@link CcmApplication} to which the {@link
* PageModel} belongs (see
* {@link PageModel#application}).
* @param pageModelName The name of the {@link PageModel} to retrieve (see
* {@link PageModel#name}).
*
* @return A JSON object containing the data of the {@link PageModel}.
*
* @throws NotFoundException If there is not {@link CcmApplication} with the
* primary URL {@code appPath} a {@link
* NotFoundException} is thrown resulting in a 404
* response. A {@link NotFoundException} is also
* thrown if there no {@link PageModel} identified
* by {@code pageModelName} for the {@link
* CcmApplication} with the primary URL {@code
* appPath}.
*/
@GET
@Path(PageModelsApp.PAGE_MODEL_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject getPageModel(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
final CcmApplication app = controller
.findCcmApplication(String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
return mapPageModelToJson(pageModel);
}
@POST
@Path(PageModelsApp.PAGE_MODEL_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject publishPageModel(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@FormParam("action") String action) {
if ("publish".equals(action)) {
final CcmApplication app = controller
.findCcmApplication(String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
pageModelManager.publish(pageModel);
}
return getPageModel(appPath, pageModelName);
}
/**
* Creates or updates a {@link PageModel}.
*
* If a {@link PageModel} with the name {@code pageModelName} already exists
* for the {@link CcmApplication} with the primary URL {@code appPath} the
* {@link PageModel} is updated. If there is no such {@link PageModel} a new
* {@link PageModel} is created and associated with the {@link
* CcmApplication} identified by the primary URL {@code appPath}.
*
* @param appPath The primary URL of the {@link CcmApplication} to
* which the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel}.
* @param pageModelData The data for creating or updating the {@link
* PageModel}.
*
* @return The new or updated {@link PageModel}.
*/
@PUT
@Path(PageModelsApp.PAGE_MODEL_PATH)
@Consumes("application/json; charset=utf-8")
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject putPageModel(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
final JsonObject pageModelData) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
final CcmApplication app = controller
.findCcmApplication(String.format("/%s/", appPath));
final KernelConfig kernelConfig = confManager
.findConfiguration(KernelConfig.class);
final PageModel pageModel;
if (controller.existsPageModel(app, pageModelName)) {
pageModel = controller.findPageModel(app, pageModelName);
} else {
pageModel = pageModelManager.createPageModel(pageModelName, app);
}
if (pageModelData.containsKey("title")) {
pageModel.getTitle().putValue(kernelConfig.getDefaultLocale(),
pageModelData.getString("title"));
}
if (pageModelData.containsKey("description")) {
pageModel
.getDescription()
.putValue(kernelConfig.getDefaultLocale(),
pageModelData.getString("description"));
}
controller.savePageModel(pageModel);
return mapPageModelToJson(pageModel);
}
/**
* Deletes a {@link PageModel}.
*
* @param appPath The primary URL of the {@link CcmApplication} to
* which the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to delete.
*/
@DELETE
@Path(PageModelsApp.PAGE_MODEL_PATH)
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void deletePageModel(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
final CcmApplication app = controller
.findCcmApplication(String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
pageModelRepo.delete(pageModel);
}
/**
* Helper method for mapping a {@link PageModel} object to JSON:
*
* @param pageModel The {@link PageModel} to map.
*
* @return A {@link JsonObject} object with the data of the provided {@link
* PageModel}.
*/
private JsonObject mapPageModelToJson(final PageModel pageModel) {
Objects.requireNonNull(pageModel);
final long lastPublished;
final Optional<PageModel> liveModel = pageModelManager
.getLiveVersion(pageModel);
if (liveModel.isPresent()
&& liveModel.get().getLastModified() != null) {
lastPublished = liveModel.get().getLastModified().getTime();
} else {
lastPublished = 0;
}
final long lastModified;
if (pageModel.getLastModified() == null) {
lastModified = 0;
} else {
lastModified = pageModel.getLastModified().getTime();
}
return Json
.createObjectBuilder()
.add("containers", mapContainersToJson(pageModel))
.add("description",
globalizationHelper
.getValueFromLocalizedString(pageModel.getDescription()))
.add("modelUuid", pageModel.getModelUuid())
.add("name", pageModel.getName())
.add("pageModelId", Long.toString(pageModel.getPageModelId()))
.add("title",
globalizationHelper
.getValueFromLocalizedString(pageModel.getTitle()))
.add("type", pageModel.getType())
.add("uuid", pageModel.getUuid())
.add("version", pageModel.getVersion().toString())
.add("publicationStatus",
getPublicationStatus(pageModel).toString())
.add("lastModified", lastModified)
.add("lastPublished", lastPublished)
.build();
}
private JsonArray mapContainersToJson(final PageModel pageModel) {
final JsonArrayBuilder containers = Json.createArrayBuilder();
pageModel
.getContainers()
.stream()
.map(this::mapContainerToJson)
.forEach(container -> containers.add(container));
return containers.build();
}
private JsonObject mapContainerToJson(final ContainerModel container) {
return Json
.createObjectBuilder()
.add("containerUuid", container.getContainerUuid())
.add("key", container.getKey())
.add("uuid", container.getUuid())
.build();
}
/**
* Check if the {@link PublicationStatus} of the provided PageModel.
*
* @param pageModel
*
* @return
*/
private PublicationStatus getPublicationStatus(final PageModel pageModel) {
final PageModel draftModel = pageModelManager
.getDraftVersion(pageModel);
final Optional<PageModel> liveModel = pageModelManager
.getLiveVersion(pageModel);
final PublicationStatus publicationStatus;
if (liveModel.isPresent()) {
// Fallback if one the last modified dates is null
if (draftModel.getLastModified() == null
|| liveModel.get().getLastModified() == null) {
return PublicationStatus.NEEDS_UPDATE;
} else if (draftModel
.getLastModified()
.before(liveModel.get().getLastModified())) {
publicationStatus = PublicationStatus.PUBLISHED;
} else {
publicationStatus = PublicationStatus.NEEDS_UPDATE;
}
} else {
publicationStatus = PublicationStatus.NOT_PUBLISHED;
}
return publicationStatus;
}
}

View File

@ -1,88 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.rs;
import org.libreccm.pagemodel.PageModel;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Application;
/**
* JAX-RS application for managing {@link PageModel}s.
*
* The several paths used by the classes of this JAX-RS application are defined
* in this class as string constants to avoid problems. Some other parts which
* specific to one of the classes are might defined in that class.
*
* All methods providing RESTful endpoints will throw a
* {@link NotFoundException} if one the objects in their path is not found. If
* this is the case the application server will send a 404 response to the
* client.
*
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@ApplicationPath("/page-models")
public class PageModelsApp extends Application {
protected static final String APP_NAME = "appName";
protected static final String PAGE_MODEL_NAME = "pageModelName";
protected static final String CONTAINER_KEY = "containerKey";
protected static final String COMPONENT_KEY = "componentKey";
protected static final String PAGE_MODELS_PATH = "/{" + APP_NAME + "}";
protected static final String PAGE_MODEL_PATH = PAGE_MODELS_PATH
+ "/{"
+ PAGE_MODEL_NAME
+ "}";
protected static final String CONTAINERS_PATH = PAGE_MODEL_PATH
+ "/containers";
protected static final String CONTAINER_PATH = CONTAINERS_PATH
+ "/{"
+ CONTAINER_KEY
+ "}";
protected static final String COMPONENTS_PATH = CONTAINER_PATH
+ "/components";
protected static final String COMPONENT_PATH = COMPONENTS_PATH
+ "/{"
+ COMPONENT_KEY
+ "}";
protected static final String STYLES_PATH = CONTAINER_PATH + "/styles";
@Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<>();
classes.add(PageModels.class);
classes.add(Containers.class);
classes.add(Components.class);
classes.add(StylesRs.class);
classes.add(StylesMediaRule.class);
classes.add(StylesRule.class);
return classes;
}
}

View File

@ -1,181 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.rs;
import org.libreccm.pagemodel.ComponentModel;
import org.libreccm.pagemodel.ComponentModelRepository;
import org.libreccm.pagemodel.ContainerModel;
import org.libreccm.pagemodel.ContainerModelRepository;
import org.libreccm.pagemodel.PageModel;
import org.libreccm.pagemodel.PageModelRepository;
import org.libreccm.web.ApplicationRepository;
import org.libreccm.web.CcmApplication;
import java.util.Objects;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.NotFoundException;
/**
* A helper class providing some functionality used by the JAX-RS classes in
* this package.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
class PageModelsController {
@Inject
private ApplicationRepository appRepo;
@Inject
private ComponentModelRepository componentModelRepo;
@Inject
private ContainerModelRepository containerRepo;
@Inject
private PageModelRepository pageModelRepo;
/**
* Finds a {@link CcmApplication} using its {@code primaryUrl}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
*
* @return The {@link CcmApplication} with the provided primary URL.
*/
@Transactional(Transactional.TxType.REQUIRED)
protected CcmApplication findCcmApplication(final String appPath) {
return appRepo
.retrieveApplicationForPath(Objects.requireNonNull(appPath))
.orElseThrow(() -> new NotFoundException(String
.format("No application with path \"%s\" found.",
appPath)));
}
/**
* Finds a {@link ComponentModel} using its {@code componentKey}.
*
* @param app The {@link CcmApplication}.
* @param pageModel The {@link PageModel}.
* @param containerModel The {@link ContainerModel}.
* @param componentKey The key the {@link ComponentModel}.
*
* @return The {@link ComponentModel} identified by the provided
* {@code componentKey}.
*/
@Transactional(Transactional.TxType.REQUIRED)
protected ComponentModel findComponentModel(
final CcmApplication app,
final PageModel pageModel,
final ContainerModel containerModel,
final String componentKey) {
return componentModelRepo
.findComponentByContainerAndKey(containerModel, componentKey)
.orElseThrow(() -> new NotFoundException(String
.format(
"The Container \"%s\" of the PageModel \"%s\" of application"
+ "\"%s\" does not contain a component with the key \"%s\".",
containerModel.getKey(),
pageModel.getName(),
app.getPrimaryUrl(),
componentKey)));
}
/**
* Finds a {@link ContainerModel} using its {@code containerKey}.
*
* @param app The {@link CcmApplication}.
* @param pageModel The {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
*
* @return The {@link ContainerModel} identified by the provided
* {@code containerKey}.
*/
@Transactional(Transactional.TxType.REQUIRED)
protected ContainerModel findContainer(final CcmApplication app,
final PageModel pageModel,
final String containerKey) {
return containerRepo
.findContainerByKeyAndPageModel(
Objects.requireNonNull(containerKey),
Objects.requireNonNull(pageModel))
.orElseThrow(() -> new NotFoundException(String
.format("The PageModel \"%s\" of application \"%s\" does not have "
+ "a container identified by the key \"%s\".",
pageModel.getName(),
app.getPrimaryUrl(),
containerKey)));
}
/**
* Determines if a {@link PageModel} with the provided name exists for the
* provided {@link CcmApplication}.
*
* @param app The {@link CcmApplication} to which the
* {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel}.
*
* @return {@code true} if a {@link PageModel} with the name provided by the
* parameter {@code pageModelName} exists for the provided
* {@link CcmApplication} {@code app}, {@code false} otherwise.
*/
@Transactional(Transactional.TxType.REQUIRED)
protected boolean existsPageModel(final CcmApplication app,
final String pageModelName) {
return pageModelRepo
.findDraftByApplicationAndName(app, pageModelName)
.isPresent();
}
/**
* Finds a {@link PageModel} using its name.
*
* @param app The {@link CcmApplication} to which the
* {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to retrieve.
*
* @return The {@link PageModel} identified by the name
* {@code pageModelName} for the {@link CcmApplication} {@code app}.
*/
@Transactional(Transactional.TxType.REQUIRED)
protected PageModel findPageModel(final CcmApplication app,
final String pageModelName) {
return pageModelRepo
.findDraftByApplicationAndName(
Objects.requireNonNull(app),
Objects.requireNonNull(pageModelName))
.orElseThrow(() -> new NotFoundException(String.format(
"No PageModel with name \"%s\" for application \"%s\".",
pageModelName, app.getPrimaryUrl())));
}
@Transactional(Transactional.TxType.REQUIRED)
protected void savePageModel(final PageModel pageModel) {
pageModelRepo.save(pageModel);
}
}

View File

@ -1,10 +0,0 @@
package org.libreccm.pagemodel.rs;
@Deprecated
public enum PublicationStatus {
NOT_PUBLISHED,
PUBLISHED,
NEEDS_UPDATE,
}

View File

@ -1,201 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.rs;
import org.libreccm.pagemodel.styles.CssProperty;
import org.libreccm.pagemodel.styles.Dimension;
import org.libreccm.pagemodel.styles.MediaQuery;
import org.libreccm.pagemodel.styles.MediaRule;
import org.libreccm.pagemodel.styles.Rule;
import java.util.List;
import java.util.Objects;
import javax.enterprise.context.RequestScoped;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
/**
* Utility class for mapping the entities from the
* {@link org.libreccm.pagemodel.styles} package to JSON.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
class StylesJsonMapper {
/**
* Map a {@link Dimension} object to JSON.
*
* @param dimension The {@link Dimension} object to map.
*
* @return A JSON object representing the provided {@link Dimension} object.
*/
protected JsonObject mapDimensionToJson(final Dimension dimension) {
Objects.requireNonNull(dimension);
return Json
.createObjectBuilder()
.add("value", dimension.getValue())
.add("unit", dimension.getUnit().toString())
.build();
}
/**
* Maps a List of {@link MediaRule} objects to JSON.
*
* @param mediaRules The {@link MediaRule}s to map.
*
* @return An JSON array with the data from the {@link MediaRule} objects in
* the list.
*/
protected JsonArray mapMediaRulesToJson(final List<MediaRule> mediaRules) {
final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
Objects
.requireNonNull(mediaRules)
.stream()
.map(this::mapMediaRuleToJson)
.forEach(arrayBuilder::add);
return arrayBuilder.build();
}
/**
* Maps a {@link MediaRule} object to JSON.
*
* @param mediaRule The {@link MediaRule} object to map.
*
* @return The JSON representation of the provided {@link MediaRule} object.
*/
protected JsonObject mapMediaRuleToJson(final MediaRule mediaRule) {
Objects.requireNonNull(mediaRule);
return Json
.createObjectBuilder()
.add("mediaRuleId", mediaRule.getMediaRuleId())
.add("mediaQuery", mapMediaQueryToJson(mediaRule.getMediaQuery()))
.add("rules", mapRulesToJson(mediaRule.getRules()))
.build();
}
/**
* Maps a {@link MediaQuery} object to JSON.
*
* @param mediaQuery The {@link MediaQuery} object to map.
*
* @return The JSON representation of the provided {@link MediaQuery}
* object.
*/
protected JsonObject mapMediaQueryToJson(final MediaQuery mediaQuery) {
Objects.requireNonNull(mediaQuery);
return Json
.createObjectBuilder()
.add("mediaQueryId", mediaQuery.getMediaQueryId())
.add("mediaType", mediaQuery.getMediaType().toString())
.add("minWidth", mapDimensionToJson(mediaQuery.getMinWidth()))
.add("maxWidth", mapDimensionToJson(mediaQuery.getMaxWidth()))
.build();
}
/**
* Maps a list of {@link Rule} objects to JSON.
*
* @param rules The list of {@link Rule} objects to map.
*
* @return A JSON array with the JSON representations of the {@link Rule}
* objects in the list.
*/
protected JsonArray mapRulesToJson(final List<Rule> rules) {
final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
Objects
.requireNonNull(rules)
.stream()
.map(this::mapRuleToJson)
.forEach(arrayBuilder::add);
return arrayBuilder.build();
}
/**
* Maps a {@link Rule} object to JSON.
*
* @param rule The {@link Rule} object to map.
*
* @return The JSON representation of the provided {@link RuleObject}.
*/
protected JsonObject mapRuleToJson(final Rule rule) {
Objects.requireNonNull(rule);
return Json
.createObjectBuilder()
.add("ruleId", rule.getRuleId())
.add("selector", rule.getSelector())
.add("properties", mapPropertiesToJson(rule.getProperties()))
.build();
}
/**
* Maps a list of {@link CssProperty} objects to JSON.
*
* @param properties The list of {@link CssProperty} objects to map.
*
* @return A JSON array containing the JSON representations of the
* {@link CssProperty} objects in the list.
*/
protected JsonArray mapPropertiesToJson(final List<CssProperty> properties) {
final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
Objects
.requireNonNull(properties)
.stream()
.map(this::mapCssPropertyToJson)
.forEach(arrayBuilder::add);
return arrayBuilder.build();
}
/**
* Maps a {@link CssProperty} object to JSON.
*
* @param property The {@link CssProperty} to map.
* @return The JSON representation of the provided {@link CssProperty}.
*/
protected JsonObject mapCssPropertyToJson(final CssProperty property) {
Objects.requireNonNull(property);
return Json
.createObjectBuilder()
.add("propertyId", property.getPropertyId())
.add("name", property.getName())
.add("value", property.getValue())
.build();
}
}

View File

@ -1,623 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.rs;
import org.libreccm.core.CoreConstants;
import org.libreccm.pagemodel.ContainerModel;
import org.libreccm.pagemodel.styles.CssProperty;
import org.libreccm.pagemodel.styles.MediaRule;
import org.libreccm.pagemodel.styles.Rule;
import org.libreccm.pagemodel.styles.StylesManager;
import org.libreccm.pagemodel.styles.StylesRepository;
import org.libreccm.security.AuthorizationRequired;
import org.libreccm.security.RequiresPrivilege;
import org.libreccm.web.CcmApplication;
import java.io.Serializable;
import java.util.Objects;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
/**
* Provides RESTful endpoints for retrieving, creating, updating and deleting
* {@link MediaRule}s.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@Path(StylesRs.MEDIA_RULE_PATH)
public class StylesMediaRule implements Serializable {
private static final long serialVersionUID = 3257114872624583807L;
protected final static String PROPERTY_ID = "propertyId";
protected final static String RULE_ID = "ruleId";
protected final static String RULES_PATH = "/rules";
protected final static String RULE_PATH = RULES_PATH
+ "/{"
+ RULE_ID
+ "}";
protected final static String PROPERTIES_PATH = RULE_PATH + "/properties";
protected final static String PROPERTY_PATH = PROPERTIES_PATH
+ "/{"
+ PROPERTY_ID
+ "}";
@Inject
private StylesJsonMapper stylesJsonMapper;
@Inject
private StylesManager stylesManager;
@Inject
private StylesRepository stylesRepo;
@Inject
private StylesRs stylesRs;
/**
* Retrieves all {@link Rule}s of a {@link MediaRule}.
*
* @param appPath The path of the {@link CcmApplication} to which
* the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param containerKey The key of the {@link ContainerModel} to which
* the {@link MediaRule} belongs.
* @param mediaRuleIdParam The ID of the {@link MediaRule}.
*
* @return A JSON array with the JSON representations of all {@link Rule}s
* belonging the {@link MediaRule} identified by the provided path.
*/
@GET
@Path(RULES_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonArray getRules(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(StylesRs.MEDIA_RULE_ID) final String mediaRuleIdParam) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(mediaRuleIdParam);
final MediaRule mediaRule = stylesRs.findMediaRule(appPath,
pageModelName,
containerKey,
mediaRuleIdParam);
return stylesJsonMapper.mapRulesToJson(mediaRule.getRules());
}
/**
* Retrieves a specific {@link Rule} from a {@link MediaRule}.
*
* @param appPath The path of the {@link CcmApplication} to which
* the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param containerKey The key of the {@link ContainerModel} to which
* the {@link MediaRule} belongs.
* @param mediaRuleIdParam The ID of the {@link MediaRule}.
* @param ruleIdParam The ID of the {@link Rule} to retrieve.
*
* @return The JSON representation of the {@link Rule} identified by the
* provided path.
*/
@GET
@Path(RULE_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject getRule(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(StylesRs.MEDIA_RULE_ID) final String mediaRuleIdParam,
@PathParam(RULE_ID) String ruleIdParam) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(mediaRuleIdParam);
Objects.requireNonNull(ruleIdParam);
final MediaRule mediaRule = stylesRs.findMediaRule(appPath,
pageModelName,
containerKey,
mediaRuleIdParam);
return stylesJsonMapper.mapRuleToJson(findRule(mediaRule,
ruleIdParam));
}
/**
* Creates a new {@link Rule} for a {@link MediaRule}.
*
* @param appPath The path of the {@link CcmApplication} to which
* the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param containerKey The key of the {@link ContainerModel} to which
* the {@link MediaRule} belongs.
* @param mediaRuleIdParam The ID of the {@link MediaRule}.
* @param ruleData The data from which the new {@link Rule} is
* created.
*
* @return The JSON representation of the new {@link Rule}.
*/
@POST
@Path(RULES_PATH)
@Consumes("application/json; charset=utf-8")
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject createRule(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(StylesRs.MEDIA_RULE_ID) final String mediaRuleIdParam,
final JsonObject ruleData) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(mediaRuleIdParam);
Objects.requireNonNull(ruleData);
final MediaRule mediaRule = stylesRs.findMediaRule(appPath,
pageModelName,
containerKey,
mediaRuleIdParam);
final Rule rule = new Rule();
rule.setSelector(ruleData.getString("selector"));
stylesManager.addRuleToMediaRule(rule, mediaRule);
return stylesJsonMapper.mapRuleToJson(rule);
}
/**
* Updates an existing {@link Rule}
*
* @param appPath The path of the {@link CcmApplication} to which
* the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param containerKey The key of the {@link ContainerModel} to which
* the {@link MediaRule} belongs.
* @param mediaRuleIdParam The ID of the {@link MediaRule}.
* @param ruleIdParam The ID of the {@link Rule} to update.
* @param ruleData The data from which used to update the
* {@link Rule}.
*
* @return The JSON representation of the updated {@link Rule}.
*/
@PUT
@Path(RULE_PATH)
@Consumes("application/json; charset=utf-8")
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject updateRule(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(StylesRs.MEDIA_RULE_ID) final String mediaRuleIdParam,
@PathParam(RULE_ID) String ruleIdParam,
final JsonObject ruleData) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(mediaRuleIdParam);
Objects.requireNonNull(ruleIdParam);
Objects.requireNonNull(ruleData);
final MediaRule mediaRule = stylesRs.findMediaRule(appPath,
pageModelName,
containerKey,
mediaRuleIdParam);
final Rule rule = findRule(mediaRule, ruleIdParam);
rule.setSelector(ruleData.getString("selector"));
stylesManager.addRuleToMediaRule(rule, mediaRule);
return stylesJsonMapper.mapRuleToJson(rule);
}
@DELETE
@Path(RULE_PATH)
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void deleteRule(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(StylesRs.MEDIA_RULE_ID) final String mediaRuleIdParam,
@PathParam(RULE_ID) String ruleIdParam) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(mediaRuleIdParam);
Objects.requireNonNull(ruleIdParam);
final MediaRule mediaRule = stylesRs.findMediaRule(appPath,
pageModelName,
containerKey,
mediaRuleIdParam);
final Rule rule = findRule(mediaRule, ruleIdParam);
stylesManager.removeRuleFromMediaRule(rule, mediaRule);
stylesRepo.deleteRule(rule);
}
/**
* Retrieves all {@link CssProperty} objects assigned to {@link Rule} which
* is assigned to {@link MediaRule}.
*
* @param appPath The path of the {@link CcmApplication} to which
* the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param containerKey The key of the {@link ContainerModel} to which
* the {@link MediaRule} belongs.
* @param mediaRuleIdParam The ID of the {@link MediaRule}.
* @param ruleIdParam The ID of the {@link Rule} from which the
* {@link CssProperty} objects are retrieved.
*
* @return A JSON array with the JSON representations of the
* {@link CssProperty} objects.
*/
@GET
@Path(PROPERTIES_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonArray getProperties(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(StylesRs.MEDIA_RULE_ID) final String mediaRuleIdParam,
@PathParam(RULE_ID) String ruleIdParam) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(mediaRuleIdParam);
Objects.requireNonNull(ruleIdParam);
final MediaRule mediaRule = stylesRs.findMediaRule(appPath,
pageModelName,
containerKey,
mediaRuleIdParam);
final Rule rule = findRule(mediaRule, ruleIdParam);
return stylesJsonMapper.mapPropertiesToJson(rule.getProperties());
}
/**
* Retrieve a {@link CssProperty} assigned to {@link Rule} which is assigned
* to {@link MediaRule}.
*
* @param appPath The path of the {@link CcmApplication} to which
* the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param containerKey The key of the {@link ContainerModel} to which
* the {@link MediaRule} belongs.
* @param mediaRuleIdParam The ID of the {@link MediaRule}.
* @param ruleIdParam The ID of the {@link Rule} from which the
* {@link CssProperty} is retrieved.
* @param propertyIdParam The ID of the {@link CssProperty} to retrieve.
*
* @return The JSON representation of the {@link CssProperty} identified by
* the provided path.
*/
@GET
@Path(PROPERTY_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject getProperty(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(StylesRs.MEDIA_RULE_ID) final String mediaRuleIdParam,
@PathParam(RULE_ID) final String ruleIdParam,
@PathParam(PROPERTY_ID) final String propertyIdParam) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(mediaRuleIdParam);
Objects.requireNonNull(ruleIdParam);
Objects.requireNonNull(propertyIdParam);
final MediaRule mediaRule = stylesRs.findMediaRule(appPath,
pageModelName,
containerKey,
mediaRuleIdParam);
final Rule rule = findRule(mediaRule, ruleIdParam);
final CssProperty property = findProperty(rule, propertyIdParam);
return stylesJsonMapper.mapCssPropertyToJson(property);
}
/**
* Creates a new {@link CssProperty} for a {@link Rule} of a
* {@link MediaRule}.
*
* @param appPath The path of the {@link CcmApplication} to which
* the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param containerKey The key of the {@link ContainerModel} to which
* the {@link MediaRule} belongs.
* @param mediaRuleIdParam The ID of the {@link MediaRule}.
* @param ruleIdParam The ID of the {@link Rule} for which the new
* {@link CssProperty} is created.
* @param propertyData The data from which the new {@link CssProperty}
* is created.
*
* @return The JSON representation of the new {@link CssProperty}.
*/
@POST
@Path(PROPERTIES_PATH)
@Consumes("application/json; charset=utf-8")
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject createProperty(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(StylesRs.MEDIA_RULE_ID) final String mediaRuleIdParam,
@PathParam(RULE_ID) String ruleIdParam,
final JsonObject propertyData) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(mediaRuleIdParam);
Objects.requireNonNull(ruleIdParam);
Objects.requireNonNull(propertyData);
final MediaRule mediaRule = stylesRs.findMediaRule(appPath,
pageModelName,
containerKey,
mediaRuleIdParam);
final Rule rule = findRule(mediaRule, ruleIdParam);
final CssProperty property = new CssProperty();
setCssPropertyData(property, propertyData);
stylesManager.addCssPropertyToRule(property, rule);
return stylesJsonMapper.mapCssPropertyToJson(property);
}
/**
* Updates an existing {@link CssProperty} of {@link Rule} of a
* {@link MediaRule}.
*
* @param appPath The path of the {@link CcmApplication} to which
* the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param containerKey The key of the {@link ContainerModel} to which
* the {@link MediaRule} belongs.
* @param mediaRuleIdParam The ID of the {@link MediaRule}.
* @param ruleIdParam The ID of the {@link Rule} to which the
* {@link CssProperty} belongs.
* @param propertyIdParam The ID of the {@link CssProperty} to update.
* @param propertyData The data which is used to update the
* {@link CssProperty}.
*
* @return The JSON representation of the updated {@link CssProperty}.
*/
@PUT
@Path(PROPERTY_PATH)
@Consumes("application/json; charset=utf-8")
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject updateProperty(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(StylesRs.MEDIA_RULE_ID) final String mediaRuleIdParam,
@PathParam(RULE_ID) String ruleIdParam,
@PathParam(PROPERTY_ID) final String propertyIdParam,
final JsonObject propertyData) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(mediaRuleIdParam);
Objects.requireNonNull(ruleIdParam);
Objects.requireNonNull(propertyIdParam);
Objects.requireNonNull(propertyData);
final MediaRule mediaRule = stylesRs.findMediaRule(appPath,
pageModelName,
containerKey,
mediaRuleIdParam);
final Rule rule = findRule(mediaRule, ruleIdParam);
final CssProperty property = findProperty(rule, propertyIdParam);
setCssPropertyData(property, propertyData);
stylesRepo.saveCssProperty(property);
return stylesJsonMapper.mapCssPropertyToJson(property);
}
/**
* Deletes a {@link CssProperty} of a {@link Rule} assigned to a
* {@link MediaRule}.
*
* @param appPath The path of the {@link CcmApplication} to which
* the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param containerKey The key of the {@link ContainerModel} to which
* the {@link MediaRule} belongs.
* @param mediaRuleIdParam The ID of the {@link MediaRule}.
* @param ruleIdParam The ID of the {@link Rule} to which the
* {@link CssProperty} belongs.
* @param propertyIdParam The ID of the {@link CssProperty} to delete.
*/
@DELETE
@Path(PROPERTY_PATH)
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void deleteProperty(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(StylesRs.MEDIA_RULE_ID) final String mediaRuleIdParam,
@PathParam(RULE_ID) String ruleIdParam,
@PathParam(PROPERTY_ID) final String propertyIdParam) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(mediaRuleIdParam);
Objects.requireNonNull(ruleIdParam);
Objects.requireNonNull(propertyIdParam);
final MediaRule mediaRule = stylesRs.findMediaRule(appPath,
pageModelName,
containerKey,
mediaRuleIdParam);
final Rule rule = findRule(mediaRule, ruleIdParam);
final CssProperty property = findProperty(rule, propertyIdParam);
stylesManager.removeCssPropertyFromRule(property, rule);
stylesRepo.deleteCssProperty(property);
}
/**
* Helper method for finding a {@link CssProperty}.
*
* @param rule The {@link Rule} to which the {@link CssProperty}
* belongs.
* @param propertyIdParam The ID of the {@link CssProperty} to find.
*
* @return The {@link CssProperty}.
*/
private CssProperty findProperty(final Rule rule,
final String propertyIdParam) {
final long propertyId;
try {
propertyId = Long.parseLong(propertyIdParam);
} catch (NumberFormatException ex) {
throw new WebApplicationException(ex);
}
return rule
.getProperties()
.stream()
.filter(property -> propertyId == property.getPropertyId())
.findAny()
.orElseThrow(() -> new NotFoundException());
}
/**
* Helper method for finding a {@link Rule} assigned to {@link MediaRule}.
*
* @param mediaRule The {@link MediaRule}.
* @param ruleIdParam The ID of {@link Rule} to find.
*
* @return The {@link Rule}.
*/
private Rule findRule(final MediaRule mediaRule,
final String ruleIdParam) {
final long ruleId;
try {
ruleId = Long.parseLong(ruleIdParam);
} catch (NumberFormatException ex) {
throw new WebApplicationException(ex);
}
Objects.requireNonNull(mediaRule);
return mediaRule
.getRules()
.stream()
.filter(rule -> ruleId == rule.getRuleId())
.findAny()
.orElseThrow(() -> new NotFoundException());
}
/**
* Helper method for updating the values of the properties of
* {@link CssProperty} object from its JSON representation.
*
* @param property The {@link CssProperty}.
* @param propertyData The {@link JsonObject} containing the data.
*/
private void setCssPropertyData(final CssProperty property,
final JsonObject propertyData) {
Objects.requireNonNull(property);
Objects.requireNonNull(propertyData);
property.setName(propertyData.getString("name"));
property.setValue(propertyData.getString("value"));
}
}

View File

@ -1,667 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.rs;
import org.libreccm.core.CoreConstants;
import org.libreccm.pagemodel.ContainerModel;
import org.libreccm.pagemodel.PageModel;
import org.libreccm.pagemodel.styles.Dimension;
import org.libreccm.pagemodel.styles.MediaRule;
import org.libreccm.pagemodel.styles.MediaType;
import org.libreccm.pagemodel.styles.Rule;
import org.libreccm.pagemodel.styles.Styles;
import org.libreccm.pagemodel.styles.StylesManager;
import org.libreccm.pagemodel.styles.StylesRepository;
import org.libreccm.pagemodel.styles.Unit;
import org.libreccm.security.AuthorizationRequired;
import org.libreccm.security.RequiresPrivilege;
import org.libreccm.web.CcmApplication;
import java.util.Objects;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
/**
* Provides RESTful endpoints for managing the (CSS) styles of a
* {@link ContainerModel}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@Path(PageModelsApp.STYLES_PATH)
public class StylesRs {
protected static final String MEDIA_RULE_ID = "mediaRuleId";
protected static final String RULE_ID = "ruleId";
protected static final String MEDIA_RULES_PATH = "/media-rules";
protected static final String MEDIA_RULE_PATH = MEDIA_RULES_PATH
+ "/{"
+ MEDIA_RULE_ID
+ "}";
protected static final String RULES_PATH = "/rules";
protected static final String RULE_PATH = RULES_PATH
+ "/{"
+ RULE_ID
+ "}";
@Inject
private PageModelsController controller;
@Inject
private StylesJsonMapper stylesJsonMapper;
@Inject
private StylesManager stylesManager;
@Inject
private StylesRepository stylesRepo;
/**
* Retrieves all {@link MediaRule}s from the {@link Styles} entity of a
* {@link ContainerModel}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
*
* @return The JSON Array with the JSON representations of all
* {@link MediaRule}s of the {@link ContainerModel} identified by
* the provided path.
*/
@GET
@Path(MEDIA_RULES_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonArray getMediaRules(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final ContainerModel container = controller.findContainer(app,
pageModel,
containerKey);
final Styles styles = container.getStyles();
return stylesJsonMapper.mapMediaRulesToJson(styles.getMediaRules());
}
/**
* Retrieves a specific {@link MediaRule} from the {@link Styles} entity of
* a {@link ContainerModel}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
* @param mediaRuleIdParam The ID of the {@link MediaRule} to retrieve.
*
* @return The JSON representation of the {@link MediaRule}.
*/
@GET
@Path(MEDIA_RULE_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject getMediaRule(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(MEDIA_RULE_ID) final String mediaRuleIdParam) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(mediaRuleIdParam);
return stylesJsonMapper
.mapMediaRuleToJson(findMediaRule(appPath,
pageModelName,
containerKey,
mediaRuleIdParam));
}
/**
* Creates a new {@link MediaRule}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
* @param mediaRuleData The data for the new {@link MediaRule}.
*
* @return The JSON representation of the new {@link MediaRule}.
*/
@POST
@Path(MEDIA_RULES_PATH)
@Consumes("application/json; charset=utf-8")
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject createMediaRule(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
final JsonObject mediaRuleData) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(mediaRuleData);
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final ContainerModel container = controller.findContainer(app,
pageModel,
containerKey);
final Styles styles = container.getStyles();
final MediaRule mediaRule = new MediaRule();
setMediaRuleProperties(mediaRuleData, mediaRule);
stylesManager.addMediaRuleToStyles(mediaRule, styles);
return stylesJsonMapper.mapMediaRuleToJson(mediaRule);
}
/**
* Update a {@link MediaRule}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
* @param mediaRuleIdParam The ID of the {@link MediaRule} to update.
* @param mediaRuleData The data for updating the {@link MediaRule}.
*
* @return The JSON representation of the updated {@link MediaRule}.
*/
@PUT
@Path(MEDIA_RULE_PATH)
@Consumes("application/json; charset=utf-8")
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject updateMediaRule(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(MEDIA_RULE_ID) final String mediaRuleIdParam,
final JsonObject mediaRuleData) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(mediaRuleIdParam);
Objects.requireNonNull(mediaRuleData);
final MediaRule mediaRule = findMediaRule(appPath,
pageModelName,
containerKey,
mediaRuleIdParam);
setMediaRuleProperties(mediaRuleData, mediaRule);
stylesRepo.saveMediaRule(mediaRule);
return stylesJsonMapper.mapMediaRuleToJson(mediaRule);
}
/**
* Deletes a {@link MediaRule}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
* @param mediaRuleIdParam The ID of the {@link MediaRule} to delete.
*/
@DELETE
@Path(MEDIA_RULE_PATH)
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void deleteMediaRule(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(MEDIA_RULE_ID) final String mediaRuleIdParam) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(mediaRuleIdParam);
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final ContainerModel container = controller.findContainer(app,
pageModel,
containerKey);
final Styles styles = container.getStyles();
final MediaRule mediaRule = findMediaRule(pageModel,
container,
mediaRuleIdParam);
stylesManager.removeMediaRuleFromStyles(mediaRule, styles);
}
/**
* Retrieves all {@link Rule}s from the {@link Styles} entity of a
* {@link ContainerModel}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
*
* @return A JSON array with the JSON representation of all {@link Rule}s of
* the {@link ContainerModel}.
*/
@GET
@Path(RULES_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonArray getRules(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final ContainerModel container = controller.findContainer(app,
pageModel,
containerKey);
final Styles styles = container.getStyles();
return stylesJsonMapper.mapRulesToJson(styles.getRules());
}
/**
* Retrieves a specific {@link Rule} from the {@link Styles} entity of a
* {@link ContainerModel}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
* @param ruleIdParam The ID of the {@link Rule} to retrieve.
*
* @return The JSON representation of the {@link Rule}.
*/
@GET
@Path(RULE_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject getRule(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(RULE_ID) final String ruleIdParam) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(ruleIdParam);
return stylesJsonMapper
.mapRuleToJson(findRule(appPath,
pageModelName,
containerKey,
ruleIdParam));
}
/**
* Creates a new {@link Rule}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
* @param ruleData The data for the new {@link Rule}.
*
* @return The JSON representation of the new {@link Rule}.
*/
@POST
@Path(RULES_PATH)
@Consumes("application/json; charset=utf-8")
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject createRule(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
final JsonObject ruleData) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(ruleData);
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final ContainerModel container = controller.findContainer(app,
pageModel,
containerKey);
final Styles styles = container.getStyles();
final Rule rule = new Rule();
rule.setSelector(ruleData.getString("selector"));
stylesManager.addRuleToStyles(rule, styles);
return stylesJsonMapper.mapRuleToJson(rule);
}
/**
* Updates an existing {@link Rule}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
* @param ruleIdParam The ID of the {@link Rule} to update.
* @param ruleData The data for updating the {@link Rule}.
*
* @return The JSON representation of the updated {@link Rule}.
*/
@PUT
@Path(RULE_PATH)
@Consumes("application/json; charset=utf-8")
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject updateRule(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(RULE_ID) final String ruleIdParam,
final JsonObject ruleData) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(ruleIdParam);
Objects.requireNonNull(ruleData);
final Rule rule = findRule(appPath,
pageModelName,
containerKey,
ruleIdParam);
rule.setSelector(ruleData.getString("selector"));
stylesRepo.saveRule(rule);
return stylesJsonMapper.mapRuleToJson(rule);
}
/**
* Deletes a {@link Rule}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
* @param ruleIdParam The ID of the {@link Rule} to delete.
*/
@DELETE
@Path(RULE_PATH)
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void deleteRule(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(RULE_ID) final String ruleIdParam) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(ruleIdParam);
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final ContainerModel container = controller.findContainer(app,
pageModel,
containerKey);
final Styles styles = container.getStyles();
final Rule rule = findRule(pageModel, container, ruleIdParam);
stylesManager.removeRuleFromStyles(rule, styles);
}
/**
* An utility method for finding a {@link MediaRule}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
* @param mediaRuleIdParam The ID of the {@link MediaRule} to find.
*
* @return The {@link MediaRule} with the provided {@code mediaRuleId}.
*/
protected MediaRule findMediaRule(final String appPath,
final String pageModelName,
final String containerKey,
final String mediaRuleIdParam) {
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final ContainerModel container = controller.findContainer(app,
pageModel,
containerKey);
return findMediaRule(pageModel, container, mediaRuleIdParam);
}
/**
* An utility method for finding a {@link MediaRule}.
*
* @param pageModel The {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param container The {@link ContainerModel} to which the
* {@link MediaRule} belongs.
* @param mediaRuleIdParam The ID of the {@link MediaRule} to find.
*
* @return The {@link MediaRule} with the ID {@code mediaRuleIdParam}.
*/
private MediaRule findMediaRule(final PageModel pageModel,
final ContainerModel container,
final String mediaRuleIdParam) {
final Styles styles = container.getStyles();
final long mediaRuleId;
try {
mediaRuleId = Long.parseLong(mediaRuleIdParam);
} catch (NumberFormatException ex) {
throw new WebApplicationException(String.format(
"The provided mediaRuleId \"%s\" numeric.", mediaRuleIdParam));
}
return styles
.getMediaRules()
.stream()
.filter(mediaRule -> mediaRuleId == mediaRule.getMediaRuleId())
.findAny()
.orElseThrow(() -> new NotFoundException(String.format(
"No MediaRule with ID %d available in the Styles for "
+ "Container \"%s\" of PageModel \"%s\".",
mediaRuleId,
container.getKey(),
pageModel.getName())));
}
/**
* Utility method for finding a {@link Rule}.
*
* @param appPath The primary URL of the {@link CcmApplication}.
* @param pageModelName The name of the {@link PageModel}.
* @param containerKey The key of the {@link ContainerModel}.
* @param ruleIdParam The ID of the {@link Rule} to find.
*
* @return The {@link Rule} identified by {@code ruleIdParam}.
*/
protected Rule findRule(final String appPath,
final String pageModelName,
final String containerKey,
final String ruleIdParam) {
final CcmApplication app = controller.findCcmApplication(
String.format("/%s/", appPath));
final PageModel pageModel = controller.findPageModel(app,
pageModelName);
final ContainerModel container = controller.findContainer(app,
pageModel,
containerKey);
return findRule(pageModel, container, ruleIdParam);
}
/**
* An utility method for finding a {@link Rule}.
*
* @param pageModel The {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param container The {@link ContainerModel} to which the {@link Rule}
* belongs.
* @param ruleIdParam The ID of the {@link Rule} to find.
*
* @return The {@link Rule} with the ID {@code ruleIdParam}.
*/
private Rule findRule(final PageModel pageModel,
final ContainerModel container,
final String ruleIdParam) {
final Styles styles = container.getStyles();
final long ruleId;
try {
ruleId = Long.parseLong(ruleIdParam);
} catch (NumberFormatException ex) {
throw new WebApplicationException(String.format(
"The provided mediaRuleId \"%s\" numeric.", ruleIdParam));
}
return styles
.getRules()
.stream()
.filter(rule -> ruleId == rule.getRuleId())
.findAny()
.orElseThrow(() -> new NotFoundException(String.format(
"No Rule with ID %d available in the Styles for "
+ "Container \"%s\" of PageModel \"%s\".",
ruleId,
container.getKey(),
pageModel.getName())));
}
/**
* Helper method for setting the values of the properties of a
* {@link MediaRule} using the data from a JSON object.
*
* @param mediaRuleData The JSON object providing the data.
* @param mediaRule The {@link MediaRule}.
*/
private void setMediaRuleProperties(final JsonObject mediaRuleData,
final MediaRule mediaRule) {
Objects.requireNonNull(mediaRuleData);
Objects.requireNonNull(mediaRule);
final JsonObject mediaQueryData = mediaRuleData
.getJsonObject("mediaQuery");
final JsonObject maxWidthData = mediaQueryData
.getJsonObject("maxWidth");
final JsonObject minWidthData = mediaQueryData
.getJsonObject("minWidth");
final Dimension maxWidth = new Dimension();
maxWidth.setUnit(Unit.valueOf(maxWidthData.getString("unit")));
maxWidth.setValue(maxWidthData.getJsonNumber("value").doubleValue());
final MediaType mediaType = MediaType.valueOf(mediaQueryData
.getString("mediaType"));
final Dimension minWidth = new Dimension();
minWidth.setUnit(Unit.valueOf(minWidthData.getString("unit")));
minWidth.setValue(minWidthData.getJsonNumber("minWidth").doubleValue());
mediaRule.getMediaQuery().setMaxWidth(maxWidth);
mediaRule.getMediaQuery().setMediaType(mediaType);
mediaRule.getMediaQuery().setMinWidth(minWidth);
}
}

View File

@ -1,356 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.rs;
import org.libreccm.core.CoreConstants;
import org.libreccm.pagemodel.ContainerModel;
import org.libreccm.pagemodel.styles.CssProperty;
import org.libreccm.pagemodel.styles.Rule;
import org.libreccm.pagemodel.styles.StylesManager;
import org.libreccm.pagemodel.styles.StylesRepository;
import org.libreccm.security.AuthorizationRequired;
import org.libreccm.security.RequiresPrivilege;
import org.libreccm.web.CcmApplication;
import java.io.Serializable;
import java.util.Objects;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
/**
* Provides RESTful endpoints for retrieving, creating, updating and deleting
* {@link Rule} objects.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
@Path(StylesRs.RULE_PATH)
public class StylesRule implements Serializable {
private static final long serialVersionUID = -8447970787677773230L;
protected final static String PROPERTY_ID = "propertyId";
protected final static String PROPERTIES_PATH = "/properties";
protected final static String PROPERTY_PATH = PROPERTIES_PATH
+ "/{"
+ PROPERTY_ID
+ "}";
@Inject
private StylesJsonMapper stylesJsonMapper;
@Inject
private StylesManager stylesManager;
@Inject
private StylesRepository stylesRepo;
@Inject
private StylesRs stylesRs;
/**
* Retrieves all {@link CssProperty} objects of a {@link Rule} assigned to
* the {@link Styles} entity of a {@link ContainerModel}.
*
* @param appPath The primary URL of the {@link CcmApplication} to
* which the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param containerKey The key of the {@link ContainerModel} to which the
* {@link Rule} belongs.
* @param ruleIdParam The ID of the {@link Rule} from which the
* {@link CssProperty} objects are retrieved.
*
* @return A JSON array with the JSON representation of the
* {@link CssProperty} objects of the {@link Rule} identified by the
* provided path.
*/
@GET
@Path(PROPERTIES_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonArray getProperties(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(StylesRs.RULE_ID) final String ruleIdParam) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(ruleIdParam);
final Rule rule = stylesRs.findRule(appPath,
pageModelName,
containerKey,
ruleIdParam);
return stylesJsonMapper.mapPropertiesToJson(rule.getProperties());
}
/**
* Retrieves a specific {@link CssProperty} from a {@link Rule} assigned to
* the {@link Styles} entity of a {@link ContainerModel}.
*
* @param appPath The primary URL of the {@link CcmApplication} to
* which the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param containerKey The key of the {@link ContainerModel} to which the
* {@link Rule} belongs.
* @param ruleIdParam The ID of the {@link Rule} to which the
* {@link CssProperty} is assigned.
* @param propertyIdParam The ID of the {@link CssProperty} to retrieve.
*
* @return The JSON representation of the {@link CssProperty}.
*/
@GET
@Path(PROPERTY_PATH)
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject getProperty(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(StylesRs.RULE_ID) final String ruleIdParam,
@PathParam(PROPERTY_ID) final String propertyIdParam) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(ruleIdParam);
Objects.requireNonNull(propertyIdParam);
final Rule rule = stylesRs.findRule(appPath,
pageModelName,
containerKey,
ruleIdParam);
return stylesJsonMapper
.mapCssPropertyToJson(findProperty(rule,
propertyIdParam));
}
/**
* Creates a new {@link CssProperty} for a {@link Rule} assigned to the
* {@link Styles} entity of a {@link ContainerModel}.
*
* @param appPath The primary URL of the {@link CcmApplication} to
* which the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param containerKey The key of the {@link ContainerModel} to which the
* {@link Rule} belongs.
* @param ruleIdParam The ID of the {@link Rule} to which the
* {@link CssProperty} is assigned.
* @param propertyData The data used to create the new {@link CssProperty}.
*
* @return The JSON representation of the new {@link CssProperty}.
*/
@POST
@Path(PROPERTIES_PATH)
@Consumes("application/json; charset=utf-8")
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject createProperty(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(StylesRs.RULE_ID) final String ruleIdParam,
final JsonObject propertyData) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(ruleIdParam);
Objects.requireNonNull(propertyData);
final Rule rule = stylesRs.findRule(appPath,
pageModelName,
containerKey,
ruleIdParam);
final CssProperty property = new CssProperty();
setCssPropertyData(property, propertyData);
stylesManager.addCssPropertyToRule(property, rule);
return stylesJsonMapper.mapCssPropertyToJson(property);
}
/**
* Updates an existing {@link CssProperty} for a {@link Rule} assigned to
* the {@link Styles} entity of a {@link ContainerModel}.
*
* @param appPath The primary URL of the {@link CcmApplication} to
* which the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param containerKey The key of the {@link ContainerModel} to which the
* {@link Rule} belongs.
* @param ruleIdParam The ID of the {@link Rule} to which the
* {@link CssProperty} is assigned.
* @param propertyIdParam The ID of the {@link CssProperty} to update.
* @param propertyData The data used to update the {@link CssProperty}.
*
* @return The JSON representation of the updated {@link CssProperty}.
*/
@PUT
@Path(PROPERTY_PATH)
@Consumes("application/json; charset=utf-8")
@Produces("application/json; charset=utf-8")
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public JsonObject updateProperty(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(StylesRs.RULE_ID) final String ruleIdParam,
@PathParam(PROPERTY_ID) final String propertyIdParam,
final JsonObject propertyData) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(ruleIdParam);
Objects.requireNonNull(propertyIdParam);
Objects.requireNonNull(propertyData);
final Rule rule = stylesRs.findRule(appPath,
pageModelName,
containerKey,
ruleIdParam);
final CssProperty property = findProperty(rule, propertyIdParam);
setCssPropertyData(property, propertyData);
stylesRepo.saveCssProperty(property);
return stylesJsonMapper.mapCssPropertyToJson(property);
}
/**
* Deletes{@link CssProperty} for a {@link Rule} assigned to the
* {@link Styles} entity of a {@link ContainerModel}.
*
* @param appPath The primary URL of the {@link CcmApplication} to
* which the {@link PageModel} belongs.
* @param pageModelName The name of the {@link PageModel} to which the
* {@link ContainerModel} belongs.
* @param containerKey The key of the {@link ContainerModel} to which the
* {@link Rule} belongs.
* @param ruleIdParam The ID of the {@link Rule} to which the
* {@link CssProperty} is assigned.
* @param propertyIdParam The ID of the {@link CssProperty} to delete.
*/
@DELETE
@Path(PROPERTY_PATH)
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void deleteProperty(
@PathParam(PageModelsApp.APP_NAME) final String appPath,
@PathParam(PageModelsApp.PAGE_MODEL_NAME) final String pageModelName,
@PathParam(PageModelsApp.CONTAINER_KEY) final String containerKey,
@PathParam(StylesRs.RULE_ID) final String ruleIdParam,
@PathParam(PROPERTY_ID) final String propertyIdParam) {
Objects.requireNonNull(appPath);
Objects.requireNonNull(pageModelName);
Objects.requireNonNull(containerKey);
Objects.requireNonNull(ruleIdParam);
Objects.requireNonNull(propertyIdParam);
final Rule rule = stylesRs.findRule(appPath,
pageModelName,
containerKey,
ruleIdParam);
final CssProperty property = findProperty(rule, propertyIdParam);
stylesManager.removeCssPropertyFromRule(property, rule);
stylesRepo.deleteCssProperty(property);
}
/**
* Helper method for finding a {@link CssProperty} assigned to {@link Rule}.
*
* @param rule The {@link Rule}.
* @param propertyIdParam The ID of the {@link CssProperty} to find.
*
* @return The {@link CssProperty} identified by {@code propertyIdParam}.
*/
private CssProperty findProperty(final Rule rule,
final String propertyIdParam) {
Objects.requireNonNull(rule);
Objects.requireNonNull(propertyIdParam);
final long propertyId;
try {
propertyId = Long.parseLong(propertyIdParam);
} catch (NumberFormatException ex) {
throw new WebApplicationException(ex);
}
return rule
.getProperties()
.stream()
.filter(property -> propertyId == property.getPropertyId())
.findAny()
.orElseThrow(() -> new NotFoundException());
}
/**
* Helper method for updating a {@link CssProperty} object with data from
* its JSON representation.
*
* @param property The {@link CssProperty}.
* @param propertyData The data.
*/
private void setCssPropertyData(final CssProperty property,
final JsonObject propertyData) {
Objects.requireNonNull(property);
Objects.requireNonNull(propertyData);
property.setName(propertyData.getString("name"));
property.setValue(propertyData.getString("value"));
}
}

View File

@ -1,25 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
/**
* The classes in this package provide a RESTful API as backend for PageModel
* editors.
*
*/
package org.libreccm.pagemodel.rs;

View File

@ -1,145 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.styles;
import org.libreccm.core.CoreConstants;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* A single CSS property like {@code font-weight: bold}.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Entity
@Table(name = "STYLE_PROPERTIES", schema = CoreConstants.DB_SCHEMA)
public class CssProperty implements Serializable {
private static final long serialVersionUID = -4697757123207731769L;
/**
* ID of the CSS property
*/
@Id
@Column(name = "PROPERTY_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private long propertyId;
/**
* The name of the property.
*/
@Column(name = "NAME", length = 256)
private String name;
/**
* The value of the property.
*/
@Column(name = "PROPERTY_VALUE", length = 4096)
private String value;
public long getPropertyId() {
return propertyId;
}
protected void setPropertyId(long propertyId) {
this.propertyId = propertyId;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(final String value) {
this.value = value;
}
@Override
public int hashCode() {
int hash = 7;
hash = 17 * hash + (int) (propertyId ^ (propertyId >>> 32));
hash = 17 * hash + Objects.hashCode(name);
hash = 17 * hash + Objects.hashCode(value);
return hash;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof CssProperty)) {
return false;
}
final CssProperty other = (CssProperty) obj;
if (!other.canEqual(this)) {
return false;
}
if (!Objects.equals(name, other.getName())) {
return false;
}
return Objects.equals(value, other.getValue());
}
public boolean canEqual(final Object obj) {
return obj instanceof CssProperty;
}
@Override
public String toString() {
return toString("");
}
public String toString(final String data) {
return String.format("%s{ "
+ "name = \"%s\", "
+ "value = \"%s\"%s"
+ " }",
super.toString(),
name,
value,
data);
}
public String toCss() {
return String.format("%s: %s",
name,
value);
}
}

View File

@ -1,120 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.styles;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Embeddable
public class Dimension implements Serializable {
private static final long serialVersionUID = 44299305931240403L;
@Column(name = "DIMENSION_VALUE")
private double value;
@Column(name = "UNIT")
@Enumerated(EnumType.STRING)
private Unit unit;
public double getValue() {
return value;
}
public void setValue(final double value) {
this.value = value;
}
public Unit getUnit() {
return unit;
}
public void setUnit(final Unit unit) {
this.unit = unit;
}
@Override
public int hashCode() {
int hash = 7;
hash = 37 * hash
+ (int) (Double.doubleToLongBits(value)
^ (Double.doubleToLongBits(value) >>> 32));
hash = 37 * hash + Objects.hashCode(unit);
return hash;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Dimension)) {
return false;
}
final Dimension other = (Dimension) obj;
if (!other.canEqual(this)) {
return false;
}
if (Double.doubleToLongBits(value)
!= Double.doubleToLongBits(other.getValue())) {
return false;
}
return unit == other.getUnit();
}
public boolean canEqual(final Object obj) {
return obj instanceof Dimension;
}
public String toString(final String data) {
return String.format("%s{ "
+ "value = %f, "
+ "unit = \"%s\"%s"
+ " }",
super.toString(),
value,
Objects.toString(unit),
data);
}
@Override
public final String toString() {
return toString("");
}
public String toCss() {
return String.format("%s%s", value, unit.toString().toLowerCase());
}
}

View File

@ -1,200 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.styles;
import org.libreccm.core.CoreConstants;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Entity
@Table(name = "STYLE_MEDIA_QUERIES", schema = CoreConstants.DB_SCHEMA)
public class MediaQuery implements Serializable {
private static final long serialVersionUID = 8047120379515301590L;
@Id
@Column(name = "MEDIA_QUERY_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private long mediaQueryId;
@Column(name = "MEDIA_TYPE")
@Enumerated(EnumType.STRING)
private MediaType mediaType;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "value",
column = @Column(name = "MIN_WIDTH_VALUE"))
,
@AttributeOverride(name = "unit",
column = @Column(name = "MIN_WIDTH_UNIT"))
})
private Dimension minWidth;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "value",
column = @Column(name = "MAX_WIDTH_VALUE"))
,
@AttributeOverride(name = "unit",
column = @Column(name = "MAX_WIDTH_UNIT"))
})
private Dimension maxWidth;
public long getMediaQueryId() {
return mediaQueryId;
}
protected void setMediaQueryId(long mediaQueryId) {
this.mediaQueryId = mediaQueryId;
}
public MediaType getMediaType() {
return mediaType;
}
public void setMediaType(final MediaType mediaType) {
this.mediaType = mediaType;
}
public Dimension getMinWidth() {
return minWidth;
}
public void setMinWidth(final Dimension minWidth) {
this.minWidth = minWidth;
}
public Dimension getMaxWidth() {
return maxWidth;
}
public void setMaxWidth(final Dimension maxWidth) {
this.maxWidth = maxWidth;
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (int) (mediaQueryId ^ (mediaQueryId >>> 32));
hash = 31 * hash + Objects.hashCode(mediaType);
hash = 31 * hash + Objects.hashCode(minWidth);
hash = 31 * hash + Objects.hashCode(maxWidth);
return hash;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MediaQuery)) {
return false;
}
final MediaQuery other = (MediaQuery) obj;
if (!other.canEqual(this)) {
return false;
}
if (mediaQueryId != other.getMediaQueryId()) {
return false;
}
if (mediaType != other.getMediaType()) {
return false;
}
if (!Objects.equals(minWidth, other.getMinWidth())) {
return false;
}
return Objects.equals(maxWidth, other.getMaxWidth());
}
public boolean canEqual(final Object obj) {
return obj instanceof MediaQuery;
}
public String toString(final String data) {
return String.format("%s{ "
+ "mediaQueryId = %d, "
+ "mediaType = \"%s\", "
+ "minWidth = %s, "
+ "maxWidth = %s%s"
+ " }",
super.toString(),
mediaQueryId,
Objects.toString(mediaType),
Objects.toString(minWidth),
Objects.toString(maxWidth),
data);
}
@Override
public final String toString() {
return toString("");
}
public String toCss() {
final StringBuilder builder = new StringBuilder("@media");
if (mediaType != null) {
builder.append(" ").append(mediaType.toString()).append(" ");
}
if (minWidth != null) {
if (builder.length() > "@media".length()) {
builder.append(" and ");
}
builder.append(String.format("(min-width: %s", minWidth.toCss()));
}
if (maxWidth != null) {
if (builder.length() > "@media".length()) {
builder.append(" and ");
}
builder.append(String.format("(max-width: %s", maxWidth.toCss()));
}
return builder.toString();
}
}

View File

@ -1,170 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.styles;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.libreccm.core.CoreConstants;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Entity
@Table(name = "STYLE_MEDIA_RULES", schema = CoreConstants.DB_SCHEMA)
public class MediaRule implements Serializable {
private static final long serialVersionUID = -5776387865481417402L;
@Id
@Column(name = "MEDIA_RULE_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private long mediaRuleId;
@OneToOne
@JoinColumn(name = "MEDIA_QUERY_ID")
@Cascade(CascadeType.ALL)
private MediaQuery mediaQuery;
@OneToMany
@JoinColumn(name = "STYLE_ID")
@Cascade(CascadeType.ALL)
private List<Rule> rules;
public long getMediaRuleId() {
return mediaRuleId;
}
protected void setMediaRuleId(final long mediaRuleId) {
this.mediaRuleId = mediaRuleId;
}
public MediaQuery getMediaQuery() {
return mediaQuery;
}
public void setMediaQuery(final MediaQuery mediaQuery) {
this.mediaQuery = mediaQuery;
}
public List<Rule> getRules() {
return Collections.unmodifiableList(rules);
}
public void setRules(final List<Rule> rules) {
this.rules = new ArrayList<>(rules);
}
public void addRule(final Rule rule) {
rules.add(rule);
}
public void removeRule(final Rule rule) {
rules.remove(rule);
}
@Override
public int hashCode() {
int hash = 7;
hash = 67 * hash + (int) (mediaRuleId ^ (mediaRuleId >>> 32));
hash = 67 * hash + Objects.hashCode(mediaQuery);
hash = 67 * hash + Objects.hashCode(rules);
return hash;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MediaRule)) {
return false;
}
final MediaRule other = (MediaRule) obj;
if (!other.canEqual(this)) {
return false;
}
if (mediaRuleId != other.getMediaRuleId()) {
return false;
}
if (!Objects.equals(mediaQuery, other.getMediaQuery())) {
return false;
}
return Objects.equals(rules, other.getRules());
}
public boolean canEqual(final Object obj) {
return obj instanceof MediaRule;
}
public String toString(final String data) {
return String.format("%s{ "
+ "mediaRuleId = %d, "
+ "mediaQuery = %s, "
+ "rules = %s%s"
+ " }",
super.toString(),
mediaRuleId,
Objects.toString(mediaQuery),
Objects.toString(rules),
data);
}
@Override
public final String toString() {
return toString("");
}
public String toCss() {
final String rulesCss = rules
.stream()
.map(Rule::toCss)
.collect(Collectors.joining(";\n%t"));
return String.format("%s {%n"
+ "%s%n"
+ "}%n",
mediaQuery.toCss(),
rulesCss);
}
}

View File

@ -1,33 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.styles;
/**
* Media types for CSS. Only the well supported ones are supported
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
public enum MediaType {
ALL,
PRINT,
SCREEN,
}

View File

@ -1,170 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.styles;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.libreccm.core.CoreConstants;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Entity
@Table(name = "STYLE_RULES", schema = CoreConstants.DB_SCHEMA)
public class Rule implements Serializable {
private static final long serialVersionUID = -4027217790520373364L;
@Id
@Column(name = "RULE_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private long ruleId;
@Column(name = "SELECTOR", length = 2048)
private String selector;
@OneToMany
@JoinColumn(name = "RULE_ID")
@Cascade({CascadeType.ALL})
private List<CssProperty> properties;
public Rule() {
properties = new ArrayList<>();
}
public long getRuleId() {
return ruleId;
}
protected void setRuleId(long ruleId) {
this.ruleId = ruleId;
}
public String getSelector() {
return selector;
}
public void setSelector(final String selector) {
this.selector = selector;
}
public List<CssProperty> getProperties() {
return Collections.unmodifiableList(properties);
}
public void setProperties(final List<CssProperty> properties) {
this.properties = new ArrayList<>(properties);
}
public void addProperty(final CssProperty property) {
properties.add(property);
}
public void removeProperties(final CssProperty property) {
properties.remove(property);
}
@Override
public int hashCode() {
int hash = 7;
hash = 29 * hash + (int) (ruleId ^ (ruleId >>> 32));
hash = 29 * hash + Objects.hashCode(selector);
hash = 29 * hash + Objects.hashCode(properties);
return hash;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Rule)) {
return false;
}
final Rule other = (Rule) obj;
if (!other.canEqual(this)) {
return false;
}
if (ruleId != other.getRuleId()) {
return false;
}
if (!Objects.equals(selector, other.getSelector())) {
return false;
}
return Objects.equals(properties, other.getProperties());
}
public boolean canEqual(final Object obj) {
return obj instanceof Rule;
}
@Override
public final String toString() {
return toString("");
}
public String toString(final String data) {
return String.format("%s{ "
+ "ruleId = %d, "
+ "selector = \"%s\", "
+ "properties = %s%s"
+ " }",
super.toString(),
ruleId,
selector,
Objects.toString(properties),
data);
}
public String toCss() {
final String propertiesCss = properties
.stream()
.map(CssProperty::toCss)
.collect(Collectors.joining(";\n\t"));
return String.format("%s {%n"
+ "%s%n"
+ "}%n",
selector,
propertiesCss);
}
}

View File

@ -1,197 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.styles;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.libreccm.core.CoreConstants;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@Entity
@Table(name = "STYLES", schema = CoreConstants.DB_SCHEMA)
public class Styles implements Serializable {
private static final long serialVersionUID = -6166372396205730453L;
@Id
@Column(name = "STYLE_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private long styleId;
@Column(name = "STYLENAME")
private String styleName;
@OneToMany
@JoinColumn(name = "STYLE_ID")
@Cascade(CascadeType.ALL)
private List<Rule> rules;
@OneToMany
@JoinColumn(name = "STYLE_ID")
@Cascade(CascadeType.ALL)
private List<MediaRule> mediaRules;
public long getStyleId() {
return styleId;
}
public void setStyleId(long styleId) {
this.styleId = styleId;
}
public String getStyleName() {
return styleName;
}
public void setStyleName(final String styleName) {
this.styleName = styleName;
}
public List<Rule> getRules() {
return Collections.unmodifiableList(rules);
}
public void setRules(final List<Rule> rules) {
this.rules = new ArrayList<>(rules);
}
public void addRule(final Rule rule) {
rules.add(rule);
}
public void removeRule(final Rule rule) {
rules.remove(rule);
}
public List<MediaRule> getMediaRules() {
return Collections.unmodifiableList(mediaRules);
}
public void setMediaRules(final List<MediaRule> mediaRules) {
this.mediaRules = new ArrayList<>(mediaRules);
}
public void addMediaRule(final MediaRule mediaRule) {
mediaRules.add(mediaRule);
}
public void removeMediaRule(final MediaRule mediaRule) {
mediaRules.remove(mediaRule);
}
@Override
public int hashCode() {
int hash = 5;
hash = 97 * hash + (int) (styleId ^ (styleId >>> 32));
hash = 97 * hash + Objects.hashCode(styleName);
hash = 97 * hash + Objects.hashCode(rules);
hash = 97 * hash + Objects.hashCode(mediaRules);
return hash;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Styles)) {
return false;
}
final Styles other = (Styles) obj;
if (!other.canEqual(this)) {
return false;
}
if (styleId != other.getStyleId()) {
return false;
}
if (!Objects.equals(styleName, other.getStyleName())) {
return false;
}
return Objects.equals(rules, other.getRules());
}
public boolean canEqual(final Object obj) {
return obj instanceof Styles;
}
@Override
public final String toString() {
return toString("");
}
public String toString(final String data) {
return String.format("%s{ "
+ "styleId = %d, "
+ "styleName = \"%s\", "
+ "rules = %s, "
+ "mediaRules = %s%s"
+ " }",
super.toString(),
styleId,
styleName,
Objects.toString(rules),
Objects.toString(mediaRules),
data);
}
public String toCss() {
final String rulesCss = rules
.stream()
.map(Rule::toCss)
.collect(Collectors.joining(";\n\n"));
final String mediaRulesCss = mediaRules
.stream()
.map(MediaRule::toCss)
.collect(Collectors.joining(";\n\n"));
final StringBuilder builder = new StringBuilder();
return builder
.append(rulesCss)
.append(mediaRulesCss)
.toString();
}
}

View File

@ -1,150 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.styles;
import org.libreccm.core.CoreConstants;
import org.libreccm.security.AuthorizationRequired;
import org.libreccm.security.RequiresPrivilege;
import java.io.Serializable;
import java.util.Objects;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
public class StylesManager implements Serializable {
private static final long serialVersionUID = -2906584926633549611L;
@Inject
private StylesRepository stylesRepo;
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void addCssPropertyToRule(final CssProperty property,
final Rule rule) {
Objects.requireNonNull(property);
Objects.requireNonNull(rule);
rule.addProperty(property);
stylesRepo.saveRule(rule);
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void removeCssPropertyFromRule(final CssProperty property,
final Rule rule) {
Objects.requireNonNull(property);
Objects.requireNonNull(rule);
rule.removeProperties(property);
stylesRepo.saveRule(rule);
stylesRepo.deleteCssProperty(property);
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void addMediaRuleToStyles(final MediaRule mediaRule,
final Styles styles) {
Objects.requireNonNull(styles);
Objects.requireNonNull(mediaRule);
styles.addMediaRule(mediaRule);
stylesRepo.saveStyles(styles);
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void removeMediaRuleFromStyles(final MediaRule mediaRule,
final Styles styles) {
Objects.requireNonNull(styles);
Objects.requireNonNull(mediaRule);
styles.removeMediaRule(mediaRule);
stylesRepo.saveStyles(styles);
stylesRepo.deleteMediaRule(mediaRule);
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void addRuleToMediaRule(final Rule rule, final MediaRule mediaRule) {
Objects.requireNonNull(rule);
Objects.requireNonNull(mediaRule);
mediaRule.addRule(rule);
stylesRepo.saveMediaRule(mediaRule);
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void removeRuleFromMediaRule(final Rule rule,
final MediaRule mediaRule) {
Objects.requireNonNull(rule);
Objects.requireNonNull(mediaRule);
mediaRule.removeRule(rule);
stylesRepo.saveMediaRule(mediaRule);
stylesRepo.deleteRule(rule);
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void addRuleToStyles(final Rule rule, final Styles styles) {
Objects.requireNonNull(rule);
Objects.requireNonNull(styles);
styles.addRule(rule);
stylesRepo.saveStyles(styles);
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void removeRuleFromStyles(final Rule rule, final Styles styles) {
Objects.requireNonNull(rule);
Objects.requireNonNull(styles);
styles.removeRule(rule);
stylesRepo.deleteRule(rule);
}
}

View File

@ -1,169 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.styles;
import org.libreccm.core.CoreConstants;
import org.libreccm.security.AuthorizationRequired;
import org.libreccm.security.RequiresPrivilege;
import java.io.Serializable;
import java.util.Objects;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
/**
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
@RequestScoped
public class StylesRepository implements Serializable {
private static final long serialVersionUID = 8350984709496516542L;
@Inject
private EntityManager entityManager;
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void saveCssProperty(final CssProperty cssProperty) {
Objects.requireNonNull(cssProperty);
if (cssProperty.getPropertyId() == 0) {
entityManager.persist(cssProperty);
} else {
entityManager.merge(cssProperty);
}
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void deleteCssProperty(final CssProperty cssProperty) {
Objects.requireNonNull(cssProperty);
entityManager.remove(cssProperty);
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void saveMediaQuery(final MediaQuery mediaQuery) {
Objects.requireNonNull(mediaQuery);
if (mediaQuery.getMediaQueryId() == 0) {
entityManager.persist(mediaQuery);
} else {
entityManager.merge(mediaQuery);
}
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void deleteMediaQuery(final MediaQuery mediaQuery){
Objects.requireNonNull(mediaQuery);
entityManager.remove(mediaQuery);
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void saveMediaRule(final MediaRule mediaRule) {
Objects.requireNonNull(mediaRule);
if (mediaRule.getMediaRuleId() == 0) {
entityManager.persist(mediaRule);
} else {
entityManager.merge(mediaRule);
}
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void deleteMediaRule(final MediaRule mediaRule) {
Objects.requireNonNull(mediaRule);
entityManager.remove(mediaRule);
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void saveRule(final Rule rule) {
Objects.requireNonNull(rule);
if (rule.getRuleId() == 0) {
entityManager.persist(rule);
} else {
entityManager.merge(rule);
}
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void deleteRule(final Rule rule) {
Objects.requireNonNull(rule);
entityManager.remove(rule);
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void saveStyles(final Styles styles) {
Objects.requireNonNull(styles);
if (styles.getStyleId() == 0) {
entityManager.persist(styles);
} else {
entityManager.merge(styles);
}
}
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@RequiresPrivilege(CoreConstants.PRIVILEGE_ADMIN)
public void deleteStyles(final Styles styles) {
Objects.requireNonNull(styles);
entityManager.remove(styles);
}
}

View File

@ -1,37 +0,0 @@
/*
* Copyright (C) 2018 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.libreccm.pagemodel.styles;
/**
* Common units used in CSS for length values.
*
* @author <a href="mailto:jens.pelzetter@googlemail.com">Jens Pelzetter</a>
*/
@Deprecated
public enum Unit {
EM,
EX,
PERCENT,
PX,
REM,
VH,
VW,
}

View File

@ -21,7 +21,6 @@ package org.libreccm.theming;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.libreccm.core.UnexpectedErrorException;
import org.libreccm.pagemodel.PageModel;
import java.io.InputStream;
import java.io.Serializable;
@ -206,7 +205,7 @@ public class Themes implements Serializable {
}
/**
* Creates HTML from the result of rendering a {@link PageModel}.
* Creates HTML from the result of rendering a model.
*
* @param page The page to convert to HTML.
* @param theme The theme to use.

View File

@ -0,0 +1,10 @@
drop table CCM_CORE.STYLE_PROPERTIES;
drop table CCM_CORE.STYLE_RULES;
drop table CCM_CORE.STYLE_MEDIA_RULES;
drop table CCM_CORE.STYLE_MEDIA_QUERIES;
drop table CCM_CORE.PAGE_MODEL_COMPONENT_MODELS;
drop table CCM_CORE.PAGE_MODEL_CONTAINER_MODELS;
drop table CCM_CORE.STYLES;
drop table CCM_CORE.PAGE_MODEL_DESCRIPTIONS;
drop table CCM_CORE.PAGE_MODEL_TITLES;
drop table CCM_CORE.PAGE_MODELS;

View File

@ -0,0 +1,10 @@
drop table CCM_CORE.STYLE_PROPERTIES;
drop table CCM_CORE.STYLE_RULES;
drop table CCM_CORE.STYLE_MEDIA_RULES;
drop table CCM_CORE.STYLE_MEDIA_QUERIES;
drop table CCM_CORE.PAGE_MODEL_COMPONENT_MODELS;
drop table CCM_CORE.PAGE_MODEL_CONTAINER_MODELS;
drop table CCM_CORE.STYLES;
drop table CCM_CORE.PAGE_MODEL_DESCRIPTIONS;
drop table CCM_CORE.PAGE_MODEL_TITLES;
drop table CCM_CORE.PAGE_MODELS;