it.openutils.mgnlutils.el.MgnlUtilsElFunctions Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of openutils-mgnlutils Show documentation
Show all versions of openutils-mgnlutils Show documentation
A collection of Magnolia utilities and extensions
/**
*
* Magnolia generic utilities (http://www.openmindlab.com/lab/products/mgnlutils.html)
* Copyright(C) 2009-2010, Openmind S.r.l. http://www.openmindonline.it
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package it.openutils.mgnlutils.el;
import info.magnolia.cms.beans.config.ContentRepository;
import info.magnolia.cms.core.Content;
import info.magnolia.cms.core.ItemType;
import info.magnolia.cms.core.Path;
import info.magnolia.cms.core.SystemProperty;
import info.magnolia.cms.util.NodeMapWrapper;
import info.magnolia.context.MgnlContext;
import info.magnolia.context.WebContext;
import info.magnolia.link.LinkException;
import info.magnolia.link.LinkUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.jcr.RepositoryException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.jackrabbit.util.ISO9075;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Generic utility EL functions.
* @author fgiust
* @version $Id: MgnlUtilsElFunctions.java 2105 2010-03-08 13:49:14Z diego_schivo $
*/
public final class MgnlUtilsElFunctions
{
/**
* Logger.
*/
private static Logger log = LoggerFactory.getLogger(MgnlUtilsElFunctions.class);
public MgnlUtilsElFunctions()
{
// allow instantion for freemarker
}
/**
* Test if exists a parent page with content in the collectionName given as parameter, if exist set the parent page
* as actpage
* @param collectionName (column) of magnolia contentNode
* @return true if exists a parent page with content in the collectionName given as parameter, if exist set the
* parent page as actpage
*/
public static boolean firstPageWithCollection(String collectionName)
{
Content actpage = MgnlContext.getAggregationState().getCurrentContent();
try
{
while (actpage.getLevel() > 1)
{
actpage = actpage.getParent();
if (actpage.hasContent(collectionName) && actpage.getContent(collectionName).hasChildren())
{
MgnlContext.getAggregationState().setCurrentContent(actpage);
return true;
}
}
}
catch (RepositoryException e)
{
log.error("Error looking for collection " + collectionName + " in " + actpage.getHandle(), e);
}
return false;
}
/**
* Return the content of a given path and repository
* @param path content path
* @param repository repository type
* @return the content of a given path and repository
*/
public static Content contentByPath(String path, String repository)
{
try
{
return MgnlContext.getHierarchyManager(repository).getContent(path);
}
catch (RepositoryException e)
{
return null;
}
}
/**
* Return a map key=value of all magnolia request attributes
* @return a map key=value of all magnolia request attributes
*/
@SuppressWarnings("unchecked")
public static Map getRequestAttributeMap()
{
Map attrs = new HashMap();
HttpServletRequest request = MgnlContext.getWebContext().getRequest();
Enumeration attributeNames = request.getAttributeNames();
while (attributeNames.hasMoreElements())
{
String key = attributeNames.nextElement();
attrs.put(key, request.getAttribute(key));
attrs.put(key, key);
}
return attrs;
}
/**
* Return the message of a given message key
* @param key string
* @return return the message string of a given message key
*/
public static String message(String key)
{
return MgnlContext.getMessages().get(key);
}
/**
* Test the system property 'magnolia.develop'
* @return true if the system property = 'magnolia.develop'
*/
public static boolean develop()
{
return SystemProperty.getBooleanProperty("magnolia.develop");
}
/**
* Parse uuidOrPathOrUrl string and return a url.
* @param uuidOrPathOrUrl url (http://, internal link, UUID, generic url)
* @return cleaned url (external or internal)
*/
public static String link(String uuidOrPathOrUrl)
{
String cleanedurl = StringUtils.replace(StringUtils.trim(uuidOrPathOrUrl), "&", "&");
String contextPath = ((WebContext) MgnlContext.getInstance()).getContextPath();
if (StringUtils.isBlank(cleanedurl))
{
return contextPath;
}
if (cleanedurl.startsWith("http") || cleanedurl.startsWith("#"))
{
return cleanedurl;
}
// Check if there is already an extensions, else add default one
if (cleanedurl.startsWith("/"))
{
cleanedurl = contextPath + cleanedurl;
if (!cleanedurl.endsWith(".html") && cleanedurl.indexOf(".") < 0)
{
return cleanedurl + ".html";
}
return cleanedurl;
}
// Check if uuidOrPathOrUrl is an UUID
try
{
cleanedurl = MgnlContext.getContextPath()
+ LinkUtil.convertUUIDtoURI(cleanedurl, ContentRepository.WEBSITE);
}
catch (LinkException e)
{
log.debug("Failed to parse links with from "
+ MgnlContext.getAggregationState().getCurrentURI()
+ e.getMessage());
}
// If got an error return the cleaned string
return cleanedurl;
}
/**
* Create an html complete link from a string composed by link \t link text. If the link is empty the function
* return only the text
* @param tabseparatedstring string
* @return a link or a text
*/
public static String tolinkOrText(String tabseparatedstring)
{
if (StringUtils.isBlank(tabseparatedstring))
{
return StringUtils.EMPTY;
}
String[] splitted = StringUtils.split(tabseparatedstring, "\t");
if (splitted.length > 1)
{
String url = link(splitted[1]);
boolean external = false;
if (splitted.length > 2 && "true".equals(StringUtils.trim(splitted[2])))
{
external = true;
}
StringBuilder sb = new StringBuilder();
if (!StringUtils.isBlank(url))
{
sb.append("");
sb.append(splitted[0]);
sb.append("");
}
else
{
sb.append(splitted[0]);
}
return sb.toString();
}
// param external
if (splitted[0].equals("false") || splitted[0].equals("true"))
{
return StringUtils.EMPTY;
}
else
{
return splitted[0];
}
}
/**
* Count the nodes in a collection with a given content and the name of the collection
* @param content Content
* @param subnode String
* @return the number of nodes in a collection
*/
public static int countNodesInCollection(Content content, String subnode)
{
int count = 0;
Content collection = null;
if (content != null)
{
try
{
if (content.hasContent(subnode))
{
collection = content.getContent(subnode);
count = collection.getChildren().size();
}
}
catch (RepositoryException e)
{
// ignore
}
}
return count;
}
/**
* Count subpages with a given content
* @param content Content
* @return the number of subpages
*/
public static int countSubpages(Content content)
{
int count = 0;
if (content != null)
{
count = content.getChildren(ItemType.CONTENT).size();
}
return count;
}
/**
* Return the collection of subpages of a given page
* @param content Content
* @return a Collection of subpages of a given page
*/
public static Collection subpages(Content content)
{
if (content != null)
{
return content.getChildren(ItemType.CONTENT);
}
return null;
}
/**
* Return true if the current user has a given role
* @param role String
* @return boolean value
*/
public static boolean userInRole(String role)
{
return MgnlContext.getUser().hasRole(role);
}
/**
* Evaluates if primary node type of the associated Node of an object is a mgnl:contentNode
* @param content Content
* @return boolean value
*/
public static boolean isPage(Content content)
{
return content != null && !content.isNodeType(ItemType.CONTENTNODE.getSystemName());
}
/**
* Return the Content of the object passed or of the first parent page that has content type = mgnl:content
* @param content Content
* @return the Content of the object passed or of the first parent page that has content type = mgnl:content
*/
public static Content getPage(Content content)
{
Content page = content;
while (page != null && page.isNodeType(ItemType.CONTENTNODE.getSystemName()))
{
try
{
page = page.getParent();
}
catch (RepositoryException e)
{
log.debug("Unable to read parent of " + page.getHandle(), e);
}
}
return page;
}
/**
* retrieve validate label for input string
* @param value the string to validate
* @return the validated label, or null if value was null
* @see {@link Path#getValidatedLabel(String)}
*/
public static String getValidatedLabel(String value)
{
if (value == null)
{
return null;
}
return Path.getValidatedLabel(value);
}
/**
* splits a list according to a separator and returns true if one of the values equals the input value
* @param list the string to be split
* @param value the value to check
* @param separator the separator
* @return true if the value equals one of the values obtained from splitting the string, false otherwise
* @see {@link String#split()}
*/
public static boolean isStringInSeparatedList(String list, String value, String separator)
{
if (StringUtils.isNotEmpty(list) && StringUtils.isNotEmpty(value))
{
String[] listValues = list.split(separator);
for (String v : listValues)
{
if (v.equals(value))
{
return true;
}
}
}
return false;
}
/**
* check if the second argument equals at least one line of the first argument
* @param list the list of lines
* @param value the value to check
* @return true if the value equals one of the lines, false otherwise
*/
public static boolean isLine(String list, String value)
{
return isStringInSeparatedList(list, value, "\r\n") || isStringInSeparatedList(list, value, "\n");
}
/**
* encode handle for a JackRabbit search
* @param handle the page handle
* @return handle encoded ISO9075
*/
public static String encodeISO9075(String handle)
{
return ISO9075.encodePath(handle);
}
/**
* Splits the given strings on newline (\n
) and after on tabs (\t
) Usually used to
* retrieve data from a magnolia grid component
* @param string string to be split
* @return array
*/
public static String[][] splitAndTokenize(String string)
{
List list = new ArrayList();
for (String line : StringUtils.splitPreserveAllTokens(string, '\n'))
{
line = StringUtils.removeEnd(line, "\r");
if (StringUtils.isNotBlank(line))
{
list.add(StringUtils.splitPreserveAllTokens(line, '\t'));
}
}
return list.toArray(new String[0][]);
}
/**
* Extracts a map from a bi-dimensional array of strings, getting keys and values from the specified columns
* @param tokens
* @param keyIndex index of the column storing keys
* @param valueIndex index of the column storing values
* @return
*/
public static Map mapTokens(String[][] tokens, int keyIndex, int valueIndex)
{
Map map = new HashMap(tokens.length);
for (String[] row : tokens)
{
if (keyIndex < row.length && valueIndex < row.length)
{
map.put(row[keyIndex], row[valueIndex]);
}
}
return map;
}
/**
* Same as mapTokens, but the resulting map is multi-value, i.e. the same key can have more than one value.
* Rows having no key specified are considered entries of the last used key.
* @param tokens
* @param keyIndex
* @param valueIndex
* @return
*/
public static Map multiMapTokens(String[][] tokens, int keyIndex, int valueIndex)
{
Map> tmpMap = new HashMap>();
String currentKey = null;
for (String[] row : tokens)
{
if (keyIndex < row.length && valueIndex < row.length)
{
String key = StringUtils.trimToNull(row[keyIndex]);
if (key == null)
{
key = currentKey;
}
if (key != null)
{
List values = tmpMap.get(key);
if (values == null)
{
values = new ArrayList();
tmpMap.put(key, values);
}
values.add(row[valueIndex]);
}
}
}
Map map = new HashMap(tmpMap.size());
for (Entry> entry : tmpMap.entrySet())
{
map.put(entry.getKey(), entry.getValue().toArray(new String[0]));
}
return map;
}
/**
* Returns the base URL for the request (scheme + server + port + context path, like http://server:81/context/)
* @return the base URL for the request (scheme + server + port + context path, like http://server:81/context/
*/
public static String baseUrl()
{
return baseUrlWithoutContextPath() + MgnlContext.getWebContext().getRequest().getContextPath();
}
/**
* Returns the base URL for the request without the context path (scheme + server + port, like http://server:81/)
* @return the base URL for the request (scheme + server + port , like http://server:81/
*/
public static String baseUrlWithoutContextPath()
{
HttpServletRequest request = MgnlContext.getWebContext().getRequest();
StringBuffer baseUrl = new StringBuffer();
baseUrl.append(request.getScheme());
baseUrl.append("://");
baseUrl.append(request.getServerName());
if (("http".equals(request.getScheme()) && request.getServerPort() != 80)
|| ("https".equals(request.getScheme()) && request.getServerPort() != 443))
{
baseUrl.append(":");
baseUrl.append(request.getServerPort());
}
return baseUrl.toString();
}
/**
* Returns the full url to the given content (starting with http)
* @param content magnolia content
* @return the full url to the given content (starting with http)
*/
public static String pageFullUrl(Content content)
{
if (content != null)
{
return baseUrl() + content.getHandle() + ".html";
}
return null;
}
/**
* Returns the full url to the current page (starting with http)
* @return the full url to the current page (starting with http)
*/
public static String activePageFullUrl()
{
return baseUrl() + MgnlContext.getAggregationState().getMainContent() + ".html";
}
/**
* Returns a link from an uuid. Accepts in input uuid. Returns "#" if provided uuid is not found.
* @param uuid uuid to find
* @param repo repository within search - can be null - default is 'website'
* @return a link from an uuid.
*/
public static String repoUuidLink(String uuid, String repo)
{
String url = "#";
try
{
url = MgnlContext.getContextPath()
+ LinkUtil.convertUUIDtoURI(uuid, StringUtils.isNotBlank(repo) ? repo : ContentRepository.WEBSITE);
}
catch (LinkException e)
{
log.debug("Failed to parse links with from "
+ MgnlContext.getAggregationState().getCurrentURI()
+ e.getMessage());
}
return url;
}
/**
* Convert a content list into a collection, also wrapping the content inside a I18NNodeMapWrapper
* @param list the list to be converted
* @return a collection with the user's content
*/
public static List convertToCollection(List list)
{
List itemsList = new ArrayList();
Collection result = list;
for (Content content : result)
{
itemsList.add(new NodeMapWrapper(content, content.getHandle()));
}
return itemsList;
}
/**
* Check if the content parameter has a child with title equal the title parameter
* @param content
* @param title
* @return
*/
public static Boolean hasChildWithTitle(Content content, String title)
{
for (Content currentChild : content.getChildren())
{
if (currentChild.getTitle() != null && currentChild.getTitle().equalsIgnoreCase(title))
{
return true;
}
}
return false;
}
/**
* Get child nodes of specified content type and its subtypes
* @param content
* @param contentType
* @return
*/
public static Collection contentChildrenOfType(Content content, String contentType)
{
return content.getChildren(contentType);
}
}