file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
MCRXPathBuilder.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRXPathBuilder.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.Parent;
import org.mycore.common.MCRConstants;
/**
* Builds an absolute XPath expression for a given element or attribute within a JDOM XML structure.
*
* @author Frank Lützenkirchen
*/
public class MCRXPathBuilder {
/**
* Builds an absolute XPath expression for a given element or attribute within a JDOM XML structure.
* For each element that is not the root element, the XPath will also contain a position predicate.
* For all namespaces commonly used in MyCoRe, their namespace prefixes will be used.
*
* @param object a JDOM element or attribute
* @return absolute XPath of that object. In case there is a root Document, it will begin with a "/".
*/
public static String buildXPath(Object object) {
if (object instanceof Element element) {
return buildXPath(element);
} else if (object instanceof Attribute attribute) {
return buildXPath(attribute);
} else {
return "";
}
}
/**
* Builds an absolute XPath expression for the given attribute within a JDOM XML structure.
* For each element that is not the root element, the XPath will also contain a position predicate.
* For all namespaces commonly used in MyCoRe, their namespace prefixes will be used.
*
* @param attribute a JDOM attribute
* @return absolute XPath of that attribute. In case there is a root Document, it will begin with a "/".
*/
public static String buildXPath(Attribute attribute) {
String parentXPath = buildXPath(attribute.getParent());
if (!parentXPath.isEmpty()) {
parentXPath += "/";
}
return parentXPath + "@" + attribute.getQualifiedName();
}
/**
* Builds an absolute XPath expression for the given element within a JDOM XML structure.
* For each element that is not the root element, the XPath will also contain a position predicate.
* For all namespaces commonly used in MyCoRe, their namespace prefixes will be used.
*
* @param element a JDOM element
* @return absolute XPath of that element. In case there is a root Document, it will begin with a "/".
*/
public static String buildXPath(Element element) {
if (element == null) {
return "";
}
String parentXPath = buildXPath(element.getParent());
if ((!parentXPath.isEmpty()) || (element.getParent() instanceof Document)) {
parentXPath += "/";
}
return parentXPath + buildChildPath(element);
}
/**
* Builds a local XPath fragment as combined namespace prefix, local element name and position predicate
*/
public static String buildChildPath(Element element) {
return getNamespacePrefix(element) + element.getName() + buildPositionPredicate(element);
}
/**
* Returns the namespace prefix for this element, followed by a ":",
* or the empty string if no namespace prefix known.
*/
public static String getNamespacePrefix(Element element) {
Namespace nsElement = element.getNamespace();
for (Namespace ns : MCRConstants.getStandardNamespaces()) {
if (ns.equals(nsElement)) {
return ns.getPrefix() + ":";
}
}
String prefix = nsElement.getPrefix();
if ((prefix != null) && !prefix.isEmpty()) {
return prefix + ":";
} else {
return "";
}
}
private static String buildPositionPredicate(Element element) {
Parent parent = element.getParent();
if ((parent instanceof Document) || (parent == null)) {
return "";
}
Element parentElement = (Element) parent;
List<Element> siblings = parentElement.getChildren(element.getName(), element.getNamespace());
int pos = siblings.indexOf(element) + 1;
return "[" + pos + "]";
}
}
| 4,848 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXPathEvaluator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRXPathEvaluator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Parent;
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.mycore.common.MCRConstants;
import org.mycore.common.config.MCRConfiguration2;
/**
* @author Frank Lützenkirchen
*/
public class MCRXPathEvaluator {
private static final Logger LOGGER = LogManager.getLogger(MCRXPathEvaluator.class);
private static final Pattern PATTERN_XPATH = Pattern.compile("\\{([^\\}]+)\\}");
private static final XPathFactory XPATH_FACTORY = MCRConfiguration2.getString("MCR.XPathFactory.Class")
.map(XPathFactory::newInstance)
.orElseGet(XPathFactory::instance);
private Map<String, Object> variables;
private List<Object> context;
public MCRXPathEvaluator(Map<String, Object> variables, List<Object> context) {
this.variables = variables;
this.context = context;
}
public MCRXPathEvaluator(Map<String, Object> variables, Parent context) {
this.variables = variables;
this.context = new ArrayList<>();
this.context.add(context);
}
public String replaceXPaths(String text, boolean urlEncode) {
Matcher m = PATTERN_XPATH.matcher(text);
StringBuilder sb = new StringBuilder();
while (m.find()) {
String replacement = replaceXPathOrI18n(m.group(1));
if (urlEncode) {
replacement = URLEncoder.encode(replacement, StandardCharsets.UTF_8);
}
m.appendReplacement(sb, replacement);
}
m.appendTail(sb);
return sb.toString();
}
public String replaceXPathOrI18n(String expression) {
expression = migrateLegacyI18nSyntaxToExtensionFunction(expression);
return evaluateXPath(expression);
}
private String migrateLegacyI18nSyntaxToExtensionFunction(String expression) {
if (expression.startsWith("i18n:")) {
expression = expression.substring(5);
if (expression.contains(",")) {
int pos = expression.indexOf(",");
String key = expression.substring(0, pos);
String xPath = expression.substring(pos + 1);
expression = "i18n:translate('" + key + "'," + xPath + ")";
} else {
expression = "i18n:translate('" + expression + "')";
}
}
return expression;
}
public String evaluateXPath(String xPathExpression) {
xPathExpression = "string(" + xPathExpression + ")";
Object result = evaluateFirst(xPathExpression);
return result == null ? "" : (String) result;
}
public boolean test(String xPathExpression) {
Object result = evaluateFirst(xPathExpression);
if (result == null) {
return false;
} else if (result instanceof Boolean b) {
return b;
} else {
return true;
}
}
public Object evaluateFirst(String xPathExpression) {
try {
XPathExpression<Object> xPath = XPATH_FACTORY.compile(xPathExpression, Filters.fpassthrough(), variables,
MCRConstants.getStandardNamespaces());
return xPath.evaluateFirst(context);
} catch (Exception ex) {
LOGGER.warn("unable to evaluate XPath: {}", xPathExpression);
LOGGER.warn("XPath factory used is {} {}", XPATH_FACTORY.getClass().getCanonicalName(),
MCRConfiguration2.getString("MCR.XPathFactory.Class").orElse(null));
LOGGER.warn(ex);
return null;
}
}
}
| 4,653 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLParserErrorHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRXMLParserErrorHandler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
/**
* Handles errors during XML parsing.
*
* @author Frank Lützenkirchen
*/
public class MCRXMLParserErrorHandler implements ErrorHandler {
private static final Logger LOGGER = LogManager.getLogger(MCRXMLParserErrorHandler.class);
protected boolean silent;
public MCRXMLParserErrorHandler() {
this(false);
}
public MCRXMLParserErrorHandler(boolean silent) {
this.silent = silent;
}
/**
* Handles parser warnings
*/
public void warning(SAXParseException ex) {
if (!silent) {
LOGGER.warn(getSAXErrorMessage(ex), ex);
}
}
/**
* Handles parse errors
*/
public void error(SAXParseException ex) {
if (!silent) {
LOGGER.error(getSAXErrorMessage(ex), ex);
}
throw new RuntimeException(ex);
}
/**
* Handles fatal parse errors
*/
public void fatalError(SAXParseException ex) {
if (!silent) {
LOGGER.fatal(getSAXErrorMessage(ex));
}
throw new RuntimeException(ex);
}
/**
* Returns a text indicating at which line and column the error occured.
*
* @param ex the SAXParseException exception
* @return the location string
*/
public static String getSAXErrorMessage(SAXParseException ex) {
StringBuilder str = new StringBuilder();
String systemId = ex.getSystemId();
if (systemId != null) {
int index = systemId.lastIndexOf('/');
if (index != -1) {
systemId = systemId.substring(index + 1);
}
str.append(systemId).append(": ");
}
str.append("line ").append(ex.getLineNumber());
str.append(", column ").append(ex.getColumnNumber());
str.append(", ");
str.append(ex.getLocalizedMessage());
return str.toString();
}
}
| 2,814 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRURIResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRURIResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPathExpressionException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.transform.JDOMSource;
import org.mycore.access.MCRAccessManager;
import org.mycore.common.MCRCache;
import org.mycore.common.MCRClassTools;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRCoreVersion;
import org.mycore.common.MCRDeveloperTools;
import org.mycore.common.MCRException;
import org.mycore.common.MCRHTTPClient;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRUsageException;
import org.mycore.common.MCRUserInformation;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationDir;
import org.mycore.common.content.MCRByteContent;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRPathContent;
import org.mycore.common.content.MCRSourceContent;
import org.mycore.common.content.MCRStreamContent;
import org.mycore.common.content.transformer.MCRContentTransformer;
import org.mycore.common.content.transformer.MCRParameterizedTransformer;
import org.mycore.common.content.transformer.MCRXSLTransformer;
import org.mycore.common.xsl.MCRLazyStreamSource;
import org.mycore.common.xsl.MCRParameterCollector;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.utils.MCRCategoryTransformer;
import org.mycore.datamodel.common.MCRAbstractMetadataVersion;
import org.mycore.datamodel.common.MCRDataURL;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRFileMetadata;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectDerivate;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.datamodel.niofs.MCRPathXML;
import org.mycore.frontend.MCRLayoutUtilities;
import org.mycore.services.i18n.MCRTranslation;
import org.mycore.tools.MCRObjectFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import jakarta.servlet.ServletContext;
/**
* Reads XML documents from various URI types. This resolver is used to read DTDs, XML Schema files, XSL document()
* usages, xsl:include usages and MyCoRe Editor include declarations. DTDs and Schema files are read from the CLASSPATH
* of the application when XML is parsed. XML document() calls and xsl:include calls within XSL stylesheets can be read
* from URIs of type resource, webapp, file, session, query or mcrobject. MyCoRe editor include declarations can read
* XML files from resource, webapp, file, session, http or https, query, or mcrobject URIs.
*
* @author Frank Lützenkirchen
* @author Thomas Scheffler (yagee)
*/
public final class MCRURIResolver implements URIResolver {
static final Logger LOGGER = LogManager.getLogger(MCRURIResolver.class);
static final String SESSION_OBJECT_NAME = "URI_RESOLVER_DEBUG";
private static final String CONFIG_PREFIX = "MCR.URIResolver.";
private static final String HTTP_CLIENT_CLASS = "MCR.HTTPClient.Class";
private static final Marker UNIQUE_MARKER = MarkerManager.getMarker("tryResolveXML");
private static Map<String, URIResolver> SUPPORTED_SCHEMES;
private static MCRResolverProvider EXT_RESOLVER;
private static MCRURIResolver singleton;
private static ServletContext context;
static {
try {
EXT_RESOLVER = getExternalResolverProvider();
singleton = new MCRURIResolver();
} catch (Exception exc) {
LOGGER.error("Unable to initialize MCRURIResolver", exc);
}
}
/**
* Creates a new MCRURIResolver
*/
private MCRURIResolver() {
SUPPORTED_SCHEMES = Collections.unmodifiableMap(getResolverMapping());
}
private static MCRResolverProvider getExternalResolverProvider() {
return MCRConfiguration2.getClass(CONFIG_PREFIX + "ExternalResolver.Class")
.map(c -> {
try {
return (MCRResolverProvider) c.getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
LOGGER.warn("Could not instantiate external Resolver class", e);
return null;
}
}).orElse(HashMap::new);
}
/**
* Returns the MCRURIResolver singleton
*/
public static MCRURIResolver instance() {
return singleton;
}
/**
* Initializes the MCRURIResolver for servlet applications.
*
* @param ctx
* the servlet context of this web application
*/
public static synchronized void init(ServletContext ctx) {
context = ctx;
}
public static Hashtable<String, String> getParameterMap(String key) {
String[] param;
StringTokenizer tok = new StringTokenizer(key, "&");
Hashtable<String, String> params = new Hashtable<>();
while (tok.hasMoreTokens()) {
param = tok.nextToken().split("=");
params.put(param[0], param.length >= 2 ? param[1] : "");
}
return params;
}
static URI resolveURI(String href, String base) {
return Optional.ofNullable(base)
.map(URI::create)
.map(u -> u.resolve(href))
.orElse(URI.create(href));
}
public static ServletContext getServletContext() {
return context;
}
private HashMap<String, URIResolver> getResolverMapping() {
final Map<String, URIResolver> extResolverMapping = EXT_RESOLVER.getURIResolverMapping();
extResolverMapping.putAll(new MCRModuleResolverProvider().getURIResolverMapping());
// set Map to final size with loadfactor: full
HashMap<String, URIResolver> supportedSchemes = new HashMap<>(10 + extResolverMapping.size(), 1);
// don't let interal mapping be overwritten
supportedSchemes.putAll(extResolverMapping);
supportedSchemes.put("webapp", new MCRWebAppResolver());
supportedSchemes.put("ifs", new MCRIFSResolver());
supportedSchemes.put("mcrfile", new MCRMCRFileResolver());
supportedSchemes.put("mcrobject", new MCRObjectResolver());
supportedSchemes.put("session", new MCRSessionResolver());
supportedSchemes.put("access", new MCRACLResolver());
supportedSchemes.put("resource", new MCRResourceResolver());
supportedSchemes.put("localclass", new MCRLocalClassResolver());
supportedSchemes.put("classification", new MCRClassificationResolver());
supportedSchemes.put("buildxml", new MCRBuildXMLResolver());
supportedSchemes.put("catchEx", new MCRExceptionAsXMLResolver());
supportedSchemes.put("notnull", new MCRNotNullResolver());
supportedSchemes.put("xslStyle", new MCRXslStyleResolver());
supportedSchemes.put("xslStyleXEditor", new MCRXslStyleXEditorResolver());
supportedSchemes.put("xslTransform", new MCRLayoutTransformerResolver());
supportedSchemes.put("xslInclude", new MCRXslIncludeResolver());
supportedSchemes.put("xslImport", new MCRXslImportResolver());
supportedSchemes.put("currentUserInfo", new MCRCurrentUserInfoResolver());
supportedSchemes.put("version", new MCRVersionResolver());
supportedSchemes.put("layoutUtils", new MCRLayoutUtilsResolver());
supportedSchemes.put("versioninfo", new MCRVersionInfoResolver());
supportedSchemes.put("deletedMcrObject", new MCRDeletedObjectResolver());
supportedSchemes.put("fileMeta", new MCRFileMetadataResolver());
supportedSchemes.put("basket", new org.mycore.frontend.basket.MCRBasketResolver());
supportedSchemes.put("language", new org.mycore.datamodel.language.MCRLanguageResolver());
supportedSchemes.put("chooseTemplate", new MCRChooseTemplateResolver());
supportedSchemes.put("redirect", new MCRRedirectResolver());
supportedSchemes.put("data", new MCRDataURLResolver());
supportedSchemes.put("i18n", new MCRI18NResolver());
supportedSchemes.put("checkPermissionChain", new MCRCheckPermissionChainResolver());
supportedSchemes.put("checkPermission", new MCRCheckPermissionResolver());
MCRRESTResolver restResolver = new MCRRESTResolver();
supportedSchemes.put("http", restResolver);
supportedSchemes.put("https", restResolver);
supportedSchemes.put("file", new MCRFileResolver());
supportedSchemes.put("cache", new MCRCachingResolver());
return supportedSchemes;
}
/**
* Tries to calculate the resource uri to the directory of the stylesheet that includes the given file.
* @param base the base uri of the stylesheet that includes the given file
* @return the resource uri to the directory of the stylesheet that includes the given file.
*/
static String getParentDirectoryResourceURI(String base) {
if (base == null) {
// the file was not included from another file, so we need to use the default resource directory
final String xslFolder = MCRConfiguration2.getStringOrThrow("MCR.Layout.Transformer.Factory.XSLFolder");
return "resource:" + xslFolder + "/";
} else {
String resolvingBase = null;
String configurationResourceDir = MCRConfigurationDir.getConfigurationDirectory().toPath()
.toAbsolutePath()
.normalize()
.resolve("resources")
.toFile()
.toURI()
.toString();
String webappPath = context != null ? new File(context.getRealPath("/WEB-INF/classes/")).toURI().toString()
: null;
Optional<String> matching = MCRDeveloperTools.getOverridePaths()
.map(Path::toAbsolutePath)
.map(Path::toFile)
.map(File::toURI)
.map(URI::toString)
.filter(base::startsWith)
.findFirst();
if (matching.isPresent()) {
// in this case the developer mode is active and the file is in the override directory e.G.
// /root/workspace/mir/src/main/resources/xsl/mir-accesskey-utils.xsl
resolvingBase = base.substring(matching.get().length());
} else if (base.contains(".jar!")) {
// in this case the file is in a jar file e.G.
// /root/.m2/repository/some/directory/some.jar!/xsl/directory/myfile.xsl
resolvingBase = base.lastIndexOf(".jar!") > 0
? base.substring(base.lastIndexOf(".jar!") + ".jar!".length())
: base;
} else if (base.startsWith(configurationResourceDir)) {
// in this case the file is in the configuration directory e.G.
// file:/root/.mycore/dev-mir/resources/xsl/mir-accesskey-utils.xsl
resolvingBase = base.substring(configurationResourceDir.length());
} else if (webappPath != null && base.startsWith(webappPath)) {
// in this case the file is in the webapp directory e.G.
// file:/../mir/mir-webapp/target/catalina-base/webapps/mir/WEB-INF/classes/xsl/mir-accesskey-utils.xsl
resolvingBase = base.substring(webappPath.length());
}
if (resolvingBase != null) {
resolvingBase = resolvingBase.startsWith("/") ? resolvingBase.substring(1) : resolvingBase;
resolvingBase = "resource:" + resolvingBase;
} else {
resolvingBase = base;
}
if (!resolvingBase.endsWith("/") && resolvingBase.lastIndexOf('/') > 0) {
resolvingBase = resolvingBase.substring(0, resolvingBase.lastIndexOf('/') + 1);
}
return resolvingBase;
}
}
/**
* URI Resolver that resolves XSL document() or xsl:include calls.
*
* @see javax.xml.transform.URIResolver
*/
@Override
public Source resolve(String href, String base) throws TransformerException {
if (LOGGER.isDebugEnabled()) {
if (base != null) {
LOGGER.debug("Including {} from {}", href, base);
addDebugInfo(href, base);
} else {
LOGGER.debug("Including {}", href);
addDebugInfo(href, null);
}
}
if (!href.contains(":")) {
if (!href.endsWith(".xsl")) {
return null;
}
return tryResolveXSL(href, base);
}
String scheme = getScheme(href, base);
URIResolver uriResolver = SUPPORTED_SCHEMES.get(scheme);
if (uriResolver != null) {
Source resolved = uriResolver.resolve(href, base);
if (resolved.getSystemId() == null) {
resolved.setSystemId(href);
}
return resolved;
} else { // try to handle as URL, use default resolver for file:// and
try {
InputSource entity = MCREntityResolver.instance().resolveEntity(null, href);
if (entity != null) {
LOGGER.debug("Resolved via EntityResolver: {}", entity.getSystemId());
return new MCRLazyStreamSource(entity::getByteStream, entity.getSystemId());
}
} catch (IOException e) {
LOGGER.debug("Error while resolving uri: {}", href);
}
// http://
if (href.endsWith("/") && scheme.equals("file")) {
//cannot stream directories
return null;
}
StreamSource streamSource = new StreamSource();
streamSource.setSystemId(href);
return streamSource;
}
}
private Source tryResolveXSL(String href, String base) throws TransformerException {
String baseURI = getParentDirectoryResourceURI(base);
final String uri = baseURI + href;
LOGGER.debug("Trying to resolve {} from uri {}", href, uri);
Source newResolveMethodResult = SUPPORTED_SCHEMES.get("resource").resolve(uri, base);
if (newResolveMethodResult != null) {
return newResolveMethodResult;
}
// new relative include did not work, now fall back to old behaviour and print a warning if it works
final String xslFolder = MCRConfiguration2.getStringOrThrow("MCR.Layout.Transformer.Factory.XSLFolder");
Source oldResolveMethodResult = SUPPORTED_SCHEMES.get("resource")
.resolve("resource:" + xslFolder + "/" + href, base);
if (oldResolveMethodResult != null) {
LOGGER.warn(UNIQUE_MARKER, "The Stylesheet {} has include {} which only works with an old " +
"absolute include mechanism. Please change the include to relative!", base, href);
}
return oldResolveMethodResult;
}
private void addDebugInfo(String href, String base) {
MCRURIResolverFilter.uriList.get().add(href + " from " + base);
}
/**
* Reads XML from URIs of various type.
*
* @param uri
* the URI where to read the XML from
* @return the root element of the XML document
*/
public Element resolve(String uri) {
if (LOGGER.isDebugEnabled()) {
addDebugInfo(uri, "JAVA method invocation");
}
MCRSourceContent content;
try {
content = MCRSourceContent.getInstance(uri);
return content == null ? null : content.asXML().getRootElement().detach();
} catch (Exception e) {
throw new MCRException("Error while resolving " + uri, e);
}
}
/**
* Returns the protocol or scheme for the given URI.
*
* @param uri
* the URI to parse
* @param base
* if uri is relative, resolve scheme from base parameter
* @return the protocol/scheme part before the ":"
*/
public String getScheme(String uri, String base) {
StringTokenizer uriTokenizer = new StringTokenizer(uri, ":");
if (uriTokenizer.hasMoreTokens()) {
return uriTokenizer.nextToken();
}
if (base != null) {
uriTokenizer = new StringTokenizer(base, ":");
if (uriTokenizer.hasMoreTokens()) {
return uriTokenizer.nextToken();
}
}
return null;
}
@Deprecated
URIResolver getResolver(String scheme) {
if (SUPPORTED_SCHEMES.containsKey(scheme)) {
return SUPPORTED_SCHEMES.get(scheme);
}
String msg = "Unsupported scheme type: " + scheme;
throw new MCRUsageException(msg);
}
/**
* Reads xml from an InputStream and returns the parsed root element.
*
* @param in
* the InputStream that contains the XML document
* @return the root element of the parsed input stream
*/
@Deprecated
protected Element parseStream(InputStream in) throws JDOMException, IOException {
final MCRStreamContent streamContent = new MCRStreamContent(in);
return MCRXMLParserFactory
.getNonValidatingParser()
.parseXML(streamContent)
.getRootElement();
}
/**
* provides a URI -- Resolver Mapping One can implement this interface to provide additional URI schemes this
* MCRURIResolver should handle, too. To add your mapping you have to set the
* <code>MCR.URIResolver.ExternalResolver.Class</code> property to the implementing class.
*
* @author Thomas Scheffler
*/
public interface MCRResolverProvider {
/**
* provides a Map of URIResolver mappings. Key is the scheme, e.g. <code>http</code>, where value is an
* implementation of {@link URIResolver}.
*
* @see URIResolver
* @return a Map of URIResolver mappings
*/
Map<String, URIResolver> getURIResolverMapping();
}
public interface MCRXslIncludeHrefs {
List<String> getHrefs();
}
private static class MCRModuleResolverProvider implements MCRResolverProvider {
private final Map<String, URIResolver> resolverMap = new HashMap<>();
MCRModuleResolverProvider() {
MCRConfiguration2.getSubPropertiesMap(CONFIG_PREFIX + "ModuleResolver.")
.forEach(this::registerUriResolver);
}
@Override
public Map<String, URIResolver> getURIResolverMapping() {
return resolverMap;
}
private void registerUriResolver(String scheme, String className) {
try {
resolverMap.put(scheme, MCRConfiguration2.instantiateClass(className));
} catch (RuntimeException re) {
throw new MCRException("Cannot instantiate " + className + " for URI scheme " + scheme, re);
}
}
}
private static class MCRFileResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
URI hrefURI = MCRURIResolver.resolveURI(href, base);
if (!hrefURI.getScheme().equals("file")) {
throw new TransformerException("Unsupport file uri scheme: " + hrefURI.getScheme());
}
Path path = Paths.get(hrefURI);
StreamSource source;
try {
source = new StreamSource(Files.newInputStream(path), hrefURI.toASCIIString());
return source;
} catch (IOException e) {
throw new TransformerException(e);
}
}
}
private static class MCRRESTResolver implements URIResolver {
private MCRHTTPClient client;
MCRRESTResolver() {
this.client = (MCRHTTPClient) MCRConfiguration2.getInstanceOf(HTTP_CLIENT_CLASS).get();
}
@Override
public Source resolve(String href, String base) throws TransformerException {
URI hrefURI = MCRURIResolver.resolveURI(href, base);
try {
final Source source = client.get(hrefURI).getSource();
source.setSystemId(hrefURI.toASCIIString());
return source;
} catch (IOException e) {
throw new TransformerException(e);
}
}
}
private static class MCRObjectResolver implements URIResolver {
/**
* Reads local MCRObject with a given ID from the store.
*
* @param href
* for example, "mcrobject:DocPortal_document_07910401"
* @return XML representation from MCRXMLContainer
*/
@Override
public Source resolve(String href, String base) throws TransformerException {
String id = href.substring(href.indexOf(":") + 1);
LOGGER.debug("Reading MCRObject with ID {}", id);
Map<String, String> params;
StringTokenizer tok = new StringTokenizer(id, "?");
id = tok.nextToken();
if (tok.hasMoreTokens()) {
params = getParameterMap(tok.nextToken());
} else {
params = Collections.emptyMap();
}
MCRObjectID mcrid = MCRObjectID.getInstance(id);
try {
MCRXMLMetadataManager xmlmm = MCRXMLMetadataManager.instance();
MCRContent content = params.containsKey("r")
? xmlmm.retrieveContent(mcrid, params.get("r"))
: xmlmm.retrieveContent(mcrid);
if (content == null) {
return null;
}
LOGGER.debug("end resolving {}", href);
return content.getSource();
} catch (IOException e) {
throw new TransformerException(e);
}
}
}
/**
* Reads XML from a static file within the web application. the URI in the format webapp:path/to/servlet
*/
private static class MCRWebAppResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
String path = href.substring(href.indexOf(":") + 1);
if (path.charAt(0) != '/') {
path = '/' + path;
}
if (MCRDeveloperTools.overrideActive()) {
final Optional<Path> overriddenFilePath = MCRDeveloperTools.getOverriddenFilePath(path, true);
if (overriddenFilePath.isPresent()) {
return new StreamSource(overriddenFilePath.get().toFile());
}
}
LOGGER.debug("Reading xml from webapp {}", path);
try {
URL resource = context.getResource(path);
if (resource != null) {
return new StreamSource(resource.toURI().toASCIIString());
}
} catch (Exception ex) {
throw new TransformerException(ex);
}
LOGGER.error("File does not exist: {}", context.getRealPath(path));
throw new TransformerException("Could not find web resource: " + path);
}
}
private static class MCRChooseTemplateResolver implements URIResolver {
private static Document getStylesheets(List<String> temps) {
Element rootOut = new Element("stylesheet", MCRConstants.XSL_NAMESPACE).setAttribute("version", "1.0");
Document jdom = new Document(rootOut);
if (temps.isEmpty()) {
return jdom;
}
for (String templateName : temps) {
rootOut.addContent(
new Element("include", MCRConstants.XSL_NAMESPACE).setAttribute("href", templateName + ".xsl"));
}
// first template named "chooseTemplate" in chooseTemplate.xsl
Element template = new Element("template", MCRConstants.XSL_NAMESPACE).setAttribute("name",
"chooseTemplate");
Element choose = new Element("choose", MCRConstants.XSL_NAMESPACE);
// second template named "get.templates" in chooseTemplate.xsl
Element template2 = new Element("template", MCRConstants.XSL_NAMESPACE).setAttribute("name",
"get.templates");
Element templates = new Element("templates");
for (String templateName : temps) {
// add elements in the first template
Element when = new Element("when", MCRConstants.XSL_NAMESPACE).setAttribute("test",
"$template = '" + templateName + "'");
when.addContent(
new Element("call-template", MCRConstants.XSL_NAMESPACE).setAttribute("name", templateName));
choose.addContent(when);
// add elements in the second template
templates.addContent(new Element("template").setAttribute("category", "master").setText(templateName));
}
// first
template.addContent(choose);
rootOut.addContent(template);
// second
template2.addContent(templates);
rootOut.addContent(template2);
return jdom;
}
@Override
public Source resolve(String href, String base) {
String type = href.substring(href.indexOf(":") + 1);
String path = "/templates/" + type + "/";
LOGGER.debug("Reading templates from {}", path);
Set<String> resourcePaths = context.getResourcePaths(path);
ArrayList<String> templates = new ArrayList<>();
if (resourcePaths != null) {
for (String resourcePath : resourcePaths) {
if (!resourcePath.endsWith("/")) {
//only handle directories
continue;
}
String templateName = resourcePath.substring(path.length(), resourcePath.length() - 1);
LOGGER.debug("Checking if template: {}", templateName);
if (templateName.contains("/")) {
continue;
}
templates.add(templateName);
}
Collections.sort(templates);
}
LOGGER.info("Found theses templates: {}", templates);
return new JDOMSource(getStylesheets(templates));
}
}
/**
* Reads XML from the CLASSPATH of the application. the location of the file in the format resource:path/to/file
*/
private static class MCRResourceResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
String path = href.substring(href.indexOf(":") + 1);
URL resource = MCRConfigurationDir.getConfigResource(path);
if (resource != null) {
//have to use SAX here to resolve entities
if (path.endsWith(".xsl")) {
XMLReader reader;
try {
reader = MCRXMLParserFactory.getNonValidatingParser().getXMLReader();
} catch (SAXException | ParserConfigurationException e) {
throw new TransformerException(e);
}
reader.setEntityResolver(MCREntityResolver.instance());
InputSource input = new InputSource(resource.toString());
SAXSource saxSource = new SAXSource(reader, input);
LOGGER.debug("include stylesheet: {}", saxSource.getSystemId());
return saxSource;
}
return MCRURIResolver.instance().resolve(resource.toString(), base);
}
return null;
}
}
/**
* Delivers a jdom Element created by any local class that implements URIResolver
* interface. the class name of the file in the format localclass:org.mycore.ClassName?mode=getAll
*/
private static class MCRLocalClassResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
String classname = href.substring(href.indexOf(":") + 1, href.indexOf("?"));
Class<? extends URIResolver> cl = null;
LogManager.getLogger(this.getClass()).debug("Loading Class: {}", classname);
URIResolver resolver;
try {
cl = MCRClassTools.forName(classname);
resolver = cl.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new TransformerException(e);
}
return resolver.resolve(href, base);
}
}
private static class MCRSessionResolver implements URIResolver {
/**
* Reads XML from URIs of type session:key. The method MCRSession.get( key ) is called and must return a JDOM
* element.
*
* @see org.mycore.common.MCRSession#get(Object)
* @param href
* the URI in the format session:key
* @return the root element of the xml document
*/
@Override
public Source resolve(String href, String base) {
String key = href.substring(href.indexOf(":") + 1);
LOGGER.debug("Reading xml from session using key {}", key);
Element value = (Element) MCRSessionMgr.getCurrentSession().get(key);
return new JDOMSource(value.clone());
}
}
private static class MCRIFSResolver implements URIResolver {
/**
* Reads XML from a http or https URL.
*
* @param href
* the URL of the xml document
* @return the root element of the xml document
*/
@Override
public Source resolve(String href, String base) throws TransformerException {
LOGGER.debug("Reading xml from url {}", href);
String path = href.substring(href.indexOf(":") + 1);
int i = path.indexOf("?host");
if (i > 0) {
path = path.substring(0, i);
}
StringTokenizer st = new StringTokenizer(path, "/");
String ownerID = st.nextToken();
try {
String aPath = MCRXMLFunctions.decodeURIPath(path.substring(ownerID.length() + 1));
// TODO: make this more pretty
if (ownerID.endsWith(":")) {
ownerID = ownerID.substring(0, ownerID.length() - 1);
}
LOGGER.debug("Get {} path: {}", ownerID, aPath);
return new JDOMSource(MCRPathXML.getDirectoryXML(MCRPath.getPath(ownerID, aPath)));
} catch (IOException | URISyntaxException e) {
throw new TransformerException(e);
}
}
}
private static class MCRMCRFileResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
LOGGER.debug("Reading xml from MCRFile {}", href);
MCRPath file = null;
String id = href.substring(href.indexOf(":") + 1);
if (id.contains("/")) {
// assume thats a derivate with path
try {
MCRObjectID derivateID = MCRObjectID.getInstance(id.substring(0, id.indexOf("/")));
String path = id.substring(id.indexOf("/"));
file = MCRPath.getPath(derivateID.toString(), path);
} catch (MCRException exc) {
// just check if the id is valid, don't care about the exception
}
}
if (file == null) {
throw new TransformerException("mcrfile: Resolver needs a path: " + href);
}
try {
return new MCRPathContent(file).getSource();
} catch (Exception e) {
throw new TransformerException(e);
}
}
}
private static class MCRACLResolver implements URIResolver {
private static final String ACTION_PARAM = "action";
private static final String OBJECT_ID_PARAM = "object";
/**
* Returns access controll rules as XML
*/
@Override
public Source resolve(String href, String base) {
String key = href.substring(href.indexOf(":") + 1);
LOGGER.debug("Reading xml from query result using key :{}", key);
String[] param;
StringTokenizer tok = new StringTokenizer(key, "&");
Hashtable<String, String> params = new Hashtable<>();
while (tok.hasMoreTokens()) {
param = tok.nextToken().split("=");
params.put(param[0], param[1]);
}
String action = params.get(ACTION_PARAM);
String objId = params.get(OBJECT_ID_PARAM);
if (action == null || objId == null) {
return null;
}
Element container = new Element("servacls").setAttribute("class", "MCRMetaAccessRule");
if(MCRAccessManager.implementsRulesInterface()) {
if (action.equals("all")) {
for (String permission : MCRAccessManager.getPermissionsForID(objId)) {
// one pool Element under access per defined AccessRule in pool for (Object-)ID
addRule(container, permission,
MCRAccessManager.requireRulesInterface().getRule(objId, permission));
}
} else {
addRule(container, action, MCRAccessManager.requireRulesInterface().getRule(objId, action));
}
}
return new JDOMSource(container);
}
private void addRule(Element root, String pool, Element rule) {
if (rule != null && pool != null) {
Element poolElement = new Element("servacl").setAttribute("permission", pool);
poolElement.addContent(rule);
root.addContent(poolElement);
}
}
}
private static class MCRClassificationResolver implements URIResolver {
private static final Pattern EDITORFORMAT_PATTERN = Pattern.compile("(\\[)([^\\]]*)(\\])");
private static final String FORMAT_CONFIG_PREFIX = CONFIG_PREFIX + "Classification.Format.";
private static final String SORT_CONFIG_PREFIX = CONFIG_PREFIX + "Classification.Sort.";
private static MCRCache<String, Element> categoryCache;
private static MCRCategoryDAO DAO;
static {
try {
DAO = MCRCategoryDAOFactory.getInstance();
categoryCache = new MCRCache<>(
MCRConfiguration2.getInt(CONFIG_PREFIX + "Classification.CacheSize").orElse(1000),
"URIResolver categories");
} catch (Exception exc) {
LOGGER.error("Unable to initialize classification resolver", exc);
}
}
MCRClassificationResolver() {
}
private static String getLabelFormat(String editorString) {
Matcher m = EDITORFORMAT_PATTERN.matcher(editorString);
if (m.find() && m.groupCount() == 3) {
String formatDef = m.group(2);
return MCRConfiguration2.getStringOrThrow(FORMAT_CONFIG_PREFIX + formatDef);
}
return null;
}
private static boolean shouldSortCategories(String classId) {
return MCRConfiguration2.getBoolean(SORT_CONFIG_PREFIX + classId).orElse(true);
}
private static long getSystemLastModified() {
long xmlLastModified = MCRXMLMetadataManager.instance().getLastModified();
long classLastModified = DAO.getLastModified();
return Math.max(xmlLastModified, classLastModified);
}
/**
* returns a classification in a specific format. Syntax:
* <code>classification:{editor[Complete]['['formatAlias']']|metadata}:{Levels}[:noEmptyLeaves]:{parents|
* children}:{ClassID}[:CategID] formatAlias: MCRConfiguration property
* MCR.UURResolver.Classification.Format.FormatAlias
*
* @param href
* URI in the syntax above
* @return the root element of the XML document
* @see MCRCategoryTransformer
*/
@Override
public Source resolve(String href, String base) {
LOGGER.debug("start resolving {}", href);
String cacheKey = getCacheKey(href);
Element returns = categoryCache.getIfUpToDate(cacheKey, getSystemLastModified());
if (returns == null) {
returns = getClassElement(href);
if (returns != null) {
categoryCache.put(cacheKey, returns);
}
}
return new JDOMSource(returns);
}
protected String getCacheKey(String uri) {
return uri;
}
private Element getClassElement(String uri) {
StringTokenizer pst = new StringTokenizer(uri, ":", true);
if (pst.countTokens() < 9) {
// sanity check
throw new IllegalArgumentException("Invalid format of uri for retrieval of classification: " + uri);
}
pst.nextToken(); // "classification"
pst.nextToken(); // :
String format = pst.nextToken();
pst.nextToken(); // :
String levelS = pst.nextToken();
pst.nextToken(); // :
int levels = Objects.equals(levelS, "all") ? -1 : Integer.parseInt(levelS);
String axis;
String token = pst.nextToken();
pst.nextToken(); // :
boolean emptyLeaves = !Objects.equals(token, "noEmptyLeaves");
if (!emptyLeaves) {
axis = pst.nextToken();
pst.nextToken(); // :
} else {
axis = token;
}
String classID = pst.nextToken();
StringBuilder categID = new StringBuilder();
if (pst.hasMoreTokens()) {
pst.nextToken(); // :
while (pst.hasMoreTokens()) {
categID.append(pst.nextToken());
}
}
String categ;
try {
categ = MCRXMLFunctions.decodeURIPath(categID.toString());
} catch (URISyntaxException e) {
categ = categID.toString();
}
MCRCategory cl = null;
LOGGER.debug("categoryCache entry invalid or not found: start MCRClassificationQuery");
if (axis.equals("children")) {
if (categ.length() > 0) {
cl = DAO.getCategory(new MCRCategoryID(classID, categ), levels);
} else {
cl = DAO.getCategory(MCRCategoryID.rootID(classID), levels);
}
} else if (axis.equals("parents")) {
if (categ.length() == 0) {
LOGGER.error("Cannot resolve parent axis without a CategID. URI: {}", uri);
throw new IllegalArgumentException(
"Invalid format (categID is required in mode 'parents') "
+ "of uri for retrieval of classification: "
+ uri);
}
cl = DAO.getRootCategory(new MCRCategoryID(classID, categ), levels);
}
if (cl == null) {
return null;
}
Element returns;
LOGGER.debug("start transformation of ClassificationQuery");
if (format.startsWith("editor")) {
boolean completeId = format.startsWith("editorComplete");
boolean sort = shouldSortCategories(classID);
String labelFormat = getLabelFormat(format);
if (labelFormat == null) {
returns = MCRCategoryTransformer.getEditorItems(cl, sort, emptyLeaves, completeId);
} else {
returns = MCRCategoryTransformer.getEditorItems(cl, labelFormat, sort, emptyLeaves, completeId);
}
} else if (format.equals("metadata")) {
returns = MCRCategoryTransformer.getMetaDataDocument(cl, false).getRootElement().detach();
} else {
LOGGER.error("Unknown target format given. URI: {}", uri);
throw new IllegalArgumentException(
"Invalid target format (" + format + ") in uri for retrieval of classification: " + uri);
}
LOGGER.debug("end resolving {}", uri);
return returns;
}
}
private static class MCRExceptionAsXMLResolver implements URIResolver {
@Override
public Source resolve(String href, String base) {
String target = href.substring(href.indexOf(":") + 1);
try {
return MCRURIResolver.instance().resolve(target, base);
} catch (Exception ex) {
LOGGER.debug("Caught {}. Put it into XML to process in XSL!", ex.getClass().getName());
Element exception = new Element("exception");
Element message = new Element("message");
Element stacktraceElement = new Element("stacktrace");
stacktraceElement.setAttribute("space", "preserve", Namespace.XML_NAMESPACE);
exception.addContent(message);
exception.addContent(stacktraceElement);
message.setText(ex.getMessage());
try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
ex.printStackTrace(pw);
stacktraceElement.setText(pw.toString());
} catch (IOException e) {
throw new MCRException("Error while writing Exception to String!", e);
}
return new JDOMSource(exception);
}
}
}
/**
* Ensures that the return of the given uri is never null. When the return is null, or the uri throws an exception,
* this resolver will return an empty XML element instead. Usage: notnull:<anyMyCoReURI>
*/
private static class MCRNotNullResolver implements URIResolver {
@Override
public Source resolve(String href, String base) {
String target = href.substring(href.indexOf(":") + 1);
// fixes exceptions if suburi is empty like "mcrobject:"
String subUri = target.substring(target.indexOf(":") + 1);
if (subUri.length() == 0) {
return new JDOMSource(new Element("null"));
}
// end fix
LOGGER.debug("Ensuring xml is not null: {}", target);
try {
Source result = MCRURIResolver.instance().resolve(target, base);
if (result != null) {
// perform actual construction of xml document, as in MCRURIResolver#resolve(String),
// by performing the same actions as MCRSourceContent#asXml(),
// but with a MCRXMLParser configured to be silent to suppress undesirable log messages
MCRContent content = new MCRSourceContent(result).getBaseContent();
Document document = MCRXMLParserFactory.getParser(false, true).parseXML(content);
return new JDOMSource(document.getRootElement().detach());
} else {
LOGGER.debug("MCRNotNullResolver returning empty xml");
return new JDOMSource(new Element("null"));
}
} catch (Exception ex) {
LOGGER.info("MCRNotNullResolver caught exception: {}", ex.getLocalizedMessage());
LOGGER.debug(ex.getStackTrace());
LOGGER.debug("MCRNotNullResolver returning empty xml");
return new JDOMSource(new Element("null"));
}
}
}
/**
* Transform result of other resolver with stylesheet. Usage: xslStyle:<stylesheet><,stylesheet><?param1=value1
* <¶m2=value2>>:<anyMyCoReURI> To <stylesheet> is extension .xsl added. File is searched in classpath.
*/
private static class MCRXslStyleResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
String help = href.substring(href.indexOf(":") + 1);
String stylesheets = new StringTokenizer(help, ":").nextToken();
String target = help.substring(help.indexOf(":") + 1);
String subUri = target.substring(target.indexOf(":") + 1);
if (subUri.length() == 0) {
return new JDOMSource(new Element("null"));
}
Map<String, String> params;
StringTokenizer tok = new StringTokenizer(stylesheets, "?");
stylesheets = tok.nextToken();
if (tok.hasMoreTokens()) {
params = getParameterMap(tok.nextToken());
} else {
params = Collections.emptyMap();
}
Source resolved = MCRURIResolver.instance().resolve(target, base);
try {
if (resolved != null) {
if (resolved.getSystemId() == null) {
resolved.setSystemId(target);
}
MCRSourceContent content = new MCRSourceContent(resolved);
MCRXSLTransformer transformer = getTransformer(stylesheets.split(","));
MCRParameterCollector paramcollector = MCRParameterCollector.getInstanceFromUserSession();
paramcollector.setParameters(params);
MCRContent result = transformer.transform(content, paramcollector);
return result.getSource();
} else {
LOGGER.debug("MCRXslStyleResolver returning empty xml");
return new JDOMSource(new Element("null"));
}
} catch (IOException e) {
Throwable cause = e.getCause();
while (cause != null) {
if (cause instanceof TransformerException te) {
throw te;
}
cause = cause.getCause();
}
throw new TransformerException(e);
}
}
protected MCRXSLTransformer getTransformer(String... stylesheet) {
final String xslFolder = MCRConfiguration2.getStringOrThrow("MCR.Layout.Transformer.Factory.XSLFolder");
String[] stylesheets = new String[stylesheet.length];
for (int i = 0; i < stylesheets.length; i++) {
stylesheets[i] = xslFolder + "/" + stylesheet[i] + ".xsl";
}
return MCRXSLTransformer.getInstance(stylesheets);
}
}
private static class MCRXslStyleXEditorResolver extends MCRXslStyleResolver {
@Override
protected MCRXSLTransformer getTransformer(String... stylesheet) {
String[] stylesheets = new String[stylesheet.length];
for (int i = 0; i < stylesheets.length; i++) {
stylesheets[i] = "xsl/" + stylesheet[i] + ".xsl";
}
return MCRXSLTransformer.getInstance(stylesheets);
}
}
/**
* Transform result of other resolver with stylesheet. Usage: xslTransform:<transformer><?param1=value1
* <¶m2=value2>>:<anyMyCoReURI>
*/
private static class MCRLayoutTransformerResolver implements URIResolver {
private static final String TRANSFORMER_FACTORY_PROPERTY = "MCR.Layout.Transformer.Factory";
@Override
public Source resolve(String href, String base) throws TransformerException {
String help = href.substring(href.indexOf(":") + 1);
String transformerId = new StringTokenizer(help, ":").nextToken();
String target = help.substring(help.indexOf(":") + 1);
String subUri = target.substring(target.indexOf(":") + 1);
if (subUri.length() == 0) {
return new JDOMSource(new Element("null"));
}
Map<String, String> params;
StringTokenizer tok = new StringTokenizer(transformerId, "?");
transformerId = tok.nextToken();
if (tok.hasMoreTokens()) {
params = getParameterMap(tok.nextToken());
} else {
params = Collections.emptyMap();
}
Source resolved = MCRURIResolver.instance().resolve(target, base);
try {
if (resolved != null) {
MCRSourceContent content = new MCRSourceContent(resolved);
MCRLayoutTransformerFactory factory = MCRConfiguration2
.<MCRLayoutTransformerFactory>getInstanceOf(TRANSFORMER_FACTORY_PROPERTY)
.orElseGet(MCRLayoutTransformerFactory::new);
MCRContentTransformer transformer = factory.getTransformer(transformerId);
MCRContent result;
if (transformer instanceof MCRParameterizedTransformer parameterizedTransformer) {
MCRParameterCollector paramcollector = MCRParameterCollector.getInstanceFromUserSession();
paramcollector.setParameters(params);
result = parameterizedTransformer.transform(content, paramcollector);
} else {
result = transformer.transform(content);
}
return result.getSource();
} else {
LOGGER.debug("MCRLayoutStyleResolver returning empty xml");
return new JDOMSource(new Element("null"));
}
} catch (Exception e) {
Throwable cause = e.getCause();
while (cause != null) {
if (cause instanceof TransformerException te) {
throw te;
}
cause = cause.getCause();
}
throw new TransformerException(e);
}
}
}
/**
* <p>
* Includes xsl files which are set in the mycore.properties file.
* </p>
* Example: MCR.URIResolver.xslIncludes.components=iview.xsl,wcms.xsl
* <p>
* Or retrieve the include hrefs from a class implementing
* {@link org.mycore.common.xml.MCRURIResolver.MCRXslIncludeHrefs}. The class. part have to be set, everything after
* class. can be freely choosen.
* </p>
* Example: MCR.URIResolver.xslIncludes.class.template=org.foo.XSLHrefs
*
* @return A xsl file with the includes as href.
*/
private static class MCRXslIncludeResolver implements URIResolver {
private static final Logger LOGGER = LogManager.getLogger(MCRXslIncludeResolver.class);
@Override
public Source resolve(String href, String base) {
String includePart = href.substring(href.indexOf(":") + 1);
Namespace xslNamespace = Namespace.getNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
Element root = new Element("stylesheet", xslNamespace);
root.setAttribute("version", "1.0");
// get the parameters from mycore.properties
String propertyName = "MCR.URIResolver.xslIncludes." + includePart;
List<String> propValue;
if (includePart.startsWith("class.")) {
MCRXslIncludeHrefs incHrefClass = MCRConfiguration2
.getOrThrow(propertyName, MCRConfiguration2::instantiateClass);
propValue = incHrefClass.getHrefs();
} else {
propValue = MCRConfiguration2.getString(propertyName)
.map(MCRConfiguration2::splitValue)
.map(s -> s.collect(Collectors.toList()))
.orElseGet(Collections::emptyList);
}
final String xslFolder = MCRConfiguration2.getStringOrThrow("MCR.Layout.Transformer.Factory.XSLFolder");
for (String include : propValue) {
// create a new include element
Element includeElement = new Element("include", xslNamespace);
includeElement.setAttribute("href",
include.contains(":") ? include : "resource:" + xslFolder + "/" + include);
root.addContent(includeElement);
LOGGER.debug("Resolved XSL include: {}", include);
}
return new JDOMSource(root);
}
}
/**
* Imports xsl files which are set in the mycore.properties file. Example:
* MCR.URIResolver.xslImports.components=first.xsl,second.xsl Every file must import this URIResolver to form a
* import chain:
*
* <pre>
* <xsl:import href="xslImport:components:first.xsl">
* </pre>
*
* @return A xsl file with the import as href.
*/
private static class MCRXslImportResolver implements URIResolver {
URIResolver fallback = new MCRResourceResolver();
@Override
public Source resolve(String href, String base) throws TransformerException {
final String baseURI = getParentDirectoryResourceURI(base);
// set xslt folder
final String xslFolder;
if (StringUtils.startsWith(baseURI, "resource:xsl/")) {
xslFolder = "xsl";
} else if (StringUtils.startsWith(baseURI, "resource:xslt/")) {
xslFolder = "xslt";
} else {
xslFolder = MCRConfiguration2.getStringOrThrow("MCR.Layout.Transformer.Factory.XSLFolder");
}
String importXSL = MCRXMLFunctions.nextImportStep(href.substring(href.indexOf(':') + 1));
if (importXSL.isEmpty()) {
LOGGER.debug("End of import queue: {}", href);
Namespace xslNamespace = Namespace.getNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
Element root = new Element("stylesheet", xslNamespace);
root.setAttribute("version", "1.0");
return new JDOMSource(root);
}
LOGGER.debug("xslImport importing {}", importXSL);
return fallback.resolve("resource:" + xslFolder + "/" + importXSL, base);
}
}
/**
* Builds XML trees from a string representation. Multiple XPath expressions can be separated by & Example:
* buildxml:_rootName_=mycoreobject&metadata/parents/parent/@href= 'FooBar_Document_4711' This will return:
* <mycoreobject> <metadata> <parents> <parent href="FooBar_Document_4711" />
* </parents> </metadata> </mycoreobject>
*/
private static class MCRBuildXMLResolver implements URIResolver {
private static Hashtable<String, String> getParameterMap(String key) {
String[] param;
StringTokenizer tok = new StringTokenizer(key, "&");
Hashtable<String, String> params = new Hashtable<>();
while (tok.hasMoreTokens()) {
param = tok.nextToken().split("=");
params.put(URLDecoder.decode(param[0], StandardCharsets.UTF_8),
URLDecoder.decode(param[1], StandardCharsets.UTF_8));
}
return params;
}
private static void constructElement(Element current, String xpath, String value) {
StringTokenizer st = new StringTokenizer(xpath, "/");
String name = null;
while (st.hasMoreTokens()) {
name = st.nextToken();
if (name.startsWith("@")) {
break;
}
String localName = getLocalName(name);
Namespace namespace = getNamespace(name);
Element child = current.getChild(localName, namespace);
if (child == null) {
child = new Element(localName, namespace);
current.addContent(child);
}
current = child;
}
if (name.startsWith("@")) {
name = name.substring(1);
String localName = getLocalName(name);
Namespace namespace = getNamespace(name);
current.setAttribute(localName, value, namespace);
} else {
current.setText(value);
}
}
private static Namespace getNamespace(String name) {
if (!name.contains(":")) {
return Namespace.NO_NAMESPACE;
}
String prefix = name.split(":")[0];
Namespace ns = MCRConstants.getStandardNamespace(prefix);
return ns == null ? Namespace.NO_NAMESPACE : ns;
}
private static String getLocalName(String name) {
if (!name.contains(":")) {
return name;
} else {
return name.split(":")[1];
}
}
/**
* Builds a simple xml node tree on basis of name value pair
*/
@Override
public Source resolve(String href, String base) {
String key = href.substring(href.indexOf(":") + 1);
LOGGER.debug("Building xml from {}", key);
Hashtable<String, String> params = getParameterMap(key);
Element defaultRoot = new Element("root");
Element root = defaultRoot;
String rootName = params.get("_rootName_");
if (rootName != null) {
root = new Element(getLocalName(rootName), getNamespace(rootName));
params.remove("_rootName_");
}
for (Map.Entry<String, String> entry : params.entrySet()) {
constructElement(root, entry.getKey(), entry.getValue());
}
if (root == defaultRoot && root.getChildren().size() > 1) {
LOGGER.warn("More than 1 root node defined, returning first");
return new JDOMSource(root.getChildren().get(0).detach());
}
return new JDOMSource(root);
}
}
/**
* Resolves the current user information. Example: currentUserInfo:attribute=eMail&attribute=realName&role=administrator <br>
* Returns: <br>
* <code>
* <user id="admin"> <br>
* <attribute name="eMail">example@mycore.de</attribute><br>
* <attribute name="realName">Administrator</attribute><br>
* <role name="administrator">true</role><br>
* </user><br>
* </code>
*/
private static class MCRCurrentUserInfoResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
MCRUserInformation userInformation = MCRSessionMgr.getCurrentSession().getUserInformation();
String userID = userInformation.getUserID();
String[] split = href.split(":");
Set<String> suppliedAttributes = new HashSet<>();
Set<String> suppliedRoles = new HashSet<>();
Element root = new Element("user");
root.setAttribute("id", userID);
if (split.length == 2) {
String req = split[1];
URLEncodedUtils.parse(req, StandardCharsets.UTF_8).forEach(nv -> {
if (nv.getName().equals("attribute")) {
if (suppliedAttributes.contains(nv.getValue())) {
LOGGER.warn("Duplicate attribute {} in user info request", nv.getValue());
return;
}
suppliedAttributes.add(nv.getValue());
Element attribute = new Element("attribute");
attribute.setAttribute("name", nv.getValue());
attribute.setText(userInformation.getUserAttribute(nv.getValue()));
root.addContent(attribute);
} else if (nv.getName().equals("role")) {
if (suppliedRoles.contains(nv.getValue())) {
LOGGER.warn("Duplicate role {} in user info request", nv.getValue());
return;
}
suppliedRoles.add(nv.getValue());
Element role = new Element("role");
role.setAttribute("name", nv.getValue());
role.setText(String.valueOf(userInformation.isUserInRole(nv.getValue())));
root.addContent(role);
}
});
}
return new JDOMSource(root);
}
}
/**
* Resolves the software Version of the MyCoRe Instance. The following types are supported: gitDescribe, abbrev,
* branch, version, revision, completeVersion. The default is completeVersion.
* The resulting XML looks like this:
* <code>
* <version>MyCoRe 2022.06.3-SNAPSHOT 2022.06.x:v2022.06.2-1-g881e24d</version>
* </code>
*/
private static class MCRVersionResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
String versionType = href.substring(href.indexOf(":") + 1);
final Element versionElement = new Element("version");
versionElement.setText(
switch (versionType) {
case "gitDescribe" -> MCRCoreVersion.getGitDescribe();
case "abbrev" -> MCRCoreVersion.getAbbrev();
case "branch" -> MCRCoreVersion.getBranch();
case "version" -> MCRCoreVersion.getVersion();
case "revision" -> MCRCoreVersion.getRevision();
default -> MCRCoreVersion.getCompleteVersion();
});
return new JDOMSource(versionElement);
}
}
/**
* Resolver for MCRLayoutUtils. The following types are supported: readAccess:$webpageID,
* readAccess:$webpageID:split:$blockerWebpageID
* returns
* <code>
* <true />
* </code>
* or
* <code>
* <false />
* </code>
*/
private static class MCRLayoutUtilsResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
String[] args = href.split(":", 3);
if (args.length < 2) {
throw new TransformerException("No arguments given");
}
String function = args[1];
if (function.equals("readAccess")) {
String[] params = args[2].split(":split:");
if (params.length == 1) {
return new JDOMSource(new Element(String.valueOf(MCRLayoutUtilities.readAccess(params[0]))));
} else if (params.length == 2) {
return new JDOMSource(
new Element(String.valueOf(MCRLayoutUtilities.readAccess(params[0], params[1]))));
}
} else if (function.equals("personalNavigation")) {
try {
return new DOMSource(MCRLayoutUtilities.getPersonalNavigation());
} catch (JDOMException | XPathExpressionException e) {
throw new MCRException("Error while loading personal navigation!", e);
}
}
throw new TransformerException("Unknown argument: " + args[2]);
}
}
private static class MCRVersionInfoResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
String id = href.substring(href.indexOf(":") + 1);
LOGGER.debug("Reading version info of MCRObject with ID {}", id);
MCRObjectID mcrId = MCRObjectID.getInstance(id);
MCRXMLMetadataManager metadataManager = MCRXMLMetadataManager.instance();
try {
List<? extends MCRAbstractMetadataVersion<?>> versions = metadataManager.listRevisions(mcrId);
if (versions != null && !versions.isEmpty()) {
return getSource(versions);
} else {
return getSource(Instant.ofEpochMilli(metadataManager.getLastModified(mcrId))
.truncatedTo(ChronoUnit.MILLIS));
}
} catch (Exception e) {
throw new TransformerException(e);
}
}
private Source getSource(Instant lastModified) {
Element e = new Element("versions");
Element v = new Element("version");
e.addContent(v);
v.setAttribute("date", lastModified.toString());
return new JDOMSource(e);
}
private Source getSource(List<? extends MCRAbstractMetadataVersion<?>> versions) {
Element e = new Element("versions");
for (MCRAbstractMetadataVersion<?> version : versions) {
Element v = new Element("version");
v.setAttribute("user", version.getUser());
v.setAttribute("date", MCRXMLFunctions.getISODate(version.getDate(), null));
v.setAttribute("r", version.getRevision());
v.setAttribute("action", Character.toString(version.getType()));
e.addContent(v);
}
return new JDOMSource(e);
}
}
private static class MCRDeletedObjectResolver implements URIResolver {
/**
* Returns a deleted mcr object xml for the given id. If there is no such object a dummy object with an empty
* metadata element is returned.
*
* @param href
* an uri starting with <code>deletedMcrObject:</code>
* @param base
* may be null
*/
@Override
public Source resolve(String href, String base) throws TransformerException {
String[] parts = href.split(":");
MCRObjectID mcrId = MCRObjectID.getInstance(parts[parts.length - 1]);
LOGGER.info("Resolving deleted object {}", mcrId);
try {
MCRContent lastPresentVersion = MCRXMLMetadataManager.instance().retrieveContent(mcrId);
if (lastPresentVersion == null) {
LOGGER.warn("Could not resolve deleted object {}", mcrId);
return new JDOMSource(MCRObjectFactory.getSampleObject(mcrId));
}
return lastPresentVersion.getSource();
} catch (IOException e) {
throw new TransformerException(e);
}
}
}
private static class MCRFileMetadataResolver implements URIResolver {
@Override
public Source resolve(String href, String base) {
String[] parts = href.split(":");
String completePath = parts[1];
String[] pathParts = completePath.split("/", 2);
MCRObjectID derivateID = MCRObjectID.getInstance(pathParts[0]);
MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateID);
MCRObjectDerivate objectDerivate = derivate.getDerivate();
if (pathParts.length == 1) {
//only derivate is given;
Element fileset = new Element("fileset");
if (objectDerivate.getURN() != null) {
fileset.setAttribute("urn", objectDerivate.getURN());
for (MCRFileMetadata fileMeta : objectDerivate.getFileMetadata()) {
fileset.addContent(fileMeta.createXML());
}
}
return new JDOMSource(fileset);
}
MCRFileMetadata fileMetadata = objectDerivate.getOrCreateFileMetadata("/" + pathParts[1]);
return new JDOMSource(fileMetadata.createXML());
}
}
/**
* Redirect to different URIResolver that is defined via property. This resolver is meant to serve static content as
* no variable substitution takes place Example: MCR.URIResolver.redirect.alias=webapp:path/to/alias.xml
*/
private static class MCRRedirectResolver implements URIResolver {
private static final Logger LOGGER = LogManager.getLogger(MCRRedirectResolver.class);
@Override
public Source resolve(String href, String base) throws TransformerException {
String configsuffix = href.substring(href.indexOf(":") + 1);
// get the parameters from mycore.properties
String propertyName = "MCR.URIResolver.redirect." + configsuffix;
String propValue = MCRConfiguration2.getStringOrThrow(propertyName);
LOGGER.info("Redirect {} to {}", href, propValue);
return singleton.resolve(propValue, base);
}
}
/**
* Resolves an data url and returns the content.
*
* @see MCRDataURL
*/
private static class MCRDataURLResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
try {
final MCRDataURL dataURL = MCRDataURL.parse(href);
final MCRByteContent content = new MCRByteContent(dataURL.getData());
content.setSystemId(href);
content.setMimeType(dataURL.getMimeType());
content.setEncoding(dataURL.getCharset().name());
return content.getSource();
} catch (IOException e) {
throw new TransformerException(e);
}
}
}
private static class MCRI18NResolver implements URIResolver {
/**
* Resolves the I18N String value for the given property.<br><br>
* <br>
* Syntax: <code>i18n:{i18n-code},{i18n-prefix}*,{i18n-prefix}*...</code> or <br>
* <code>i18n:{i18n-code}[:param1:param2:…paramN]</code>
* <br>
* Result: <code> <br>
* <i18n> <br>
* <translation key="key1">translation1</translation> <br>
* <translation key="key2">translation2</translation> <br>
* <translation key="key3">translation3</translation> <br>
* </i18n> <br>
* </code>
* <br/>
* If just one i18n-code is passed, then the translation element is skipped.
* <code>
* <i18n> <br>translation</i18n><br>
* </code>
* Additionally, if the singular i18n-code is followed by a ":"-separated list of values,
* the translation result is interpreted to be in Java MessageFormat and will be formatted with those values.
* E.g.
* <code>i18n:module.dptbase.common.results.nResults:15</code> (<code>{0} objects found</code>)
* -> "<code>15 objects found</code>"
* @param href
* URI in the syntax above
* @param base
* not used
*
* @return the element with result format above
* @see javax.xml.transform.URIResolver
*/
@Override
public Source resolve(String href, String base) {
String target = href.substring(href.indexOf(":") + 1);
final Element i18nElement = new Element("i18n");
if (!target.contains("*") && !target.contains(",")) {
String translation;
if (target.contains(":")) {
final int i = target.indexOf(":");
translation = MCRTranslation.translate(target.substring(0, i),
(Object[]) target.substring(i + 1).split(":"));
} else {
translation = MCRTranslation.translate(target);
}
i18nElement.addContent(translation);
return new JDOMSource(i18nElement);
}
final String[] translationKeys = target.split(",");
// Combine translations to prevent duplicates
HashMap<String, String> translations = new HashMap<>();
for (String translationKey : translationKeys) {
if (translationKey.endsWith("*")) {
final String prefix = translationKey.substring(0, translationKey.length() - 1);
translations.putAll(MCRTranslation.translatePrefix(prefix));
} else {
translations.put(translationKey,
MCRTranslation.translate(translationKey));
}
}
translations.forEach((key, value) -> {
final Element translation = new Element("translation");
translation.setAttribute("key", key);
translation.setText(value);
i18nElement.addContent(translation);
});
return new JDOMSource(i18nElement);
}
}
private static class MCRCheckPermissionChainResolver implements URIResolver {
/**
* Checks the permission and if granted resolve the uri
*
* Syntax: <code>checkPermissionChain:{?id}:{permission}:{$uri}</code>
*
* @param href
* URI in the syntax above
* @param base
* not used
*
* @return if you have the permission then the resolved uri otherwise an Exception
* @see javax.xml.transform.URIResolver
*/
@Override
public Source resolve(String href, String base) throws TransformerException {
final String[] split = href.split(":", 4);
if (split.length != 4) {
throw new MCRException(
"Syntax needs to be checkPermissionChain:{?id}:{permission}:{uri} but was " + href);
}
final String permission = split[2];
final String uri = split[3];
final boolean hasAccess;
if (!split[1].isBlank()) {
hasAccess = MCRAccessManager.checkPermission(split[1], permission);
} else {
hasAccess = MCRAccessManager.checkPermission(permission);
}
if (!hasAccess) {
throw new TransformerException("No Access to " + uri + " (" + href + " )");
}
return MCRURIResolver.instance().resolve(uri, base);
}
}
private static class MCRCheckPermissionResolver implements URIResolver {
/**
* returns the boolean value for the given ACL permission.
*
* Syntax: <code>checkPermission:{id}:{permission}</code> or <code>checkPermission:{permission}</code>
*
* @param href
* URI in the syntax above
* @param base
* not used
*
* @return the root element "boolean" of the XML document with content string true of false
* @see javax.xml.transform.URIResolver
*/
@Override
public Source resolve(String href, String base) {
final String[] split = href.split(":");
boolean permission = switch (split.length) {
case 2 -> MCRAccessManager.checkPermission(split[1]);
case 3 -> MCRAccessManager.checkPermission(split[1], split[2]);
default -> throw new IllegalArgumentException(
"Invalid format of uri for retrieval of checkPermission: " + href);
};
Element root = new Element("boolean");
root.setText(Boolean.toString(permission));
return new JDOMSource(root);
}
}
/**
* @author Frank Lützenkirchen
*/
private static class MCRCachingResolver implements URIResolver {
private final static Logger LOGGER = LogManager.getLogger();
private final static String CONFIG_PREFIX = "MCR.URIResolver.CachingResolver";
private final long maxAge;
private final MCRCache<String, Element> cache;
MCRCachingResolver() {
int capacity = MCRConfiguration2.getOrThrow(CONFIG_PREFIX + ".Capacity", Integer::parseInt);
maxAge = MCRConfiguration2.getOrThrow(CONFIG_PREFIX + ".MaxAge", Long::parseLong);
cache = new MCRCache<>(capacity, MCRCachingResolver.class.getName());
}
/**
* Resolves XML content from a given URI and caches it for re-use.
*
* If the URI was already resolved within the last
* MCR.URIResolver.CachingResolver.MaxAge milliseconds, the cached version is returned.
* The default max age is one hour.
*
* The cache capacity is configured via MCR.URIResolver.CachingResolver.Capacity
* The default capacity is 100.
*/
@Override
public Source resolve(String href, String base) {
String hrefToCache = href.substring(href.indexOf(":") + 1);
LOGGER.debug("resolving: " + hrefToCache);
long maxDateCached = System.currentTimeMillis() - maxAge;
Element resolvedXML = cache.getIfUpToDate(hrefToCache, maxDateCached);
if (resolvedXML == null) {
LOGGER.debug(hrefToCache + " not in cache, must resolve");
resolvedXML = MCRURIResolver.instance().resolve(hrefToCache);
cache.put(hrefToCache, resolvedXML);
} else {
LOGGER.debug(hrefToCache + " already in cache");
}
return new JDOMSource(resolvedXML);
}
}
}
| 81,238 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLFunctions.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRXMLFunctions.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.FileStore;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.Normalizer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeSet;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.xml.utils.XMLChar;
import org.jdom2.JDOMException;
import org.jdom2.output.DOMOutputter;
import org.mycore.access.MCRAccessManager;
import org.mycore.common.MCRCalendar;
import org.mycore.common.MCRClassTools;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.MCRUtils;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationDir;
import org.mycore.common.content.MCRSourceContent;
import org.mycore.datamodel.classifications2.MCRCategLinkReference;
import org.mycore.datamodel.classifications2.MCRCategLinkService;
import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
import org.mycore.datamodel.common.MCRISO8601Date;
import org.mycore.datamodel.common.MCRLinkTableManager;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
import org.mycore.datamodel.metadata.MCRMetaLinkID;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.metadata.MCRObjectStructure;
import org.mycore.datamodel.niofs.MCRPath;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import jakarta.activation.MimetypesFileTypeMap;
import jakarta.ws.rs.core.UriBuilder;
/**
* @author Thomas Scheffler (yagee)
* @author Jens Kupferschmidt
* @author shermann
* @author René Adler (eagle)
*/
public class MCRXMLFunctions {
private static final String TAG_START = "\\<\\w+((\\s+\\w+(\\s*\\=\\s*(?:\".*?\"|'.*?'|[^'\"\\>\\s]+))?)+"
+ "\\s*|\\s*)\\>";
private static final String TAG_END = "\\</\\w+\\>";
private static final String TAG_SELF_CLOSING = "\\<\\w+((\\s+\\w+(\\s*\\=\\s*(?:\".*?\"|'.*?'|[^'\"\\>\\s]+))?)+"
+ "\\s*|\\s*)/\\>";
private static final String HTML_ENTITY = "&[a-zA-Z][a-zA-Z0-9]+;";
private static final Pattern TAG_PATTERN = Pattern.compile(TAG_START + "((.*?[^\\<]))" + TAG_END, Pattern.DOTALL);
private static final Pattern HTML_MATCH_PATTERN = Pattern
.compile("(" + TAG_START + "((.*?[^\\<]))" + TAG_END + ")|(" + TAG_SELF_CLOSING + ")|(" + HTML_ENTITY + ")",
Pattern.DOTALL);
private static final Logger LOGGER = LogManager.getLogger(MCRXMLFunctions.class);
public static volatile MimetypesFileTypeMap MIMETYPE_MAP = null;
public static Node document(String uri) throws JDOMException, IOException, TransformerException {
MCRSourceContent sourceContent = MCRSourceContent.getInstance(uri);
if (sourceContent == null) {
throw new TransformerException("Could not load document: " + uri);
}
DOMOutputter out = new DOMOutputter();
return out.output(sourceContent.asXML());
}
/**
* returns the given String trimmed
*
* @param arg0
* String to be trimmed
* @return trimmed copy of arg0
* @see java.lang.String#trim()
*/
public static String trim(String arg0) {
return arg0.trim();
}
/**
* returns the given String in unicode NFC normal form.
*
* @param arg0 String to be normalized
* @see Normalizer#normalize(CharSequence, java.text.Normalizer.Form)
*/
public static String normalizeUnicode(String arg0) {
return Normalizer.normalize(arg0, Normalizer.Form.NFC);
}
public static String formatISODate(String isoDate, String simpleFormat, String iso639Language) {
return formatISODate(isoDate, null, simpleFormat, iso639Language);
}
public static String formatISODate(String isoDate, String isoFormat, String simpleFormat, String iso639Language) {
return formatISODate(isoDate, isoFormat, simpleFormat, iso639Language, TimeZone.getDefault().getID());
}
public static String formatISODate(String isoDate, String isoFormat, String simpleFormat, String iso639Language,
String timeZone) {
if (LOGGER.isDebugEnabled()) {
String sb = "isoDate=" + isoDate + ", simpleFormat=" + simpleFormat + ", isoFormat=" + isoFormat
+ ", iso639Language=" + iso639Language + ", timeZone=" + timeZone;
LOGGER.debug(sb);
}
Locale locale = Locale.forLanguageTag(iso639Language);
MCRISO8601Date mcrdate = new MCRISO8601Date();
mcrdate.setFormat(isoFormat);
mcrdate.setDate(isoDate);
try {
String formatted = mcrdate.format(simpleFormat, locale, timeZone);
return formatted == null ? "?" + isoDate + "?" : formatted;
} catch (RuntimeException iae) {
LOGGER.error("Unable to format date {} to {} with locale {} and timezone {}", mcrdate.getISOString(),
simpleFormat, locale, timeZone, iae);
return "?";
}
}
public static String getISODate(String simpleDate, String simpleFormat, String isoFormat) throws ParseException {
Date date;
if (simpleFormat.equals("long")) {
date = new Date(Long.parseLong(simpleDate));
} else {
SimpleDateFormat df = new SimpleDateFormat(simpleFormat, Locale.ROOT);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
// or else testcase
// "1964-02-24" would
// result "1964-02-23"
date = df.parse(simpleDate);
}
return getISODate(date, isoFormat);
}
public static String getISODate(Date date, String isoFormat) {
MCRISO8601Date mcrdate = new MCRISO8601Date();
mcrdate.setDate(date);
mcrdate.setFormat(isoFormat);
return mcrdate.getISOString();
}
public static String getISODate(String simpleDate, String simpleFormat) throws ParseException {
return getISODate(simpleDate, simpleFormat, null);
}
/**
* The method get a date String in format yyyy-MM-ddThh:mm:ssZ for ancient date values.
*
* @param date the date string
* @param fieldName the name of field of MCRMetaHistoryDate, it should be 'von' or 'bis'
* @param calendarName the name if the calendar defined in MCRCalendar
* @return the date in format yyyy-MM-ddThh:mm:ssZ
*/
public static String getISODateFromMCRHistoryDate(String date, String fieldName, String calendarName) {
if (fieldName == null || fieldName.trim().length() == 0) {
return "";
}
boolean useLastValue = Objects.equals(fieldName, "bis");
return MCRCalendar.getISODateToFormattedString(date, useLastValue, calendarName);
}
/**
* Returns a string representing the current date. One can customize the
* format of the returned string by providing a proper value for the format
* parameter. If null or an invalid format is provided the default format
* "yyyy-MM-dd" will be used.
*
* @param format
* the format in which the date should be formatted
* @return the current date in the desired format
* @see SimpleDateFormat format description
*/
public static String getCurrentDate(String format) {
SimpleDateFormat sdf;
try {
sdf = new SimpleDateFormat(format, Locale.ROOT);
} catch (Exception i) {
LOGGER.warn("Could not parse date format string, will use default \"yyyy-MM-dd\"", i);
sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT);
}
return sdf.format(new Date());
}
/**
* A delegate for {@link String#compareTo(String)}.
*
* @return s1.compareTo(s2)
*/
public static int compare(String s1, String s2) {
return s1.compareTo(s2);
}
/**
* @param source the source string to operate on
* @param regex the regular expression to apply
*/
public static String regexp(String source, String regex, String replace) {
try {
return source.replaceAll(regex, replace);
} catch (Exception e) {
LOGGER.warn("Could not apply regular expression. Returning source string ({}).", source);
return source;
}
}
/**
* Get the string matching the regular expression from the source paramater.
*
* @param source the string to search
* @param regex the regular expression
*
* @return the string matching in the source parameter matching the given regular expression
*/
public static String getMatchingString(String source, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(source);
return m.find() ? m.group() : "";
}
public static boolean classAvailable(String className) {
try {
MCRClassTools.forName(className);
LOGGER.debug("found class: {}", className);
return true;
} catch (ClassNotFoundException e) {
LOGGER.debug("did not find class: {}", className);
return false;
}
}
public static boolean resourceAvailable(String resourceName) {
URL resource = MCRConfigurationDir.getConfigResource(resourceName);
if (resource == null) {
LOGGER.debug("did not find resource: {}", resourceName);
return false;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("resource: {} found at {}", resourceName, resource.toString());
}
return true;
}
/**
* Encodes the given url so that one can safely embed that string in a part
* of an URI
*
* @return the encoded source
*/
public static String encodeURL(String source, String encoding) {
String result = null;
try {
result = URLEncoder.encode(source, encoding);
} catch (UnsupportedEncodingException e) {
LOGGER.error(e);
}
return result;
}
/**
* Encodes the given URL so, that it is a valid RFC 2396 URL.
*/
public static String normalizeAbsoluteURL(String url) throws MalformedURLException, URISyntaxException {
try {
return new URI(url).toASCIIString();
} catch (Exception e) {
return UriBuilder.fromUri(url)
.build()
.toString();
}
}
/**
* Encodes the path so that it can be safely used in an URI.
* Same as calling {@link #encodeURIPath(String, boolean)} with boolean parameter set to false.
* @return encoded path as described in RFC 2396
*/
public static String encodeURIPath(String path) throws URISyntaxException {
return encodeURIPath(path, false);
}
/**
* Encodes the path so that it can be safely used in an URI.
* @param asciiOnly
* if true, return only ASCII characters (e.g. encode umlauts)
* @return encoded path as described in RFC 2396
*/
public static String encodeURIPath(String path, boolean asciiOnly) throws URISyntaxException {
URI relativeURI = new URI(null, null, path, null, null);
return asciiOnly ? relativeURI.toASCIIString() : relativeURI.getRawPath();
}
/**
* Decodes the path so that it can be displayed without encoded octets.
* @param path
* encoded path as described in RFC 2396
* @return decoded path
*/
public static String decodeURIPath(String path) throws URISyntaxException {
URI relativeURI = new URI(path);
return relativeURI.getPath();
}
public static boolean isDisplayedEnabledDerivate(String derivateId) {
return MCRAccessManager.checkDerivateDisplayPermission(derivateId);
}
/**
* Checks if the given object has derivates that are all accessible to guest user.
*
* Normally this implies that all derivates are readable by everyone. Only non-hidden
* derivates are taken into account. So if an object only contains hidden
* @param objId MCRObjectID as String
* @see #isWorldReadable(String)
*/
public static boolean isWorldReadableComplete(String objId) {
LOGGER.info("World completely readable: {}", objId);
if (!MCRObjectID.isValid(objId)) {
return false;
}
MCRObjectID mcrObjectID = MCRObjectID.getInstance(objId);
CompletableFuture<Boolean> permission = MCRAccessManager.checkPermission(
MCRSystemUserInformation.getGuestInstance(),
() -> MCRAccessManager.checkPermission(mcrObjectID, MCRAccessManager.PERMISSION_READ)
&& checkReadPermissionOfDerivates(mcrObjectID));
try {
return permission.join();
} catch (CancellationException | CompletionException e) {
LOGGER.error("Error while retriving ACL information for Object {}", objId, e);
return false;
}
}
private static boolean checkReadPermissionOfDerivates(MCRObjectID mcrObjectID) {
List<MCRObjectID> derivateIds = MCRMetadataManager.getDerivateIds(mcrObjectID, 0, TimeUnit.SECONDS);
if (derivateIds.isEmpty()) {
return MCRConfiguration2.getOrThrow("MCR.XMLFunctions.WorldReadableComplete.NoDerivates",
Boolean::parseBoolean);
}
Set<String> displayableDerivates = derivateIds
.stream()
.map(MCRObjectID::toString)
.filter(MCRXMLFunctions::isDisplayedEnabledDerivate)
.collect(Collectors.toSet());
return !displayableDerivates.isEmpty() && displayableDerivates.stream()
.allMatch(derId -> MCRAccessManager.checkPermission(derId, MCRAccessManager.PERMISSION_READ));
}
/**
* Checks if the given object is readable to guest user.
* @param objId MCRObjectID as String
*/
public static boolean isWorldReadable(String objId) {
if (!MCRObjectID.isValid(objId)) {
return false;
}
MCRObjectID mcrObjectID = MCRObjectID.getInstance(objId);
CompletableFuture<Boolean> permission = MCRAccessManager.checkPermission(
MCRSystemUserInformation.getGuestInstance(),
() -> MCRAccessManager.checkPermission(mcrObjectID, MCRAccessManager.PERMISSION_READ));
try {
return permission.join();
} catch (CancellationException | CompletionException e) {
LOGGER.error("Error while retriving ACL information for Object {}", objId, e);
return false;
}
}
/**
* @param objectId
* the id of the derivate owner
* @return <code>true</code> if the derivate owner has a least one derivate
* with the display attribute set to true, <code>false</code>
* otherwise
*/
public static boolean hasDisplayableDerivates(String objectId) {
return Optional.of(MCRObjectID.getInstance(objectId))
.filter(MCRMetadataManager::exists)
.map(MCRMetadataManager::retrieveMCRObject)
.map(MCRObject::getStructure)
.map(MCRObjectStructure::getDerivates)
.map(List::stream)
.map(s -> s.map(MCRMetaLinkID::getXLinkHrefID)
.map(MCRMetadataManager::retrieveMCRDerivate)
.anyMatch(d -> MCRAccessManager.checkDerivateDisplayPermission(d.getId().toString())))
.orElse(false);
}
/**
* Returns a list of link targets of a given MCR object type. The structure
* is <em>link</em>. If no links are found an empty NodeList is returned.
*
* @param mcrid
* MCRObjectID as String as the link source
* @param destinationType
* MCR object type
* @return a NodeList with <em>link</em> elements
*/
public static NodeList getLinkDestinations(String mcrid, String destinationType) {
DocumentBuilder documentBuilder = MCRDOMUtils.getDocumentBuilderUnchecked();
try {
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("linklist");
document.appendChild(rootElement);
MCRLinkTableManager ltm = MCRLinkTableManager.instance();
for (String id : ltm.getDestinationOf(mcrid, destinationType)) {
Element link = document.createElement("link");
link.setTextContent(id);
rootElement.appendChild(link);
}
return rootElement.getChildNodes();
} finally {
MCRDOMUtils.releaseDocumentBuilder(documentBuilder);
}
}
/**
* Returns a list of link sources of a given MCR object type. The structure
* is <em>link</em>. If no links are found an empty NodeList is returned.
*
* @param mcrid
* MCRObjectID as String as the link target
* @param sourceType
* MCR object type
* @return a NodeList with <em>link</em> elements
*/
public static NodeList getLinkSources(String mcrid, String sourceType) {
DocumentBuilder documentBuilder = MCRDOMUtils.getDocumentBuilderUnchecked();
try {
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("linklist");
document.appendChild(rootElement);
MCRLinkTableManager ltm = MCRLinkTableManager.instance();
for (String id : ltm.getSourceOf(mcrid)) {
if (sourceType == null || MCRObjectID.getIDParts(id)[1].equals(sourceType)) {
Element link = document.createElement("link");
link.setTextContent(id);
rootElement.appendChild(link);
}
}
return rootElement.getChildNodes();
} finally {
MCRDOMUtils.releaseDocumentBuilder(documentBuilder);
}
}
/**
* same as {@link #getLinkSources(String, String)} with
* <code>sourceType</code>=<em>null</em>
*
*/
public static NodeList getLinkSources(String mcrid) {
return getLinkSources(mcrid, null);
}
/**
* Determines the mime type for the file given by its name.
*
* @param f
* the name of the file
* @return the mime type of the given file
*/
public static String getMimeType(String f) {
if (f == null) {
return "application/octet-stream";
}
if (MIMETYPE_MAP == null) {
synchronized (MCRXMLFunctions.class) {
if (MIMETYPE_MAP == null) {
MIMETYPE_MAP = new MimetypesFileTypeMap();
}
}
}
return MIMETYPE_MAP.getContentType(f.toLowerCase(Locale.ROOT));
}
/**
* @return the name of the maindoc of the given derivate or null if maindoc is not set
*/
public static String getMainDocName(String derivateId) {
if (derivateId == null || derivateId.isEmpty()) {
return null;
}
MCRObjectID objectID = MCRObjectID.getInstance(derivateId);
if (!MCRMetadataManager.exists(objectID)) {
return null;
}
return MCRMetadataManager.retrieveMCRDerivate(objectID).getDerivate().getInternals().getMainDoc();
}
/**
* The method return a org.w3c.dom.NodeList as subpath of the doc input
* NodeList selected by a path as String.
*
* @param doc
* the input org.w3c.dom.Nodelist
* @param path
* the path of doc as String
* @return a subpath of doc selected by path as org.w3c.dom.NodeList
*/
public static NodeList getTreeByPath(NodeList doc, String path) {
NodeList n = null;
DocumentBuilder documentBuilder = MCRDOMUtils.getDocumentBuilderUnchecked();
try {
// build path selection
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile(path);
// select part
Document document = documentBuilder.newDocument();
if (doc.item(0).getNodeName().equals("#document")) {
// LOGGER.debug("NodeList is a document.");
Node child = doc.item(0).getFirstChild();
if (child != null) {
Node node = doc.item(0).getFirstChild();
Node imp = document.importNode(node, true);
document.appendChild(imp);
} else {
document.appendChild(doc.item(0));
}
}
n = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
} catch (Exception e) {
LOGGER.error("Error while getting tree by path {}", path, e);
} finally {
MCRDOMUtils.releaseDocumentBuilder(documentBuilder);
}
return n;
}
/**
* checks if the current user is in a specific role
*
* @param role
* a role name
* @return true if user has this role
*/
public static boolean isCurrentUserInRole(String role) {
return MCRSessionMgr.getCurrentSession().getUserInformation().isUserInRole(role);
}
public static boolean isCurrentUserSuperUser() {
return MCRSessionMgr.getCurrentSession().getUserInformation().getUserID()
.equals(MCRSystemUserInformation.getSuperUserInstance().getUserID());
}
public static boolean isCurrentUserGuestUser() {
return MCRSessionMgr.getCurrentSession().getUserInformation().getUserID()
.equals(MCRSystemUserInformation.getGuestInstance().getUserID());
}
public static String getCurrentUserAttribute(String attribute) {
return MCRSessionMgr.getCurrentSession().getUserInformation().getUserAttribute(attribute);
}
public static boolean exists(String objectId) {
return MCRMetadataManager.exists(MCRObjectID.getInstance(objectId));
}
/**
* Verifies if object is in specified category.
* @see MCRCategLinkService#isInCategory(MCRCategLinkReference, MCRCategoryID)
* @param objectId valid MCRObjectID as String
* @param categoryId valid MCRCategoryID as String
* @return true if object is in category, else false
*/
public static boolean isInCategory(String objectId, String categoryId) {
try {
MCRCategoryID categID = MCRCategoryID.fromString(categoryId);
MCRObjectID mcrObjectID = MCRObjectID.getInstance(objectId);
MCRCategLinkReference reference = new MCRCategLinkReference(mcrObjectID);
return MCRCategLinkServiceHolder.INSTANCE.isInCategory(reference, categID);
} catch (Throwable e) {
LOGGER.error("Error while checking if object is in category", e);
return false;
}
}
/**
* Checks if the User-Agent is sent from a mobile device
* @return true if the User-Agent is sent from a mobile device
*/
public static boolean isMobileDevice(String userAgent) {
return userAgent.toLowerCase(Locale.ROOT).contains("mobile");
}
public static boolean hasParentCategory(String classificationId, String categoryId) {
MCRCategoryID categID = new MCRCategoryID(classificationId, categoryId);
//root category has level 0
return !categID.isRootID() && MCRCategoryDAOFactory.getInstance().getCategory(categID, 0).getLevel() > 1;
}
public static String getDisplayName(String classificationId, String categoryId) {
try {
MCRCategoryID categID = new MCRCategoryID(classificationId, categoryId);
MCRCategoryDAO dao = MCRCategoryDAOFactory.getInstance();
MCRCategory category = dao.getCategory(categID, 0);
return Optional.ofNullable(category)
.map(MCRCategory::getCurrentLabel)
.filter(Optional::isPresent)
.map(Optional::get)
.map(MCRLabel::getText)
.orElse("");
} catch (Throwable e) {
LOGGER.error("Could not determine display name for classification id {} and category id {}",
classificationId, categoryId, e);
return "";
}
}
public static boolean isCategoryID(String classificationId, String categoryId) {
if (classificationId == null || classificationId.isEmpty()) {
LOGGER.debug("Classification identifier is null or empty");
return false;
}
if (categoryId == null || categoryId.isEmpty()) {
LOGGER.debug("Category identifier is null or empty");
return false;
}
if (classificationId.length() > MCRCategoryID.ROOT_ID_LENGTH) {
LOGGER.debug("Could not determine state for classification id {} and category id {}", classificationId);
return false;
}
MCRCategory category = null;
try {
MCRCategoryID categID = MCRCategoryID.fromString(classificationId + ":" + categoryId);
MCRCategoryDAO dao = MCRCategoryDAOFactory.getInstance();
category = dao.getCategory(categID, 0);
} catch (Throwable e) {
LOGGER.error("Could not determine state for classification id {} and category id {}", classificationId,
categoryId, e);
}
return category != null;
}
/**
* Method returns the amount of space consumed by the files contained in the
* derivate container. The returned string is already formatted meaning it
* has already the optimal measurement unit attached (e.g. 142 MB, ).
*
* @param derivateId
* the derivate id for which the size should be returned
* @return the size as formatted string
*/
public static String getSize(String derivateId) throws IOException {
MCRPath rootPath = MCRPath.getPath(derivateId, "/");
final AtomicLong size = new AtomicLong();
Files.walkFileTree(rootPath, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
size.addAndGet(attrs.size());
return super.visitFile(file, attrs);
}
});
return MCRUtils.getSizeFormatted(size.get());
}
/**
* Returns the number of files of the given derivate.
*
* @param derivateId the id of the derivate
*
* @return the number of files
* */
public static long getFileCount(String derivateId) throws IOException {
AtomicInteger i = new AtomicInteger(0);
Files.walkFileTree(MCRPath.getPath(derivateId, "/"), new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
i.incrementAndGet();
return FileVisitResult.CONTINUE;
}
});
return i.get();
}
/**
* @param derivateID
* the derivate id
* @return the id of the mycore object that contains the derivate with the
* given id
*/
public static String getMCRObjectID(String derivateID) {
return getMCRObjectID(derivateID, 5000);
}
/**
* Same as {@link MCRMetadataManager#getObjectId(MCRObjectID, long, TimeUnit)} with String representation.
*/
public static String getMCRObjectID(final String derivateID, final long expire) {
return MCRMetadataManager.getObjectId(MCRObjectID.getInstance(derivateID), expire, TimeUnit.MILLISECONDS)
.toString();
}
/**
* @param uri the uri to resolve
*/
public static NodeList resolve(String uri) throws JDOMException {
org.jdom2.Element element = MCRURIResolver.instance().resolve(uri);
element.detach();
org.jdom2.Document document = new org.jdom2.Document(element);
return new DOMOutputter().output(document).getDocumentElement().getChildNodes();
}
/**
* Helper function for xslImport URI Resolver and {@link #hasNextImportStep(String)}
* @param includePart substring after "xmlImport:"
*/
public static String nextImportStep(String includePart) {
int border = includePart.indexOf(':');
String selfName = null;
if (border > 0) {
selfName = includePart.substring(border + 1);
includePart = includePart.substring(0, border);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("get next import step for {}", includePart);
}
// get the parameters from mycore.properties
List<String> importList = MCRConfiguration2.getString("MCR.URIResolver.xslImports." + includePart)
.map(MCRConfiguration2::splitValue)
.map(s -> s.collect(Collectors.toList()))
.orElseGet(Collections::emptyList);
if (importList.isEmpty()) {
LOGGER.info("MCR.URIResolver.xslImports.{} has no Stylesheets defined", includePart);
} else {
ListIterator<String> listIterator = importList.listIterator(importList.size());
if (selfName == null && listIterator.hasPrevious()) {
return listIterator.previous();
}
while (listIterator.hasPrevious()) {
String currentStylesheet = listIterator.previous();
if (currentStylesheet.equals(selfName)) {
if (listIterator.hasPrevious()) {
return listIterator.previous();
} else {
LOGGER.debug("xslImport reached end of chain:{}", importList);
return "";
}
}
//continue;
}
LOGGER.warn("xslImport could not find {} in {}", selfName, importList);
}
return "";
}
public static boolean hasNextImportStep(String uri) {
boolean returns = !nextImportStep(uri).isEmpty();
LOGGER.debug("hasNextImportStep('{}') -> {}", uri, returns);
return returns;
}
public static String shortenText(String text, int length) {
if (text.length() <= length) {
return text;
}
int i = text.indexOf(' ', length);
if (i < 0) {
return text;
}
return text.substring(0, i) + "…";
}
public static String shortenPersonLabel(String text) {
int pos = text.indexOf("(");
if (pos == -1) {
return text;
}
return text.substring(0, pos - 1);
}
/**
* Return <code>true</code> if s contains HTML markup tags or entities.
*
* @param s string to test
* @return true if string contains HTML
*/
public static boolean isHtml(final String s) {
boolean ret = false;
if (s != null) {
ret = HTML_MATCH_PATTERN.matcher(s).find();
}
return ret;
}
/**
* Stripes HTML tags from string.
*
* @param s string to strip HTML tags of
* @return the plain text without tags
*/
public static String stripHtml(final String s) {
StringBuilder res = new StringBuilder(s);
for (Matcher m = TAG_PATTERN.matcher(res.toString()); m.find(); m = TAG_PATTERN.matcher(res.toString())) {
res.delete(m.start(), m.end());
res.insert(m.start(), stripHtml(m.group(m.groupCount() - 1)));
}
return StringEscapeUtils.unescapeHtml4(res.toString()).replaceAll(TAG_SELF_CLOSING, "");
}
/**
* Returns approximately the usable space in the MCR.datadir in bytes as in {@link FileStore#getUsableSpace()}.
*
* @return approximately the usable space in the MCR.datadir
* @throws IOException
* */
public static long getUsableSpace() throws IOException{
Path dataDir = Paths.get(MCRConfiguration2.getStringOrThrow("MCR.datadir"));
dataDir = dataDir.toRealPath();
FileStore fs = Files.getFileStore(dataDir);
return fs.getUsableSpace();
}
/**
* Converts a string to valid NCName.
*
* @see <a href="https://www.w3.org/TR/1999/WD-xmlschema-2-19990924/#NCName">w3.org</a>
*
* @param name the string to convert
* @return a string which is a valid NCName
* @throws IllegalArgumentException if there is no way to convert the string to an NCName
*/
public static String toNCName(String name) {
while (name.length() > 0 && !XMLChar.isNameStart(name.charAt(0))) {
name = name.substring(1);
}
name = toNCNameSecondPart(name);
if (name.length() == 0) {
throw new IllegalArgumentException("Unable to convert '" + name + "' to valid NCName.");
}
return name;
}
/**
* Converts a string to a valid second part (everything after the first character) of a NCName. This includes
* "a-Z A-Z 0-9 - . _".
*
* @see <a href="https://www.w3.org/TR/1999/WD-xmlschema-2-19990924/#NCName">w3.org</a>
*
* @param name the string to convert
* @return a valid NCName
*/
public static String toNCNameSecondPart(String name) {
return name.replaceAll("[^\\w\\-\\.]*", "");
}
/**
* This only works with text nodes
* @return the order of nodes maybe changes
*/
public static NodeList distinctValues(NodeList nodes) {
SortedSet<Node> distinctNodeSet = new TreeSet<>((node, t1) -> {
String nodeValue = node.getNodeValue();
String nodeValue1 = t1.getNodeValue();
return Objects.equals(nodeValue1, nodeValue) ? 0 : -1;
});
for (int i = 0; i < nodes.getLength(); i++) {
distinctNodeSet.add(nodes.item(i));
}
return new SetNodeList(distinctNodeSet);
}
//use holder to not initialize MCRXMLMetadataManager to early (simplifies junit testing)
private static class MCRXMLMetaDataManagerHolder {
public static final MCRXMLMetadataManager INSTANCE = MCRXMLMetadataManager.instance();
}
private static class MCRCategLinkServiceHolder {
public static final MCRCategLinkService INSTANCE = MCRCategLinkServiceFactory.getInstance();
}
private static class SetNodeList implements NodeList {
private final Object[] objects;
SetNodeList(Set<Node> set) {
objects = set.toArray();
}
@Override
public Node item(int index) {
return (Node) objects[index];
}
@Override
public int getLength() {
return objects.length;
}
}
}
| 37,441 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRXMLHelper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Attribute;
import org.jdom2.Comment;
import org.jdom2.Content;
import org.jdom2.DocType;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.Parent;
import org.jdom2.ProcessingInstruction;
import org.jdom2.Text;
import org.jdom2.Verifier;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.transform.JDOMSource;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRException;
import org.mycore.common.content.MCRByteContent;
import org.mycore.common.content.streams.MCRByteArrayOutputStream;
import org.mycore.common.xsl.MCRLazyStreamSource;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
/**
* This class provides some static utility methods to deal with XML/DOM
* elements, nodes etc.
*
* @author Detlev Degenhardt
* @author Frank Lützenkirchen
* @author Thomas Scheffler (yagee)
*/
public class MCRXMLHelper {
private static final Logger LOGGER = LogManager.getLogger();
/**
* Protects XMLReader instance to XML External Entity (XXE) attacks.
*
* Try to set featues is this order
* <ol>
* <li>{@link XMLConstants#FEATURE_SECURE_PROCESSING}</li>
* <li>"http://apache.org/xml/features/disallow-doctype-decl"</li>
* </ol>
* @param reader a potential unprotected XMLReader
* @return the secured instance of <code>reader</code>
* @throws SAXNotSupportedException if setting any feature from above failes with this exception
* @throws SAXNotRecognizedException if setting any feature from above failes with this exception
*/
public static XMLReader asSecureXMLReader(XMLReader reader)
throws SAXNotSupportedException, SAXNotRecognizedException {
//prevent https://find-sec-bugs.github.io/bugs.htm#XXE_XMLREADER
try {
reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
} catch (SAXNotRecognizedException | SAXNotSupportedException e) {
LOGGER.warn(() -> "XML Parser feature " + XMLConstants.FEATURE_SECURE_PROCESSING
+ " is not supported, try to disable XSD support instead.");
try {
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
} catch (SAXNotRecognizedException | SAXNotSupportedException ex) {
ex.addSuppressed(e);
throw ex;
}
}
return reader;
}
/**
* Removes characters that are illegal in XML text nodes or attribute
* values.
*
* @param text
* the String that should be used in XML elements or attributes
* @return the String with all illegal characters removed
*/
public static String removeIllegalChars(String text) {
if (text == null || text.trim().length() == 0) {
return text;
}
if (Verifier.checkCharacterData(text) == null) {
return text;
}
// It seems we have to filter out invalid XML characters...
StringBuilder sb = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
if (Verifier.isXMLCharacter(text.charAt(i))) {
sb.append(text.charAt(i));
}
}
return sb.toString();
}
/**
* validates <code>doc</code> using XML Schema defined <code>schemaURI</code>
* @param doc document to be validated
* @param schemaURI URI of XML Schema document
* @throws SAXException if validation fails
* @throws IOException if resolving resources fails
*/
public static void validate(Document doc, String schemaURI) throws SAXException, IOException {
Schema schema = resolveSchema(schemaURI, false);
Validator validator = schema.newValidator();
validator.setResourceResolver(MCREntityResolver.instance());
validator.validate(new JDOMSource(doc));
}
/**
* Resolve the schema from the schemaURI honoring the catalog.xml
* @param schemaURI URI of XML Schema document
* @param disableSchemaFullCheckingFeature if true disable the feature
* http://apache.org/xml/features/validation/schema-full-checking
* @return the schema
*/
public static synchronized Schema resolveSchema(String schemaURI, boolean disableSchemaFullCheckingFeature)
throws IOException, SAXException {
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
if (disableSchemaFullCheckingFeature) {
sf.setFeature("http://apache.org/xml/features/validation/schema-full-checking", false);
}
sf.setResourceResolver(MCREntityResolver.instance());
Source source = resolveSource(schemaURI);
return sf.newSchema(source);
}
/**
* Resolves XML Source against the supplied <code>schemaURI</code>.
* First {@link MCREntityResolver#resolveEntity(String, String)} is tried to resolve against XMLCatalog and if
* no {@link InputSource} is returned finally {@link MCRURIResolver#resolve(String, String)}
* is called as a fallback.
*
* @param schemaURI uri to the XML document, e.g. XSD file
* @return a resolved XML document as Source or null
*/
public static Source resolveSource(String schemaURI) throws IOException, SAXException {
InputSource entity = MCREntityResolver.instance().resolveEntity(null, schemaURI);
if (entity != null) {
return new MCRLazyStreamSource(entity::getByteStream, entity.getSystemId());
}
try {
return MCRURIResolver.instance().resolve(schemaURI, null);
} catch (TransformerException e) {
Throwable cause = e.getCause();
if (cause instanceof IOException ioe) {
throw ioe;
}
if (cause instanceof SAXException se) {
throw se;
}
throw new IOException(e);
}
}
/**
* @see JDOMtoGSONSerializer
*
* @param content the jdom element to serialize
* @return a gson element
*/
public static JsonElement jsonSerialize(Content content) {
return JDOMtoGSONSerializer.serialize(content);
}
/**
* @see JDOMtoGSONSerializer#serializeElement(Element)
*
* @param element the jdom element to serialize
* @return a gson object
*/
public static JsonObject jsonSerialize(Element element) {
return JDOMtoGSONSerializer.serializeElement(element);
}
/**
* checks whether two documents are equal.
*
* This test performs a deep check across all child components of a
* Document.
*
* @param d1
* first Document to compare
* @param d2
* second Document to compare
* @return true, if d1 and d2 are deep equal
* @see Document#equals(java.lang.Object)
*/
public static boolean deepEqual(Document d1, Document d2) {
try {
return JDOMEquivalent.equivalent(canonicalElement(d1), canonicalElement(d2));
} catch (Exception e) {
LOGGER.warn("Could not compare documents.", e);
return false;
}
}
/**
* checks whether two elements are equal.
*
* This test performs a deep check across all child components of a
* element.
*
* @param e1
* first Element to compare
* @param e2
* second Element to compare
* @return true, if e1 and e2 are deep equal
* @see Document#equals(java.lang.Object)
*/
public static boolean deepEqual(Element e1, Element e2) {
try {
return JDOMEquivalent.equivalent(canonicalElement(e1), canonicalElement(e2));
} catch (Exception e) {
LOGGER.warn("Could not compare elements.", e);
return false;
}
}
private static Element canonicalElement(Parent p) throws IOException, JDOMException {
XMLOutputter xout = new XMLOutputter(Format.getCompactFormat());
MCRByteArrayOutputStream bout = new MCRByteArrayOutputStream();
if (p instanceof Element e) {
xout.output(e, bout);
} else {
xout.output((Document) p, bout);
}
Document xml = MCRXMLParserFactory.getNonValidatingParser()
.parseXML(new MCRByteContent(bout.getBuffer(), 0, bout.size()));
return xml.getRootElement();
}
private static class JDOMEquivalent {
private JDOMEquivalent() {
}
public static boolean equivalent(Element e1, Element e2) {
return equivalentName(e1, e2) && equivalentAttributes(e1, e2)
&& equivalentContent(e1.getContent(), e2.getContent());
}
public static boolean equivalent(Text t1, Text t2) {
String v1 = t1.getValue();
String v2 = t2.getValue();
boolean equals = v1.equals(v2);
if (!equals && LOGGER.isDebugEnabled()) {
LOGGER.debug("Text differs \"{}\"!=\"{}\"", t1, t2);
}
return equals;
}
public static boolean equivalent(DocType d1, DocType d2) {
boolean equals = d1.getPublicID().equals(d2.getPublicID()) && d1.getSystemID().equals(d2.getSystemID());
if (!equals && LOGGER.isDebugEnabled()) {
LOGGER.debug("DocType differs \"{}\"!=\"{}\"", d1, d2);
}
return equals;
}
public static boolean equivalent(Comment c1, Comment c2) {
String v1 = c1.getValue();
String v2 = c2.getValue();
boolean equals = v1.equals(v2);
if (!equals && LOGGER.isDebugEnabled()) {
LOGGER.debug("Comment differs \"{}\"!=\"{}\"", c1, c2);
}
return equals;
}
public static boolean equivalent(ProcessingInstruction p1, ProcessingInstruction p2) {
String t1 = p1.getTarget();
String t2 = p2.getTarget();
String d1 = p1.getData();
String d2 = p2.getData();
boolean equals = t1.equals(t2) && d1.equals(d2);
if (!equals && LOGGER.isDebugEnabled()) {
LOGGER.debug("ProcessingInstruction differs \"{}\"!=\"{}\"", p1, p2);
}
return equals;
}
public static boolean equivalentAttributes(Element e1, Element e2) {
List<Attribute> aList1 = e1.getAttributes();
List<Attribute> aList2 = e2.getAttributes();
if (aList1.size() != aList2.size()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Number of attributes differ \"{}\"!=\"{}\" for element {}", aList1, aList2,
e1.getName());
}
return false;
}
HashSet<String> orig = new HashSet<>(aList1.size());
for (Attribute attr : aList1) {
orig.add(attr.toString());
}
for (Attribute attr : aList2) {
orig.remove(attr.toString());
}
if (!orig.isEmpty() && LOGGER.isDebugEnabled()) {
LOGGER.debug("Attributes differ \"{}\"!=\"{}\"", aList1, aList2);
}
return orig.isEmpty();
}
public static boolean equivalentContent(List<Content> l1, List<Content> l2) {
if (l1.size() != l2.size()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Number of content list elements differ {}!={}", l1.size(), l2.size());
}
return false;
}
boolean result = true;
Iterator<Content> i1 = l1.iterator();
Iterator<Content> i2 = l2.iterator();
while (result && i1.hasNext() && i2.hasNext()) {
Object o1 = i1.next();
Object o2 = i2.next();
if (o1 instanceof Element e1 && o2 instanceof Element e2) {
result = equivalent(e1, e2);
} else if (o1 instanceof Text t1 && o2 instanceof Text t2) {
result = equivalent(t1, t2);
} else if (o1 instanceof Comment c1 && o2 instanceof Comment c2) {
result = equivalent(c1, c2);
} else if (o1 instanceof ProcessingInstruction p1 && o2 instanceof ProcessingInstruction p2) {
result = equivalent(p1, p2);
} else if (o1 instanceof DocType d1 && o2 instanceof DocType d2) {
result = equivalent(d1, d2);
} else {
result = false;
}
}
return result;
}
public static boolean equivalentName(Element e1, Element e2) {
Namespace ns1 = e1.getNamespace();
String localName1 = e1.getName();
Namespace ns2 = e2.getNamespace();
String localName2 = e2.getName();
return ns1.equals(ns2) && localName1.equals(localName2);
}
}
/**
* Helper class to serialize jdom XML to gson JSON.
* <p>
* To support fast javascript dot property access its decided to use the underscore (_)
* for attributes and the dollar sign ($) for text nodes. The colon sign (:) is used for
* namespaces (you have to use square brackets in javascript for accessing those).
* </p>
*
* <ul>
* <li><b>_version</b> -> version attribute</li>
* <li><b>$text</b> -> text node</li>
* <li><b>_xmlns:mods</b> -> mods namespace</li>
* <li><b>_mods:title</b> -> title attribute with mods namespace</li>
* </ul>
*
* <b>Example</b>
* <pre>
* {
* "_version": "3.0",
* "_xmlns:mods": "http://www.loc.gov/mods/v3"
* "mods:titleInfo": {
* "mods:title": {
* "$text": "hello xml serializer"
* }
* }
* }
* </pre>
* <ul>
* <li><b>get the version</b> -> mods._version -> "3.0"</li>
* <li><b>get the text of the title</b> -> mods["mods:titleInfo"]["mods:title"].$text
* -> "hello xml serializer"</li>
* </ul>
* <b>BE AWARE THAT MIXED CONTENT IS NOT SUPPORTED!</b>
*
* @author Matthias Eichner
*/
private static class JDOMtoGSONSerializer {
/**
* This method is capable of serializing Elements and Text nodes.
* Return null otherwise.
*
* @param content the content to serialize
* @return the serialized content, or null if the type is not supported
*/
public static JsonElement serialize(Content content) {
if (content instanceof Element element) {
return serializeElement(element);
}
if (content instanceof Text text) {
return serializeText(text);
}
return null;
}
static JsonPrimitive serializeText(Text text) {
return new JsonPrimitive(text.getText());
}
static JsonObject serializeElement(Element element) {
JsonObject json = new JsonObject();
// text
String text = element.getText();
if (text != null && text.trim().length() > 0) {
json.addProperty("$text", text);
}
// attributes
element.getAttributes().forEach(attr -> json.addProperty(getName(attr), attr.getValue()));
// namespaces
element.getAdditionalNamespaces().forEach(ns -> json.addProperty(getName(ns), ns.getURI()));
// children
// - build child map of <name,namespace> pair with their respective elements
Map<Pair<String, Namespace>, List<Element>> childContentMap = new HashMap<>();
for (Element child : element.getChildren()) {
Pair<String, Namespace> key = new Pair<>(child.getName(), child.getNamespace());
List<Element> contentList = childContentMap.computeIfAbsent(key, k -> new ArrayList<>());
contentList.add(child);
}
// - run through the map and serialize
for (Map.Entry<Pair<String, Namespace>, List<Element>> entry : childContentMap.entrySet()) {
Pair<String, Namespace> key = entry.getKey();
List<Element> contentList = entry.getValue();
String name = getName(key.x, key.y);
if (entry.getValue().size() == 1) {
json.add(name, serializeElement(contentList.get(0)));
} else if (contentList.size() >= 2) {
JsonArray arr = new JsonArray();
contentList.forEach(child -> arr.add(serialize(child)));
json.add(name, arr);
} else {
throw new MCRException(
"Unexcpected error while parsing children of element '" + element.getName() + "'");
}
}
return json;
}
private static String getName(Namespace ns) {
return "_xmlns:" + getCononicalizedPrefix(ns);
}
private static String getName(Attribute attribute) {
return "_" + getName(attribute.getName(), attribute.getNamespace());
}
private static String getName(String name, Namespace namespace) {
if (namespace != null && !namespace.getURI().equals("")) {
return getCononicalizedPrefix(namespace) + ":" + name;
}
return name;
}
private static String getCononicalizedPrefix(Namespace namespace) {
return MCRConstants
.getStandardNamespaces()
.parallelStream()
.filter(namespace::equals)
.findAny()
.map(Namespace::getPrefix)
.orElse(namespace.getPrefix());
}
private record Pair<X, Y>(X x, Y y) {
}
}
}
| 19,723 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUserAndObjectRightsURIResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRUserAndObjectRightsURIResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.util.Objects;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;
import javax.xml.transform.dom.DOMSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.access.MCRAccessManager;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* URI-Resolver, that checks if a MyCoRe object is
* worldReadable or worldReadableComplete and certain user and role information
*
* It is used as replacement for Xalan-Java functions in XSLT3 stylesheets.
*
*
* It is registered as property:
* MCR.URIResolver.ModuleResolver.userobjectrights=org.mycore.common.xml.MCRUserAndObjectRightsURIResolver
*
* returns for boolean results
* an XML element <boolean> with text 'true' or 'false'
*
* or for user attributes
* an XML element <userattribute name='{key}'>{value}</userattribute>
*
* sample usage (usually in SOLR indexing templates):
*
* <field name="worldReadable">
* <xsl:value-of select="document(concat('userobjectrights:isWorldReadable:',@ID))/boolean" />
* </field>
* <field name="worldReadableComplete">
* <xsl:value-of select="document(concat('userobjectrights:isWorldReadableComplete:',@ID))/boolean" />
* </field>
*
*/
public class MCRUserAndObjectRightsURIResolver implements URIResolver {
static final Logger LOGGER = LogManager.getLogger(MCRURIResolver.class);
@Override
public Source resolve(String href, String base) {
String query = href.substring(href.indexOf(":") + 1);
String key = query.substring(0, query.indexOf(":"));
String value = query.substring(query.indexOf(":") + 1);
try {
Document doc = MCRDOMUtils.getDocumentBuilder().newDocument();
Element result = doc.createElement("boolean");
doc.appendChild(result);
if (Objects.equals(key, "isWorldReadable")) {
result.appendChild(doc.createTextNode(Boolean.toString(MCRXMLFunctions.isWorldReadable(value))));
return new DOMSource(doc);
}
if (Objects.equals(key, "isWorldReadableComplete")) {
result.appendChild(
doc.createTextNode(Boolean.toString(MCRXMLFunctions.isWorldReadableComplete(value))));
return new DOMSource(doc);
}
if (Objects.equals(key, "isDisplayedEnabledDerivate")) {
result.appendChild(
doc.createTextNode(Boolean.toString(MCRAccessManager.checkDerivateDisplayPermission(value))));
return new DOMSource(doc);
}
if (Objects.equals(key, "isCurrentUserInRole")) {
result.appendChild(
doc.createTextNode(
Boolean.toString(MCRSessionMgr.getCurrentSession().getUserInformation().isUserInRole(value))));
return new DOMSource(doc);
}
if (Objects.equals(key, "isCurrentUserSuperUser")) {
result.appendChild(
doc.createTextNode(
Boolean.toString(MCRSessionMgr.getCurrentSession().getUserInformation().getUserID()
.equals(MCRSystemUserInformation.getSuperUserInstance().getUserID()))));
return new DOMSource(doc);
}
if (Objects.equals(key, "isCurrentUserGuestUser")) {
result.appendChild(
doc.createTextNode(
Boolean.toString(MCRSessionMgr.getCurrentSession().getUserInformation().getUserID()
.equals(MCRSystemUserInformation.getGuestInstance().getUserID()))));
return new DOMSource(doc);
}
if (Objects.equals(key, "getCurrentUserAttribute")) {
doc = MCRDOMUtils.getDocumentBuilder().newDocument();
Element attr = doc.createElement("userattribute");
attr.setAttribute("name", key);
doc.appendChild(attr);
attr.appendChild(
doc.createTextNode(MCRSessionMgr.getCurrentSession().getUserInformation().getUserAttribute(value)));
return new DOMSource(doc);
}
return new DOMSource(doc);
} catch (ParserConfigurationException e) {
LOGGER.error("Could not create DOM document", e);
}
return null;
}
}
| 5,405 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLayoutTransformerFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRLayoutTransformerFactory.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRClassTools;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.transformer.MCRContentTransformer;
import org.mycore.common.content.transformer.MCRContentTransformerFactory;
import org.mycore.common.content.transformer.MCRIdentityTransformer;
import org.mycore.common.content.transformer.MCRXSLTransformer;
import org.xml.sax.SAXException;
import com.google.common.collect.Lists;
/**
* This class acts as a {@link MCRContentTransformer} factory for {@link MCRLayoutService}.
* @author Thomas Scheffler (yagee)
* @author Sebastian Hofmann
*/
public class MCRLayoutTransformerFactory {
/** Map of transformer instances by ID */
private static Map<String, MCRContentTransformer> transformers = new ConcurrentHashMap<>();
private static Logger LOGGER = LogManager.getLogger(MCRLayoutTransformerFactory.class);
protected static final MCRIdentityTransformer NOOP_TRANSFORMER = new MCRIdentityTransformer("text/xml", "xml");
/**
* Returns the transformer with the given ID. If the transformer is not instantiated yet,
* it is created and initialized.
*/
public MCRContentTransformer getTransformer(String id) {
return transformers.computeIfAbsent(id, (transformerID) -> {
try {
Optional<MCRContentTransformer> configuredTransformer = getConfiguredTransformer(id);
if (configuredTransformer.isPresent()) {
return configuredTransformer.get();
}
return buildLayoutTransformer(id);
} catch (Exception e) {
throw new MCRException("Error while creating Transformer!", e);
}
});
}
protected Optional<MCRContentTransformer> getConfiguredTransformer(String id) {
return Optional.ofNullable(MCRContentTransformerFactory.getTransformer(id.replaceAll("-default$", "")));
}
private MCRContentTransformer buildLayoutTransformer(String id)
throws ParserConfigurationException, TransformerException, SAXException {
String idStripped = id.replaceAll("-default$", "");
LOGGER.debug("Configure property MCR.ContentTransformer.{}.Class if you do not want to use default behaviour.",
idStripped);
String stylesheet = getResourceName(id);
if (stylesheet == null) {
LOGGER.debug("Using noop transformer for {}", idStripped);
return NOOP_TRANSFORMER;
}
String[] stylesheets = getStylesheets(idStripped, stylesheet);
MCRContentTransformer transformer = MCRXSLTransformer.getInstance(stylesheets);
LOGGER.debug("Using stylesheet '{}' for {}", Lists.newArrayList(stylesheets), idStripped);
return transformer;
}
protected String[] getStylesheets(String id, String stylesheet)
throws TransformerException, SAXException, ParserConfigurationException {
List<String> ignore = MCRConfiguration2.getString("MCR.LayoutTransformerFactory.Default.Ignore")
.map(MCRConfiguration2::splitValue)
.map(s1 -> s1.collect(Collectors.toList()))
.orElseGet(Collections::emptyList);
List<String> defaults = Collections.emptyList();
if (!ignore.contains(id)) {
MCRXSLTransformer transformerTest = MCRXSLTransformer.getInstance(stylesheet);
String outputMethod = transformerTest.getOutputProperties().getProperty(OutputKeys.METHOD, "xml");
if (isXMLOutput(outputMethod, transformerTest)) {
defaults = MCRConfiguration2.getString("MCR.LayoutTransformerFactory.Default.Stylesheets")
.map(MCRConfiguration2::splitValue)
.map(s -> s.collect(Collectors.toList()))
.orElseGet(Collections::emptyList);
}
}
String[] stylesheets = new String[1 + defaults.size()];
stylesheets[0] = stylesheet;
for (int i = 0; i < defaults.size(); i++) {
stylesheets[i + 1] = defaults.get(i);
}
return stylesheets;
}
protected boolean isXMLOutput(String outputMethod, MCRXSLTransformer transformerTest)
throws ParserConfigurationException, TransformerException, SAXException {
return Objects.equals(outputMethod, "xml");
}
private String getResourceName(String id) {
LOGGER.debug("MCRLayoutService using style {}", id);
String styleName = buildStylesheetName(id);
try {
if (MCRXMLResource.instance().exists(styleName, MCRClassTools.getClassLoader())) {
return styleName;
}
} catch (Exception e) {
throw new MCRException("Error while loading stylesheet: " + styleName, e);
}
// If no stylesheet exists, forward raw xml instead
// You can transform raw xml code by providing a stylesheed named
// [doctype]-xml.xsl now
if (id.endsWith("-xml") || id.endsWith("-default")) {
LOGGER.warn("XSL stylesheet not found: {}", styleName);
return null;
}
throw new MCRException("XSL stylesheet not found: " + styleName);
}
/**
* Builds the filename of the stylesheet to use, e. g. "playlist-simple.xsl"
*/
private String buildStylesheetName(String id) {
final String xslFolder = MCRConfiguration2.getStringOrThrow("MCR.Layout.Transformer.Factory.XSLFolder");
return String.format(Locale.ROOT, "%s/%s.xsl", xslFolder, id.replaceAll("-default$", ""));
}
}
| 6,828 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRXMLParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.mycore.common.content.MCRContent;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* Parses XML content and returns it as JDOM document.
*
* Implementations of this interface are not thread safe.
*
* @author Frank Lützenkirchen
* @author Thomas Scheffler (yagee)
*/
public interface MCRXMLParser {
boolean isValidating();
Document parseXML(MCRContent content) throws JDOMException, IOException;
XMLReader getXMLReader() throws SAXException, ParserConfigurationException;
}
| 1,431 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRURIResolverFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRURIResolverFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.WriteListener;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;
/**
* Servlet Filter for adding debug information to servlet output.
*
* @author Thomas Scheffler (yagee)
*/
public class MCRURIResolverFilter implements Filter {
private static final Logger LOGGER = LogManager.getLogger(MCRURIResolver.class);
static ThreadLocal<List<String>> uriList = ThreadLocal.withInitial(ArrayList::new);
/**
* adds debug information from MCRURIResolver to Servlet output.
*
* The information includes all URIs resolved by MCRURIResolver by the
* current request. The filter is triggered by the log4j statement of the
* MCRURIResolver. To switch it on set the logger to DEBUG level.
*
* @see jakarta.servlet.Filter#doFilter(jakarta.servlet.ServletRequest,
* jakarta.servlet.ServletResponse, jakarta.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,
ServletException {
/*
* isDebugEnabled() may return a different value when called a second
* time. Since we initialize things in the first block, we need to make
* sure to visit the second block only if we visited the first block,
* too.
*/
final boolean debugEnabled = LOGGER.isDebugEnabled();
if (!debugEnabled) {
//do not filter...
filterChain.doFilter(request, response);
} else {
MyResponseWrapper wrapper = new MyResponseWrapper((HttpServletResponse) response);
// process request
filterChain.doFilter(request, wrapper);
final String origOutput = wrapper.toString();
final String characterEncoding = wrapper.getCharacterEncoding();
if (!uriList.get().isEmpty() && origOutput.length() > 0
&& (response.getContentType().contains("text/html")
|| response.getContentType().contains("text/xml"))) {
final StringBuilder buf
= new StringBuilder("\n<!-- \nThe following includes where resolved by MCRURIResolver:\n\n");
for (String obj : uriList.get()) {
buf.append(obj);
buf.append('\n');
}
buf.deleteCharAt(buf.length() - 1);
buf.append("\n-->");
final byte[] insertBytes = buf.toString().getBytes(characterEncoding);
response.setContentLength(origOutput.getBytes(characterEncoding).length + insertBytes.length);
int pos = getInsertPosition(origOutput);
try (ServletOutputStream out = response.getOutputStream()) {
out.write(origOutput.substring(0, pos).getBytes(characterEncoding));
out.write(insertBytes);
out.write(origOutput.substring(pos).getBytes(characterEncoding));
// delete debuglist
uriList.remove();
LOGGER.debug("end filter: {}", origOutput.substring(origOutput.length() - 10));
}
} else {
LOGGER.debug("Sending original response");
byte[] byteArray = wrapper.output.toByteArray();
if (byteArray.length > 0) {
try (ServletOutputStream out = response.getOutputStream()) {
out.write(byteArray);
}
}
}
}
}
private int getInsertPosition(final String origOutput) {
// if html document, before head-tag
int pos = origOutput.indexOf("<head>");
if (pos < 0) {
// for xml output, after <?xml *?>
pos = origOutput.indexOf("?>") + 2;
}
if (pos < 2) {
// for the rest
pos = 0;
}
return pos;
}
/*
* (non-Javadoc)
*
* @see jakarta.servlet.Filter#destroy()
*/
public void destroy() {
// nothing to be done so far
}
/*
* (non-Javadoc)
*
* @see jakarta.servlet.Filter#init(jakarta.servlet.FilterConfig)
*/
public void init(FilterConfig arg0) {
// no inititalization parameters required so far
}
/**
* wrapper arround the servlet response to change the output afterwards.
*
* @author Thomas Scheffler (yagee)
*/
private static class MyResponseWrapper extends HttpServletResponseWrapper {
private ByteArrayOutputStream output;
@Override
public String toString() {
try {
return output.toString(getCharacterEncoding());
} catch (UnsupportedEncodingException e) {
LOGGER.error("Fall back to DEFAULT encoding.");
return output.toString(Charset.defaultCharset());
}
}
MyResponseWrapper(HttpServletResponse response) {
super(response);
output = new ByteArrayOutputStream(16 * 1024);
}
@Override
public PrintWriter getWriter() {
return new PrintWriter(new OutputStreamWriter(output, Charset.forName(getCharacterEncoding())));
}
@Override
public ServletOutputStream getOutputStream() {
return new MyServletOutputStream();
}
@Override
public String getCharacterEncoding() {
final String encoding = super.getCharacterEncoding();
LOGGER.debug("Character Encoding: {}", encoding);
return encoding;
}
private class MyServletOutputStream extends ServletOutputStream {
@Override
public void print(String arg0) throws IOException {
output.write(arg0.getBytes(getResponse().getCharacterEncoding()));
}
@Override
public void write(int b) {
output.write(b);
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setWriteListener(WriteListener writeListener) {
//isReady() is always ready
}
}
}
}
| 7,721 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAttributeValueFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRAttributeValueFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.filter.ElementFilter;
/**
* A jdom-filter which compares attribute values.
*/
public class MCRAttributeValueFilter extends ElementFilter {
private static final long serialVersionUID = 1L;
protected String attrKey;
protected String attrValue;
protected Namespace ns;
public MCRAttributeValueFilter(String attrKey, Namespace ns, String attrValue) {
super();
this.attrKey = attrKey;
this.attrValue = attrValue;
this.ns = ns;
}
public Element filter(Object arg0) {
Element e = super.filter(arg0);
if (e == null) {
return null;
}
String value = e.getAttributeValue(attrKey, ns);
return (value != null && value.equals(attrValue)) ? e : null;
}
}
| 1,593 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXSLTransformerUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRXSLTransformerUtils.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.util.Map;
import java.util.Properties;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import org.mycore.common.config.MCRConfiguration2;
public class MCRXSLTransformerUtils {
private static final Map<String, String> MIME_TYPE_EXTENSIONS;
private static final Map<String, String> METHOD_EXTENSIONS;
static {
MIME_TYPE_EXTENSIONS = MCRConfiguration2.getSubPropertiesMap("MCR.XMLUtils.FileExtension.MimeType.");
METHOD_EXTENSIONS = MCRConfiguration2.getSubPropertiesMap("MCR.XMLUtils.FileExtension.Method.");
}
/**
* Returns the preferred file extension for a transformer based on the transformers output properties.
* This will inspect, in this order, the output properties <code>media-type</code> and <code>method</code> and
* return the first associated file extension, or the provided fallback, if no such file extension is found.
* <br/>
* To look up an associated file extension, the configuration keys
* <code>MCR.XMLUtils.FileExtension.MimeType.{$mimeType}</code> and
* <code>MCR.XMLUtils.FileExtension.Method.{$method}</code>, respectively are used.
*
* @param transformer the transformer
* @param fallback the fallback
* @return the file extension
*/
public static String getFileExtension(Transformer transformer, String fallback) {
return getFileExtension(transformer.getOutputProperties(), fallback);
}
/**
* Returns the preferred file extension for a transformers output properties.
* This will inspect, in this order, the output properties <code>media-type</code> and <code>method</code> and
* return the first associated file extension, or the provided fallback, if no such file extension is found.
* <br/>
* To look up an associated file extension, the configuration keys
* <code>MCR.XMLUtils.FileExtension.MimeType.{$mimeType}</code> and
* <code>MCR.XMLUtils.FileExtension.Method.{$method}</code>, respectively are used.
*
* @param outputProperties the output properties
* @param fallback the fallback
* @return the file extension
*/
public static String getFileExtension(Properties outputProperties, String fallback) {
String mimeType = outputProperties.getProperty(OutputKeys.MEDIA_TYPE);
if (mimeType != null) {
String mimeTypeExtension = MIME_TYPE_EXTENSIONS.get(mimeType);
if (mimeTypeExtension != null) {
return mimeTypeExtension;
}
}
String method = outputProperties.getProperty(OutputKeys.METHOD);
if (method != null) {
String methodExtension = METHOD_EXTENSIONS.get(method);
if (methodExtension != null) {
return methodExtension;
}
}
return fallback;
}
}
| 3,634 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREntityResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCREntityResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.spi.FileSystemProvider;
import java.util.Enumeration;
import java.util.Objects;
import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogManager;
import javax.xml.catalog.CatalogResolver;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRCache;
import org.mycore.common.MCRClassTools;
import org.mycore.common.MCRStreamUtils;
import org.mycore.common.MCRUtils;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.function.MCRThrowFunction;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import org.xml.sax.ext.EntityResolver2;
/**
* MCREntityResolver uses {@link CatalogResolver} for resolving entities or - for compatibility reasons - looks in
* classpath to resolve XSD and DTD files.
*
* @author Thomas Scheffler (yagee)
* @since 2013.10
*/
public class MCREntityResolver implements EntityResolver2, LSResourceResolver {
public static final Logger LOGGER = LogManager.getLogger(MCREntityResolver.class);
private static final String CONFIG_PREFIX = "MCR.URIResolver.";
CatalogResolver catalogResolver;
private MCRCache<String, InputSourceProvider> bytesCache;
private MCREntityResolver() {
Enumeration<URL> systemResources;
try {
systemResources = MCRClassTools.getClassLoader().getResources("catalog.xml");
} catch (IOException e) {
throw new ExceptionInInitializerError(e);
}
URI[] catalogURIs = MCRStreamUtils.asStream(systemResources)
.map(URL::toString)
.peek(c -> LOGGER.info("Using XML catalog: {}", c))
.map(URI::create)
.toArray(URI[]::new);
catalogResolver = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalogURIs);
int cacheSize = MCRConfiguration2.getInt(CONFIG_PREFIX + "StaticFiles.CacheSize").orElse(100);
bytesCache = new MCRCache<>(cacheSize, "EntityResolver Resources");
}
public static MCREntityResolver instance() {
return MCREntityResolverHolder.instance;
}
private static boolean isAbsoluteURL(String url) {
try {
URI testUri = new URI(url);
return testUri.isAbsolute();
} catch (URISyntaxException e) {
return false;
}
}
private InputSource resolveEntity(String publicId, String systemId,
MCRThrowFunction<CatalogEntityIdentifier, InputSource, IOException> alternative) throws IOException {
try {
InputSource entity = catalogResolver.resolveEntity(publicId, systemId);
if (entity != null) {
return resolvedEntity(entity);
}
} catch (CatalogException e) {
LOGGER.debug(e.getMessage());
}
return alternative.apply(new CatalogEntityIdentifier(publicId, systemId));
}
/* (non-Javadoc)
* @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String)
*/
@Override
public InputSource resolveEntity(String publicId, String systemId) throws IOException {
LOGGER.debug("Resolving: \npublicId: {}\nsystemId: {}", publicId, systemId);
return resolveEntity(publicId, systemId, id -> resolveClassRessource(id.publicId, id.systemId));
}
/* (non-Javadoc)
* @see org.xml.sax.ext.EntityResolver2#getExternalSubset(java.lang.String, java.lang.String)
*/
@Override
public InputSource getExternalSubset(String name, String baseURI) {
LOGGER.debug("External Subset: \nname: {}\nbaseURI: {}", name, baseURI);
return null;
}
/* (non-Javadoc)
* @see org.xml.sax.ext.EntityResolver2#resolveEntity(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public InputSource resolveEntity(String name, String publicId, String baseURI, String systemId)
throws IOException {
LOGGER.debug("Resolving: \nname: {}\npublicId: {}\nbaseURI: {}\nsystemId: {}", name, publicId, baseURI,
systemId);
return resolveEntity(publicId, systemId, id -> resolveRelativeEntity(baseURI, id));
}
private InputSource resolveRelativeEntity(String baseURI, CatalogEntityIdentifier id)
throws IOException {
if (id.systemId == null) {
return null; // Use default resolver
}
if (id.systemId.length() == 0) {
// if you overwrite SYSTEM by empty String in XSL
return new InputSource(new StringReader(""));
}
//resolve against base:
URI absoluteSystemId = resolveRelativeURI(baseURI, id.systemId);
if (absoluteSystemId.isAbsolute()) {
if (uriExists(absoluteSystemId)) {
InputSource inputSource = new InputSource(absoluteSystemId.toString());
inputSource.setPublicId(id.publicId);
return resolvedEntity(inputSource);
}
//resolve absolute URI against catalog first
return resolveEntity(id.publicId, absoluteSystemId.toString(),
id2 -> resolveClassRessource(id.publicId, id.systemId));
}
return resolveClassRessource(id.publicId, id.systemId);
}
private InputSource resolveClassRessource(String publicId, String systemId) throws IOException {
if (MCRUtils.filterTrimmedNotEmpty(systemId).isEmpty()) {
return null;
}
//required for XSD files that are usually classpath resources
InputSource is = getCachedResource("/" + systemId);
if (is == null) {
return null;
}
is.setPublicId(publicId);
return resolvedEntity(is);
}
private boolean uriExists(URI absoluteSystemId) {
if (absoluteSystemId.getScheme().startsWith("http")) {
return false; //default resolver handles http anyway
}
if (absoluteSystemId.getScheme().equals("jar")) {
//multithread issues, when using ZIP filesystem with second check
try {
URL jarURL = absoluteSystemId.toURL();
try (InputStream is = jarURL.openStream()) {
return is != null;
}
} catch (IOException e) {
LOGGER.error("Error while checking (URL) URI: {}", absoluteSystemId, e);
}
}
try {
if (isFileSystemAvailable(absoluteSystemId.getScheme())) {
Path pathTest = Paths.get(absoluteSystemId);
LOGGER.debug("Checking: {}", pathTest);
return Files.exists(pathTest);
}
} catch (Exception e) {
LOGGER.error("Error while checking (Path) URI: {}", absoluteSystemId, e);
}
return false;
}
private boolean isFileSystemAvailable(String scheme) {
return FileSystemProvider
.installedProviders()
.stream()
.map(FileSystemProvider::getScheme)
.anyMatch(Objects.requireNonNull(scheme)::equals);
}
private URI resolveRelativeURI(String baseURI, String systemId) {
if (baseURI == null || isAbsoluteURL(systemId)) {
return URI.create(systemId);
}
return URI.create(baseURI).resolve(systemId);
}
@Override
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
LOGGER.debug("Resolving resource: \ntype: {}\nnamespaceURI: {}\npublicId: {}\nsystemId: {}\nbaseURI: {}",
type, namespaceURI, publicId, systemId, baseURI);
return catalogResolver.resolveResource(type, namespaceURI, publicId, systemId, baseURI);
}
private InputSource resolvedEntity(InputSource entity) {
String msg = "Resolved to: " + entity.getSystemId() + ".";
LOGGER.debug(msg);
return entity;
}
private InputSource getCachedResource(String classResource) throws IOException {
URL resourceURL = this.getClass().getResource(classResource);
if (resourceURL == null) {
LOGGER.debug("{} not found", classResource);
return null;
}
InputSourceProvider is = bytesCache.get(classResource);
if (is == null) {
LOGGER.debug("Resolving resource {}", classResource);
final byte[] bytes;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream in = resourceURL.openStream()) {
IOUtils.copy(in, baos);
bytes = baos.toByteArray();
}
is = new InputSourceProvider(bytes, resourceURL);
bytesCache.put(classResource, is);
}
return is.newInputSource();
}
private static class MCREntityResolverHolder {
public static MCREntityResolver instance = new MCREntityResolver();
}
private static class InputSourceProvider {
byte[] bytes;
URL url;
InputSourceProvider(byte[] bytes, URL url) {
this.bytes = bytes;
this.url = url;
}
public InputSource newInputSource() {
InputSource is = new InputSource(url.toString());
is.setByteStream(new ByteArrayInputStream(bytes));
return is;
}
}
private static class CatalogEntityIdentifier {
private String publicId;
private String systemId;
private CatalogEntityIdentifier(String publicId, String systemId) {
this.publicId = publicId;
this.systemId = systemId;
}
}
}
| 10,857 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFunctionResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRFunctionResolver.java | package org.mycore.common.xml;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.jdom2.transform.JDOMSource;
import org.mycore.common.MCRClassTools;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* Resolves arbitrary static methods of arbitrary classes. Parameters are considerd to be of type
* {@link java.lang.String}.
* <br/><br/>
* <strong>Invocation</strong>
* <pre><code>function:<class name>:<method name>:<param1>:<param2></code></pre>
* <br/>
* <strong>Example</strong>
* <pre><code>function:de.uni_jena.thunibib.user.ThUniBibUtils:getLeadId:id_connection:foobar;</code></pre>
*
* @author shermann (Silvio Hermann)
* */
public class MCRFunctionResolver implements URIResolver {
private static Logger LOGGER = LogManager.getLogger(MCRFunctionResolver.class);
@Override
public Source resolve(String href, String base) throws TransformerException {
LOGGER.debug("Resolving {}", href);
String[] parts = href.split(":");
String className = parts[1];
String methodName = parts[2];
Object[] params = Arrays.stream(parts).skip(3).toArray(String[]::new);
try {
Class[] types = new Class[params.length];
Arrays.fill(types, String.class);
Object result = null;
Method method = MCRClassTools.forName(className).getMethod(methodName, types);
result = method.invoke(null, params);
Element string = new Element("string");
string.setText(result == null ? "" : String.valueOf(result));
return new JDOMSource(string);
} catch (Exception e) {
throw new TransformerException(e);
}
}
}
| 1,917 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNodeBuilder.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRNodeBuilder.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jaxen.BaseXPath;
import org.jaxen.JaxenException;
import org.jaxen.dom.DocumentNavigator;
import org.jaxen.expr.EqualityExpr;
import org.jaxen.expr.Expr;
import org.jaxen.expr.LiteralExpr;
import org.jaxen.expr.LocationPath;
import org.jaxen.expr.NameStep;
import org.jaxen.expr.Predicate;
import org.jaxen.expr.Step;
import org.jaxen.saxpath.Axis;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.Parent;
import org.mycore.common.MCRConstants;
/**
* @author Frank Lützenkirchen
*/
public class MCRNodeBuilder {
private static final Logger LOGGER = LogManager.getLogger(MCRNodeBuilder.class);
private Map<String, Object> variables;
private Object firstNodeBuilt = null;
public MCRNodeBuilder() {
}
public MCRNodeBuilder(Map<String, Object> variables) {
this.variables = variables;
}
public Object getFirstNodeBuilt() {
return firstNodeBuilt;
}
public Element buildElement(String xPath, String value, Parent parent) throws JaxenException {
return (Element) buildNode(xPath, value, parent);
}
public Attribute buildAttribute(String xPath, String value, Parent parent) throws JaxenException {
return (Attribute) buildNode(xPath, value, parent);
}
public Object buildNode(String xPath, String value, Parent parent) throws JaxenException {
BaseXPath baseXPath = new BaseXPath(xPath, new DocumentNavigator());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("start building {} relative to {}", simplify(xPath), MCRXPathBuilder.buildXPath(parent));
}
return buildExpression(baseXPath.getRootExpr(), value, parent);
}
private Object buildExpression(Expr expression, String value, Parent parent) throws JaxenException {
if (expression instanceof EqualityExpr equalityExpr) {
return buildEqualityExpression(equalityExpr, parent);
} else if (expression instanceof LocationPath locationPathExpr) {
return buildLocationPath(locationPathExpr, value, parent);
} else {
return canNotBuild(expression);
}
}
@SuppressWarnings("unchecked")
private Object buildLocationPath(LocationPath locationPath, String value, Parent parent) throws JaxenException {
Object existingNode = null;
List<Step> steps = locationPath.getSteps();
int i, indexOfLastStep = steps.size() - 1;
for (i = indexOfLastStep; i >= 0; i--) {
String xPath = buildXPath(steps.subList(0, i + 1));
existingNode = evaluateFirst(xPath, parent);
if (existingNode instanceof Element existingElement) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("element already existing");
}
parent = existingElement;
break;
} else if (existingNode instanceof Attribute) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("attribute already existing");
}
break;
} else if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{} does not exist or is not a node, will try to build it", xPath);
}
}
if (i == indexOfLastStep) {
return existingNode;
} else {
return buildLocationSteps(steps.subList(i + 1, steps.size()), value, parent);
}
}
private Object evaluateFirst(String xPath, Parent parent) {
return new MCRXPathEvaluator(variables, parent).evaluateFirst(xPath);
}
private String buildXPath(List<Step> steps) {
StringBuilder path = new StringBuilder();
for (Step step : steps) {
path.append('/').append(step.getText());
}
return simplify(path.substring(1));
}
private Object buildLocationSteps(List<Step> steps, String value, Parent parent) throws JaxenException {
Object built = null;
for (Iterator<Step> iterator = steps.iterator(); iterator.hasNext();) {
Step step = iterator.next();
built = buildStep(step, iterator.hasNext() ? null : value, parent);
if (built == null) {
return parent;
} else if (firstNodeBuilt == null) {
firstNodeBuilt = built;
}
if (built instanceof Parent newParent) {
parent = newParent;
}
}
return built;
}
private Object buildStep(Step step, String value, Parent parent) throws JaxenException {
if (step instanceof NameStep nameStep) {
return buildNameStep(nameStep, value, parent);
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("ignoring step, can not be built: {} {}", step.getClass().getName(),
simplify(step.getText()));
}
return null;
}
}
@SuppressWarnings("unchecked")
private Object buildNameStep(NameStep nameStep, String value, Parent parent) throws JaxenException {
String name = nameStep.getLocalName();
String prefix = nameStep.getPrefix();
Namespace ns = prefix.isEmpty() ? Namespace.NO_NAMESPACE : MCRConstants.getStandardNamespace(prefix);
if (nameStep.getAxis() == Axis.CHILD) {
if (parent instanceof Document parentDoc) {
return buildPredicates(nameStep.getPredicates(), parentDoc.getRootElement());
} else {
return buildPredicates(nameStep.getPredicates(), buildElement(ns, name, value, (Element) parent));
}
} else if (nameStep.getAxis() == Axis.ATTRIBUTE) {
return buildAttribute(ns, name, value, (Element) parent);
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("ignoring axis, can not be built: {} {}{}", nameStep.getAxis(),
prefix.isEmpty() ? "" : prefix + ":", name);
}
return null;
}
}
private Element buildPredicates(List<Predicate> predicates, Element parent) throws JaxenException {
for (Predicate predicate : predicates) {
new MCRNodeBuilder(variables).buildExpression(predicate.getExpr(), null, parent);
}
return parent;
}
private Object buildEqualityExpression(EqualityExpr ee, Parent parent) throws JaxenException {
if (ee.getOperator().equals("=")) {
if ((ee.getLHS() instanceof LocationPath) && (ee.getRHS() instanceof LiteralExpr rLiteral)) {
return assignLiteral(ee.getLHS(), rLiteral, parent);
} else if ((ee.getRHS() instanceof LocationPath) && (ee.getLHS() instanceof LiteralExpr lLiteral)) {
return assignLiteral(ee.getRHS(), lLiteral, parent);
} else if (ee.getLHS() instanceof LocationPath) {
String value = getValueOf(ee.getRHS().getText(), parent);
if (value != null) {
return assignLiteral(ee.getLHS(), value, parent);
}
}
}
return canNotBuild(ee);
}
/**
* Resolves the first match for the given XPath and returns its value as a String
*
* @param xPath the XPath expression
* @param parent the context element or document
* @return the value of the element or attribute as a String
*/
public String getValueOf(String xPath, Parent parent) {
Object result = evaluateFirst(xPath, parent);
if (result instanceof String s) {
return s;
} else if (result instanceof Element e) {
return e.getText();
} else if (result instanceof Attribute a) {
return a.getValue();
} else {
return null;
}
}
private Object assignLiteral(Expr expression, LiteralExpr literal, Parent parent) throws JaxenException {
String xPath = simplify(expression.getText()) + "[.=" + literal.getText() + "]";
return assignLiteral(expression, literal.getLiteral(), parent, xPath);
}
private Object assignLiteral(Expr expression, String literal, Parent parent) throws JaxenException {
String delimiter = literal.contains("'") ? "\"" : "'";
String xPath = simplify(expression.getText()) + "[.=" + delimiter + literal + delimiter + "]";
return assignLiteral(expression, literal, parent, xPath);
}
private Object assignLiteral(Expr expression, String literal, Parent parent, String xPath) throws JaxenException {
Object result = evaluateFirst(xPath, parent);
if ((result instanceof Element) || (result instanceof Attribute)) {
return result;
} else {
xPath = simplify(expression.getText()) + "[9999]";
return buildNode(xPath, literal, parent);
}
}
private Element buildElement(Namespace ns, String name, String value, Element parent) {
Element element = new Element(name, ns);
if ((value != null) && !value.isEmpty()) {
element.setText(value);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("building new element {}", element.getName());
}
if (parent != null) {
parent.addContent(element);
}
return element;
}
private Attribute buildAttribute(Namespace ns, String name, String value, Element parent) {
Attribute attribute = new Attribute(name, value == null ? "" : value, ns);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("building new attribute {}", attribute.getName());
}
if (parent != null) {
parent.setAttribute(attribute);
}
return attribute;
}
/**
* Removes obsolete child:: and attribute:: axis prefixes from given XPath
*/
public static String simplify(String xPath) {
return xPath.replaceAll("child::", "").replaceAll("attribute::", "@");
}
private Object canNotBuild(Expr expression) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("ignoring expression, can not be built: {} {}", expression.getClass().getName(),
simplify(expression.getText()));
}
return null;
}
}
| 11,271 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDOMUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRDOMUtils.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.mycore.common.MCRException;
import org.mycore.common.events.MCRShutdownHandler;
import org.mycore.common.events.MCRShutdownHandler.Closeable;
/**
* Helper class to get {@link DocumentBuilder} instances from a common pool
* @author Thomas Scheffler (yagee)
*/
public class MCRDOMUtils implements Closeable {
DocumentBuilderFactory docBuilderFactory;
ConcurrentLinkedQueue<DocumentBuilder> builderQueue;
private MCRDOMUtils() {
builderQueue = new ConcurrentLinkedQueue<>();
docBuilderFactory = DocumentBuilderFactory.newDefaultInstance();
docBuilderFactory.setNamespaceAware(true);
MCRShutdownHandler.getInstance().addCloseable(this);
}
public static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
DocumentBuilder documentBuilder = LazyHolder.INSTANCE.builderQueue.poll();
return documentBuilder != null ? resetDocumentBuilder(documentBuilder) : createDocumentBuilder();
}
public static DocumentBuilder getDocumentBuilderUnchecked() {
try {
return getDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new MCRException(e);
}
}
public static void releaseDocumentBuilder(DocumentBuilder documentBuilder) {
LazyHolder.INSTANCE.builderQueue.add(documentBuilder);
}
private static DocumentBuilder resetDocumentBuilder(DocumentBuilder documentBuilder) {
documentBuilder.reset();
documentBuilder.setEntityResolver(MCREntityResolver.instance());
return documentBuilder;
}
private static DocumentBuilder createDocumentBuilder() throws ParserConfigurationException {
DocumentBuilder documentBuilder = LazyHolder.INSTANCE.docBuilderFactory.newDocumentBuilder();
return resetDocumentBuilder(documentBuilder);
}
@Override
public void close() {
while (!builderQueue.isEmpty()) {
DocumentBuilder documentBuilder = builderQueue.poll();
documentBuilder.reset();
documentBuilder.setEntityResolver(null);
}
}
@Override
public int getPriority() {
return 0;
}
private static class LazyHolder {
private static final MCRDOMUtils INSTANCE = new MCRDOMUtils();
}
}
| 3,268 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDynamicURIResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRDynamicURIResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Hashtable;
import java.util.Iterator;
import javax.xml.transform.URIResolver;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.mycore.common.MCRTextResolver;
/**
* <p>
* Extend this class to include dynamic jdom content. The content is loaded
* from a xml file, which have to be set by the <code>setXmlFile</code>
* method.
* </p><p>
* The dynamic comes into play by the variables that can be defined for the
* uri. In general they are set directly behind the uri prefix. For example:
* </p>
* <pre>
* uriprefix:value1:value2:value3... or
* uriprefix:varname1=varvalue1:varname2=varvalue2:varname3=varname3...
* </pre>
* In the xml file you can use these variables with curly brackets '{}'.
* For more informations about the syntax see
* <code>MCRTextResolver</code>. Heres only a short example
* what is possible:
* <p>myURIResolver:classId=class_000_1:levels=-1:axis=children</p>
* <pre>
* <dynIncl>
* <panel>
* <hidden var="@classid" default="{classId}"/>
* <include uri="dynClassification:editor:{levels}:{axis}:{classId}[:{categId}]"/>
* <panel/>
* </dynIncl>
* </pre>
*
* @see MCRTextResolver
* @author Matthias Eichner
*/
public abstract class MCRDynamicURIResolver implements URIResolver {
private static final Logger LOGGER = LogManager.getLogger(MCRDynamicURIResolver.class);
protected Element cachedElement;
protected File xmlFile;
protected long lastModified;
public MCRDynamicURIResolver() {
lastModified = 0;
cachedElement = null;
xmlFile = null;
}
/**
* Sets the xml file. From this file the jdom content
* will be created.
*
* @param xmlFile xml file object
*/
public void setXmlFile(File xmlFile) {
this.xmlFile = xmlFile;
if (!xmlFile.exists()) {
LOGGER.error(new FileNotFoundException());
}
}
public Element resolveElement(String uri) {
if (xmlFile == null) {
throw new NullPointerException("No xml file set in '" + this.getClass().getName() + "'!");
}
Element rootElement = getRootElement();
Hashtable<String, String> variablesMap = createVariablesMap(uri);
resolveVariablesFromElement(rootElement, variablesMap);
return rootElement;
}
protected Element getRootElement() {
if (cachedElement == null || xmlFile.lastModified() > lastModified) {
try {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(xmlFile);
cachedElement = doc.getRootElement();
lastModified = System.currentTimeMillis();
} catch (Exception exc) {
LOGGER.error("Error while parsing {}!", xmlFile, exc);
return null;
}
}
// clone it for further replacements
// TODO: whats faster? cloning or building it new from file
return cachedElement.clone();
}
/**
* This method creates a hashtable that contains variables. There are two
* possibilities for getting the name of a variable from the uri:
* <ol>
* <li>uriprefix:value1:value2:value3</li>
* <li>uriprefix:varname1=varvalue1:varname2=varvalue2:varname3=varname3</li>
* </ol>
* Both options can be mixed, but this is not recommended.<br>
* For the first option the name of the variables is 'x', where 'x' is a number
* for the position in the uri. To get the first value use {1}, to get the second
* one use {2} and so on.
*
* @param uri the whole uri
* @return a hashtable with all variables from the uri
*/
protected Hashtable<String, String> createVariablesMap(String uri) {
Hashtable<String, String> variablesMap = new Hashtable<>();
String uriValue = uri.substring(uri.indexOf(':') + 1);
String[] variablesArr = uriValue.split(":");
for (int i = 0; i < variablesArr.length; i++) {
int equalsSignIndex = variablesArr[i].indexOf("=");
if (equalsSignIndex == -1) {
String varName = String.valueOf(i + 1);
String varValue = variablesArr[i];
variablesMap.put(varName, varValue);
} else {
String varName = variablesArr[i].substring(0, equalsSignIndex);
String varValue = variablesArr[i].substring(equalsSignIndex + 1);
variablesMap.put(varName, varValue);
}
}
return variablesMap;
}
/**
* This method runs through the whole content of the startElement and
* tries to resolve all variables in texts and attributes.
*
* @param startElement where to start to resolve the variables
* @param variablesMap a map of all variables
*/
protected void resolveVariablesFromElement(Element startElement, Hashtable<String, String> variablesMap) {
Iterator<Element> it = startElement.getDescendants(Filters.element());
MCRTextResolver varResolver = new MCRTextResolver(variablesMap);
while (it.hasNext()) {
Element element = it.next();
// text
String text = element.getText();
if (text != null && !text.equals("") && text.contains("{")) {
element.setText(varResolver.resolve(text));
}
// attributes
for (Attribute attrib : element.getAttributes()) {
String attribValue = attrib.getValue();
if (attribValue.contains("{")) {
attrib.setValue(varResolver.resolve(attribValue));
}
}
}
}
}
| 6,777 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTableMessage.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/log/MCRTableMessage.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.log;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
/**
* A {@link MCRTableMessage} is a table-like data structure that can be rendered as a two-dimensional string
* representation of that table.
* <p>
* Intended to create log messages that reveal the construction of tabular data.
* <p>
* Example output:
* <pre>
* │ Arabic │ Roman │ Englich │
* ├────────┼───────┼──────────────┤
* │ 0 │ │ zero │
* │ 1 │ I │ one │
* │ 23 │ XXIII │ twenty-three │
* │ 42 │ XLII │ forty-two │
* </pre>
*/
public final class MCRTableMessage<T> {
private final List<Column<? super T>> columns;
private final List<T> rows = new LinkedList<>();
@SafeVarargs
public MCRTableMessage(Column<? super T>... columns) {
this(Arrays.asList(columns));
}
public MCRTableMessage(List<Column<? super T>> columns) {
this.columns = new ArrayList<>(Objects.requireNonNull(columns));
this.columns.forEach(Objects::requireNonNull);
}
public String logMessage(String introduction) {
List<String> tableLines = tableLines();
String separator = System.lineSeparator();
return columns.isEmpty() ? introduction : introduction + separator + String.join(separator, tableLines);
}
public void add(T row) {
rows.add(Objects.requireNonNull(row));
}
public List<String> tableLines() {
LinkedList<String> lines = new LinkedList<>();
int[] lengths = new int[columns.size()];
String[] names = new String[columns.size()];
String[][] values = new String[rows.size()][columns.size()];
addNames(names, lengths);
addValues(values, lengths);
lines.add(rowLine(names, lengths));
lines.add(separatorLine(lengths));
for (int r = 0; r < rows.size(); r++) {
lines.add(rowLine(values[r], lengths));
}
return lines;
}
private void addNames(String[] names, int[] lengths) {
for (int c = 0; c < columns.size(); c++) {
Column<? super T> column = columns.get(c);
String name = column.name;
lengths[c] = name.length();
names[c] = name;
}
}
private void addValues(String[][] values, int[] lengths) {
for (int r = 0; r < rows.size(); r++) {
T row = rows.get(r);
for (int c = 0; c < columns.size(); c++) {
Column<? super T> column = columns.get(c);
String value = stringValue(column, row);
lengths[c] = Math.max(lengths[c], value.length());
values[r][c] = value;
}
}
}
private String stringValue(Column<? super T> column, T row) {
return stringValue(column.mapper.apply(row));
}
private String stringValue(Object value) {
if (value == null) {
return "";
} else if (value instanceof String string) {
return string;
} else if (value instanceof Optional<?> optional) {
return optional.map(this::stringValue).orElse("");
} else {
return value.toString();
}
}
private String rowLine(String[] values, int[] lengths) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < values.length; i++) {
String value = values[i];
builder.append('│');
builder.append(' ');
builder.append(value);
builder.append(" ".repeat(lengths[i] - value.length()));
builder.append(' ');
}
builder.append('│');
return builder.toString();
}
private String separatorLine(int[] lengths) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < lengths.length; i++) {
builder.append(i == 0 ? '├' : '┼');
builder.append('─');
builder.append("─".repeat(lengths[i]));
builder.append('─');
}
builder.append('┤');
return builder.toString();
}
public record Column<T>(String name, Function<T, Object> mapper) {
public Column(String name, Function<T, Object> mapper) {
this.name = Objects.requireNonNull(name);
this.mapper = Objects.requireNonNull(mapper);
}
}
}
| 5,363 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRThrowableTask.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/function/MCRThrowableTask.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.function;
import java.util.Objects;
@FunctionalInterface
public interface MCRThrowableTask<T extends Throwable> {
void run() throws T;
/**
* Returns a composed task that first runs the {@code before}
* task, and then runs this task.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*
* @see #andThen(MCRThrowableTask)
*/
default MCRThrowableTask<T> compose(MCRThrowableTask<? extends T> before) {
Objects.requireNonNull(before);
return () -> {
before.run();
run();
};
}
/**
* Returns a composed task that first this task, and then runs the {@code after} task.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param after the function to apply after this function is applied
* @return a composed task that first runs this task and then
* the {@code after} task
* @throws NullPointerException if after is null
*
* @see #compose(MCRThrowableTask)
*/
default MCRThrowableTask<T> andThen(MCRThrowableTask<? extends T> after) {
Objects.requireNonNull(after);
return () -> {
run();
after.run();
};
}
}
| 2,353 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFunctions.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/function/MCRFunctions.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.function;
import java.nio.file.FileSystem;
import java.util.regex.PatternSyntaxException;
import org.mycore.datamodel.niofs.MCRAbstractFileSystem;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRFunctions {
private static char END_OF_PATTERN = 0;
private static final String GLOB_RESERVED_CHARS = "?*\\{[";
private static final String REGEX_RESERVED_CHARS = "^$.{()+*[]|";
/**
* converts a Glob pattern into a regex pattern.
* @param globPattern a pattern like <code>"/foo/*{@literal}/bar/*.txt"</code>
* @see FileSystem#getPathMatcher(String) "glob" style
*/
public static String convertGlobToRegex(final String globPattern) {
boolean isInGroup = false;
final StringBuilder regex = new StringBuilder("^");
int nextPos = 0;
while (nextPos < globPattern.length()) {
final char c = globPattern.charAt(nextPos++);
switch (c) {
//Character handling
//CSOFF: InnerAssignment
case '\\' -> nextPos = escapeCharacter(regex, globPattern, nextPos);
case '[' -> nextPos = addCharacterClass(regex, globPattern, nextPos);
case '*' -> nextPos = handleWildcard(regex, globPattern, nextPos);
case '?' -> regex.append("[^/]");
//Group handling
case '{' -> isInGroup = startGroup(regex, globPattern, nextPos, isInGroup);
case '}' -> isInGroup = endGroup(regex, isInGroup);
//CSON: InnerAssignment
case ',' -> {
if (isInGroup) {
regex.append(")|(?:");//separate values
} else {
regex.append(',');
}
}
default -> {
if (isRegexReserved(c)) {
regex.append('\\');
}
regex.append(c);
}
}
}
if (isInGroup) {
throw new PatternSyntaxException("Missing '}'.", globPattern, nextPos - 1);
}
return regex.append('$').toString();
}
private static int addCharacterClass(final StringBuilder regex, final String globPattern, int nextPos) {
regex.append("[[^/]&&[");
if (nextCharAt(globPattern, nextPos) == '^') {
// escape the regex negation char if it appears
regex.append("\\^");
nextPos++;
} else {
// negation
if (nextCharAt(globPattern, nextPos) == '!') {
regex.append('^');
nextPos++;
}
// hyphen allowed at start
if (nextCharAt(globPattern, nextPos) == '-') {
regex.append('-');
nextPos++;
}
}
boolean inRange = false;
char rangeStartChar = 0;
char curChar = '[';
while (nextPos < globPattern.length()) {
curChar = globPattern.charAt(nextPos++);
if (curChar == ']') {
break;
}
if (curChar == MCRAbstractFileSystem.SEPARATOR) {
throw new PatternSyntaxException("Chracter classes cannot cross directory boundaries.", globPattern,
nextPos - 1);
}
if (curChar == '\\' || curChar == '[' || curChar == '&' && nextCharAt(globPattern, nextPos) == '&') {
// escape '\', '[' or "&&"
regex.append('\\');
}
regex.append(curChar);
if (curChar == '-') {
if (!inRange) {
throw new PatternSyntaxException("Invalid range.", globPattern, nextPos - 1);
}
curChar = nextCharAt(globPattern, nextPos++);
if (curChar == END_OF_PATTERN || curChar == ']') {
break;
}
if (curChar < rangeStartChar) {
throw new PatternSyntaxException("Invalid range.", globPattern, nextPos - 3);
}
regex.append(curChar);
inRange = false;
} else {
inRange = true;
rangeStartChar = curChar;
}
}
if (curChar != ']') {
throw new PatternSyntaxException("Missing ']'.", globPattern, nextPos - 1);
}
regex.append("]]");
return nextPos;
}
private static boolean endGroup(final StringBuilder regex, boolean isInGroup) {
if (isInGroup) {
isInGroup = false;
regex.append("))");
} else {
regex.append('}');
}
return isInGroup;
}
private static int escapeCharacter(final StringBuilder regex, final String globPattern, int nextPos) {
if (nextPos == globPattern.length()) {
throw new PatternSyntaxException("No character left to escape.", globPattern, nextPos - 1);
}
final char next = globPattern.charAt(nextPos++);
if (isGlobReserved(next) || isRegexReserved(next)) {
regex.append('\\');
}
regex.append(next);
return nextPos;
}
private static int handleWildcard(final StringBuilder regex, final String globPattern, int nextPos) {
if (nextCharAt(globPattern, nextPos) == '*') {
//The ** characters matches zero or more characters crossing directory boundaries.
regex.append(".*");
nextPos++;
} else {
//The * character matches zero or more characters of a name component without crossing directory boundaries
regex.append("[^/]*");
}
return nextPos;
}
private static boolean isGlobReserved(final char c) {
return GLOB_RESERVED_CHARS.indexOf(c) != -1;
}
private static boolean isRegexReserved(final char c) {
return REGEX_RESERVED_CHARS.indexOf(c) != -1;
}
private static char nextCharAt(final String glob, final int i) {
if (i < glob.length()) {
return glob.charAt(i);
}
return END_OF_PATTERN;
}
private static boolean startGroup(final StringBuilder regex, final String globPattern, final int nextPos,
final boolean isInGroup) {
if (isInGroup) {
throw new PatternSyntaxException("Nested groups are not supported.", globPattern, nextPos - 1);
}
regex.append("(?:(?:");
return true;
}
}
| 7,308 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRThrowFunction.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/function/MCRThrowFunction.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.function;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* Represents a function that accepts one argument and produces a result and throws an Exception.
*
* <p>Use {@link #toFunction()} or {@link #toFunction(BiFunction, Class)} to transform this
* MCRThrowFunction into a Function that can be handled throughout Java 8.</p>
*
* @param <T> the type of the input to the function
* @param <R> the type of the result of the function
* @param <E> the exception that is throw by this function-
*
* @since 2015.12
*/
@FunctionalInterface
public interface MCRThrowFunction<T, R, E extends Throwable> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t) throws E;
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of input to the {@code before} function, and to the
* composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*
* @see #andThen(MCRThrowFunction)
*/
default <V> MCRThrowFunction<V, R, E> compose(MCRThrowFunction<? super V, ? extends T, ? extends E> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*
* @see #compose(MCRThrowFunction)
*/
default <V> MCRThrowFunction<T, V, E> andThen(MCRThrowFunction<? super R, ? extends V, ? extends E> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
/**
* Returns a function that catches <E> and forwards it to the <code>throwableHandler</code> together with the Exception.
*
* Use this method if you want to react on the certain Exceptions and return a result
* or rethrow a specific RuntimeExption.
* @param throwableHandler a BiFunction that handles original Input and caught Exception
* @param exClass class of exception to catch
*/
default Function<T, R> toFunction(BiFunction<T, E, R> throwableHandler, Class<? super E> exClass) {
return t -> {
try {
return this.apply(t);
} catch (Throwable e) {
if (exClass.isAssignableFrom(e.getClass())) {
@SuppressWarnings("unchecked")
E handableException = (E) e;
return throwableHandler.apply(t, handableException);
}
throw (RuntimeException) e;
}
};
}
/**
* Returns a Function that applies <T> and catches any exception and wraps it into a {@link RuntimeException} if needed.
* Use this if you just want no specific exception handling.
*/
default Function<T, R> toFunction() {
return toFunction((t, e) -> {
if (e instanceof RuntimeException rte) {
throw rte;
}
throw new RuntimeException(e);
}, Throwable.class);
}
}
| 4,856 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
package-info.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/function/package-info.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Java 8 Lambdas
* @author Thomas Scheffler
*
*/
package org.mycore.common.function;
| 820 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTriConsumer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/function/MCRTriConsumer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.function;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Represents an operation that accepts two input arguments and returns no result. This is the three-arity
* specialization of {@link Consumer}. Unlike most other {@link FunctionalInterface functional interfaces},
* <code>MCRTriConsumer</code> is expected to operate via side-effects.
* <p>
* This is a {@link FunctionalInterface functional interface} whose functional method is
* {@link #accept(Object, Object, Object)}.
* </p>
*
* @author Thomas Scheffler (yagee)
*/
@FunctionalInterface
public interface MCRTriConsumer<T, U, V> {
/**
* Performs this operation on the given arguments.
*
* @param t
* the first input argument
* @param u
* the second input argument
* @param v
* the third input argument
*/
void accept(T t, U u, V v);
/**
* Returns a composed MCRTriConsumer that performs, in sequence, this operation followed by the after operation. If
* performing either operation throws an exception, it is relayed to the caller of the composed operation. If
* performing this operation throws an exception, the after operation will not be performed.
*
* @param after
* the Operation to perform after this operation
* @return a composed MCRTriConsumer that performs in sequence this operation followed by the after operation
* @throws NullPointerException
* if after is null
*/
default MCRTriConsumer<T, U, V> andThen(MCRTriConsumer<? super T, ? super U, ? super V> after) {
Objects.requireNonNull(after);
return (a, b, c) -> {
accept(a, b, c);
after.accept(a, b, c);
};
}
}
| 2,542 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWrappedContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRWrappedContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.CopyOption;
import java.nio.file.Path;
import javax.xml.transform.Source;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.mycore.datamodel.ifs.MCRContentInputStream;
import org.xml.sax.InputSource;
/**
* @author Thomas Scheffler (yagee)
*
*/
public abstract class MCRWrappedContent extends MCRContent {
private static final Logger LOGGER = LogManager.getLogger(MCRWrappedContent.class);
private MCRContent baseContent;
public MCRContent getBaseContent() {
return baseContent;
}
protected void setBaseContent(MCRContent baseContent) {
LOGGER.debug("Wrapped {}: {}", baseContent.getClass().getCanonicalName(), baseContent.getSystemId());
this.baseContent = baseContent;
}
/* (non-Javadoc)
* @see org.mycore.common.content.MCRContent#getInputStream()
*/
@Override
public InputStream getInputStream() throws IOException {
return getBaseContent().getInputStream();
}
@Override
void setSystemId(String systemId) {
getBaseContent().setSystemId(systemId);
}
@Override
public String getSystemId() {
return getBaseContent().getSystemId();
}
@Override
public MCRContentInputStream getContentInputStream() throws IOException {
return getBaseContent().getContentInputStream();
}
@Override
public Source getSource() throws IOException {
return getBaseContent().getSource();
}
@Override
public void sendTo(OutputStream out) throws IOException {
getBaseContent().sendTo(out);
}
@Override
public void sendTo(OutputStream out, boolean close) throws IOException {
getBaseContent().sendTo(out, close);
}
@Override
public void sendTo(Path target, CopyOption... options) throws IOException {
getBaseContent().sendTo(target, options);
}
@Override
public InputSource getInputSource() throws IOException {
return getBaseContent().getInputSource();
}
@Override
public void sendTo(File target) throws IOException {
getBaseContent().sendTo(target);
}
@Override
public byte[] asByteArray() throws IOException {
return getBaseContent().asByteArray();
}
@Override
public String asString() throws IOException {
return getBaseContent().asString();
}
@Override
public Document asXML() throws JDOMException, IOException {
return getBaseContent().asXML();
}
@Override
public MCRContent ensureXML() throws IOException, JDOMException {
return getBaseContent().ensureXML();
}
@Override
public String getDocType() throws IOException {
return getBaseContent().getDocType();
}
@Override
public boolean isReusable() {
return getBaseContent().isReusable();
}
@Override
public MCRContent getReusableCopy() throws IOException {
return getBaseContent().getReusableCopy();
}
@Override
public long length() throws IOException {
return getBaseContent().length();
}
@Override
public long lastModified() throws IOException {
return getBaseContent().lastModified();
}
@Override
public void setLastModified(long lastModified) {
getBaseContent().setLastModified(lastModified);
}
@Override
public String getETag() throws IOException {
return getBaseContent().getETag();
}
@Override
public ReadableByteChannel getReadableByteChannel() throws IOException {
return getBaseContent().getReadableByteChannel();
}
@Override
public void setDocType(String docType) {
getBaseContent().setDocType(docType);
}
@Override
public String getMimeType() throws IOException {
return getBaseContent().getMimeType();
}
@Override
public void setMimeType(String mimeType) {
getBaseContent().setMimeType(mimeType);
}
@Override
public String getName() {
return getBaseContent().getName();
}
@Override
public void setName(String name) {
getBaseContent().setName(name);
}
@Override
public boolean isUsingSession() {
return getBaseContent().isUsingSession();
}
@Override
public void setUsingSession(boolean usingSession) {
getBaseContent().setUsingSession(usingSession);
}
}
| 5,415 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRByteContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRByteContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Arrays;
import org.mycore.common.content.streams.MCRMD5InputStream;
/**
* Reads MCRContent from a byte[] array.
*
* @author Frank Lützenkichen
*/
public class MCRByteContent extends MCRContent {
private byte[] bytes;
private int offset;
private int length;
private long lastModified;
public MCRByteContent(byte[] bytes) {
this(bytes, 0, bytes.length);
}
public MCRByteContent(byte[] bytes, int offset, int length) {
this(bytes, offset, length, System.currentTimeMillis());
}
public MCRByteContent(byte[] bytes, long lastModified) {
this(bytes, 0, bytes.length, lastModified);
}
public MCRByteContent(byte[] bytes, int offset, int length, long lastModified) {
this.bytes = bytes;
this.offset = offset;
this.length = length;
this.lastModified = lastModified;
}
@Override
public void setSystemId(String systemId) {
this.systemId = systemId;
}
@Override
public InputStream getInputStream() {
return new ByteArrayInputStream(bytes, offset, length);
}
@Override
public byte[] asByteArray() {
if (offset == 0 && length == 0) {
return bytes;
}
synchronized (this) {
if (offset == 0 && length == bytes.length) {
return bytes;
}
bytes = Arrays.copyOfRange(bytes, offset, offset + length);
offset = 0;
length = bytes.length;
}
return bytes;
}
@Override
public long length() {
return length;
}
@Override
public long lastModified() {
return lastModified;
}
@Override
public String getETag() {
MessageDigest md5Digest = MCRMD5InputStream.buildMD5Digest();
md5Digest.update(bytes, offset, length);
byte[] digest = md5Digest.digest();
String md5String = MCRMD5InputStream.getMD5String(digest);
return '"' + md5String + '"';
}
}
| 2,891 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJAXBContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRJAXBContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.transform.Source;
import org.jdom2.Document;
import org.jdom2.transform.JDOMResult;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.util.JAXBSource;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRJAXBContent<T> extends MCRXMLContent {
JAXBContext ctx;
T jaxbObject;
public MCRJAXBContent(JAXBContext ctx, T jaxbObject) {
super();
this.ctx = ctx;
this.jaxbObject = jaxbObject;
Class<?> clazz = jaxbObject.getClass();
if (!clazz.isAnnotationPresent(XmlRootElement.class)) {
throw new IllegalArgumentException("Class " + clazz.getName() + " is not a JAXB annotated.");
}
this.docType = getRootTag(jaxbObject);
setName(jaxbObject.getClass().getSimpleName() + "-" + jaxbObject + ".xml");
setSystemId(jaxbObject.toString());
}
private String getRootTag(T jaxbObject) {
return jaxbObject.getClass().getAnnotation(XmlRootElement.class).name();
}
private Marshaller getMarshaller() throws JAXBException {
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, getSafeEncoding());
return marshaller;
}
public T getObject() {
return jaxbObject;
}
/* (non-Javadoc)
* @see org.mycore.common.content.MCRContent#getSource()
*/
@Override
public Source getSource() throws IOException {
try {
Marshaller marshaller = getMarshaller();
return new JAXBSource(marshaller, jaxbObject);
} catch (JAXBException e) {
throw new IOException(e);
}
}
/* (non-Javadoc)
* @see org.mycore.common.content.MCRContent#sendTo(java.io.OutputStream)
*/
@Override
public void sendTo(OutputStream out) throws IOException {
try {
Marshaller marshaller = getMarshaller();
marshaller.marshal(jaxbObject, out);
} catch (Exception e) {
throw new IOException(e);
}
}
/* (non-Javadoc)
* @see org.mycore.common.content.MCRContent#sendTo(java.io.File)
*/
@Override
public void sendTo(File target) throws IOException {
try {
Marshaller marshaller = getMarshaller();
marshaller.marshal(jaxbObject, target);
} catch (Exception e) {
throw new IOException(e);
}
}
/* (non-Javadoc)
* @see org.mycore.common.content.MCRContent#asXML()
*/
@Override
public Document asXML() throws IOException {
JDOMResult result = new JDOMResult();
try {
Marshaller marshaller = getMarshaller();
marshaller.marshal(jaxbObject, result);
} catch (JAXBException e) {
throw new IOException(e);
}
return result.getDocument();
}
}
| 3,843 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJDOMContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRJDOMContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.transform.Source;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;
import org.jdom2.transform.JDOMSource;
/**
* Reads MCRContent from a JDOM XML document.
*
* @author Frank Lützenkichen
*/
public class MCRJDOMContent extends MCRXMLContent {
private Document jdom;
/**
* @param jdom the JDOM XML document to read from
*/
public MCRJDOMContent(Document jdom) {
super();
this.jdom = jdom;
super.docType = jdom.getDocType() == null ? jdom.getRootElement().getName()
: jdom.getDocType()
.getElementName();
}
/**
* Alternative constructor for newly created root elements
* that do not have a Document parent yet, which is a very
* common use case.
*
* @param jdom the JDOM XML root element to read from
*/
public MCRJDOMContent(Element jdom) {
this(new Document(jdom));
}
@Override
public Source getSource() {
JDOMSource source = new JDOMSource(jdom);
source.setSystemId(systemId);
return source;
}
@Override
public void sendTo(OutputStream out) throws IOException {
if (jdom == null) {
throw new IOException("JDOM document is null and cannot be written to OutputStream");
}
new XMLOutputter(format).output(jdom, out);
}
@Override
public Document asXML() {
return jdom;
}
}
| 2,298 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRBaseContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRBaseContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRObjectService;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRBaseContent extends MCRJDOMContent {
public MCRBaseContent(MCRBase base) {
super(base.createXML());
setName(base.getId() + ".xml");
setLastModified(base.getService().getDate(MCRObjectService.DATE_TYPE_MODIFYDATE).getTime());
}
}
| 1,191 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Base64;
import javax.xml.transform.Source;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRUtils;
import org.mycore.common.xml.MCRXMLParserFactory;
import org.mycore.common.xsl.MCRLazyStreamSource;
import org.mycore.datamodel.common.MCRDataURL;
import org.mycore.datamodel.common.MCRDataURLEncoding;
import org.mycore.datamodel.ifs.MCRContentInputStream;
import org.xml.sax.InputSource;
/**
* Used to read/write content from any source to any target. Sources and targets can be strings, local files, Apache VFS
* file objects, XML documents, byte[] arrays and streams. The different sources are implemented by subclasses.
*
* @author Frank Lützenkirchen
* @author Thomas Scheffler (yagee)
*/
public abstract class MCRContent {
/**
* Holds the systemID of the current content
*/
protected String systemId;
/**
* Holds the docType of the current content
*/
protected String docType;
/**
* Size of content in bytes
*/
protected long length = -1;
/**
* Last modified timestamp
*/
protected long lastModified = -1;
protected String mimeType, encoding, name;
protected boolean usingSession = false;
/**
* Sets the systemID of the current content
*/
void setSystemId(String systemId) {
this.systemId = systemId;
if (getName() == null && systemId != null) {
String fileName = getFilenameFromSystemId();
setName(fileName);
}
}
private String getFilenameFromSystemId() {
String fileName = systemId;
String path = null;
try {
path = new URI(systemId).getPath();
} catch (URISyntaxException e2) {
LogManager.getLogger(getClass()).debug("Could not get file name from URI.", e2);
}
if (path != null) {
fileName = path;
}
if (fileName.endsWith("/")) {
fileName = FilenameUtils.getPathNoEndSeparator(fileName); //removes final '/';
}
return FilenameUtils.getName(fileName);
}
/**
* Returns the systemID of the current content
*/
public String getSystemId() {
return systemId;
}
/**
* Returns content as input stream. Be sure to close this stream properly!
*
* @return input stream to read content from
*/
public abstract InputStream getInputStream() throws IOException;
/**
* Returns an readable bytechannel to this content or null if one is not available.
*/
public ReadableByteChannel getReadableByteChannel() throws IOException {
InputStream inputStream = getInputStream();
return inputStream == null ? null : Channels.newChannel(inputStream);
}
/**
* Returns content as content input stream, which provides MD5 functionality. Be sure to close this stream properly!
*
* @return the content input stream
*/
public MCRContentInputStream getContentInputStream() throws IOException {
return new MCRContentInputStream(getInputStream());
}
/**
* Return the content as Source
*
* @return content as Source
*/
public Source getSource() throws IOException {
return new MCRLazyStreamSource(this::getInputStream, getSystemId());
}
/**
* Sends content to the given OutputStream. The OutputStream is NOT automatically closed afterwards.
*
* @param out
* the OutputStream to write the content to
*/
public void sendTo(OutputStream out) throws IOException {
try (InputStream in = getInputStream()) {
IOUtils.copy(in, out);
}
}
/**
* Sends content to the given OutputStream.
*
* @param out
* the OutputStream to write the content to
* @param close
* if true, close OutputStream afterwards
*/
public void sendTo(OutputStream out, boolean close) throws IOException {
try {
sendTo(out);
} finally {
if (close) {
out.close();
}
}
}
/**
* Returns content as SAX input source.
*
* @return input source to read content from
*/
public InputSource getInputSource() throws IOException {
InputSource source = new InputSource(getInputStream());
source.setSystemId(getSystemId());
return source;
}
/**
* Sends content to the given local file
*
* @param target
* the file to write the content to
*/
public void sendTo(File target) throws IOException {
sendTo(target.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
/**
* Sends content to the given path.
* @param target target path to write content to
* @param options see {@link Files#copy(InputStream, Path, CopyOption...)}} for help on copy options
*/
public void sendTo(Path target, CopyOption... options) throws IOException {
try (InputStream in = getInputStream()) {
Files.copy(in, target, options);
}
}
/**
* Returns the raw content
*
* @return the content
*/
public byte[] asByteArray() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
sendTo(baos);
baos.close();
return baos.toByteArray();
}
/**
* Returns content as String, assuming encoding from {@link #getEncoding()} or {@link MCRConstants#DEFAULT_ENCODING}
* .
*
* @return content as String
*/
public String asString() throws IOException {
return new String(asByteArray(), getSafeEncoding());
}
/**
* Returns content as "data:" URL.
*/
public MCRDataURL asDataURL() throws IOException {
return new MCRDataURL(asByteArray(), getDataURLEncoding(), getMimeType(), getSafeEncoding());
}
protected MCRDataURLEncoding getDataURLEncoding() throws IOException {
return getMimeType().startsWith("text/") ? MCRDataURLEncoding.URL
: MCRDataURLEncoding.BASE64;
}
/**
* Parses content, assuming it is XML, and returns the parsed document.
*
* @return the XML document parsed from content
*/
public Document asXML() throws JDOMException, IOException {
return MCRXMLParserFactory.getNonValidatingParser().parseXML(this);
}
/**
* Ensures that content is XML. The content is parsed as if asXML() is called. When content is XML, an MCRContent
* instance is returned that guarantees that. When XML can not be parsed, an exception is thrown.
*/
public MCRContent ensureXML() throws IOException, JDOMException {
return new MCRJDOMContent(asXML());
}
/**
* Return the document type of the content, assuming content is XML
*
* @return document type as String
*/
public String getDocType() throws IOException {
if (docType != null) {
return docType;
}
if (!isReusable()) {
throw new IOException("Cannot determine DOCTYPE as it would destroy underlaying InputStream.");
}
try (MCRContentInputStream cin = getContentInputStream()) {
byte[] header = cin.getHeader();
return MCRUtils.parseDocumentType(new ByteArrayInputStream(header));
}
}
/**
* Overwrites DocType detection.
*
* @see MCRContent#getDocType()
*/
public void setDocType(String docType) {
this.docType = docType;
}
/**
* If true, content can be read more than once by calling getInputStream() and similar methods. If false, content
* may be consumed when it is read more than once. Most subclasses provide reusable content.
*/
public boolean isReusable() {
return true;
}
/**
* Returns a reusable copy of this content, that is an instance (may be the same instance) thats content can be read
* more than once without consuming the stream.
*/
public MCRContent getReusableCopy() throws IOException {
if (isReusable()) {
return this;
} else {
MCRContent copy = new MCRByteContent(asByteArray(), lastModified());
copy.setSystemId(getSystemId());
copy.setName(getName());
copy.setMimeType(getMimeType());
if (docType != null) {
copy.setDocType(getDocType());
}
return copy;
}
}
/**
* Return the length of this content.
*
* @return -1 if length is unknown
*/
public long length() throws IOException {
return length;
}
/**
* Returns the last modified time
*
* @return -1 if last modified time is unknown
*/
public long lastModified() throws IOException {
return lastModified;
}
/**
* Returns either strong or weak ETag.
*
* @return null, if no ETag could be generated
*/
public String getETag() throws IOException {
return getSimpleWeakETag(getSystemId(), length, lastModified);
}
/**
* Uses provided parameter to compute simple weak ETag.
*
* @param systemId
* != null, {@link #getSystemId()}
* @param length
* >= 0, {@link #length()}
* @param lastModified
* >= 0, {@link #lastModified()}
* @return null if any preconditions are not met.
*/
protected String getSimpleWeakETag(String systemId, long length, long lastModified) {
if (systemId == null || length < 0 || lastModified < 0) {
return null;
}
StringBuilder b = new StringBuilder(32);
b.append("W/\"");
long lhash = systemId.hashCode();
byte[] unencodedETag = ByteBuffer.allocate(Long.SIZE / 4).putLong(lastModified ^ lhash).putLong(length ^ lhash)
.array();
b.append(Base64.getEncoder().encodeToString(unencodedETag));
b.append('"');
return b.toString();
}
public String getMimeType() throws IOException {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setLastModified(long lastModified) {
this.lastModified = lastModified;
}
/**
* Tells if this content may contain data from the current MCRSession. Use this information to alter cache behavior.
*
* @return true if it MAY contain session data
*/
public boolean isUsingSession() {
return usingSession;
}
public void setUsingSession(boolean usingSession) {
this.usingSession = usingSession;
}
public String getEncoding() {
return encoding;
}
protected String getSafeEncoding() {
String enc = getEncoding();
return enc != null ? enc : MCRConstants.DEFAULT_ENCODING;
}
public void setEncoding(String encoding) throws UnsupportedEncodingException {
this.encoding = encoding;
}
}
| 12,714 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRXMLContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import org.jdom2.output.Format;
import org.mycore.common.MCRConstants;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.streams.MCRMD5InputStream;
/**
* Reads MCRContent from an XML document.
* Provides functionality to output XML using different formatters.
*
* @author Frank Lützenkichen
*/
public abstract class MCRXMLContent extends MCRContent {
/**
* The default format used when outputting XML as a byte stream.
* By default, content is outputted using {@link MCRConstants#DEFAULT_ENCODING}.
* If MCR.IFS2.PrettyXML=true, a pretty format with indentation is used.
*/
protected static Format defaultFormat;
static {
boolean prettyXML = MCRConfiguration2.getBoolean("MCR.IFS2.PrettyXML").orElse(true);
defaultFormat = prettyXML ? Format.getPrettyFormat().setIndent(" ") : Format.getRawFormat();
defaultFormat.setEncoding(MCRConstants.DEFAULT_ENCODING);
}
/** The default format used when outputting this XML as a byte stream */
protected Format format = defaultFormat;
public MCRXMLContent() {
try {
this.setEncoding(MCRConstants.DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* Sets the format used when outputting XML as a byte stream.
* By default, content is outputted using {@link MCRConstants#DEFAULT_ENCODING}.
* If MCR.IFS2.PrettyXML=true, a pretty format with indentation is used.
*/
public void setFormat(Format format) {
this.format = format;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(asByteArray());
}
@Override
public MCRContent ensureXML() {
return this;
}
@Override
public String getMimeType() throws IOException {
return super.getMimeType() == null ? "text/xml" : super.getMimeType();
}
@Override
public long length() throws IOException {
return asByteArray().length;
}
@Override
public String getETag() throws IOException {
MessageDigest md5Digest = MCRMD5InputStream.buildMD5Digest();
byte[] byteArray = asByteArray();
md5Digest.update(byteArray, 0, byteArray.length);
byte[] digest = md5Digest.digest();
String md5String = MCRMD5InputStream.getMD5String(digest);
return '"' + md5String + '"';
}
@Override
public void setEncoding(String encoding) throws UnsupportedEncodingException {
super.setEncoding(encoding);
this.format = format.clone();
format.setEncoding(encoding);
}
}
| 3,652 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSeekableChannelContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRSeekableChannelContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import java.io.IOException;
import java.nio.channels.SeekableByteChannel;
/**
* An optional interface to MCRContent implementations.
*
* Allows random reads.
* @author Thomas Scheffler (yagee)
*
*/
public interface MCRSeekableChannelContent {
SeekableByteChannel getSeekableByteChannel() throws IOException;
}
| 1,087 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFileContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRFileContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import java.io.File;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
/**
* Reads MCRContent from a local file.
*
* @author Thomas Scheffler
*/
public class MCRFileContent extends MCRPathContent {
private File file;
public MCRFileContent(File file) {
super(file.toPath());
this.file = file;
}
public MCRFileContent(String file) {
this(new File(file));
}
@Override
public Source getSource() {
return new StreamSource(file);
}
}
| 1,300 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSAXContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRSAXContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import org.jdom2.Document;
import org.jdom2.input.sax.SAXHandler;
import org.mycore.common.xml.MCRXMLHelper;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRSAXContent extends MCRXMLContent {
private XMLReader xmlReader;
private InputSource inputSource;
public MCRSAXContent(XMLReader xmlReader, InputSource inputSource) {
super();
this.xmlReader = xmlReader;
this.inputSource = inputSource;
setSystemId(inputSource.getSystemId());
}
/* (non-Javadoc)
* @see org.mycore.common.content.MCRContent#getInputStream()
*/
@Override
public InputStream getInputStream() {
return inputSource.getByteStream();
}
@Override
public Source getSource() {
return new SAXSource(this.xmlReader, this.inputSource);
}
@Override
public Document asXML() throws IOException {
SAXHandler jdomContentHandler = new SAXHandler();
xmlReader.setContentHandler(jdomContentHandler);
try {
MCRXMLHelper.asSecureXMLReader(xmlReader).parse(inputSource);
} catch (SAXException e) {
throw new IOException(e);
}
return jdomContentHandler.getDocument();
}
@Override
public void setEncoding(String encoding) {
//defined by inputSource
}
@Override
public String getEncoding() {
return inputSource.getEncoding();
}
}
| 2,419 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStringContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRStringContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.mycore.common.MCRConstants;
/**
* Reads MCRContent from a String's text.
*
* @author Frank Lützenkichen
*/
public class MCRStringContent extends MCRContent {
private String text;
private byte[] bytes;
/**
* Reads content from the given string,
*/
public MCRStringContent(String text) {
this.text = text;
try {
setEncoding(MCRConstants.DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* Sets the character encoding to use when transforming the text to a byte stream.
* By default, this is {@link MCRConstants#DEFAULT_ENCODING}.
*/
@Override
public void setEncoding(String encoding) throws UnsupportedEncodingException {
super.setEncoding(encoding);
this.bytes = asByteArray();
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(asByteArray());
}
@Override
public byte[] asByteArray() throws UnsupportedEncodingException {
return text.getBytes(encoding);
}
public String asString() {
return text;
}
@Override
public long length() {
return bytes.length;
}
@Override
public long lastModified() {
return -1;
}
@Override
public String getETag() {
String eTag = getSimpleWeakETag(getSystemId(), length(), lastModified());
return eTag == null ? null : eTag.substring(2);
}
}
| 2,458 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStreamContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRStreamContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import java.io.IOException;
import java.io.InputStream;
import org.mycore.datamodel.ifs.MCRContentInputStream;
/**
* Reads MCRContent from an input stream. Typically, this content is not reusable, so that
* content can only be read once. Please be aware that an instance of this object contains an
* open input stream. Thus one has to invoke {@link MCRStreamContent#getInputStream()}.close() when
* finished with this object.
*
* @author Frank Lützenkichen
*/
public class MCRStreamContent extends MCRContent {
private InputStream in;
public MCRStreamContent(InputStream in) {
if (in == null) {
throw new NullPointerException("Cannot instantiate MCRStreamContent without InputStream.");
}
this.in = in;
}
/**
* @param systemId the systemID of this stream
*/
public MCRStreamContent(InputStream in, String systemId) {
this(in);
setSystemId(systemId);
}
/**
* @param systemId the systemID of this stream
*/
public MCRStreamContent(InputStream in, String systemId, String docType) {
this(in, systemId);
super.docType = docType;
}
@Override
public InputStream getInputStream() {
return in;
}
@Override
public MCRContentInputStream getContentInputStream() throws IOException {
if (!(in instanceof MCRContentInputStream)) {
in = super.getContentInputStream();
}
return (MCRContentInputStream) in;
}
/**
* Returns false, because input streams can only be read once.
* Use getReusableCopy() to circumvent this.
*/
@Override
public boolean isReusable() {
return false;
}
}
| 2,479 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRURLContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRURLContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.io.FilenameUtils;
import org.xml.sax.InputSource;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRURLContent extends MCRContent {
private URL url;
public MCRURLContent(URL url) {
super();
this.url = url;
this.setSystemId(url.toString());
String fileName = url.getPath();
if (fileName.endsWith("/")) {
fileName = FilenameUtils.getPathNoEndSeparator(fileName); //removes final '/';
}
setName(FilenameUtils.getName(fileName));
}
@Override
public InputStream getInputStream() throws IOException {
return url.openStream();
}
@Override
public Source getSource() {
return new StreamSource(getSystemId());
}
@Override
public InputSource getInputSource() {
return new InputSource(getSystemId());
}
@Override
public long length() throws IOException {
return url.openConnection().getContentLengthLong();
}
@Override
public long lastModified() throws IOException {
return url.openConnection().getLastModified();
}
@Override
public String getETag() throws IOException {
URLConnection openConnection = url.openConnection();
openConnection.connect();
String eTag = openConnection.getHeaderField("ETag");
if (eTag != null) {
return eTag;
}
long lastModified = openConnection.getLastModified();
long length = openConnection.getContentLengthLong();
eTag = getSimpleWeakETag(url.toString(), length, lastModified);
return eTag == null ? null : eTag.substring(2);
}
@Override
public String getMimeType() throws IOException {
return super.getMimeType() == null ? url.openConnection().getContentType() : super.getMimeType();
}
}
| 2,810 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSourceContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRSourceContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.transform.JDOMSource;
import org.mycore.common.MCRException;
import org.mycore.common.xml.MCRURIResolver;
import org.w3c.dom.Node;
import jakarta.xml.bind.util.JAXBSource;
/**
* @author Thomas Scheffler (yagee)
*/
public class MCRSourceContent extends MCRWrappedContent {
private static final MCRURIResolver URI_RESOLVER = MCRURIResolver.instance();
private Source source;
public MCRSourceContent(Source source) {
if (source == null) {
throw new NullPointerException("Source cannot be null");
}
this.source = source;
MCRContent baseContent = null;
if (source instanceof JDOMSource src) {
Document xml = src.getDocument();
if (xml != null) {
baseContent = new MCRJDOMContent(xml);
} else {
for (Object node : src.getNodes()) {
if (node instanceof Element element) {
Document doc = element.getDocument();
if (doc == null) {
baseContent = new MCRJDOMContent(element);
} else {
if (doc.getRootElement() == element) {
baseContent = new MCRJDOMContent(doc);
} else {
baseContent = new MCRJDOMContent(element.clone());
}
}
break;
} else if (node instanceof Document doc) {
baseContent = new MCRJDOMContent(doc);
break;
}
}
}
} else if (source instanceof JAXBSource) {
TransformerFactory transformerFactory = TransformerFactory.newDefaultInstance();
try {
Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
transformer.transform(source, new StreamResult(bout));
baseContent = new MCRByteContent(bout.toByteArray());
} catch (TransformerException e) {
throw new MCRException("Error while resolving JAXBSource", e);
}
} else if (source instanceof SAXSource src) {
baseContent = new MCRSAXContent(src.getXMLReader(), src.getInputSource());
} else if (source instanceof DOMSource domSource) {
Node node = domSource.getNode();
baseContent = new MCRDOMContent(node.getOwnerDocument());
} else if (source instanceof StreamSource streamSource) {
InputStream inputStream = streamSource.getInputStream();
if (inputStream != null) {
baseContent = new MCRStreamContent(inputStream);
} else {
try {
URI uri = new URI(source.getSystemId());
baseContent = new MCRURLContent(uri.toURL());
} catch (URISyntaxException | MalformedURLException e) {
throw new MCRException("Could not create instance of MCRURLContent for SYSTEMID: "
+ source.getSystemId(), e);
}
}
}
if (baseContent == null) {
throw new MCRException("Could not get MCRContent from " + source.getClass().getCanonicalName()
+ ", systemId:" + source.getSystemId());
}
baseContent.setSystemId(getSystemId());
this.setBaseContent(baseContent);
}
/**
* Build instance of MCRSourceContent by resolving via {@link MCRURIResolver}
*
* @throws TransformerException
* thrown by {@link MCRURIResolver#resolve(String, String)}
*/
public static MCRSourceContent getInstance(String uri) throws TransformerException {
Source source = URI_RESOLVER.resolve(uri, null);
if (source == null) {
return null;
}
return new MCRSourceContent(source);
}
@Override
public String getSystemId() {
return source.getSystemId();
}
@Override
public Source getSource() {
return source;
}
}
| 5,583 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDOMContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRDOMContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import org.jdom2.input.DOMBuilder;
import org.jdom2.output.XMLOutputter;
import org.w3c.dom.Document;
/**
* Reads MCRContent from a W3C DOM XML document.
*
* @author Frank Lützenkichen
*/
public class MCRDOMContent extends MCRXMLContent {
private Document dom;
/**
* @param dom the W3C DOM XML document to read from
*/
public MCRDOMContent(Document dom) {
super();
this.dom = dom;
super.docType = dom.getDoctype() == null ? dom.getDocumentElement().getLocalName() : dom.getDoctype().getName();
}
@Override
public Source getSource() {
DOMSource source = new DOMSource(dom);
source.setSystemId(systemId);
return source;
}
@Override
public void sendTo(OutputStream out) throws IOException {
org.jdom2.Document jdom;
jdom = asXML();
new XMLOutputter(format).output(jdom, out);
}
@Override
public org.jdom2.Document asXML() {
return new DOMBuilder().build(dom);
}
}
| 1,915 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPathContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/MCRPathContent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.CopyOption;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.datamodel.niofs.MCRFileAttributes;
/**
* MCRContent implementation that uses Java 7 {@link FileSystem} features.
*
* @author Thomas Scheffler (yagee)
*/
public class MCRPathContent extends MCRContent implements MCRSeekableChannelContent {
private static final Logger LOGGER = LogManager.getLogger();
private Path path;
private BasicFileAttributes attrs;
private static int BUFFER_SIZE = 8192;
public MCRPathContent(Path path) {
this(path, null);
}
public MCRPathContent(Path path, BasicFileAttributes attrs) {
this.path = Objects.requireNonNull(path).toAbsolutePath().normalize();
this.attrs = attrs;
}
/* (non-Javadoc)
* @see org.mycore.common.content.MCRSeekableChannelContent#getSeekableByteChannel()
*/
@Override
public SeekableByteChannel getSeekableByteChannel() throws IOException {
return Files.newByteChannel(path, StandardOpenOption.READ);
}
@Override
public InputStream getInputStream() throws IOException {
return Files.newInputStream(path, StandardOpenOption.READ);
}
@Override
public ReadableByteChannel getReadableByteChannel() throws IOException {
return getSeekableByteChannel();
}
@Override
public byte[] asByteArray() throws IOException {
return Files.readAllBytes(path);
}
@Override
public long length() throws IOException {
return attrs != null ? attrs.size() : Files.size(path);
}
@Override
public long lastModified() throws IOException {
return (attrs != null ? attrs.lastModifiedTime() : Files.getLastModifiedTime(path)).toMillis();
}
@Override
public String getETag() throws IOException {
if (attrs instanceof MCRFileAttributes fAttrs) {
return fAttrs.md5sum();
}
if (Files.getFileStore(path).supportsFileAttributeView("md5")) {
Object fileKey = Files.getAttribute(path, "md5:md5");
if (fileKey instanceof String s) {
return s;
}
}
return super.getETag();
}
@Override
public String getMimeType() throws IOException {
return mimeType == null ? Files.probeContentType(path) : mimeType;
}
@Override
public String getSystemId() {
return path.toUri().toString();
}
@Override
public String getName() {
return name == null ? path.getFileName().toString() : super.getName();
}
@Override
public void sendTo(OutputStream out) throws IOException {
Files.copy(path, out);
}
@Override
public void sendTo(File target) throws IOException {
Files.copy(path, target.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
@Override
public void sendTo(Path target, CopyOption... options) throws IOException {
Files.copy(path, target, options);
}
}
| 4,247 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXSL2XMLTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRXSL2XMLTransformer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.transformer;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.xml.transform.sax.TransformerHandler;
import org.jdom2.Content;
import org.jdom2.DefaultJDOMFactory;
import org.jdom2.Document;
import org.jdom2.JDOMFactory;
import org.jdom2.Text;
import org.jdom2.transform.JDOMResult;
import org.mycore.common.MCRCache;
import org.mycore.common.MCRConstants;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.xml.MCRXMLHelper;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* Transforms XML content using a static XSL stylesheet.
* The stylesheet is configured via
*
* MCR.ContentTransformer.{ID}.Stylesheet
*
* Resulting MCRContent holds XML.
* Use {@link MCRXSLTransformer} if you want to produce non XML output.
* @author Thomas Scheffler (yagee)
*
*/
public class MCRXSL2XMLTransformer extends MCRXSLTransformer {
private static MCRCache<String, MCRXSL2XMLTransformer> INSTANCE_CACHE = new MCRCache<>(100,
"MCRXSLTransformer instance cache");
public MCRXSL2XMLTransformer() {
super();
}
public MCRXSL2XMLTransformer(String... stylesheets) {
super(stylesheets);
}
public static MCRXSL2XMLTransformer getInstance(String... stylesheets) {
String key = stylesheets.length == 1 ? stylesheets[0] : Arrays.toString(stylesheets);
MCRXSL2XMLTransformer instance = INSTANCE_CACHE.get(key);
if (instance == null) {
instance = new MCRXSL2XMLTransformer(stylesheets);
INSTANCE_CACHE.put(key, instance);
}
return instance;
}
@Override
protected MCRContent getTransformedContent(MCRContent source, XMLReader reader,
TransformerHandler transformerHandler) throws IOException, SAXException {
JDOMResult result = new JDOMResult();
transformerHandler.setResult(result);
// Parse the source XML, and send the parse events to the
// TransformerHandler.
MCRXMLHelper.asSecureXMLReader(reader).parse(source.getInputSource());
Document resultDoc = getDocument(result);
if (resultDoc == null) {
throw new MCRConfigurationException("Stylesheets " + Arrays.asList(templateSources)
+ " does not return any content for " + source.getSystemId());
}
return new MCRJDOMContent(resultDoc);
}
private Document getDocument(JDOMResult result) {
Document resultDoc = result.getDocument();
if (resultDoc == null) {
//Sometimes a transformation produces whitespace strings
//JDOM would produce a empty document if it detects those
//So we remove them, if they exists.
List<Content> transformResult = result.getResult();
int origSize = transformResult.size();
Iterator<Content> iterator = transformResult.iterator();
while (iterator.hasNext()) {
Content content = iterator.next();
if (content instanceof Text text) {
String trimmedText = text.getTextTrim();
if (trimmedText.length() == 0) {
iterator.remove();
}
}
}
if (transformResult.size() < origSize) {
JDOMFactory f = result.getFactory();
if (f == null) {
f = new DefaultJDOMFactory();
}
resultDoc = f.document(null);
resultDoc.setContent(transformResult);
}
}
return resultDoc;
}
@Override
protected String getDefaultExtension() {
return "xml";
}
@Override
public String getEncoding() {
return MCRConstants.DEFAULT_ENCODING;
}
}
| 4,715 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIdentityTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRIdentityTransformer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.transformer;
import org.mycore.common.content.MCRContent;
/**
* This is a noop transformer.
*
* The {@link #transform(MCRContent)} method just returns the instance given as the parameter.
* @author Thomas Scheffler (yagee)
*
*/
public class MCRIdentityTransformer extends MCRContentTransformer {
public MCRIdentityTransformer(String mimeType, String fileExtension) {
this.mimeType = mimeType;
this.fileExtension = fileExtension;
}
/* (non-Javadoc)
* @see org.mycore.common.content.transformer.MCRContentTransformer#transform(org.mycore.common.content.MCRContent)
*/
@Override
public MCRContent transform(MCRContent source) {
return source;
}
}
| 1,475 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRContentTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRContentTransformer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.transformer;
import java.io.IOException;
import java.io.OutputStream;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRContent;
/**
* Subclasses of MCRContentTransformer implement different methods
* to transform MCRContent. They may have their own additional
* configuration properties. Every transformer instance has a unique ID.
* The implementing class is configured using the property
*
* MCR.ContentTransformer.{ID}.Class
*
* Optionally, a transformer can set its returning MIME Type via
*
* MCR.ContentTransformer.{ID}.MIMEType
*
* @author Frank Lützenkirchen
*/
public abstract class MCRContentTransformer {
/** The MIME type of the output generated by this transformer */
protected String mimeType;
protected String fileExtension;
protected String contentDisposition = DEFAULT_CONTENT_DISPOSITION;
/** The default MIME type */
private static final String DEFAULT_MIME_TYPE = "application/octet-stream";
public static final String DEFAULT_CONTENT_DISPOSITION = "inline";
/** Called by the factory to initialize configuration of this transformer */
public void init(String id) {
String mimeProperty = "MCR.ContentTransformer." + id + ".MIMEType";
String extensionProperty = "MCR.ContentTransformer." + id + ".FileExtension";
this.mimeType = MCRConfiguration2.getString(mimeProperty).orElseGet(this::getDefaultMimeType);
this.fileExtension = MCRConfiguration2.getString(extensionProperty).orElseGet(this::getDefaultExtension);
this.contentDisposition = MCRConfiguration2.getString("MCR.ContentTransformer." + id + ".ContentDisposition")
.orElse("inline");
}
/** Transforms MCRContent. Subclasses implement different transformation methods */
public abstract MCRContent transform(MCRContent source) throws IOException;
public void transform(MCRContent source, OutputStream out) throws IOException {
MCRContent content = transform(source);
try {
if (getEncoding() != null) {
content.setEncoding(getEncoding());
}
} catch (RuntimeException | IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
}
content.sendTo(out);
}
/** Returns the MIME type of the transformed content, may return the default mime type */
public String getMimeType() throws Exception {
return mimeType;
}
/**
* Returns the encoding of characters in the binary stream.
*
* Will return null if the encoding is unknown or the results does not represent character data.
*/
public String getEncoding() throws Exception {
return null;
}
/**
* Returns the file extension that is usually related to the transformed content.
*/
public String getFileExtension() throws Exception {
return fileExtension;
}
public String getContentDisposition() {
return contentDisposition;
}
protected String getDefaultExtension() {
return "bin";
}
protected String getDefaultMimeType() {
return DEFAULT_MIME_TYPE;
}
}
| 3,983 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObject2JSONTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRObject2JSONTransformer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.transformer;
import java.io.IOException;
import org.jdom2.JDOMException;
import org.mycore.common.content.MCRContent;
import org.mycore.datamodel.metadata.MCRObject;
import com.google.gson.JsonObject;
/**
* Converts the source to an MCRObject object and transforms it to JSON using MCRObject.createJSON();
*
* @author Robert Stephan
*/
public class MCRObject2JSONTransformer extends MCRToJSONTransformer {
@Override
protected JsonObject toJSON(MCRContent source) throws IOException {
try {
MCRObject mcrObj = new MCRObject(source.asXML());
return mcrObj.createJSON();
} catch (JDOMException e) {
throw new IOException(
"Could not generate JSON from " + source.getClass().getSimpleName() + ": " + source.getSystemId(), e);
}
}
}
| 1,588 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXSL2JAXBTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRXSL2JAXBTransformer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.transformer;
import java.io.IOException;
import java.util.Deque;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.TransformerHandler;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJAXBContent;
import org.mycore.common.xsl.MCRParameterCollector;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.util.JAXBResult;
/**
* Transforms XML content using a static XSL stylesheet.
* The stylesheet is configured via
*
* MCR.ContentTransformer.{ID}.Stylesheet
*
* JAXBContext contextPath is configured via
*
* MCR.ContentTransformer.{ID}.Context
*
* @author Thomas Scheffler (yagee)
* @see JAXBContext#newInstance(String, ClassLoader)
*/
public class MCRXSL2JAXBTransformer<T> extends MCRXSLTransformer {
private JAXBContext context;
public MCRXSL2JAXBTransformer() {
super();
}
public MCRXSL2JAXBTransformer(JAXBContext context, String... stylesheets) {
super(stylesheets);
this.context = context;
}
public MCRXSL2JAXBTransformer(JAXBContext context) {
super();
this.context = context;
}
@Override
protected MCRContent getTransformedContent(MCRContent source, XMLReader reader,
TransformerHandler transformerHandler) throws IOException, SAXException {
T result;
try {
result = getJAXBObject(source, reader, transformerHandler);
} catch (JAXBException e) {
throw new IOException(e);
}
return new MCRJAXBContent<>(context, result);
}
private T getJAXBObject(MCRContent source, XMLReader reader, TransformerHandler transformerHandler)
throws JAXBException, IOException, SAXException {
checkContext();
JAXBResult result = new JAXBResult(context);
transformerHandler.setResult(result);
// Parse the source XML, and send the parse events to the
// TransformerHandler.
reader.parse(source.getInputSource());
Object parsedResult = result.getResult();
if (parsedResult instanceof JAXBElement<?>) {
@SuppressWarnings("unchecked")
JAXBElement<T> jaxbElement = (JAXBElement<T>) parsedResult;
return jaxbElement.getValue();
}
@SuppressWarnings("unchecked")
T jaxbResult = (T) result.getResult();
return jaxbResult;
}
public T getJAXBObject(MCRContent source, MCRParameterCollector parameter)
throws TransformerConfigurationException, SAXException, JAXBException, IOException,
ParserConfigurationException {
Deque<TransformerHandler> transformHandlers = getTransformHandlers(parameter);
XMLReader reader = getXMLReader(transformHandlers);
TransformerHandler lastTransformerHandler = transformHandlers.getLast();
return getJAXBObject(source, reader, lastTransformerHandler);
}
public JAXBContext getContext() {
return context;
}
public void setContext(JAXBContext context) {
this.context = context;
}
private void checkContext() {
if (this.context == null) {
throw new NullPointerException("No JAXBContext defined!");
}
}
@Override
public void init(String id) {
super.init(id);
String property = "MCR.ContentTransformer." + id + ".Context";
String contextPath = MCRConfiguration2.getStringOrThrow(property);
try {
JAXBContext context = JAXBContext.newInstance(contextPath, getClass().getClassLoader());
setContext(context);
} catch (JAXBException e) {
throw new MCRConfigurationException("Error while creating JAXBContext.", e);
}
}
}
| 4,817 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRParameterizedTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRParameterizedTransformer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.transformer;
import java.io.IOException;
import java.io.OutputStream;
import org.mycore.common.content.MCRContent;
import org.mycore.common.xsl.MCRParameterCollector;
/**
* @author Thomas Scheffler (yagee)
*
*/
public abstract class MCRParameterizedTransformer extends MCRContentTransformer {
/** Transforms MCRContent. Subclasses implement different transformation methods */
public abstract MCRContent transform(MCRContent source, MCRParameterCollector parameter) throws IOException;
public void transform(MCRContent source, OutputStream out, MCRParameterCollector parameter) throws IOException {
transform(source, parameter).sendTo(out);
}
}
| 1,437 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRHTML2XHTMLContentTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRHTML2XHTMLContentTransformer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.transformer;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Entities;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRStringContent;
public class MCRHTML2XHTMLContentTransformer extends MCRContentTransformer {
@Override
public MCRContent transform(MCRContent source) throws IOException {
String htmlAsString = source.asString();
Document document = Jsoup.parse(htmlAsString);
document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
document.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
String s = document.outerHtml().replace("<html>", "<html xmlns=\"http://www.w3.org/1999/xhtml\">");
MCRStringContent stringContent = new MCRStringContent(s);
stringContent.setMimeType("application/xhtml+xml");
stringContent.setName(source.getName() + ".html");
return stringContent;
}
@Override
public String getFileExtension() {
return "html";
}
@Override
public String getMimeType() {
return "application/xhtml+xml";
}
}
| 1,922 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTransformerPipe.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRTransformerPipe.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.transformer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.content.MCRContent;
import org.mycore.common.xsl.MCRParameterCollector;
/**
* Transforms MCRContent by using a pipe of multiple transformers.
* The transformers to execute are configured by giving a list of their IDs, for example
*
* MCR.ContentTransformer.{ID}.Steps=ID2 ID3
*
* @author Frank Lützenkirchen
*/
public class MCRTransformerPipe extends MCRParameterizedTransformer {
/** List of transformers to execute */
private List<MCRContentTransformer> transformers = new ArrayList<>();
public MCRTransformerPipe(MCRContentTransformer... transformers) {
this();
this.transformers.addAll(Arrays.asList(transformers));
}
/* needed for MCRConfiguration2.getInstanceOf() to work */
public MCRTransformerPipe() {
super();
}
@Override
public void init(String id) {
String steps = MCRConfiguration2.getStringOrThrow("MCR.ContentTransformer." + id + ".Steps");
StringTokenizer tokens = new StringTokenizer(steps, " ;,");
while (tokens.hasMoreTokens()) {
String transformerID = tokens.nextToken();
MCRContentTransformer transformer = MCRContentTransformerFactory.getTransformer(transformerID);
if (transformer == null) {
throw new MCRConfigurationException(
"Transformer pipe element '" + transformerID + "' is not configured.");
}
transformers.add(transformer);
}
}
@Override
public MCRContent transform(MCRContent content) throws IOException {
return transform(content, new MCRParameterCollector());
}
@Override
public String getMimeType() throws Exception {
return transformers.get(transformers.size() - 1).getMimeType();
}
@Override
public String getEncoding() throws Exception {
return transformers.get(transformers.size() - 1).getEncoding();
}
@Override
public String getContentDisposition() {
return transformers.get(transformers.size() - 1).getContentDisposition();
}
@Override
protected String getDefaultExtension() {
return transformers.get(transformers.size() - 1).getDefaultExtension();
}
@Override
public String getFileExtension() throws Exception {
return transformers.get(transformers.size() - 1).getFileExtension();
}
@Override
public MCRContent transform(MCRContent source, MCRParameterCollector parameter) throws IOException {
for (MCRContentTransformer transformer : transformers) {
if (transformer instanceof MCRParameterizedTransformer parameterizedTransformer) {
source = parameterizedTransformer.transform(source, parameter);
} else {
source = transformer.transform(source);
}
}
return source;
}
}
| 3,902 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRToJSONTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRToJSONTransformer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.transformer;
import java.io.IOException;
import java.io.OutputStream;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRStringContent;
import org.mycore.common.xml.MCRXMLHelper;
import com.google.gson.JsonObject;
/**
* Uses {@link MCRXMLHelper#jsonSerialize(org.jdom2.Element)} to transform the source (must be XML) to JSON.
* @author Thomas Scheffler (yagee)
*/
public class MCRToJSONTransformer extends MCRContentTransformer {
/* (non-Javadoc)
* @see org.mycore.common.content.transformer.MCRContentTransformer#transform(org.mycore.common.content.MCRContent)
*/
@Override
public MCRContent transform(MCRContent source) throws IOException {
JsonObject jsonObject = toJSON(source);
MCRStringContent result = new MCRStringContent(jsonObject.toString());
result.setMimeType(mimeType);
result.setEncoding(getEncoding());
result.setUsingSession(source.isUsingSession());
return result;
}
protected JsonObject toJSON(MCRContent source) throws IOException {
try {
Document xml = source.asXML();
return MCRXMLHelper.jsonSerialize(xml.getRootElement());
} catch (JDOMException e) {
throw new IOException(
"Could not generate JSON from " + source.getClass().getSimpleName() + ": " + source.getSystemId(), e);
}
}
@Override
public void transform(MCRContent source, OutputStream out) throws IOException {
JsonObject jsonObject = toJSON(source);
out.write(jsonObject.toString().getBytes(getEncoding()));
}
@Override
public String getDefaultMimeType() {
//default by RFC 4627
return "application/json";
}
@Override
public String getEncoding() {
//default by RFC 4627
return "UTF-8";
}
@Override
protected String getDefaultExtension() {
return "json";
}
}
| 2,769 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRToPrettyXML.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRToPrettyXML.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.transformer;
import java.io.IOException;
import org.jdom2.JDOMException;
import org.jdom2.output.Format;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.content.MCRXMLContent;
/**
* Transforms xml content in pretty, UTF-8 encoded format.
*
* @author Frank Lützenkirchen
*/
public class MCRToPrettyXML extends MCRContentTransformer {
@Override
public MCRContent transform(MCRContent source) throws IOException {
MCRXMLContent content;
try {
content = (source instanceof MCRXMLContent ? (MCRXMLContent) source : new MCRJDOMContent(source.asXML()));
} catch (JDOMException e) {
throw new IOException(e);
}
if (content != source) {
content.setName(source.getName());
content.setLastModified(source.lastModified());
}
content.setFormat(Format.getPrettyFormat().setEncoding(getEncoding()));
return content;
}
@Override
public String getEncoding() {
return "UTF-8";
}
@Override
protected String getDefaultExtension() {
return "xml";
}
@Override
public String getMimeType() {
return "text/xml";
}
}
| 2,021 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRContentTransformerFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRContentTransformerFactory.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.transformer;
import java.util.HashMap;
import org.mycore.common.config.MCRConfiguration2;
/**
* Creates and returns MCRContentTransformer instances by their ID.
*
* @author Frank Lützenkirchen
*/
public class MCRContentTransformerFactory {
/** Map of transformer instances by ID */
private static HashMap<String, MCRContentTransformer> transformers = new HashMap<>();
/**
* Returns the transformer with the given ID. If the transformer is not instantiated yet,
* it is created and initialized.
*/
public static MCRContentTransformer getTransformer(String id) {
if (transformers.containsKey(id)) {
return transformers.get(id);
} else {
return buildTransformer(id);
}
}
/**
* Creates and initializes the transformer with the given ID.
*/
private static synchronized MCRContentTransformer buildTransformer(String id) {
String property = "MCR.ContentTransformer." + id + ".Class";
if (MCRConfiguration2.getString(property).isEmpty()
&& MCRConfiguration2.getString("MCR.ContentTransformer." + id + ".Stylesheet").isEmpty()) {
//check for reasonable default:
return null;
}
MCRContentTransformer transformer = MCRConfiguration2.<MCRContentTransformer>getInstanceOf(property)
.orElseGet(MCRXSLTransformer::new);
transformer.init(id);
transformers.put(id, transformer);
return transformer;
}
}
| 2,269 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRBibUtilsTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRBibUtilsTransformer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.transformer;
import java.io.IOException;
import java.io.InputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRContent;
import org.mycore.frontend.cli.MCRExternalProcess;
/**
* Transforms MCRContent by invoking an external BibUtils command.
* The BibUtils commands provide functionality to convert between
* RIS, Endnote, BibTeX, ISI web of science, Word 2007 bibliography format
* and MODS. For each transformer instance, the command must be specified,
* for example
*
* MCR.ContentTransformer.{ID}.Command=cmd.exe /c C:\\Java\\bibutils_4.12\\xml2bib.exe -b -w
*
* @author Frank Lützenkirchen
*/
public class MCRBibUtilsTransformer extends MCRContentTransformer {
private static final Logger LOGGER = LogManager.getLogger();
/** The external Bibutils command to invoke */
private String command;
@Override
public void init(String id) {
super.init(id);
command = MCRConfiguration2.getStringOrThrow("MCR.ContentTransformer." + id + ".Command");
}
@Override
public MCRContent transform(MCRContent source) throws IOException {
try {
MCRContent export = export(source);
export.setLastModified(source.lastModified());
export.setMimeType(getMimeType());
return export;
} catch (RuntimeException | IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
}
}
private MCRContent export(MCRContent mods) {
String[] arguments = buildCommandArguments();
try (InputStream stdin = mods.getInputStream()) {
MCRExternalProcess ep = new MCRExternalProcess(stdin, arguments);
ep.run();
String errors = ep.getErrors();
if (!errors.isEmpty()) {
LOGGER.warn(errors);
}
return ep.getOutput();
} catch (Exception ex) {
String msg = "Exception invoking external command " + command;
throw new MCRException(msg, ex);
}
}
/**
* Builds the command arguments to invoke the external BibUtils command
*/
private String[] buildCommandArguments() {
LOGGER.info(command);
return command.split(" ");
}
}
| 3,187 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDebuggingTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRDebuggingTransformer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.transformer;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.content.MCRContent;
/**
* Does not really transform content, instead logs the current contents.
* This can be useful when multiple transformers are combined in a pipe.
*
* @author Frank Lützenkirchen
*/
public class MCRDebuggingTransformer extends MCRContentTransformer {
private static final Logger LOGGER = LogManager.getLogger(MCRDebuggingTransformer.class);
@Override
public MCRContent transform(MCRContent source) throws IOException {
if (LOGGER.isDebugEnabled()) {
if (!source.isReusable()) {
source = source.getReusableCopy();
}
LOGGER.debug(">>>>>>>>>>>>>>>>>>>>");
LOGGER.debug(source.asString());
LOGGER.debug("<<<<<<<<<<<<<<<<<<<<");
}
return source;
}
}
| 1,708 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXsonifyTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRXsonifyTransformer.java | package org.mycore.common.content.transformer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.inject.Singleton;
import org.mycore.common.MCRException;
import org.mycore.common.config.annotation.MCRInstance;
import org.mycore.common.config.annotation.MCRPostConstruction;
import org.mycore.common.config.annotation.MCRProperty;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRStringContent;
import org.mycore.common.xml.MCREntityResolver;
import org.mycore.xsonify.serialize.Json2XmlSerializer;
import org.mycore.xsonify.serialize.SerializationException;
import org.mycore.xsonify.serialize.SerializerSettings;
import org.mycore.xsonify.serialize.SerializerStyle;
import org.mycore.xsonify.serialize.Xml2JsonSerializer;
import org.mycore.xsonify.xml.XmlDocument;
import org.mycore.xsonify.xml.XmlDocumentLoader;
import org.mycore.xsonify.xml.XmlEntityResolverDocumentLoader;
import org.mycore.xsonify.xml.XmlName;
import org.mycore.xsonify.xml.XmlParseException;
import org.mycore.xsonify.xml.XmlSaxParser;
import org.mycore.xsonify.xsd.Xsd;
import org.mycore.xsonify.xsd.XsdParseException;
import org.mycore.xsonify.xsd.XsdParser;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.Locale;
import static org.mycore.xsonify.serialize.SerializerSettings.AdditionalNamespaceDeclarationStrategy;
import static org.mycore.xsonify.serialize.SerializerSettings.DEFAULT_ADDITIONAL_NAMESPACE_DECLARATION_STRATEGY;
import static org.mycore.xsonify.serialize.SerializerSettings.DEFAULT_ATTRIBUTE_PREFIX_HANDLING;
import static org.mycore.xsonify.serialize.SerializerSettings.DEFAULT_ELEMENT_PREFIX_HANDLING;
import static org.mycore.xsonify.serialize.SerializerSettings.DEFAULT_JSON_STRUCTURE;
import static org.mycore.xsonify.serialize.SerializerSettings.DEFAULT_MIXED_CONTENT_HANDLING;
import static org.mycore.xsonify.serialize.SerializerSettings.DEFAULT_NAMESPACE_HANDLING;
import static org.mycore.xsonify.serialize.SerializerSettings.DEFAULT_NORMALIZE_TEXT;
import static org.mycore.xsonify.serialize.SerializerSettings.DEFAULT_OMIT_ROOT_ELEMENT;
import static org.mycore.xsonify.serialize.SerializerSettings.DEFAULT_PLAIN_TEXT_HANDLING;
import static org.mycore.xsonify.serialize.SerializerSettings.DEFAULT_XS_ANY_NAMESPACE_STRATEGY;
import static org.mycore.xsonify.serialize.SerializerSettings.JsonStructure;
import static org.mycore.xsonify.serialize.SerializerSettings.MixedContentHandling;
import static org.mycore.xsonify.serialize.SerializerSettings.NamespaceDeclaration;
import static org.mycore.xsonify.serialize.SerializerSettings.PlainTextHandling;
import static org.mycore.xsonify.serialize.SerializerSettings.PrefixHandling;
import static org.mycore.xsonify.serialize.SerializerSettings.XsAnyNamespaceStrategy;
/**
* <p>Content Transformer to convert XML to JSON and vice versa.
* Utilizes XML Schema Definition (XSD) to ensure accurate serialization and deserialization.</p>
* <p>
* The MCRXsonifyTransformer is configured by mycore.properties.
* <pre>
* {@code
* MCR.ContentTransformer.mods-json-normal.Class=org.mycore.common.content.transformer.MCRXsonifyTransformer
* }
* </pre>
* The Schema property points to a XSD and is required.
* <pre>
* {@code
* MCR.ContentTransformer.mods-json-normal.Schema=datamodel-mods.xsd
* }
* </pre>
* Other settings and the style of the json can also be defined by mycore.properties. See {@link SerializerSettings}
* and {@link SerializerStyle} for more information.
* <pre>
* {@code
* # settings
* MCR.ContentTransformer.mods-json-normal.Settings.Class=org.mycore.common.content.transformer.MCRXsonifyTransformer$SettingsBuilder
* MCR.ContentTransformer.mods-json-normal.Settings.OmitRootElement=false
* MCR.ContentTransformer.mods-json-normal.Settings.ElementPrefixHandling=RETAIN_ORIGINAL
* # style
* MCR.ContentTransformer.mods-json-normal.Style.Class=org.mycore.common.content.transformer.MCRXsonifyTransformer$StyleBuilder
* MCR.ContentTransformer.mods-json-normal.Style.TextKey=text
* }
* </pre>
*/
@Singleton
public class MCRXsonifyTransformer extends MCRContentTransformer {
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* Path to the XSD in the classpath.
*/
@MCRProperty(name = "Schema")
public String schema;
/**
* Local Name of the root element. By default, this is <b>mycoreobject</b>. This setting is only required in the
* json2xml serialisation process and if {@link SerializerSettings#omitRootElement()} is set to <b>true</b>.
*/
@MCRProperty(name = "RootName", required = false)
public String rootName = "mycoreobject";
/**
* Map of namespaces. This setting is required for the json2xml serialisation process if the
* {@link SerializerSettings#namespaceDeclaration()} is set to <b>OMIT</b>.
* TODO: Map property doesn't seem to work right now
*/
//@MCRProperty(name = "Namespaces", required = false)
//public Map<String, String> namespaces;
@MCRInstance(name = "Settings", valueClass = SettingsBuilder.class, required = false)
public SettingsBuilder settingsBuilder;
@MCRInstance(name = "Style", valueClass = StyleBuilder.class, required = false)
public StyleBuilder styleBuilder;
private Xml2JsonSerializer xml2JsonSerializer;
private Json2XmlSerializer json2XmlSerializer;
/**
* Initializes the transformer. Takes care of setting up the required serializers.
*
* @throws ParserConfigurationException if there is a problem with the XML parser configuration.
* @throws SAXException if there is a SAX-related issue.
*/
@MCRPostConstruction
public void init() throws ParserConfigurationException, SAXException, SerializationException, XsdParseException {
XmlSaxParser saxParser = new XmlSaxParser();
XmlDocumentLoader documentLoader = new XmlEntityResolverDocumentLoader(MCREntityResolver.instance(), saxParser);
XsdParser xsdParser = new XsdParser(documentLoader);
Xsd xsd = xsdParser.parse(this.schema);
SerializerSettings settings = settingsBuilder != null ? settingsBuilder.get() : new SerializerSettings();
SerializerStyle style = styleBuilder != null ? styleBuilder.get() : new SerializerStyle();
this.xml2JsonSerializer = new Xml2JsonSerializer(xsd, settings, style);
this.json2XmlSerializer = new Json2XmlSerializer(xsd, settings, style);
if (this.rootName != null) {
// TODO setRootName should set local name -> fix in xsonify API
this.json2XmlSerializer.setRootName(new XmlName(this.rootName, null));
}
/*if (this.namespaces != null && !this.namespaces.isEmpty()) {
List<XmlNamespace> namespaceList = namespaces.entrySet().stream()
.map(entry -> new XmlNamespace(entry.getKey(), entry.getValue()))
.toList();
this.json2XmlSerializer.setNamespaces(namespaceList);
}*/
}
/**
* Transforms the given {@code MCRContent} source into XML or JSON, depending on its mime type.
*
* @param source The content to be transformed.
* @return The transformed content.
* @throws IOException if there's an error in input-output operations.
*/
@Override
public MCRContent transform(MCRContent source) throws IOException {
String mimeType = source.getMimeType().toLowerCase(Locale.ROOT);
try {
if (mimeType.endsWith("xml")) {
return xml2json(source);
} else if (mimeType.endsWith("json")) {
return json2xml(source);
}
} catch (SerializationException serializerException) {
throw new MCRException("unable to serialize source.", serializerException);
}
throw new MCRException(
"Unable to transform source because mimeType '" + mimeType + "' is neither xml nor json.");
}
/**
* Converts XML content to JSON.
*
* @param source The XML content to be transformed.
* @return The transformed JSON content.
*/
protected MCRContent xml2json(MCRContent source) throws SerializationException {
XmlDocument xml = getXmlDocument(source);
ObjectNode json = this.xml2JsonSerializer.serialize(xml);
return asContent(json, source.isUsingSession());
}
/**
* Converts JSON content to XML.
*
* @param source The JSON content to be transformed.
* @return The transformed XML content.
*/
protected MCRContent json2xml(MCRContent source) throws SerializationException {
ObjectNode json = getJsonObject(source);
XmlDocument xml = this.json2XmlSerializer.serialize(json);
return asContent(xml, source.isUsingSession());
}
protected XmlDocument getXmlDocument(MCRContent source) {
try {
XmlSaxParser saxParser = new XmlSaxParser();
return saxParser.parse(source.getInputStream());
} catch (ParserConfigurationException | SAXException | IOException | XmlParseException e) {
throw new MCRException("Unable to parse xml source " + source.getName(), e);
}
}
protected ObjectNode getJsonObject(MCRContent source) {
try {
JsonNode jsonNode = MAPPER.readTree(source.asString());
if (jsonNode.isObject()) {
return (ObjectNode) jsonNode;
}
throw new MCRException("json is not a json object '" + jsonNode + "'");
} catch (IOException ioException) {
throw new MCRException("Unable to parse json source", ioException);
}
}
protected MCRContent asContent(ObjectNode json, boolean usingSession) {
MCRContent result = new MCRStringContent(json.toString());
result.setMimeType("application/json");
result.setUsingSession(usingSession);
return result;
}
protected MCRContent asContent(XmlDocument xml, boolean usingSession) {
MCRContent result = new MCRStringContent(xml.toXml(false));
result.setMimeType("text/xml");
result.setUsingSession(usingSession);
return result;
}
/**
* SettingsBuilder is responsible for building settings used for customizing the serialization process. See
* {@link SerializerSettings} for more information.
*/
public static class SettingsBuilder {
@MCRProperty(name = "OmitRootElement", required = false)
public String omitRootElement = String.valueOf(Boolean.valueOf(DEFAULT_OMIT_ROOT_ELEMENT));
@MCRProperty(name = "NamespaceDeclaration", required = false)
public String namespaceDeclaration = DEFAULT_NAMESPACE_HANDLING.name();
@MCRProperty(name = "NormalizeText", required = false)
public String normalizeText = String.valueOf(Boolean.valueOf(DEFAULT_NORMALIZE_TEXT));
@MCRProperty(name = "ElementPrefixHandling", required = false)
public String elementPrefixHandling = DEFAULT_ELEMENT_PREFIX_HANDLING.name();
@MCRProperty(name = "AttributePrefixHandling", required = false)
public String attributePrefixHandling = DEFAULT_ATTRIBUTE_PREFIX_HANDLING.name();
@MCRProperty(name = "JsonStructure", required = false)
public String jsonStructure = DEFAULT_JSON_STRUCTURE.name();
@MCRProperty(name = "PlainTextHandling", required = false)
public String plainTextHandling = DEFAULT_PLAIN_TEXT_HANDLING.name();
@MCRProperty(name = "MixedContentHandling", required = false)
public String mixedContentHandling = DEFAULT_MIXED_CONTENT_HANDLING.name();
@MCRProperty(name = "AdditionalNamespaceDeclarationStrategy", required = false)
public String additionalNamespaceDeclarationStrategy = DEFAULT_ADDITIONAL_NAMESPACE_DECLARATION_STRATEGY.name();
@MCRProperty(name = "XsAnyNamespaceStrategy", required = false)
public String xsAnyNamespaceStrategy = DEFAULT_XS_ANY_NAMESPACE_STRATEGY.name();
public SerializerSettings get() {
return new SerializerSettings(
Boolean.parseBoolean(omitRootElement),
NamespaceDeclaration.valueOf(namespaceDeclaration),
Boolean.parseBoolean(normalizeText),
PrefixHandling.valueOf(elementPrefixHandling),
PrefixHandling.valueOf(attributePrefixHandling),
JsonStructure.valueOf(jsonStructure),
PlainTextHandling.valueOf(plainTextHandling),
MixedContentHandling.valueOf(mixedContentHandling),
AdditionalNamespaceDeclarationStrategy.valueOf(additionalNamespaceDeclarationStrategy),
XsAnyNamespaceStrategy.valueOf(xsAnyNamespaceStrategy)
);
}
}
/**
* StyleBuilder is responsible for building styles used for customizing the serialization process. See
* {@link SerializerStyle} for more information.
*/
public static class StyleBuilder {
@MCRProperty(name = "AttributePrefix", required = false)
public String attributePrefix = new SerializerStyle().attributePrefix();
@MCRProperty(name = "XmlnsPrefix", required = false)
public String xmlnsPrefix = new SerializerStyle().xmlnsPrefix();
@MCRProperty(name = "TextKey", required = false)
public String textKey = new SerializerStyle().textKey();
@MCRProperty(name = "MixedContentKey", required = false)
public String mixedContentKey = new SerializerStyle().mixedContentKey();
@MCRProperty(name = "MixedContentElementNameKey", required = false)
public String mixedContentElementNameKey = new SerializerStyle().mixedContentElementNameKey();
@MCRProperty(name = "IndexKey", required = false)
public String indexKey = new SerializerStyle().indexKey();
public SerializerStyle get() {
return new SerializerStyle(
attributePrefix,
xmlnsPrefix,
textKey,
mixedContentKey,
mixedContentElementNameKey,
indexKey
);
}
}
}
| 14,382 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDerivate2JSONTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRDerivate2JSONTransformer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.transformer;
import java.io.IOException;
import org.jdom2.JDOMException;
import org.mycore.common.content.MCRContent;
import org.mycore.datamodel.metadata.MCRDerivate;
import com.google.gson.JsonObject;
/**
* Converts the source to an MCRDerivate object and transforms it to JSON using MCRDerivate.createJSON();
*
* @author Robert Stephan
*/
public class MCRDerivate2JSONTransformer extends MCRToJSONTransformer {
@Override
protected JsonObject toJSON(MCRContent source) throws IOException {
try {
MCRDerivate mcrDer = new MCRDerivate(source.asXML());
return mcrDer.createJSON();
} catch (JDOMException e) {
throw new IOException(
"Could not generate JSON from " + source.getClass().getSimpleName() + ": " + source.getSystemId(), e);
}
}
}
| 1,600 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXSLTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/transformer/MCRXSLTransformer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.transformer;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Base64;
import java.util.Deque;
import java.util.Optional;
import java.util.Properties;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Templates;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRCache;
import org.mycore.common.MCRClassTools;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationBase;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.content.MCRByteContent;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRWrappedContent;
import org.mycore.common.content.streams.MCRByteArrayOutputStream;
import org.mycore.common.xml.MCREntityResolver;
import org.mycore.common.xml.MCRURIResolver;
import org.mycore.common.xml.MCRXMLHelper;
import org.mycore.common.xml.MCRXMLParserFactory;
import org.mycore.common.xml.MCRXSLTransformerUtils;
import org.mycore.common.xsl.MCRErrorListener;
import org.mycore.common.xsl.MCRParameterCollector;
import org.mycore.common.xsl.MCRTemplatesSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* Transforms XML content using a static XSL stylesheet. The stylesheet is configured via
* <code>MCR.ContentTransformer.{ID}.Stylesheet</code>. You may choose your own instance of
* {@link SAXTransformerFactory} via <code>MCR.ContentTransformer.{ID}.TransformerFactoryClass</code>.
* The default transformer factory implementation {@link org.apache.xalan.processor.TransformerFactoryImpl}
* is configured with <code>MCR.LayoutService.TransformerFactoryClass</code>.
*
* @author Frank Lützenkirchen
*/
public class MCRXSLTransformer extends MCRParameterizedTransformer {
private static final int INITIAL_BUFFER_SIZE = 32 * 1024;
private static final MCRURIResolver URI_RESOLVER = MCRURIResolver.instance();
private static final MCREntityResolver ENTITY_RESOLVER = MCREntityResolver.instance();
private static Logger LOGGER = LogManager.getLogger(MCRXSLTransformer.class);
private static MCRCache<String, MCRXSLTransformer> INSTANCE_CACHE = new MCRCache<>(100,
"MCRXSLTransformer instance cache");
private static long CHECK_PERIOD = MCRConfiguration2.getLong("MCR.LayoutService.LastModifiedCheckPeriod")
.orElse(60000L);
private static final Class<? extends TransformerFactory> DEFAULT_FACTORY_CLASS = MCRConfiguration2
.<TransformerFactory>getClass("MCR.LayoutService.TransformerFactoryClass")
.orElseGet(TransformerFactory.newInstance()::getClass);
/** The compiled XSL stylesheet */
protected MCRTemplatesSource[] templateSources;
protected Templates[] templates;
protected long[] modified;
protected long modifiedChecked;
protected SAXTransformerFactory tFactory;
public MCRXSLTransformer(String... stylesheets) {
this(DEFAULT_FACTORY_CLASS);
setStylesheets(stylesheets);
}
public MCRXSLTransformer() {
this(DEFAULT_FACTORY_CLASS);
}
public MCRXSLTransformer(Class<? extends TransformerFactory> tfClass) {
super();
setTransformerFactory(tfClass.getName());
}
/**
* Sets the class name for {@link TransformerFactory} used by this transformer.
*
* Must be called for thread safety before this instance is shared to other threads.
*/
private void setTransformerFactory(String factoryClass) throws TransformerFactoryConfigurationError {
TransformerFactory transformerFactory = Optional.ofNullable(factoryClass)
.map(c -> TransformerFactory.newInstance(c, MCRClassTools.getClassLoader()))
.orElseGet(TransformerFactory::newInstance);
LOGGER.debug("Transformerfactory: {}", transformerFactory.getClass().getName());
transformerFactory.setURIResolver(URI_RESOLVER);
transformerFactory.setErrorListener(MCRErrorListener.getInstance());
if (transformerFactory.getFeature(SAXSource.FEATURE) && transformerFactory.getFeature(SAXResult.FEATURE)) {
this.tFactory = (SAXTransformerFactory) transformerFactory;
} else {
throw new MCRConfigurationException("Transformer Factory " + transformerFactory.getClass().getName()
+ " does not implement SAXTransformerFactory");
}
}
public static MCRXSLTransformer getInstance(String... stylesheets) {
return getInstance(DEFAULT_FACTORY_CLASS, stylesheets);
}
public static MCRXSLTransformer getInstance(Class<? extends TransformerFactory> tfClass, String... stylesheets) {
String key = tfClass.getName() + "_"
+ (stylesheets.length == 1 ? stylesheets[0] : Arrays.toString(stylesheets));
MCRXSLTransformer instance = INSTANCE_CACHE.get(key);
if (instance == null) {
instance = new MCRXSLTransformer(tfClass);
instance.setStylesheets(stylesheets);
INSTANCE_CACHE.put(key, instance);
}
return instance;
}
@Override
public void init(String id) {
super.init(id);
String property = "MCR.ContentTransformer." + id + ".Stylesheet";
String[] stylesheets = MCRConfiguration2.getStringOrThrow(property).split(",");
setStylesheets(stylesheets);
MCRConfiguration2.getString("MCR.ContentTransformer." + id + ".TransformerFactoryClass")
.ifPresent(this::setTransformerFactory);
}
public void setStylesheets(String... stylesheets) {
this.templateSources = new MCRTemplatesSource[stylesheets.length];
for (int i = 0; i < stylesheets.length; i++) {
this.templateSources[i] = new MCRTemplatesSource(stylesheets[i].trim());
}
this.modified = new long[templateSources.length];
this.modifiedChecked = 0;
this.templates = new Templates[templateSources.length];
}
private void checkTemplateUptodate()
throws TransformerConfigurationException, SAXException, ParserConfigurationException {
boolean check = System.currentTimeMillis() - modifiedChecked > CHECK_PERIOD;
boolean useCache = MCRConfiguration2.getBoolean("MCR.UseXSLTemplateCache").orElse(true);
if (check || !useCache) {
for (int i = 0; i < templateSources.length; i++) {
long lastModified = templateSources[i].getLastModified();
if (templates[i] == null || modified[i] < lastModified || !useCache) {
SAXSource source = templateSources[i].getSource();
templates[i] = tFactory.newTemplates(source);
if (templates[i] == null) {
throw new TransformerConfigurationException(
"XSLT Stylesheet could not be compiled: " + templateSources[i].getURL());
}
modified[i] = lastModified;
}
}
modifiedChecked = System.currentTimeMillis();
}
}
@Override
public String getEncoding() throws TransformerException, SAXException, ParserConfigurationException {
return getOutputProperties().getProperty("encoding", "UTF-8");
}
@Override
public String getMimeType() throws TransformerException, SAXException, ParserConfigurationException {
return getOutputProperties().getProperty("media-type", "text/xml");
}
@Override
public MCRContent transform(MCRContent source) throws IOException {
return transform(source, new MCRParameterCollector());
}
@Override
public MCRContent transform(MCRContent source, MCRParameterCollector parameter) throws IOException {
try {
Deque<TransformerHandler> transformHandlers = getTransformHandlers(parameter);
XMLReader reader = getXMLReader(transformHandlers);
TransformerHandler lastTransformerHandler = transformHandlers.getLast();
return transform(source, reader, lastTransformerHandler, parameter);
} catch (TransformerException | SAXException | ParserConfigurationException e) {
throw new IOException(e);
}
}
@Override
public void transform(MCRContent source, OutputStream out) throws IOException {
transform(source, out, new MCRParameterCollector());
}
@Override
public void transform(MCRContent source, OutputStream out, MCRParameterCollector parameter) throws IOException {
MCRErrorListener el = null;
try {
Deque<TransformerHandler> transformHandlers = getTransformHandlers(parameter);
XMLReader reader = getXMLReader(transformHandlers);
TransformerHandler lastTransformerHandler = transformHandlers.getLast();
el = (MCRErrorListener) lastTransformerHandler.getTransformer().getErrorListener();
StreamResult result = new StreamResult(out);
lastTransformerHandler.setResult(result);
reader.parse(source.getInputSource());
} catch (TransformerConfigurationException | SAXException | IllegalArgumentException
| ParserConfigurationException e) {
throw new IOException(e);
} catch (RuntimeException e) {
if (el != null && e.getCause() == null && el.getExceptionThrown() != null) {
//typically if a RuntimeException has no cause,
//we can get the "real cause" from MCRErrorListener, yeah!!!
throw new IOException(el.getExceptionThrown());
}
throw e;
}
}
protected MCRContent transform(MCRContent source, XMLReader reader, TransformerHandler transformerHandler,
MCRParameterCollector parameter)
throws IOException, SAXException, TransformerException, ParserConfigurationException {
return new MCRTransformedContent(source, reader, transformerHandler, getLastModified(), parameter,
getFileName(source), getMimeType(), getEncoding(), this);
}
protected MCRContent getTransformedContent(MCRContent source, XMLReader reader,
TransformerHandler transformerHandler) throws IOException, SAXException {
MCRByteArrayOutputStream baos = new MCRByteArrayOutputStream(INITIAL_BUFFER_SIZE);
StreamResult serializer = new StreamResult(baos);
transformerHandler.setResult(serializer);
// Parse the source XML, and send the parse events to the
// TransformerHandler.
LOGGER.debug("Start transforming: {}", source.getSystemId() == null ? source.getName() : source.getSystemId());
MCRXMLHelper.asSecureXMLReader(reader).parse(source.getInputSource());
return new MCRByteContent(baos.getBuffer(), 0, baos.size());
}
private String getFileName(MCRContent content)
throws TransformerException, SAXException, ParserConfigurationException {
String fileName = content.getName();
if (fileName == null) {
return null;
}
//MCR-2254, ':' in fileName causes problems on Windows
fileName = fileName.replace(':', '_');
return FilenameUtils.removeExtension(fileName) + "." + getFileExtension();
}
private long getLastModified() {
long lastModified = -1;
for (long current : modified) {
if (current < 0) {
return -1;
}
lastModified = Math.max(lastModified, current);
}
return lastModified;
}
protected Deque<TransformerHandler> getTransformHandlers(MCRParameterCollector parameterCollector)
throws TransformerConfigurationException, SAXException, ParserConfigurationException {
checkTemplateUptodate();
Deque<TransformerHandler> xslSteps = new ArrayDeque<>();
//every transformhandler shares the same ErrorListener instance
MCRErrorListener errorListener = MCRErrorListener.getInstance();
for (Templates template : templates) {
TransformerHandler handler = tFactory.newTransformerHandler(template);
parameterCollector.setParametersTo(handler.getTransformer());
handler.getTransformer().setErrorListener(errorListener);
if (!xslSteps.isEmpty()) {
Result result = new SAXResult(handler);
xslSteps.getLast().setResult(result);
}
xslSteps.add(handler);
}
return xslSteps;
}
protected XMLReader getXMLReader(Deque<TransformerHandler> transformHandlerList)
throws SAXException, ParserConfigurationException {
XMLReader reader = MCRXMLParserFactory.getNonValidatingParser().getXMLReader();
reader.setEntityResolver(ENTITY_RESOLVER);
reader.setContentHandler(transformHandlerList.getFirst());
return reader;
}
public Properties getOutputProperties()
throws TransformerConfigurationException, SAXException, ParserConfigurationException {
checkTemplateUptodate();
Templates lastTemplate = templates[templates.length - 1];
Properties outputProperties = lastTemplate.getOutputProperties();
return outputProperties;
}
/* (non-Javadoc)
* @see org.mycore.common.content.transformer.MCRContentTransformer#getFileExtension()
*/
@Override
public String getFileExtension() throws TransformerException, SAXException, ParserConfigurationException {
String fileExtension = super.fileExtension;
if (fileExtension != null && !getDefaultExtension().equals(fileExtension)) {
return fileExtension;
}
return MCRXSLTransformerUtils.getFileExtension(getOutputProperties(), getDefaultExtension());
}
static class MCRTransformedContent extends MCRWrappedContent {
private MCRContent source;
private XMLReader reader;
private TransformerHandler transformerHandler;
private MCRContent transformed;
private String eTag;
private MCRXSLTransformer instance;
MCRTransformedContent(MCRContent source, XMLReader reader, TransformerHandler transformerHandler,
long transformerLastModified, MCRParameterCollector parameter, String fileName, String mimeType,
String encoding, MCRXSLTransformer instance) throws IOException {
this.source = source;
this.reader = reader;
this.transformerHandler = transformerHandler;
LOGGER.debug("Transformer lastModified: {}", transformerLastModified);
LOGGER.debug("Source lastModified : {}", source.lastModified());
this.lastModified = (transformerLastModified >= 0 && source.lastModified() >= 0)
? Math.max(transformerLastModified, source.lastModified())
: -1;
this.eTag = generateETag(lastModified, parameter.hashCode());
this.name = fileName;
this.mimeType = mimeType;
this.encoding = encoding;
this.instance = instance;
}
@Override
public String getMimeType() {
return mimeType;
}
@Override
public String getName() {
return name;
}
private String generateETag(final long lastModified, final int parameterHashCode) {
//parameterHashCode is stable for this session and current request URL
long systemLastModified = MCRConfigurationBase.getSystemLastModified();
StringBuilder b = new StringBuilder("\"");
byte[] unencodedETag = ByteBuffer.allocate(Long.SIZE / 4).putLong(lastModified ^ parameterHashCode)
.putLong(systemLastModified ^ parameterHashCode).array();
b.append(Base64.getEncoder().encodeToString(unencodedETag));
b.append('"');
return b.toString();
}
@Override
public MCRContent getBaseContent() {
if (transformed == null) {
try {
transformed = instance.getTransformedContent(source, reader, transformerHandler);
transformed.setLastModified(lastModified);
transformed.setName(name);
transformed.setMimeType(mimeType);
transformed.setEncoding(encoding);
} catch (IOException | SAXException e) {
throw new MCRException(e);
} catch (RuntimeException e) {
MCRErrorListener el = (MCRErrorListener) transformerHandler.getTransformer().getErrorListener();
if (el != null && e.getCause() == null && el.getExceptionThrown() != null) {
//typically if a RuntimeException has no cause,
//we can get the "real cause" from MCRErrorListener, yeah!!!
throw new RuntimeException(MCRErrorListener.getMyMessageAndLocation(el.getExceptionThrown()),
el.getExceptionThrown());
}
throw e;
} finally {
try {
transformerHandler.getTransformer().clearParameters();
transformerHandler.getTransformer().reset();
} catch (UnsupportedOperationException e) {
//expected and safely ignored
}
}
}
return transformed;
}
@Override
public long lastModified() {
return lastModified;
}
@Override
public String getETag() {
return eTag;
}
@Override
public boolean isUsingSession() {
return true;
}
@Override
public String getEncoding() {
return transformed == null ? encoding : getBaseContent().getEncoding();
}
}
}
| 19,416 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRBlockingInputStream.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/streams/MCRBlockingInputStream.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.streams;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* This class implements a special kind of BufferedInputStream that blocks
* invocations of the read method until the number of bytes that were requested
* are fully read from the underlying InputStream. In contrast,
* BufferedInputStream does NOT block when the requested number of bytes is not
* available yet.
*
* @see BufferedInputStream
*
* @author Frank Lützenkirchen
*/
public class MCRBlockingInputStream extends BufferedInputStream {
/**
* Constructs a new MCRBlockingInputStream, using the default buffer size of
* BufferedInputStreams.
*
* @param in
* the InputStream to read data from
*/
public MCRBlockingInputStream(InputStream in) {
super(in);
}
/**
* Constructs a new MCRBlockingInputStream that uses the given buffer size.
*
* @param in
* the InputStream to read data from
* @param size
* the size of the read buffer to be used
*/
public MCRBlockingInputStream(InputStream in, int size) {
super(in, size);
}
/**
* Reads 'len' bytes from the underlying input stream and writes the bytes
* that have been read to the buffer 'buf', starting at offset 'off' in the
* buffer byte array. In contrast to BufferedInputStream.read(), this method
* blocks the read request until 'len' bytes have been read completely or
* the end of the input stream is reached.
*
* @return the number of bytes read. If the end of the input stream is not
* reached yet, this is always the same as the number of bytes
* requested in the 'len' parameter.
*/
@Override
public int read(byte[] buf, int off, int len) throws IOException {
int total = 0;
int num = 0;
while (len > 0) {
num = super.read(buf, off, len);
if (num == 0) {
continue;
}
if (num == -1) {
break;
}
total += num;
off += num;
len -= num;
}
return total == 0 ? num : total;
}
}
| 3,011 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNotClosingInputStream.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/streams/MCRNotClosingInputStream.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.streams;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* A FilterInputStream that wraps any InputStream to prevent close() is called.
* Sometimes, third party code or code you can not change closes an InputStream after
* it returned -1 on read(). But when using ZipInputStream, this is unwanted, because
* a ZipInputStream may contain other entries that have to be read and invoked code
* must be prevented from calling close(). With this class, a ZipInputStream or any other
* stream can be wrapped to regain control of closing.
*
* @author Frank Lützenkirchen
*/
public class MCRNotClosingInputStream extends FilterInputStream {
public MCRNotClosingInputStream(InputStream in) {
super(in);
}
/**
* Does nothing. When you want to really close the stream, call reallyClose().
*/
public void close() {
}
/**
* Really closes the stream.
*/
public void reallyClose() throws IOException {
super.close();
}
}
| 1,805 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRHeaderInputStream.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/streams/MCRHeaderInputStream.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.streams;
import java.io.IOException;
import java.io.InputStream;
import org.mycore.common.MCRException;
/**
* Provides the header of the stream that is read.
* This may be useful for content type detection purposes.
* Immediately after stream construction, getHeader() can be called.
*
* @author Frank Lützenkirchen
*/
public class MCRHeaderInputStream extends MCRBlockingInputStream {
/** The number of bytes that will be read for content type detection */
public static final int MAX_HEADER_SIZE = 65536;
/** The header of the stream read */
protected byte[] header;
public MCRHeaderInputStream(InputStream in) throws IOException, MCRException {
super(in, MAX_HEADER_SIZE);
super.mark(MAX_HEADER_SIZE);
byte[] buffer = new byte[MAX_HEADER_SIZE];
try {
int num = read(buffer, 0, buffer.length);
header = new byte[Math.max(0, num)];
if (num > 0) {
System.arraycopy(buffer, 0, header, 0, num);
}
} catch (IOException ex) {
String msg = "Error while reading content input stream header";
throw new MCRException(msg, ex);
}
super.reset();
}
/**
* Returns the header of the underlying input stream, at maximum
* MAX_HEADER_SIZE bytes.
*/
public byte[] getHeader() {
return header;
}
}
| 2,164 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDevNull.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/streams/MCRDevNull.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.streams;
import java.io.OutputStream;
/**
* This is a NOOP OutputStream that does not write anywhere.
* @author Thomas Scheffler
*/
public class MCRDevNull extends OutputStream {
/* (non-Javadoc)
* @see java.io.OutputStream#write(int)
*/
@Override
public void write(int arg0) {
//intentionally does nothing
}
}
| 1,112 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRByteArrayOutputStream.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/streams/MCRByteArrayOutputStream.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.streams;
import java.io.ByteArrayOutputStream;
/**
* A extension of {@link ByteArrayOutputStream} that allows access to internal buffer.
* @author Thomas Scheffler (yagee)
*/
public class MCRByteArrayOutputStream extends ByteArrayOutputStream {
/**
* Initital buffer size is 4k.
*/
public MCRByteArrayOutputStream() {
this(4 * 1024);
}
public MCRByteArrayOutputStream(int i) {
super(i);
}
public byte[] getBuffer() {
return super.buf;
}
}
| 1,270 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMD5InputStream.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/streams/MCRMD5InputStream.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.streams;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfigurationException;
/**
* Builds an MD5 checksum String while content goes through this input stream.
*
* @author Frank Lützenkirchen
*/
public class MCRMD5InputStream extends DigestInputStream {
public MCRMD5InputStream(InputStream in) throws MCRException {
super(in, buildMD5Digest());
}
/**
* Returns the MD5 message digest that has been built during reading of the
* underlying input stream.
*
* @return the MD5 message digest checksum of all bytes that have been read
*/
public byte[] getMD5() {
return getMessageDigest().digest();
}
/**
* Returns the MD5 checksum as a String
*
* @return the MD5 checksum as a String of hex digits
*/
public String getMD5String() {
return getMD5String(getMD5());
}
/**
* Given an MD5 message digest, returns the MD5 checksum as a String
*
* @return the MD5 checksum as a String of hex digits
*/
public static String getMD5String(byte[] digest) {
StringBuilder md5SumBuilder = new StringBuilder();
for (byte b : digest) {
md5SumBuilder.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
}
return md5SumBuilder.toString();
}
/**
* Builds a MessageDigest instance for MD5 checksum computation.
*
* @throws MCRConfigurationException
* if no java classes that support MD5 algorithm could be found
*/
public static MessageDigest buildMD5Digest() {
try {
return MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException exc) {
String msg = "Could not find java classes that support MD5 checksum algorithm";
throw new MCRConfigurationException(msg, exc);
}
}
}
| 2,817 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
package-info.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/util/package-info.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author matthias
*
*/
package org.mycore.common.content.util;
| 798 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRServletContentHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/util/MCRServletContentHelper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.StringTokenizer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.content.MCRContent;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.ServletResponseWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author Thomas Scheffler (yagee)
* @author Matthias Eichner
*/
public abstract class MCRServletContentHelper {
public static final int DEFAULT_BUFFER_SIZE = ContentUtils.DEFAULT_BUFFER_SIZE;
public static final String ATT_SERVE_CONTENT = MCRServletContentHelper.class.getName() + ".serveContent";
private static Logger LOGGER = LogManager.getLogger(MCRServletContentHelper.class);
public static Config buildConfig(ServletConfig servletConfig) {
Config config = new Config();
if (servletConfig.getInitParameter("inputBufferSize") != null) {
config.inputBufferSize = Integer.parseInt(servletConfig.getInitParameter("inputBufferSize"));
}
if (servletConfig.getInitParameter("outputBufferSize") != null) {
config.outputBufferSize = Integer.parseInt(servletConfig.getInitParameter("outputBufferSize"));
}
if (servletConfig.getInitParameter("useAcceptRanges") != null) {
config.useAcceptRanges = Boolean.parseBoolean(servletConfig.getInitParameter("useAcceptRanges"));
}
if (config.inputBufferSize < ContentUtils.MIN_BUFFER_SIZE) {
config.inputBufferSize = ContentUtils.MIN_BUFFER_SIZE;
}
if (config.outputBufferSize < ContentUtils.MIN_BUFFER_SIZE) {
config.outputBufferSize = ContentUtils.MIN_BUFFER_SIZE;
}
return config;
}
public static boolean isServeContent(final HttpServletRequest request) {
return request.getAttribute(ATT_SERVE_CONTENT) != Boolean.FALSE;
}
/**
* Serve the specified content, optionally including the data content.
* This method handles both GET and HEAD requests.
*/
public static void serveContent(final MCRContent content, final HttpServletRequest request,
final HttpServletResponse response, final ServletContext context) throws IOException {
serveContent(content, request, response, context, new Config(), isServeContent(request));
}
/**
* Serve the specified content, optionally including the data content.
* This method handles both GET and HEAD requests.
*/
public static void serveContent(final MCRContent content, final HttpServletRequest request,
final HttpServletResponse response, final ServletContext context, final Config config,
final boolean withContent)
throws IOException {
boolean serveContent = withContent;
final String path = getRequestPath(request);
if (LOGGER.isDebugEnabled()) {
if (serveContent) {
LOGGER.debug("Serving '{}' headers and data", path);
} else {
LOGGER.debug("Serving '{}' headers only", path);
}
}
if (response.isCommitted()) {
//getContent has access to response
return;
}
final boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST;
if (content == null && !isError) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
return;
}
//Check if all conditional header validate
if (!isError && !checkIfHeaders(request, response, content)) {
return;
}
// Find content type.
String contentType = content.getMimeType();
final String filename = getFileName(request, content);
if (contentType == null) {
contentType = context.getMimeType(filename);
content.setMimeType(contentType);
}
String enc = content.getEncoding();
if (enc != null) {
contentType = String.format(Locale.ROOT, "%s; charset=%s", contentType, enc);
}
String eTag = null;
List<Range> ranges = null;
if (!isError) {
eTag = content.getETag();
if (config.useAcceptRanges) {
response.setHeader("Accept-Ranges", "bytes");
}
ranges = parseRange(request, response, content);
response.setHeader("ETag", eTag);
long lastModified = content.lastModified();
if (lastModified >= 0) {
response.setDateHeader("Last-Modified", lastModified);
}
if (serveContent) {
String dispositionType = request.getParameter("dl") == null ? "inline" : "attachment";
response.setHeader("Content-Disposition", dispositionType + ";filename=\"" + filename + "\"");
}
}
final long contentLength = content.length();
//No Content to serve?
if (contentLength == 0) {
serveContent = false;
}
if (content.isUsingSession()) {
response.addHeader("Cache-Control", "private, max-age=0, must-revalidate");
response.addHeader("Vary", "*");
}
try (ServletOutputStream out = serveContent ? response.getOutputStream() : null) {
if (serveContent) {
try {
response.setBufferSize(config.outputBufferSize);
} catch (final IllegalStateException e) {
//does not matter if we fail
}
}
if (response instanceof ServletResponseWrapper) {
if (request.getHeader("Range") != null) {
LOGGER.warn("Response is wrapped by ServletResponseWrapper, no 'Range' requests supported.");
}
ranges = ContentUtils.FULL;
}
if (isError || (ranges == null || ranges.isEmpty()) && request.getHeader("Range") == null
|| ranges == ContentUtils.FULL) {
//No ranges
if (contentType != null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("contentType='{}'", contentType);
}
response.setContentType(contentType);
}
if (contentLength >= 0) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("contentLength={}", contentLength);
}
setContentLengthLong(response, contentLength);
}
if (serveContent) {
ContentUtils.copy(content, out, config.inputBufferSize, config.outputBufferSize);
}
} else {
if (ranges == null || ranges.isEmpty()) {
return;
}
// Partial content response.
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
if (ranges.size() == 1) {
final Range range = ranges.get(0);
response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length);
final long length = range.end - range.start + 1;
setContentLengthLong(response, length);
if (contentType != null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("contentType='{}'", contentType);
}
response.setContentType(contentType);
}
if (serveContent) {
ContentUtils.copy(content, out, range, config.inputBufferSize, config.outputBufferSize);
}
} else {
response.setContentType("multipart/byteranges; boundary=" + ContentUtils.MIME_BOUNDARY);
if (serveContent) {
ContentUtils.copy(content, out, ranges.iterator(), contentType, config.inputBufferSize,
config.outputBufferSize);
}
}
}
}
}
/**
* Check if all conditions specified in the If headers are
* satisfied.
*/
private static boolean checkIfHeaders(final HttpServletRequest request, final HttpServletResponse response,
final MCRContent content) throws IOException {
return checkIfMatch(request, response, content) && checkIfModifiedSince(request, response, content)
&& checkIfNoneMatch(request, response, content) && checkIfUnmodifiedSince(request, response, content);
}
/**
* Check if the If-Match condition is satisfied.
*/
private static boolean checkIfMatch(final HttpServletRequest request, final HttpServletResponse response,
final MCRContent content) throws IOException {
final String eTag = content.getETag();
final String headerValue = request.getHeader("If-Match");
if (headerValue != null) {
if (headerValue.indexOf('*') == -1) {
final StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");
boolean conditionSatisfied = false;
while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
final String currentToken = commaTokenizer.nextToken();
if (currentToken.trim().equals(eTag)) {
conditionSatisfied = true;
}
}
// none of the given ETags match
if (!conditionSatisfied) {
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
}
return true;
}
/**
* Check if the If-Modified-Since condition is satisfied.
*
*/
private static boolean checkIfModifiedSince(final HttpServletRequest request, final HttpServletResponse response,
final MCRContent content) throws IOException {
try {
final long headerValue = request.getDateHeader("If-Modified-Since");
final long lastModified = content.lastModified();
if (headerValue != -1) {
// If an If-None-Match header has been specified, if modified since
// is ignored.
if (request.getHeader("If-None-Match") == null && lastModified < headerValue + 1000) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader("ETag", content.getETag());
return false;
}
}
} catch (final IllegalArgumentException illegalArgument) {
return true;
}
return true;
}
/**
* Check if the if-none-match condition is satisfied.
*/
private static boolean checkIfNoneMatch(final HttpServletRequest request, final HttpServletResponse response,
final MCRContent content) throws IOException {
final String eTag = content.getETag();
final String headerValue = request.getHeader("If-None-Match");
if (headerValue != null) {
boolean conditionSatisfied = false;
if (Objects.equals(headerValue, "*")) {
conditionSatisfied = true;
} else {
final StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");
while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
final String currentToken = commaTokenizer.nextToken();
if (currentToken.trim().equals(eTag)) {
conditionSatisfied = true;
}
}
}
if (conditionSatisfied) {
//'GET' 'HEAD' -> not modified
if ("GET".equals(request.getMethod()) || "HEAD".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader("ETag", eTag);
return false;
}
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
return true;
}
/**
* Check if the if-unmodified-since condition is satisfied.
*/
private static boolean checkIfUnmodifiedSince(final HttpServletRequest request, final HttpServletResponse response,
final MCRContent resource) throws IOException {
try {
final long lastModified = resource.lastModified();
final long headerValue = request.getDateHeader("If-Unmodified-Since");
if (headerValue != -1) {
if (lastModified >= headerValue + 1000) {
// The content has been modified.
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
} catch (final IllegalArgumentException illegalArgument) {
return true;
}
return true;
}
public static long copyLarge(InputStream input, OutputStream output, long inputOffset, long length, byte[] buffer)
throws IOException {
return ContentUtils.copyLarge(input, output, inputOffset, length, buffer);
}
private static String extractFileName(String filename) {
int filePosition = filename.lastIndexOf('/') + 1;
filename = filename.substring(filePosition);
filePosition = filename.lastIndexOf('.');
if (filePosition > 0) {
filename = filename.substring(0, filePosition);
}
return filename;
}
private static String getFileName(final HttpServletRequest req, final MCRContent content) {
final String filename = content.getName();
if (filename != null) {
return filename;
}
if (req.getPathInfo() != null) {
return extractFileName(req.getPathInfo());
}
return new MessageFormat("{0}-{1}", Locale.ROOT).format(
new Object[] { extractFileName(req.getServletPath()), System.currentTimeMillis() });
}
/**
* Returns the request path for debugging purposes.
*/
private static String getRequestPath(final HttpServletRequest request) {
return request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
}
/**
* Parses and validates the range header.
* This method ensures that all ranges are in ascending order and non-overlapping, so we can use a single
* InputStream.
*/
private static List<Range> parseRange(final HttpServletRequest request, final HttpServletResponse response,
final MCRContent content) throws IOException {
// Checking if range is still valid (lastModified)
final String headerValue = request.getHeader("If-Range");
if (headerValue != null) {
long headerValueTime = -1L;
try {
headerValueTime = request.getDateHeader("If-Range");
} catch (final IllegalArgumentException e) {
// Ignore
}
final String eTag = content.getETag();
final long lastModified = content.lastModified();
if (headerValueTime == -1L) {
// If the content changed, the complete content is served.
if (!headerValue.trim().equals(eTag)) {
return ContentUtils.FULL;
}
} else {
//add one second buffer to check if the content was modified.
if (lastModified > headerValueTime + 1000) {
return ContentUtils.FULL;
}
}
}
final long fileLength = content.length();
if (fileLength <= 0) {
return null;
}
String rangeHeader = request.getHeader("Range");
try {
return Range.parseRanges(rangeHeader, fileLength);
} catch (IllegalArgumentException e) {
response.addHeader("Content-Range", "bytes */" + fileLength);
response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
}
private static void setContentLengthLong(final HttpServletResponse response, final long length) {
response.setHeader("Content-Length", String.valueOf(length));
}
public static class Config {
public boolean useAcceptRanges = true;
public int inputBufferSize = ContentUtils.DEFAULT_BUFFER_SIZE;
public int outputBufferSize = ContentUtils.DEFAULT_BUFFER_SIZE;
}
}
| 17,948 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Range.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/util/Range.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.util;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
class Range {
public long start;
public long end;
public long length;
public static final String RANGE_UNIT = "bytes";
public boolean validate() {
if (end >= length) {
//set 'end' to content size
end = length - 1;
}
return start >= 0 && end >= 0 && start <= end && length > 0;
}
public static List<Range> parseRanges(final String rangeHeader, long fileLength) throws IllegalArgumentException {
if (rangeHeader == null) {
return null;
}
// We operate on byte level only
if (!rangeHeader.startsWith(RANGE_UNIT)) {
throw new IllegalArgumentException();
}
String rangeValue = rangeHeader.substring(RANGE_UNIT.length() + 1);
final ArrayList<Range> result = new ArrayList<>();
final StringTokenizer commaTokenizer = new StringTokenizer(rangeValue, ",");
// Parsing the range list
long lastByte = 0;
while (commaTokenizer.hasMoreTokens()) {
final String rangeDefinition = commaTokenizer.nextToken().trim();
final Range currentRange = new Range();
currentRange.length = fileLength;
final int dashPos = rangeDefinition.indexOf('-');
if (dashPos == -1) {
throw new IllegalArgumentException();
}
if (dashPos == 0) {
try {
//offset is negative
final long offset = Long.parseLong(rangeDefinition);
currentRange.start = fileLength + offset;
currentRange.end = fileLength - 1;
} catch (final NumberFormatException e) {
throw new IllegalArgumentException(e);
}
} else {
try {
currentRange.start = Long.parseLong(rangeDefinition.substring(0, dashPos));
if (dashPos < rangeDefinition.length() - 1) {
currentRange.end = Long.parseLong(rangeDefinition.substring(dashPos + 1));
} else {
currentRange.end = fileLength - 1;
}
} catch (final NumberFormatException e) {
throw new IllegalArgumentException(e);
}
}
if (!currentRange.validate() || lastByte > currentRange.start) {
throw new IllegalArgumentException();
}
lastByte = currentRange.end;
result.add(currentRange);
}
return result;
}
}
| 3,482 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestContentHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/util/MCRRestContentHelper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.util;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.content.MCRContent;
import com.google.common.collect.Iterables;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.StreamingOutput;
import jakarta.ws.rs.core.UriInfo;
import jakarta.ws.rs.ext.RuntimeDelegate;
/**
* @author Thomas Scheffler (yagee)
*/
public abstract class MCRRestContentHelper {
public static final RuntimeDelegate.HeaderDelegate<Date> DATE_HEADER_DELEGATE = RuntimeDelegate.getInstance()
.createHeaderDelegate(Date.class);
private static Logger LOGGER = LogManager.getLogger();
public static Response serveContent(final MCRContent content, final UriInfo uriInfo,
final HttpHeaders requestHeader, List<Map.Entry<String, String>> responseHeader)
throws IOException {
return serveContent(content, uriInfo, requestHeader, responseHeader, new Config());
}
public static Response serveContent(final MCRContent content, final UriInfo uriInfo,
final HttpHeaders requestHeader, final List<Map.Entry<String, String>> responseHeader, final Config config)
throws IOException {
if (content == null) {
throw new NotFoundException();
}
// Find content type.
MediaType contentType = getMediaType(content);
Response.ResponseBuilder response = Response.ok();
String eTag = content.getETag();
response.header(HttpHeaders.ETAG, eTag);
responseHeader.forEach(e -> response.header(e.getKey(), e.getValue()));
final long contentLength = content.length();
if (contentLength == 0) {
//No Content to serve?
return response.status(Response.Status.NO_CONTENT).build();
}
long lastModified = content.lastModified();
if (lastModified >= 0) {
response.lastModified(new Date(lastModified));
}
List<Range> ranges = null;
if (config.useAcceptRanges) {
response.header("Accept-Ranges", "bytes");
ranges = parseRange(requestHeader, lastModified, eTag, contentLength);
String varyHeader = Stream.of("Range", "If-Range")
.filter(h -> requestHeader.getHeaderString(h) != null)
.collect(Collectors.joining(","));
if (!varyHeader.isEmpty()) {
response.header(HttpHeaders.VARY, varyHeader);
}
}
String filename = Optional.of(content.getName())
.orElseGet(() -> Iterables.getLast(uriInfo.getPathSegments()).getPath());
response.header(HttpHeaders.CONTENT_DISPOSITION,
config.dispositionType.name() + ";filename=\"" + filename + "\"");
boolean noRangeRequest = ranges == null || ranges == ContentUtils.FULL;
if (noRangeRequest) {
LOGGER.debug("contentType='{}'", contentType);
LOGGER.debug("contentLength={}", contentLength);
response.type(contentType);
response.header(HttpHeaders.CONTENT_LENGTH, contentLength);
response.entity(
(StreamingOutput) out -> ContentUtils.copy(content, out, config.inputBufferSize,
config.outputBufferSize));
} else if (ranges.isEmpty()) {
return response.status(Response.Status.NO_CONTENT).build();
} else {
// Partial content response.
response.status(Response.Status.PARTIAL_CONTENT);
if (ranges.size() == 1) {
final Range range = ranges.get(0);
response.header("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length);
final long length = range.end - range.start + 1;
response.header(HttpHeaders.CONTENT_LENGTH, length);
LOGGER.debug("contentType='{}'", contentType);
response.type(contentType);
response.entity(
(StreamingOutput) out -> ContentUtils.copy(content, out, range, config.inputBufferSize,
config.outputBufferSize));
} else {
response.type("multipart/byteranges; boundary=" + ContentUtils.MIME_BOUNDARY);
Iterator<Range> rangeIterator = ranges.iterator();
String ct = contentType.toString();
response.entity(
(StreamingOutput) out -> ContentUtils.copy(content, out, rangeIterator, ct,
config.inputBufferSize,
config.outputBufferSize));
}
}
return response.build();
}
private static MediaType getMediaType(MCRContent content) throws IOException {
String mimeType = content.getMimeType();
if (mimeType == null) {
mimeType = MediaType.APPLICATION_OCTET_STREAM;
}
MediaType contentType = MediaType.valueOf(mimeType);
String enc = content.getEncoding();
if (enc != null) {
HashMap<String, String> param = new HashMap<>(contentType.getParameters());
param.put(MediaType.CHARSET_PARAMETER, enc);
contentType = new MediaType(contentType.getType(), contentType.getSubtype(), param);
}
return contentType;
}
/**
* Parses and validates the range header.
* This method ensures that all ranges are in ascending order and non-overlapping, so we can use a single
* InputStream.
*/
private static List<Range> parseRange(HttpHeaders headers, long lastModified, String eTag, long contentLength) {
// Checking if range is still valid (lastModified, ETag)
String ifRangeHeader = headers.getHeaderString("If-Range");
if (ifRangeHeader != null) {
long headerValueTime = -1L;
try {
headerValueTime = DATE_HEADER_DELEGATE.fromString(ifRangeHeader).getTime();
} catch (final IllegalArgumentException e) {
// Ignore
}
if (headerValueTime == -1L) {
// If the content changed, the complete content is served.
if (!eTag.equals(ifRangeHeader.trim())) {
return ContentUtils.FULL;
}
} else {
//add one second buffer to check if the content was modified.
if (lastModified > headerValueTime + 1000) {
return ContentUtils.FULL;
}
}
}
String rangeHeader = headers.getHeaderString("Range");
try {
return Range.parseRanges(rangeHeader, contentLength);
} catch (IllegalArgumentException e) {
Response errResponse = Response.status(Response.Status.REQUESTED_RANGE_NOT_SATISFIABLE)
.header("Content-Range", "bytes */" + contentLength).build();
throw new WebApplicationException(errResponse);
}
}
public enum ContentDispositionType {
inline, attachment
}
public static class Config {
public ContentDispositionType dispositionType = ContentDispositionType.attachment;
public boolean useAcceptRanges = true;
public int inputBufferSize = ContentUtils.DEFAULT_BUFFER_SIZE;
public int outputBufferSize = ContentUtils.DEFAULT_BUFFER_SIZE;
}
}
| 8,548 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
ContentUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/content/util/ContentUtils.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.content.util;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTransactionHelper;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRSeekableChannelContent;
final class ContentUtils {
static final int MIN_BUFFER_SIZE = 512;
static final int DEFAULT_BUFFER_SIZE = 65536;
static final ArrayList<Range> FULL = new ArrayList<>();
static final String MIME_BOUNDARY = "MYCORE_MIME_BOUNDARY";
private static Logger LOGGER = LogManager.getLogger();
static long copyChannel(final ReadableByteChannel src, final WritableByteChannel dest, final int bufferSize)
throws IOException {
if (src instanceof FileChannel fileChannel) {
return copyFileChannel(fileChannel, dest, bufferSize);
}
long bytes = 0;
final ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
while (src.read(buffer) != -1) {
// prepare the buffer to be drained
buffer.flip();
// write to the channel, may block
bytes += dest.write(buffer);
// If partial transfer, shift remainder down
// If buffer is empty, same as doing clear()
buffer.compact();
}
// EOF will leave buffer in fill state
buffer.flip();
// make sure the buffer is fully drained.
while (buffer.hasRemaining()) {
bytes += dest.write(buffer);
}
return bytes;
}
static long copyFileChannel(final FileChannel src, final WritableByteChannel dest, final int bufferSize)
throws IOException {
long bytes = 0L;
long time = -System.currentTimeMillis();
long size = src.size();
while (bytes < size) {
long bytesToTransfer = Math.min(bufferSize, size - bytes);
long bytesTransfered = src.transferTo(bytes, bytesToTransfer, dest);
bytes += bytesTransfered;
if (LOGGER.isDebugEnabled()) {
long percentage = Math.round(bytes / ((double) size) * 100.0);
LOGGER.debug("overall bytes transfered: {} progress {}%", bytes, percentage);
}
}
if (LOGGER.isDebugEnabled()) {
time += System.currentTimeMillis();
double kBps = (bytes / 1024.0) / (time / 1000.0);
LOGGER.debug("Transfered: {} bytes in: {} s -> {} kbytes/s", bytes, time / 1000.0, kBps);
}
return bytes;
}
/**
* Consumes the content and writes it to the ServletOutputStream.
*/
static void copy(final MCRContent content, final OutputStream out, final int inputBufferSize,
final int outputBufferSize) throws IOException {
final long bytesCopied;
long length = content.length();
if (content instanceof MCRSeekableChannelContent seekableContent) {
try (SeekableByteChannel byteChannel = seekableContent.getSeekableByteChannel();
WritableByteChannel nout = Channels.newChannel(out)) {
endCurrentTransaction();
bytesCopied = copyChannel(byteChannel, nout, outputBufferSize);
}
} else {
try (InputStream contentIS = content.getInputStream();
InputStream in = isInputStreamBuffered(contentIS, content) ? contentIS
: new BufferedInputStream(
contentIS, inputBufferSize)) {
endCurrentTransaction();
// Copy the inputBufferSize stream to the outputBufferSize stream
bytesCopied = IOUtils.copyLarge(in, out, new byte[outputBufferSize]);
}
}
if (length >= 0 && length != bytesCopied) {
throw new EOFException("Bytes to send: " + length + " actual: " + bytesCopied);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Wrote {} bytes.", bytesCopied);
}
}
/**
* Consumes the content and writes it to the ServletOutputStream.
*
* @param content The MCRContent resource to serve
* @param out The outputBufferSize stream to write to
* @param ranges Enumeration of the ranges in ascending non overlapping order the client wanted to retrieve
* @param contentType Content type of the resource
*/
static void copy(final MCRContent content, final OutputStream out, final Iterator<Range> ranges,
final String contentType, final int inputBufferSize, final int outputBufferSize) throws IOException {
IOException exception = null;
long lastByte = 0;
final String endOfLine = "\r\n";
try (InputStream resourceInputStream = content.getInputStream();
InputStream in = isInputStreamBuffered(resourceInputStream, content) ? resourceInputStream
: new BufferedInputStream(resourceInputStream, inputBufferSize)) {
endCurrentTransaction();
while (exception == null && ranges.hasNext()) {
final Range currentRange = ranges.next();
StringBuilder mimeHeader = new StringBuilder();
// Writing MIME header.
mimeHeader.append(endOfLine)
.append("--")
.append(MIME_BOUNDARY)
.append(endOfLine);
if (contentType != null) {
mimeHeader.append("Content-Type: ")
.append(contentType)
.append(endOfLine);
}
mimeHeader.append("Content-Range: bytes ").append(currentRange.start).append('-')
.append(currentRange.end).append('/').append(currentRange.length)
.append(endOfLine)
.append(endOfLine);
out.write(mimeHeader.toString().getBytes(StandardCharsets.US_ASCII));
// Printing content
exception = copyRange(in, out, lastByte, currentRange.start, currentRange.end, outputBufferSize);
lastByte = currentRange.end;
}
}
StringBuilder mimeTrailer = new StringBuilder();
mimeTrailer.append(endOfLine).append("--").append(MIME_BOUNDARY).append("--");
out.write(mimeTrailer.toString().getBytes(StandardCharsets.US_ASCII));
// Rethrow any exception that has occurred
if (exception != null) {
throw exception;
}
}
/**
* Consumes the content and writes it to the ServletOutputStream.
*
* @param content The source resource
* @param out The outputBufferSize stream to write to
* @param range Range the client wanted to retrieve
*/
static void copy(final MCRContent content, final OutputStream out, final Range range,
// TODO: beautify this
final int inputBufferSize, final int outputBufferSize) throws IOException {
if (content.isReusable()) {
try (ReadableByteChannel readableByteChannel = content.getReadableByteChannel()) {
if (readableByteChannel instanceof SeekableByteChannel seekableByteChannel) {
endCurrentTransaction();
seekableByteChannel.position(range.start);
long bytesToCopy = range.end - range.start + 1;
while (bytesToCopy > 0) {
ByteBuffer byteBuffer;
if (bytesToCopy > DEFAULT_BUFFER_SIZE) {
byteBuffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
} else {
byteBuffer = ByteBuffer.allocate((int) bytesToCopy);
}
int bytesRead = seekableByteChannel.read(byteBuffer);
bytesToCopy -= bytesRead;
out.write(byteBuffer.array());
}
return;
}
}
}
try (InputStream resourceInputStream = content.getInputStream();
InputStream in = isInputStreamBuffered(resourceInputStream, content) ? resourceInputStream
: new BufferedInputStream(resourceInputStream, inputBufferSize)) {
endCurrentTransaction();
final IOException exception = copyRange(in, out, 0, range.start, range.end, outputBufferSize);
if (exception != null) {
throw exception;
}
}
}
/**
* Copy the content with the specified range of bytes from InputStream to OutputStream.
*
* @param in The input
* @param out The output
* @param inPosition Current position of the input
* @param start Start position to be copied
* @param end End position to be copied
* @return Exception which occurred during processing or if less than <code>end - start + 1</code>
* bytes were read/written.
*/
static IOException copyRange(final InputStream in, final OutputStream out, final long inPosition,
final long start, final long end, final int outputBufferSize) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Serving bytes:{}-{}", start, end);
}
final long bytesToRead = end - start + 1;
final long skip = start - inPosition;
try {
final long copied = copyLarge(in, out, skip, bytesToRead, new byte[outputBufferSize]);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Served bytes:{}", copied);
}
if (copied != bytesToRead) {
return new EOFException("Bytes to send: " + bytesToRead + " actual: " + copied);
}
} catch (final IOException e) {
return e;
}
return null;
}
static long copyLarge(InputStream input, OutputStream output, long inputOffset, long length, byte[] buffer)
throws IOException {
if (inputOffset > 0L) {
long bytesToSkip = inputOffset;
while (bytesToSkip > 0) {
bytesToSkip -= input.skip(bytesToSkip);
}
}
if (length == 0L) {
return 0L;
} else {
int bufferLength = buffer.length;
int bytesToRead = bufferLength;
if (length > 0L && length < bufferLength) {
bytesToRead = (int) length;
}
long totalRead = 0L;
while (bytesToRead > 0) {
int read = input.read(buffer, 0, bytesToRead);
if (read == -1) {
break;
}
output.write(buffer, 0, read);
totalRead += read;
if (length > 0L) {
bytesToRead = (int) Math.min(length - totalRead, bufferLength);
}
}
return totalRead;
}
}
/**
* Called before sending data to end hibernate transaction.
*/
static void endCurrentTransaction() {
MCRSessionMgr.getCurrentSession();
MCRTransactionHelper.commitTransaction();
}
/**
* Returns if the content InputStream is already buffered.
* @param contentIS output of {@link MCRContent#getInputStream()}
* @param content MCRContent instance associated with contentIS
*/
static boolean isInputStreamBuffered(final InputStream contentIS, final MCRContent content) {
return contentIS instanceof BufferedInputStream || contentIS instanceof ByteArrayInputStream;
}
}
| 12,959 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPNGTools.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/tools/MCRPNGTools.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.tools;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.content.MCRByteContent;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.streams.MCRByteArrayOutputStream;
public class MCRPNGTools implements AutoCloseable {
private static Logger LOGGER = LogManager.getLogger(MCRPNGTools.class);
private static AtomicInteger maxPngSize = new AtomicInteger(64 * 1024);
private ImageWriteParam imageWriteParam;
private ConcurrentLinkedQueue<ImageWriter> imageWriters = new ConcurrentLinkedQueue<>();
public MCRPNGTools() {
imageWriteParam = ImageIO.getImageWritersBySuffix("png").next().getDefaultWriteParam();
try {
imageWriteParam.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);
} catch (UnsupportedOperationException e) {
LOGGER.warn("Your PNG encoder does not support progressive PNGs.");
}
}
public MCRContent toPNGContent(BufferedImage thumbnail) throws IOException {
if (thumbnail != null) {
ImageWriter imageWriter = getImageWriter();
try (MCRByteArrayOutputStream bout = new MCRByteArrayOutputStream(maxPngSize.get());
ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(bout)) {
imageWriter.setOutput(imageOutputStream);
IIOImage iioImage = new IIOImage(thumbnail, null, null);
imageWriter.write(null, iioImage, imageWriteParam);
int contentLength = bout.size();
maxPngSize.set(Math.max(maxPngSize.get(), contentLength));
MCRByteContent imageContent = new MCRByteContent(bout.getBuffer(), 0, bout.size());
imageContent.setMimeType("image/png");
return imageContent;
} finally {
imageWriter.reset();
imageWriters.add(imageWriter);
}
} else {
return null;
}
}
private ImageWriter getImageWriter() {
ImageWriter imageWriter = imageWriters.poll();
if (imageWriter == null) {
imageWriter = ImageIO.getImageWritersBySuffix("png").next();
}
return imageWriter;
}
@Override
public void close() {
for (ImageWriter imageWriter : imageWriters) {
imageWriter.dispose();
}
}
}
| 3,516 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLanguageOrientationHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/tools/MCRLanguageOrientationHelper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.tools;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.mycore.common.config.MCRConfiguration2;
public class MCRLanguageOrientationHelper {
static Set<String> RTL_LANGUAGES = getRTLLanguages();
private static Set<String> getRTLLanguages() {
return MCRConfiguration2.getString("MCR.I18N.RtlLanguageList")
.map(MCRConfiguration2::splitValue)
.orElse(Stream.empty())
.collect(Collectors.toSet());
}
public static boolean isRTL(String language) {
return RTL_LANGUAGES.contains(language);
}
}
| 1,364 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/tools/MCRObjectFactory.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.tools;
import java.util.Date;
import org.jdom2.Document;
import org.jdom2.Element;
import org.mycore.common.MCRConstants;
import org.mycore.datamodel.common.MCRISO8601Date;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* @author shermann
*/
public class MCRObjectFactory {
/**
* Creates a {@link Document} suitable for
* {@link MCRObject#MCRObject(Document)}. The metadata element of this
* mycore object is empty. The create and modify date are set to
* "right now".
*/
public static Document getSampleObject(MCRObjectID id) {
Document xml = new Document();
Element root = createRootElement(id);
xml.setRootElement(root);
root.addContent(createStructureElement());
root.addContent(createMetadataElement(id));
root.addContent(createServiceElement());
return xml;
}
private static Element createServiceElement() {
Element service = new Element("service");
Element servDates = new Element("servdates");
service.addContent(servDates);
Element createDate = new Element("servdate");
createDate.setAttribute("type", "createdate");
createDate.setAttribute("inherited", "0");
Element modifyDate = new Element("servdate");
modifyDate.setAttribute("type", "modifydate");
modifyDate.setAttribute("inherited", "0");
servDates.addContent(createDate);
servDates.addContent(modifyDate);
String text = getDateString(new Date());
createDate.setText(text);
modifyDate.setText(text);
return service;
}
private static String getDateString(Date date) {
MCRISO8601Date isoDate = new MCRISO8601Date();
isoDate.setDate(date);
return isoDate.getISOString();
}
private static Element createMetadataElement(MCRObjectID id) {
return id.getTypeId().equals("derivate") ? new Element("derivate") : new Element("metadata");
}
private static Element createRootElement(MCRObjectID id) {
String rootTag = id.getTypeId().equals("derivate") ? "mycorederivate" : "mycoreobject";
Element root = new Element(rootTag);
root.setAttribute("ID", id.toString());
root.setAttribute("label", id.toString());
root.setAttribute("noNamespaceSchemaLocation", getXSD(id), MCRConstants.XSI_NAMESPACE);
root.setAttribute("version", "2.0");
return root;
}
/**
* Creates the structure element.
*/
private static Element createStructureElement() {
return new Element("structure");
}
/**
* @return the name of the xsd schema depending on the given object id
*/
private static String getXSD(MCRObjectID id) {
return "datamodel-" + id.getTypeId();
}
}
| 3,602 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTopologicalSort.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/tools/MCRTopologicalSort.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.tools;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.datamodel.common.MCRLinkTableManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
/**
* This class implements an algorithm for topological ordering.
* It can be used to retrieve the order in which MyCoRe object can be imported to be
* sure that parent objects are imported first.
*
* It also checks for circular dependencies and will throw an exception if it occurs.
*
* The doTopoSort() method can only be called once, since it processes the internal data.
* Afterwards prepareData() must be called again or a new object has to be used.
*
* For performance reasons each node label will be mapped to an integer (position in node list)
*
* The algorithm is described in
* http://en.wikipedia.org/wiki/Topological_sorting
*
* @author Robert Stephan
*
*/
public class MCRTopologicalSort<T> {
private static final Logger LOGGER = LogManager.getLogger();
/**
* store the edges as adjacent list
* for each target node a list of corresponding source node is stored
*/
Map<Integer, TreeSet<Integer>> edgeSources = new TreeMap<>();
/**
* store the position of elements to sort in BiMap
*/
BiMap<Integer, T> nodes = HashBiMap.create();
boolean dirty = false;
/**
* parses MCRObject xml files for parent links
* and creates the graph
*
* uses StAX cursor API (higher performance)
*
* @param ts - the topological sort data structure
* @param files - a list of file names
* @param dir - the directory where the files can be found
*/
public static void prepareData(MCRTopologicalSort<String> ts, String[] files, Path dir) {
ts.reset();
String file = null;
Map<Integer, List<String>> parentNames = new HashMap<>();
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
for (int i = 0; i < files.length; i++) {
file = files[i];
try (BufferedReader br = Files.newBufferedReader(dir.resolve(file))) {
XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(br);
while (xmlStreamReader.hasNext()) {
if (xmlStreamReader.getEventType() == XMLStreamConstants.START_ELEMENT) {
switch (xmlStreamReader.getLocalName()) {
case "mycoreobject" -> ts.getNodes().forcePut(i,
xmlStreamReader.getAttributeValue(null, "ID"));
case "parent", "relatedItem" -> {
String href = xmlStreamReader
.getAttributeValue("http://www.w3.org/1999/xlink", "href");
if (MCRObjectID.isValid(href)) {
List<String> dependencyList = parentNames.computeIfAbsent(i,
e -> new ArrayList<>());
dependencyList.add(href);
}
}
default -> {
//nothing to be done
}
}
}
xmlStreamReader.next();
}
} catch (XMLStreamException | IOException e) {
LOGGER.warn("Error while reading: " + dir.resolve(file), e);
}
}
//build edges
for (int source : parentNames.keySet()) {
parentNames.get(source)
.stream()
.map(ts.getNodes().inverse()::get)
.filter(Objects::nonNull)
.forEach(target -> ts.addEdge(source, target));
}
}
/**
* reads MCRObjectIDs as Strings, retrieves parent links from MCRLinkTableManager
* and creates the graph
*
* uses StAX cursor API (higher performance)
*/
public static void prepareMCRObjects(MCRTopologicalSort<String> ts, String[] mcrids) {
ts.reset();
for (int i = 0; i < mcrids.length; i++) {
ts.getNodes().forcePut(i, mcrids[i]);
}
for (int i = 0; i < mcrids.length; i++) {
Collection<String> parents = MCRLinkTableManager.instance().getDestinationOf(String.valueOf(mcrids[i]),
MCRLinkTableManager.ENTRY_TYPE_PARENT);
for (String p : parents) {
Integer target = ts.getNodes().inverse().get(p);
if (target != null) {
ts.addEdge(i, target);
}
}
Collection<String> refs = MCRLinkTableManager.instance().getDestinationOf(String.valueOf(mcrids[i]),
MCRLinkTableManager.ENTRY_TYPE_REFERENCE);
for (String r : refs) {
Integer target = ts.getNodes().inverse().get(r);
if (target != null) {
ts.addEdge(i, target);
}
}
}
}
/**
* resets the topological sort data structure
*/
public void reset() {
nodes.clear();
edgeSources.clear();
dirty = false;
}
/**
* return the Map of Integer to NodeObjects
*/
public BiMap<Integer, T> getNodes() {
return nodes;
}
/**
* add a node to the graph
* @param name - the node name
*/
public void addNode(T name) {
if (!nodes.containsValue(name)) {
nodes.put(nodes.size(), name);
}
}
/**
* returns a node id for a given node
*
* @param name - the node name
* @return the node id
*/
public Integer getNodeID(T name) {
return nodes.inverse().get(name);
}
/**
* return the name of the given node
* @param id - the node id
* @return the node name
*/
public T getNodeName(Integer id) {
return nodes.get(id);
}
/**
* add an edge to the graph
* @param from - the source node
* @param to - the target node
*/
public void addEdge(Integer from, Integer to) {
edgeSources.computeIfAbsent(to, k -> new TreeSet<>()).add(from);
}
/**
* removes an edge from grapn
*
* @param from - the source node id
* @param to - the target node id
* @return true, if there are no more incoming edges on the [to]-node
* ([to] = leaf node)
*/
public boolean removeEdge(Integer from, Integer to) {
TreeSet<Integer> ts = edgeSources.get(to);
if (ts != null) {
ts.remove(from);
if (ts.isEmpty()) {
edgeSources.remove(to);
return true;
} else {
return false;
}
}
return true;
}
/**
* based upon first pseudo code in
* http://en.wikipedia.org/w/index.php?title=Topological_sorting&oldid=611829125
*
* The algorithm will destroy the input data -> the method can only be called once
*
* @return an array of ids which define the order
* in which the elements have to be retrieved from the given input list
* or null if an error occured
*/
public int[] doTopoSort() {
if (dirty) {
LOGGER.error(
"The data of this instance is inconsistent."
+ " Please call prepareData() again or start with a new instance!");
return null;
}
dirty = true;
// L <-array that will contain the sorted elements
int[] result = new int[nodes.size()];
// S <- Set of all nodes with no incoming edges
List<Integer> leafs = nodes.keySet()
.stream()
.filter(i -> !edgeSources.containsKey(i))
.sorted()
.collect(Collectors.toList());
int cursor = result.length - 1;
// while S is non-empty do
while (!leafs.isEmpty()) {
// remove a node n from S
Integer node = leafs.remove(0);
// add n to tail of L (we use head, because we need an inverted list !!)
result[cursor--] = node;
// for each node m with an edge e from n to m do
for (Integer to : new TreeSet<>(edgeSources.keySet())) {
Set<Integer> ts = edgeSources.get(to);
if (ts != null && ts.contains(node)) {
// remove edge e from the graph
if (removeEdge(node, to)) {
// if m has no other incoming edges then insert m into S
leafs.add(to);
}
}
}
}
// if graph has edges then return error (graph has at least one cycle)
if (!edgeSources.isEmpty()) {
LOGGER.error("The input contained circular dependencies: \n{}", toString());
return null;
// else return L (a topologically sorted order)
} else {
return result;
}
}
/**
* @return a string representation of the underlying graph
*/
@Override
public String toString() {
StringBuilder result = new StringBuilder("[");
for (Integer to : edgeSources.keySet()) {
for (Integer from : edgeSources.get(to)) {
result.append('[').append(nodes.get(from)).append("->").append(nodes.get(to)).append(']');
}
}
result.append(']');
return result.toString();
}
}
| 11,110 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MyCoReWebPageProvider.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/tools/MyCoReWebPageProvider.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.tools;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.jdom2.Content;
import org.jdom2.DocType;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.Text;
import org.jdom2.input.SAXBuilder;
import org.mycore.frontend.servlets.MCRServlet;
import org.xml.sax.InputSource;
/**
* This class provides a simple way to dynamically create MyCoRe webpages. These pages might be rendered
* through the layout service.
*
* <br>Example:
* <pre>
* MyCoReWebPageProvider wp = new MyCoReWebPageProvider();
* wp.addSection("Section Title", "Section Text", MyCoReWebPageProvider.DE);
* Document xml = wp.getXML();
*
* //call the layout service of an {@link MCRServlet}
* getLayoutService().doLayout(job.getRequest(), job.getResponse(), xml);
* </pre>
*
* @author shermann
* @author Matthias Eichner
*/
public class MyCoReWebPageProvider {
/** German language key */
public static final String EN = "en";
/** English language key */
public static final String DE = "de";
public static final String XML_MYCORE_WEBPAGE = "MyCoReWebPage";
public static final String XML_SECTION = "section";
public static final String XML_LANG = "lang";
public static final String XML_TITLE = "title";
public static final String XML_META = "meta";
public static final String XML_LOG = "log";
public static final String XML_LASTEDITOR = "lastEditor";
public static final String XML_LABELPATH = "labelPath";
public static final String XML_DATE = "date";
public static final String XML_TIME = "time";
public static final String DATE_FORMAT = "yyyy-MM-dd";
public static final String TIME_FORMAT = "HH:mm";
private final Document xml;
public MyCoReWebPageProvider() {
this.xml = new Document();
this.xml.setDocType(new DocType(XML_MYCORE_WEBPAGE));
this.xml.setRootElement(new Element(XML_MYCORE_WEBPAGE));
}
/**
* Adds a section to the MyCoRe webpage.
*
* @param title the title of the section
* @param xmlAsString xml string which is added to the section
* @param lang the language of the section specified by a language key.
* @return added section
*/
public Element addSection(String title, String xmlAsString, String lang) throws IOException,
JDOMException {
String sb = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<!DOCTYPE MyCoReWebPage PUBLIC \"-//MYCORE//DTD MYCOREWEBPAGE 1.0//DE\" "
+ "\"http://www.mycore.org/mycorewebpage.dtd\">" + "<MyCoReWebPage>" + xmlAsString + "</MyCoReWebPage>";
SAXBuilder saxBuilder = new SAXBuilder();
saxBuilder.setEntityResolver((publicId, systemId) -> {
String resource = systemId.substring(systemId.lastIndexOf("/"));
InputStream is = getClass().getResourceAsStream(resource);
if (is == null) {
throw new IOException(new FileNotFoundException("Unable to locate resource " + resource));
}
return new InputSource(is);
});
StringReader reader = new StringReader(sb);
Document doc = saxBuilder.build(reader);
return this.addSection(title, doc.getRootElement().cloneContent(), lang);
}
/**
* Adds a section to the MyCoRe webpage.
* @param title the title of the section
* @param content jdom element which is added to the section
* @param lang the language of the section specified by a language key.
* @return added section
*/
public Element addSection(String title, Content content, String lang) {
List<Content> contentList = new ArrayList<>(1);
contentList.add(content);
return addSection(title, contentList, lang);
}
/**
* Adds a section to the MyCoRe webpage
* @param title the title of the section
* @param contentList list of content added to the section
* @param lang the language of the section specified by a language key.
* @return added section
*/
public Element addSection(String title, List<Content> contentList, String lang) {
Element section = new Element(XML_SECTION);
if (lang != null) {
section.setAttribute(XML_LANG, lang, Namespace.XML_NAMESPACE);
}
if (title != null && !title.isEmpty()) {
section.setAttribute(XML_TITLE, title);
}
for (Content content : contentList) {
if (content instanceof Text text) {
if (text.getTextTrim().isEmpty()) {
continue;
}
// MyCoReWebPage.xsl ignores single text content -> wrap it in a p
section.addContent(new Element("p").addContent(content));
} else {
section.addContent(content);
}
}
this.xml.getRootElement().addContent(section);
return section;
}
/**
* Updates the meta element of the webpage.
*
* @param editor last editor of webpage
* @param labelPath path info
*/
public void updateMeta(String editor, String labelPath) {
// get meta & log element
Element meta = this.xml.getRootElement().getChild(XML_META);
if (meta == null) {
meta = new Element(XML_META);
this.xml.getRootElement().addContent(meta);
}
Element log = meta.getChild(XML_LOG);
if (log == null) {
log = new Element(XML_LOG);
meta.addContent(log);
}
// update attributes
if (editor != null) {
log.setAttribute(XML_LASTEDITOR, editor);
}
if (labelPath != null) {
log.setAttribute(XML_LABELPATH, labelPath);
}
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.ROOT);
log.setAttribute(XML_DATE, dateFormat.format(date));
SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT, Locale.ROOT);
log.setAttribute(XML_TIME, timeFormat.format(date));
}
/**
* @return an xml document with root element is <code> <MyCoReWebPage/></code>
*/
public Document getXML() {
return this.xml;
}
}
| 7,320 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRURIConverter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/MCRURIConverter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa;
import java.net.URI;
import java.util.Optional;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
/**
* Converts a {@link URI} to {@link String} for JPA 2.1.
* @author Thomas Scheffler (yagee)
*/
@Converter
public class MCRURIConverter implements AttributeConverter<URI, String> {
@Override
public String convertToDatabaseColumn(URI attribute) {
return Optional.ofNullable(attribute)
.map(URI::toString)
.orElse(null);
}
@Override
public URI convertToEntityAttribute(String dbData) {
return Optional.ofNullable(dbData)
.map(URI::create)
.orElse(null);
}
}
| 1,447 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREntityTransaction.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/MCREntityTransaction.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa;
import org.mycore.common.MCRPersistenceTransaction;
public class MCREntityTransaction implements MCRPersistenceTransaction {
@Override
public boolean isReady() {
return MCREntityManagerProvider.getEntityManagerFactory() != null;
}
@Override
public void begin() {
MCREntityManagerProvider.getCurrentEntityManager().getTransaction().begin();
}
@Override
public void commit() {
MCREntityManagerProvider.getCurrentEntityManager().getTransaction().commit();
}
@Override
public void rollback() {
MCREntityManagerProvider.getCurrentEntityManager().getTransaction().rollback();
}
@Override
public boolean getRollbackOnly() {
return MCREntityManagerProvider.getCurrentEntityManager().getTransaction().getRollbackOnly();
}
@Override
public void setRollbackOnly() throws IllegalStateException {
MCREntityManagerProvider.getCurrentEntityManager().getTransaction().setRollbackOnly();
}
@Override
public boolean isActive() {
return MCREntityManagerProvider.getCurrentEntityManager().getTransaction().isActive();
}
}
| 1,910 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREntityManagerProvider.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/MCREntityManagerProvider.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceException;
public class MCREntityManagerProvider {
private static EntityManagerFactory factory;
private static MCRSessionContext context;
private static PersistenceException initException;
public static EntityManagerFactory getEntityManagerFactory() {
return factory;
}
public static EntityManager getCurrentEntityManager() {
if (context == null && initException != null) {
throw initException;
}
return context.getCurrentEntityManager();
}
static void init(EntityManagerFactory factory) {
MCREntityManagerProvider.factory = factory;
context = new MCRSessionContext(factory);
}
static void init(PersistenceException e) {
initException = e;
}
}
| 1,654 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJPAShutdownProcessor.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/MCRJPAShutdownProcessor.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa;
import org.mycore.common.events.MCRShutdownHandler.Closeable;
/**
* Closes {@link MCREntityManagerProvider#getEntityManagerFactory()}
* @author Thomas Scheffler (yagee)
*/
class MCRJPAShutdownProcessor implements Closeable {
@Override
public int getPriority() {
return Integer.MIN_VALUE;
}
@Override
public void close() {
MCREntityManagerProvider.getEntityManagerFactory().close();
}
}
| 1,193 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectIDPK.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/MCRObjectIDPK.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa;
import java.io.Serializable;
import java.util.Objects;
import org.mycore.backend.jpa.objectinfo.MCRObjectInfoEntity;
import org.mycore.datamodel.metadata.MCRObjectID;
import jakarta.persistence.Access;
import jakarta.persistence.AccessType;
import jakarta.persistence.Basic;
import jakarta.persistence.Column;
import jakarta.persistence.Convert;
/**
* Use this wrapper if you want a {@link MCRObjectID} as a primary key with name <code>id</code>
* in your JPA mapping.
*
* <pre>{@code
* @Entity
* @IdClass(MCRObjectIDPK.class)
* public class EntityClass {
*
* private MCRObjectID id;
*
* […]
*
* @Id
* public MCRObjectID getId() {
* return id;
* }
*
* public void setId(MCRObjectID id) {
* this.id = id;
* }
*
* […]
*
* }
* }</pre>
*
* @see MCRObjectInfoEntity
*/
@Access(AccessType.FIELD)
public class MCRObjectIDPK implements Serializable {
private static final long serialVersionUID = 1L;
@Convert(converter = MCRObjectIDConverter.class)
@Basic
@Column(length = MCRObjectID.MAX_LENGTH)
public MCRObjectID id;
/**
* Use this constructor for quick queries.
*
* Sample-Code:<br>
* <pre>{@code
* EntityManager em = […];
* em.find(EntityClass.class, new MCRObjectIDPK(MCRObjectID.getInstance('mir_mods_00004711')));
* }</pre>
* @see jakarta.persistence.EntityManager#find(Class, Object)
*/
public MCRObjectIDPK(MCRObjectID id) {
this.id = id;
}
public MCRObjectIDPK() {
//empty for JPA implementations
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MCRObjectIDPK that = (MCRObjectIDPK) o;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
| 2,745 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJPABootstrapper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/MCRJPABootstrapper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.mycore.backend.hibernate.MCRHibernateConfigHelper;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.events.MCRShutdownHandler;
import org.mycore.common.events.MCRStartupHandler.AutoExecutable;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.metamodel.EntityType;
import jakarta.persistence.metamodel.Metamodel;
import jakarta.servlet.ServletContext;
/**
* Initializes JPA {@link EntityManagerFactory}
* @author Thomas Scheffler (yagee)
*/
public class MCRJPABootstrapper implements AutoExecutable {
public static final String PERSISTENCE_UNIT_NAME = "MyCoRe";
@Override
public String getName() {
return "JPA Bootstrapper";
}
@Override
public int getPriority() {
return 1000;
}
@Override
public void startUp(ServletContext servletContext) {
try {
initializeJPA();
} catch (PersistenceException e) {
//fix for MCR-1236
if (MCRConfiguration2.getBoolean("MCR.Persistence.Database.Enable").orElse(true)) {
LogManager.getLogger()
.error(() -> "Could not initialize JPA. Database access is disabled in this session.", e);
MCRConfiguration2.set("MCR.Persistence.Database.Enable", String.valueOf(false));
}
MCREntityManagerProvider.init(e);
return;
}
Metamodel metamodel = MCREntityManagerProvider.getEntityManagerFactory().getMetamodel();
checkHibernateMappingConfig(metamodel);
LogManager.getLogger()
.info("Mapping these entities: {}", metamodel.getEntities()
.stream()
.map(EntityType::getJavaType)
.map(Class::getName)
.collect(Collectors.toList()));
MCRShutdownHandler.getInstance().addCloseable(new MCRJPAShutdownProcessor());
}
public static void initializeJPA() {
initializeJPA(null, null);
}
public static void initializeJPA(String persistenceUnitName) {
initializeJPA(persistenceUnitName, null);
}
public static void initializeJPA(String persistenceUnitName, Map<?, ?> properties) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(
Optional.ofNullable(persistenceUnitName).orElse(PERSISTENCE_UNIT_NAME),
properties);
checkFactory(entityManagerFactory);
MCREntityManagerProvider.init(entityManagerFactory);
}
private static void checkFactory(EntityManagerFactory entityManagerFactory) {
MCRHibernateConfigHelper.checkEntityManagerFactoryConfiguration(entityManagerFactory);
}
private void checkHibernateMappingConfig(Metamodel metamodel) {
Set<String> mappedEntities = metamodel
.getEntities()
.stream()
.map(EntityType::getJavaType)
.map(Class::getName)
.collect(Collectors.toSet());
List<String> unMappedEntities = MCRConfiguration2.getString("MCR.Hibernate.Mappings")
.map(MCRConfiguration2::splitValue)
.orElseGet(Stream::empty)
.filter(cName -> !mappedEntities.contains(cName))
.collect(Collectors.toList());
if (!unMappedEntities.isEmpty()) {
LogManager.getLogger()
.error(() -> "JPA Mapping is incomplete. Could not find a mapping for these classes: "
+ unMappedEntities);
LogManager.getLogger()
.error(() -> "Could not initialize JPA. Database access is disabled in this session.");
MCRConfiguration2.set("MCR.Persistence.Database.Enable", String.valueOf(false));
}
}
}
| 4,803 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectIDConverter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/MCRObjectIDConverter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa;
import org.mycore.datamodel.metadata.MCRObjectID;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
/**
* Converts {@link MCRObjectID} to {@link String}.
* @author Thomas Scheffler
*
*/
@Converter
public class MCRObjectIDConverter implements AttributeConverter<MCRObjectID, String> {
@Override
public String convertToDatabaseColumn(MCRObjectID id) {
return id == null ? null : id.toString();
}
@Override
public MCRObjectID convertToEntityAttribute(String id) {
return id == null ? null : MCRObjectID.getInstance(id);
}
}
| 1,365 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSessionContext.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/MCRSessionContext.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.events.MCRSessionEvent;
import org.mycore.common.events.MCRSessionListener;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
/**
* A helper class which scopes the notion of
* current session by the current {@link MCRSession}. This implementation allows a thread of a
* {@link MCRSession} to keep the {@link EntityManager} open for a long conversation.
*
* @author Thomas Scheffler (yagee)
*
* @since 2016.03
*/
class MCRSessionContext implements MCRSessionListener {
private static final Logger LOGGER = LogManager.getLogger();
private EntityManagerFactory factory;
private ThreadLocal<EntityManager> context;
MCRSessionContext(EntityManagerFactory factory) {
this.factory = factory;
this.context = new ThreadLocal<>();
MCRSessionMgr.addSessionListener(this);
}
public void sessionEvent(MCRSessionEvent event) {
MCRSession mcrSession = event.getSession();
EntityManager currentEntityManager;
switch (event.getType()) {
case activated:
if (event.getConcurrentAccessors() <= 1) {
LOGGER.debug(() -> "First Thread to access " + mcrSession);
}
break;
case passivated:
currentEntityManager = unbind();
autoCloseSession(currentEntityManager);
break;
case destroyed:
currentEntityManager = unbind();
autoCloseSession(currentEntityManager);
break;
case created:
break;
default:
break;
}
}
private EntityManager unbind() {
EntityManager entityManager = context.get();
context.set(null);
return entityManager;
}
EntityManager getCurrentEntityManager() {
return Optional
.ofNullable(context.get())
.filter(EntityManager::isOpen)
.orElseGet(this::createEntityManagerInContext);
}
/**
* Closes Session if Session is still open.
*/
private void autoCloseSession(EntityManager currentEntityManager) {
if (currentEntityManager != null && currentEntityManager.isOpen()) {
LOGGER.debug("Autoclosing current JPA EntityManager");
currentEntityManager.close();
}
}
private EntityManager createEntityManagerInContext() {
// creates a new one
LOGGER.debug("Obtaining new entity manager.");
EntityManager entityManager = factory.createEntityManager();
LOGGER.debug(() -> "Returning entity manager with "
+ (entityManager.getTransaction().isActive() ? "active" : "non-active")
+ " transaction.");
context.set(entityManager);
return entityManager;
}
}
| 3,830 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRZonedDateTimeConverter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/MCRZonedDateTimeConverter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa;
import java.time.DateTimeException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
/**
* Converts a {@link ZonedDateTime} to {@link Date} for JPA 2.1.
* @author Thomas Scheffler (yagee)
*/
@Converter
public class MCRZonedDateTimeConverter implements AttributeConverter<ZonedDateTime, Date> {
@Override
public Date convertToDatabaseColumn(ZonedDateTime date) {
if (date == null) {
return null;
}
Instant instant = Instant.from(date);
return Date.from(instant);
}
@Override
public ZonedDateTime convertToEntityAttribute(Date dbData) {
if (dbData == null) {
return null;
}
Instant instant = dbData.toInstant();
try {
return ZonedDateTime.from(instant);
} catch (DateTimeException exc) {
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.of("UTC"));
return ZonedDateTime.of(localDateTime, ZoneId.of("UTC"));
}
}
}
| 1,938 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
package-info.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/dnbtransfer/package-info.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Classes required for persistence of {@link org.mycore.backend.jpa.dnbtransfer.MCRDNBTransferResultsTableMgr}.
* @author Thomas Scheffler (yagee)
*/
package org.mycore.backend.jpa.dnbtransfer;
| 928 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDNBTRANSFERRESULTS.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/dnbtransfer/MCRDNBTRANSFERRESULTS.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa.dnbtransfer;
import java.io.Serializable;
import java.util.Date;
import jakarta.persistence.Basic;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class MCRDNBTRANSFERRESULTS implements Serializable {
private static final long serialVersionUID = -5543608475323581768L;
private int id;
private boolean transferPackageArchived;
private String protocolType, errorMessage, deliveryRole, objectId, errorModule, tpName;
private Date date;
/**
* @return the id
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the transferPackageArchived
*/
@Basic
@Column(name = "TRANSFERPACKAGEARCHIVED")
public boolean getTransferPackageArchived() {
return transferPackageArchived;
}
/**
* @param transferPackageArchived
* the transferPackageArchived to set
*/
public void setTransferPackageArchived(boolean transferPackageArchived) {
this.transferPackageArchived = transferPackageArchived;
}
/**
* @return the protocolType
*/
@Basic
@Column(name = "PROTOCOLTYPE", length = 9, nullable = false)
public String getProtocolType() {
return protocolType;
}
/**
* @param protocolType
* the protocolType to set
*/
public void setProtocolType(String protocolType) {
this.protocolType = protocolType;
}
/**
* @return the tpName
*/
@Basic
@Column(name = "TP_NAME", length = 9, nullable = false)
public String getTpName() {
return tpName;
}
/**
* @param tpName the tpName to set
*/
public void setTpName(String tpName) {
this.tpName = tpName;
}
/**
* @return the errorMessage
*/
@Basic
@Column(name = "ERRORMESSAGE", length = 1024)
public String getErrorMessage() {
return errorMessage;
}
/**
* @param errorMessage
* the errorMessage to set
*/
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
/**
* @return the deliveryRole
*/
@Basic
@Column(name = "DELIVERYROLE", length = 32, nullable = false)
public String getDeliveryRole() {
return deliveryRole;
}
/**
* @param deliveryRole
* the deliveryRole to set
*/
public void setDeliveryRole(String deliveryRole) {
this.deliveryRole = deliveryRole;
}
/**
* @return the objectId
*/
@Basic
@Column(name = "OBJECTID", length = 124)
public String getObjectId() {
return objectId;
}
/**
* @param objectId
* the objectId to set
*/
public void setObjectId(String objectId) {
this.objectId = objectId;
}
/**
* @return the errorModule
*/
@Basic
@Column(name = "ERRORMODULE", length = 64)
public String getErrorModule() {
return errorModule;
}
/**
* @param errorModule
* the errorModule to set
*/
public void setErrorModule(String errorModule) {
this.errorModule = errorModule;
}
/**
* @return the date
*/
@Basic
@Column(name = "DATE", nullable = false)
public Date getDate() {
return date;
}
/**
* @param date
* the date to set
*/
public void setDate(Date date) {
this.date = date;
}
}
| 4,562 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDNBTransferResultsTableMgr.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/dnbtransfer/MCRDNBTransferResultsTableMgr.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa.dnbtransfer;
import java.util.Date;
import org.mycore.backend.jpa.MCREntityManagerProvider;
/**
* @author shermann
* @author Thomas Scheffler (yagee)
*/
public class MCRDNBTransferResultsTableMgr {
public static void addEntry(String protocolType, String tpName, String deliveryRole, String objectId,
boolean transferPackageArchived, String errorMessage, String errorModule, Date date) {
MCRDNBTRANSFERRESULTS transferResult = new MCRDNBTRANSFERRESULTS();
transferResult.setProtocolType(protocolType);
transferResult.setTpName(tpName);
transferResult.setDeliveryRole(deliveryRole);
transferResult.setObjectId(objectId);
transferResult.setTransferPackageArchived(transferPackageArchived);
transferResult.setErrorMessage(errorMessage);
transferResult.setErrorModule(errorModule);
transferResult.setDate(date);
MCREntityManagerProvider.getCurrentEntityManager().persist(transferResult);
}
public static void addEntry(String protocolType, String tpName, String deliveryRole, String objectId,
boolean transferPackageArchived, String errorMessage, String errorModule) {
addEntry(protocolType, tpName, deliveryRole, objectId, transferPackageArchived, errorMessage, errorModule,
new Date());
}
}
| 2,085 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
package-info.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/access/package-info.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Classes required for persistence of {@link org.mycore.access.mcrimpl.MCRAccessControlSystem}.
* @author Thomas Scheffler (yagee)
*/
package org.mycore.backend.jpa.access;
| 907 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRACCESSRULE.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/access/MCRACCESSRULE.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa.access;
import java.sql.Timestamp;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "MCRACCESSRULE")
public class MCRACCESSRULE {
@Id
@Column(name = "RID")
private String rid;
@Column(name = "CREATOR", length = 64, nullable = false)
private String creator;
@Column(name = "CREATIONDATE", length = 64, nullable = false)
private Timestamp creationdate;
@Column(name = "RULE", length = 2048000, nullable = false)
private String rule;
@Column(name = "DESCRIPTION", nullable = false)
private String description;
public Timestamp getCreationdate() {
return creationdate;
}
public void setCreationdate(Timestamp creationdate) {
this.creationdate = creationdate;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRid() {
return rid;
}
public void setRid(String rid) {
this.rid = rid;
}
public String getRule() {
return rule;
}
public void setRule(String rule) {
this.rule = rule;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (creationdate == null ? 0 : creationdate.hashCode());
result = prime * result + (creator == null ? 0 : creator.hashCode());
result = prime * result + (description == null ? 0 : description.hashCode());
result = prime * result + (rid == null ? 0 : rid.hashCode());
result = prime * result + (rule == null ? 0 : rule.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
System.out.println("EQUALS");
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MCRACCESSRULE other)) {
return false;
}
if (creationdate == null) {
if (other.getCreationdate() != null) {
return false;
}
} else {
if (other.getCreationdate() == null) {
return false;
}
// We will remove milliseconds as they don't need to be saved
long thisLong = creationdate.getTime() / 1000;
long otherLong = other.getCreationdate().getTime() / 1000;
if (thisLong != otherLong) {
return false;
}
}
if (creator == null) {
if (other.getCreator() != null) {
return false;
}
} else if (!creator.equals(other.getCreator())) {
return false;
}
if (description == null) {
if (other.getDescription() != null) {
return false;
}
} else if (!description.equals(other.getDescription())) {
return false;
}
if (rid == null) {
if (other.getRid() != null) {
return false;
}
} else if (!rid.equals(other.getRid())) {
return false;
}
if (rule == null) {
return other.getRule() == null;
} else {
return rule.equals(other.getRule());
}
}
}
| 4,353 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRACCESSPK.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/access/MCRACCESSPK.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa.access;
import java.io.Serializable;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
@Embeddable
public class MCRACCESSPK implements Serializable {
private static final long serialVersionUID = 1177905976922683366L;
@Column(name = "ACPOOL")
private String acpool;
@Column(name = "OBJID")
private String objid;
public MCRACCESSPK() {
}
public MCRACCESSPK(String acpool, String objid) {
this.acpool = acpool;
this.objid = objid;
}
public String getAcpool() {
return acpool;
}
public void setAcpool(String acpool) {
this.acpool = acpool;
}
public String getObjid() {
return objid;
}
public void setObjid(String objid) {
this.objid = objid;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (acpool == null ? 0 : acpool.hashCode());
result = prime * result + (objid == null ? 0 : objid.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MCRACCESSPK other = (MCRACCESSPK) obj;
if (acpool == null) {
if (other.acpool != null) {
return false;
}
} else if (!acpool.equals(other.acpool)) {
return false;
}
if (objid == null) {
return other.objid == null;
} else {
return objid.equals(other.objid);
}
}
}
| 2,643 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRACCESS.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/access/MCRACCESS.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa.access;
import java.sql.Timestamp;
import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "MCRACCESS")
public class MCRACCESS {
@EmbeddedId
private MCRACCESSPK key;
@ManyToOne
@JoinColumn(name = "rid", nullable = false)
private MCRACCESSRULE rule;
@Column(name = "CREATOR", length = 64, nullable = false)
private String creator;
@Column(name = "CREATIONDATE", length = 64, nullable = false)
private Timestamp creationdate;
public MCRACCESS() {
}
public MCRACCESS(MCRACCESSPK key) {
this.key = new MCRACCESSPK(key.getAcpool(), key.getObjid());
}
public MCRACCESS(MCRACCESSRULE rule, String acpool, String objid, String creator, Timestamp creationdate) {
key = new MCRACCESSPK(acpool, objid);
this.rule = rule;
this.creator = creator;
this.creationdate = creationdate;
}
public MCRACCESSPK getKey() {
return key;
}
public void setKey(MCRACCESSPK key) {
this.key = key;
}
public Timestamp getCreationdate() {
return creationdate;
}
public void setCreationdate(Timestamp creationdate) {
this.creationdate = creationdate;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public MCRACCESSRULE getRule() {
return rule;
}
public void setRule(MCRACCESSRULE rule) {
this.rule = rule;
}
}
| 2,435 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJPAAccessStore.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/access/MCRJPAAccessStore.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa.access;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.access.MCRAccessManager;
import org.mycore.access.mcrimpl.MCRAccessStore;
import org.mycore.access.mcrimpl.MCRRuleMapping;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import jakarta.persistence.EntityManager;
import jakarta.persistence.NoResultException;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Root;
/**
* JPA implementation of acceess store to manage access rights
*
* @author Arne Seifert
* @author Thomas Scheffler (yagee)
*
*/
public class MCRJPAAccessStore extends MCRAccessStore {
private final DateFormat dateFormat = new SimpleDateFormat(SQL_DATEFORMAT, Locale.ROOT);
private static final Logger LOGGER = LogManager.getLogger();
@Override
public String getRuleID(String objID, String acPool) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> query = cb.createQuery(String.class);
Root<MCRACCESS> ac = query.from(MCRACCESS.class);
try {
return em.createQuery(
query.select(ac.get(MCRACCESS_.rule).get(MCRACCESSRULE_.rid))
.where(cb.equal(ac.get(MCRACCESS_.key).get(MCRACCESSPK_.objid), objID),
cb.equal(ac.get(MCRACCESS_.key).get(MCRACCESSPK_.acpool), acPool)))
.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
/**
* method creates a new AccessDefinition in db
*
* @param rulemapping
* with values
*/
@Override
public void createAccessDefinition(MCRRuleMapping rulemapping) {
if (!existAccessDefinition(rulemapping.getPool(), rulemapping.getObjId())) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
MCRACCESSRULE accessRule = getAccessRule(rulemapping.getRuleId());
if (accessRule == null) {
throw new NullPointerException("Cannot map a null rule.");
}
MCRACCESS accdef = new MCRACCESS();
accdef.setKey(new MCRACCESSPK(rulemapping.getPool(), rulemapping.getObjId()));
accdef.setRule(accessRule);
accdef.setCreator(rulemapping.getCreator());
accdef.setCreationdate(Timestamp.valueOf(dateFormat.format(rulemapping.getCreationdate())));
em.persist(accdef);
}
}
/**
* internal helper method to check existance of object
*/
private boolean existAccessDefinition(String pool, String objid) {
MCRACCESSPK key = new MCRACCESSPK(pool, objid);
return MCREntityManagerProvider.getCurrentEntityManager().find(MCRACCESS.class, key) != null;
}
@Override
public boolean existsRule(String objid, String pool) {
if (objid == null || objid.equals("")) {
LOGGER.warn("empty parameter objid in existsRule");
return false;
}
try {
return getRuleID(objid, pool) != null;
} catch (NoResultException e) {
return false;
}
}
/**
* delete given definition in db
*
* @param rulemapping
* rule to be deleted
*/
@Override
public void deleteAccessDefinition(MCRRuleMapping rulemapping) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
em.createQuery(
"delete MCRACCESS " + "where key.acpool = '" + rulemapping.getPool() + "'" + " AND key.objid = '"
+ rulemapping.getObjId() + "'")
.executeUpdate();
MCRAccessManager.invalidAllPermissionCachesById(rulemapping.getObjId());
}
/**
* update AccessDefinition in db for given MCRAccessData
*/
@Override
public void updateAccessDefinition(MCRRuleMapping rulemapping) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
MCRACCESSRULE accessRule = getAccessRule(rulemapping.getRuleId());
if (accessRule == null) {
throw new NullPointerException("Cannot map a null rule.");
}
// update
MCRACCESS accdef = em.find(MCRACCESS.class,
new MCRACCESSPK(rulemapping.getPool(), rulemapping.getObjId()));
accdef.setRule(accessRule);
accdef.setCreator(rulemapping.getCreator());
accdef.setCreationdate(Timestamp.valueOf(dateFormat.format(rulemapping.getCreationdate())));
MCRAccessManager.invalidAllPermissionCachesById(rulemapping.getObjId());
}
/**
* method returns AccessDefinition for given key values
*
* @param pool
* name of accesspool
* @param objid
* objectid of MCRObject
* @return MCRAccessData
*/
@Override
public MCRRuleMapping getAccessDefinition(String pool, String objid) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<MCRACCESS> query = cb.createQuery(MCRACCESS.class);
Root<MCRACCESS> root = query.from(MCRACCESS.class);
MCRRuleMapping rulemapping = new MCRRuleMapping();
try {
MCRACCESS data = em
.createQuery(query.where(cb.equal(root.get(MCRACCESS_.key), new MCRACCESSPK(pool, objid))))
.getSingleResult();
rulemapping.setCreationdate(data.getCreationdate());
rulemapping.setCreator(data.getCreator());
rulemapping.setObjId(data.getKey().getObjid());
rulemapping.setPool(data.getKey().getAcpool());
rulemapping.setRuleId(data.getRule().getRid());
em.detach(data);
} catch (NoResultException e) {
//returning empty rulemapping is fine
}
return rulemapping;
}
@Override
public ArrayList<String> getMappedObjectId(String pool) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
List<MCRACCESS> l = em.createQuery("from MCRACCESS where key.acpool = '" + pool + "'", MCRACCESS.class)
.getResultList();
return l.stream()
.map(aL -> aL.getKey().getObjid())
.collect(Collectors.toCollection(ArrayList::new));
}
@Override
public ArrayList<String> getPoolsForObject(String objid) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
List<MCRACCESS> l = em.createQuery("from MCRACCESS where key.objid = '" + objid + "'", MCRACCESS.class)
.getResultList();
return l.stream()
.map(access -> access.getKey().getAcpool())
.collect(Collectors.toCollection(ArrayList::new));
}
@Override
public ArrayList<String> getDatabasePools() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaQuery<MCRACCESS> query = em.getCriteriaBuilder().createQuery(MCRACCESS.class);
return em.createQuery(query.select(query.from(MCRACCESS.class)))
.getResultList()
.stream()
.map(MCRACCESS::getKey)
.map(MCRACCESSPK::getAcpool)
.distinct()
.collect(Collectors.toCollection(ArrayList::new));
}
@Override
public List<String> getDistinctStringIDs() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> query = cb.createQuery(String.class);
Path<String> selection = query.from(MCRACCESS.class).get(MCRACCESS_.key).get(MCRACCESSPK_.objid);
return em.createQuery(query.select(selection).distinct(true).orderBy(cb.asc(selection))).getResultList();
}
/**
* Checks if a rule mappings uses the rule.
*
* @param ruleid the rule id to check
* @return true if the rule exists and is used, otherwise false
*/
@Override
public boolean isRuleInUse(String ruleid) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<MCRACCESS> query = em
.createQuery("from MCRACCESS as accdef where accdef.rule.rid = '" + ruleid + "'", MCRACCESS.class);
return !query.getResultList().isEmpty();
}
private static MCRACCESSRULE getAccessRule(String rid) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
return em.find(MCRACCESSRULE.class, rid);
}
}
| 9,731 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJPARuleStore.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/access/MCRJPARuleStore.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa.access;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.access.mcrimpl.MCRAccessRule;
import org.mycore.access.mcrimpl.MCRRuleStore;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
/**
* JPA implementation for RuleStore, storing access rules
*
* @author Arne Seifert
* @author Thomas Scheffler (yagee)
*/
public class MCRJPARuleStore extends MCRRuleStore {
private static final Logger LOGGER = LogManager.getLogger();
private static int CACHE_SIZE = MCRConfiguration2.getInt("MCR.AccessPool.CacheSize").orElse(2048);
private static LoadingCache<String, MCRAccessRule> ruleCache = CacheBuilder.newBuilder().maximumSize(CACHE_SIZE)
.build(new CacheLoader<>() {
@Override
public MCRAccessRule load(String ruleid) {
MCRAccessRule rule = null;
EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
MCRACCESSRULE hibrule = entityManager.find(MCRACCESSRULE.class, ruleid);
LOGGER.debug("Getting MCRACCESSRULE done");
if (hibrule != null) {
LOGGER.debug("new MCRAccessRule");
rule = new MCRAccessRule(ruleid, hibrule.getCreator(), hibrule.getCreationdate(),
hibrule.getRule(),
hibrule.getDescription());
LOGGER.debug("new MCRAccessRule done");
}
return rule;
}
});
/**
* Method creates new rule in database by given rule-object
*
* @param rule
* as MCRAccessRule
*/
@Override
public void createRule(MCRAccessRule rule) {
if (!existsRule(rule.getId())) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
MCRACCESSRULE hibrule = new MCRACCESSRULE();
DateFormat df = new SimpleDateFormat(SQL_DATE_FORMAT, Locale.ROOT);
hibrule.setCreationdate(Timestamp.valueOf(df.format(rule.getCreationTime())));
hibrule.setCreator(rule.getCreator());
hibrule.setRid(rule.getId());
hibrule.setRule(rule.getRuleString());
hibrule.setDescription(rule.getDescription());
em.persist(hibrule);
} else {
LOGGER.error("rule with id '{}' can't be created, rule still exists.", rule.getId());
}
}
/**
* Method retrieves the ruleIDs of rules, whose string-representation starts with given data
*/
@Override
public Collection<String> retrieveRuleIDs(String ruleExpression, String description) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder sb = em.getCriteriaBuilder();
CriteriaQuery<String> query = sb.createQuery(String.class);
Root<MCRACCESSRULE> ar = query.from(MCRACCESSRULE.class);
return em.createQuery(
query.select(
ar.get(MCRACCESSRULE_.rid))
.where(
sb.and(
sb.like(ar.get(MCRACCESSRULE_.rule), ruleExpression),
sb.like(ar.get(MCRACCESSRULE_.description), description))))
.getResultList();
}
/**
* Method updates accessrule by given rule. internal: get rule object from session set values, update via session
*/
@Override
public void updateRule(MCRAccessRule rule) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
MCRACCESSRULE hibrule = em.find(MCRACCESSRULE.class, rule.getId());
DateFormat df = new SimpleDateFormat(SQL_DATE_FORMAT, Locale.ROOT);
hibrule.setCreationdate(Timestamp.valueOf(df.format(rule.getCreationTime())));
hibrule.setCreator(rule.getCreator());
hibrule.setRule(rule.getRuleString());
hibrule.setDescription(rule.getDescription());
ruleCache.put(rule.getId(), rule);
}
/**
* Method deletes accessrule for given ruleid
*/
@Override
public void deleteRule(String ruleid) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
em.createQuery("delete MCRACCESSRULE where rid = :rid")
.setParameter("rid", ruleid)
.executeUpdate();
ruleCache.invalidate(ruleid);
}
/**
* Method returns MCRAccessRule by given id
*
* @param ruleid
* as string
* @return MCRAccessRule
*/
@Override
public MCRAccessRule getRule(String ruleid) {
return ruleCache.getUnchecked(ruleid);
}
@Override
public Collection<String> retrieveAllIDs() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaQuery<String> query = em.getCriteriaBuilder().createQuery(String.class);
return em.createQuery(
query.select(
query.from(MCRACCESSRULE.class).get(MCRACCESSRULE_.rid)))
.getResultList();
}
/**
* Method checks existance of rule in db
*
* @param ruleid
* id as string
* @return boolean value
*/
@Override
public boolean existsRule(String ruleid) throws MCRException {
if (ruleCache.getIfPresent(ruleid) != null) {
return true;
}
return MCREntityManagerProvider.getCurrentEntityManager().find(MCRACCESSRULE.class, ruleid) != null;
}
@Override
public int getNextFreeRuleID(String prefix) {
int ret = 1;
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
List<String> l = em
.createQuery("select max(rid) from MCRACCESSRULE where rid like :like", String.class)
.setParameter("like", prefix + "%")
.getResultList();
if (l.isEmpty()) {
return 1;
}
String max = l.get(0);
if (max != null) {
int lastNumber = Integer.parseInt(max.substring(prefix.length()));
ret = lastNumber + 1;
}
return ret;
}
}
| 7,485 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectInfoEntityManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/objectinfo/MCRObjectInfoEntityManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa.objectinfo;
import java.time.Instant;
import java.util.Optional;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.backend.jpa.MCRObjectIDPK;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.metadata.MCRObjectService;
import jakarta.persistence.EntityManager;
public class MCRObjectInfoEntityManager {
public static void removeAll() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
em.createQuery("delete from MCRObjectInfoEntity ").executeUpdate();
}
/**
* loads a {@link MCRObjectInfoEntity} from the database
* @param id the id of the {@link MCRObjectInfoEntity}
* @return null if MCRObjectEntity is not found
*/
public static MCRObjectInfoEntity getByID(MCRObjectID id) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
return em.find(MCRObjectInfoEntity.class, new MCRObjectIDPK(id));
}
/**
* updates an object info of an object, if the object does not have an object info entity yet, then it will be
* created
* @param obj the object which info should be updated
*/
public static void update(MCRObject obj) {
MCRObjectID id = obj.getId();
MCRObjectInfoEntity entity = getByID(id);
if (entity != null) {
applyMetadataToInfo(obj, entity);
} else {
create(obj);
}
}
/**
* creates a new {@link MCRObjectInfoEntity} for an object
* @param obj the object
*/
public static void create(MCRObject obj) {
MCRObjectInfoEntity entity = new MCRObjectInfoEntity();
applyMetadataToInfo(obj, entity);
MCREntityManagerProvider.getCurrentEntityManager().persist(entity);
}
/**
* Removes object information from the Database
* @param object the object info which should be removed from the database
*/
public static void remove(MCRObject object) {
MCRObjectInfoEntity byID = getByID(object.getId());
if (byID == null) {
return;
}
MCREntityManagerProvider.getCurrentEntityManager().remove(byID);
}
/**
* Updates the state of the object info to be deleted (does not {@link #remove(MCRObject)} the object)
* @param object the object which is deleted
* @param deletedBy the user which deleted the object
* @param deletedDate the date at which the object was deleted
*/
public static void delete(MCRObject object, Instant deletedDate, String deletedBy) {
MCRObjectID id = object.getId();
MCRObjectInfoEntity info = getByID(id);
if (info == null) {
info = new MCRObjectInfoEntity();
info.setId(object.getId());
MCREntityManagerProvider.getCurrentEntityManager().persist(info);
}
applyMetadataToInfo(object, info);
applyDeleted(deletedDate, deletedBy, info);
}
private static void applyMetadataToInfo(MCRObject obj, MCRObjectInfoEntity info) {
MCRObjectID id = obj.getId();
info.setId(id);
info.setObjectProject(id.getProjectId());
info.setObjectType(id.getTypeId());
info.setObjectNumber(id.getNumberAsInteger());
MCRObjectService service = obj.getService();
info.setCreateDate(service.getDate(MCRObjectService.DATE_TYPE_CREATEDATE).toInstant());
info.setModifyDate(service.getDate(MCRObjectService.DATE_TYPE_MODIFYDATE).toInstant());
service.getFlags(MCRObjectService.FLAG_TYPE_CREATEDBY).stream().findFirst().ifPresent(info::setCreatedBy);
service.getFlags(MCRObjectService.FLAG_TYPE_MODIFIEDBY).stream().findFirst().ifPresent(info::setModifiedBy);
info.setState(Optional.ofNullable(service.getState()).map(MCRCategoryID::toString).orElse(null));
info.setDeletedBy(null);
info.setDeleteDate(null);
}
private static void applyDeleted(Instant deletionDate, String deletedBy, MCRObjectInfoEntity entity) {
entity.setDeleteDate(deletionDate);
entity.setDeletedBy(deletedBy);
}
}
| 4,984 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectInfoEntityQueryResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/objectinfo/MCRObjectInfoEntityQueryResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa.objectinfo;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.datamodel.classifications2.MCRCategLinkReference_;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRCategoryID_;
import org.mycore.datamodel.classifications2.impl.MCRCategoryImpl;
import org.mycore.datamodel.classifications2.impl.MCRCategoryImpl_;
import org.mycore.datamodel.classifications2.impl.MCRCategoryLinkImpl;
import org.mycore.datamodel.classifications2.impl.MCRCategoryLinkImpl_;
import org.mycore.datamodel.common.MCRObjectIDDate;
import org.mycore.datamodel.ifs2.MCRObjectIDDateImpl;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.objectinfo.MCRObjectInfo;
import org.mycore.datamodel.objectinfo.MCRObjectQuery;
import org.mycore.datamodel.objectinfo.MCRObjectQueryResolver;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.metamodel.SingularAttribute;
public class MCRObjectInfoEntityQueryResolver implements MCRObjectQueryResolver {
private static final MCRObjectQuery.SortBy SORT_BY_DEFAULT = MCRObjectQuery.SortBy.created;
protected TypedQuery<MCRObjectInfoEntity> convertQuery(MCRObjectQuery query) {
Objects.requireNonNull(query, "The Query cant be null");
int offset = query.offset();
if (offset != -1 && query.afterId() != null) {
throw new IllegalArgumentException("offset and after_id should not be combined!");
}
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<MCRObjectInfoEntity> criteriaQuery = criteriaBuilder.createQuery(MCRObjectInfoEntity.class);
Root<MCRObjectInfoEntity> oe = criteriaQuery.from(MCRObjectInfoEntity.class);
criteriaQuery.select(oe);
List<Predicate> filters = getFilter(query, criteriaBuilder, oe);
applyClassificationFilter(query, criteriaBuilder, criteriaQuery, oe, filters, em);
if (query.afterId() != null) {
applyLastId(query, criteriaBuilder, criteriaQuery, oe, filters);
} else {
applySort(query, criteriaBuilder, criteriaQuery, oe);
}
if (filters.size() > 0) {
criteriaQuery.where(criteriaBuilder.and(filters.toArray(new Predicate[0])));
}
TypedQuery<MCRObjectInfoEntity> typedQuery = em.createQuery(criteriaQuery);
if (offset != -1) {
typedQuery.setFirstResult(offset);
}
int limit = query.limit();
if (limit != -1) {
typedQuery.setMaxResults(limit);
}
return typedQuery;
}
private <T> void applyClassificationFilter(MCRObjectQuery query, CriteriaBuilder criteriaBuilder,
CriteriaQuery<T> criteriaQuery, Root<MCRObjectInfoEntity> oe, List<Predicate> filters, EntityManager em) {
if (query.getIncludeCategories().size() > 0) {
List<MCRCategoryImpl> idImplMap = getCategories(query, em);
if (idImplMap.size() != query.getIncludeCategories().size()) {
throw new IllegalArgumentException(
"some of " + String.join(", ", query.getIncludeCategories()) + " do not exist!");
}
// TODO: add child categories
Predicate[] categoryPredicates = idImplMap.stream().map(cat -> {
Root<MCRCategoryLinkImpl> cl = criteriaQuery.from(MCRCategoryLinkImpl.class);
Root<MCRCategoryImpl> c = criteriaQuery.from(MCRCategoryImpl.class);
Predicate linkToObject = criteriaBuilder.equal(
cl.get(MCRCategoryLinkImpl_.objectReference).get(MCRCategLinkReference_.OBJECT_ID),
oe.get(MCRObjectInfoEntity_.ID));
Predicate categoryToLink = criteriaBuilder.equal(
cl.get(MCRCategoryLinkImpl_.CATEGORY).get(MCRCategoryImpl_.INTERNAL_ID),
c.get(MCRCategoryImpl_.INTERNAL_ID));
Predicate between = criteriaBuilder.between(
c.get(MCRCategoryImpl_.LEFT),
cat.getLeft(),
cat.getRight());
Predicate rootIdEqual = criteriaBuilder
.equal(c.get(MCRCategoryImpl_.id).get(MCRCategoryID_.ROOT_ID), cat.getRootID());
return criteriaBuilder.and(linkToObject, categoryToLink, rootIdEqual, between);
}).toArray(Predicate[]::new);
filters.add(criteriaBuilder.and(categoryPredicates));
}
}
private List<MCRCategoryImpl> getCategories(MCRObjectQuery query, EntityManager em) {
CriteriaBuilder categCb = em.getCriteriaBuilder();
CriteriaQuery<MCRCategoryImpl> categQuery = categCb.createQuery(MCRCategoryImpl.class);
Root<MCRCategoryImpl> classRoot = categQuery.from(MCRCategoryImpl.class);
categQuery.select(classRoot);
List<MCRCategoryID> categoryIDList = query.getIncludeCategories().stream()
.map(MCRCategoryID::fromString)
.collect(Collectors.toList());
categQuery.where(classRoot.get("id").in(categoryIDList));
TypedQuery<MCRCategoryImpl> typedQuery = em.createQuery(categQuery);
return typedQuery.getResultList();
}
protected void applySort(MCRObjectQuery query, CriteriaBuilder criteriaBuilder,
CriteriaQuery<MCRObjectInfoEntity> criteriaQuery, Root<MCRObjectInfoEntity> source) {
MCRObjectQuery.SortBy sf = query.sortBy() == null ? SORT_BY_DEFAULT : query.sortBy();
SingularAttribute<MCRObjectInfoEntity, ?> attribute = switch (sf) {
case id -> MCRObjectInfoEntity_.id;
case created -> MCRObjectInfoEntity_.createDate;
case modified -> MCRObjectInfoEntity_.modifyDate;
};
if (query.sortAsc() == null || query.sortAsc() == MCRObjectQuery.SortOrder.asc) {
criteriaQuery.orderBy(criteriaBuilder.asc(source.get(attribute)));
} else {
criteriaQuery.orderBy(criteriaBuilder.desc(source.get(attribute)));
}
}
protected void applyLastId(MCRObjectQuery query, CriteriaBuilder criteriaBuilder,
CriteriaQuery<MCRObjectInfoEntity> criteriaQuery, Root<MCRObjectInfoEntity> source, List<Predicate> filters) {
if (query.sortBy() != MCRObjectQuery.SortBy.id && query.sortBy() != null) {
throw new UnsupportedOperationException("last id can not be used with " + query.sortBy());
}
if (query.sortAsc() == null || query.sortAsc() == MCRObjectQuery.SortOrder.asc) {
filters.add(criteriaBuilder.greaterThan(source.get(MCRObjectInfoEntity_.id), query.afterId()));
criteriaQuery.orderBy(criteriaBuilder.asc(source.get(MCRObjectInfoEntity_.id)));
} else {
filters.add(criteriaBuilder.lessThan(source.get(MCRObjectInfoEntity_.id), query.afterId()));
criteriaQuery.orderBy(criteriaBuilder.desc(source.get(MCRObjectInfoEntity_.id)));
}
}
private List<Predicate> getFilter(MCRObjectQuery query, CriteriaBuilder criteriaBuilder,
Root<MCRObjectInfoEntity> source) {
List<Predicate> predicates = new ArrayList<>();
Optional.ofNullable(query.type())
.map(type -> criteriaBuilder.equal(source.get(MCRObjectInfoEntity_.objectType), type))
.ifPresent(predicates::add);
Optional.ofNullable(query.project())
.map(project -> criteriaBuilder.equal(source.get(MCRObjectInfoEntity_.objectProject), project))
.ifPresent(predicates::add);
Optional.ofNullable(query.createdBy())
.map(creator -> criteriaBuilder.equal(source.get(MCRObjectInfoEntity_.createdBy), creator))
.ifPresent(predicates::add);
Optional.ofNullable(query.modifiedBy())
.map(modifier -> criteriaBuilder.equal(source.get(MCRObjectInfoEntity_.modifiedBy), modifier))
.ifPresent(predicates::add);
Optional.ofNullable(query.deletedBy())
.map(deleter -> criteriaBuilder.equal(source.get(MCRObjectInfoEntity_.deletedBy), deleter))
.ifPresent(predicates::add);
Optional.ofNullable(query.createdAfter())
.map(date -> criteriaBuilder.greaterThanOrEqualTo(source.get(MCRObjectInfoEntity_.createDate), date))
.ifPresent(predicates::add);
Optional.ofNullable(query.createdBefore())
.map(date -> criteriaBuilder.lessThanOrEqualTo(source.get(MCRObjectInfoEntity_.createDate), date))
.ifPresent(predicates::add);
Optional.ofNullable(query.modifiedAfter())
.map(date -> criteriaBuilder.greaterThanOrEqualTo(source.get(MCRObjectInfoEntity_.modifyDate), date))
.ifPresent(predicates::add);
Optional.ofNullable(query.modifiedBefore())
.map(date -> criteriaBuilder.lessThanOrEqualTo(source.get(MCRObjectInfoEntity_.modifyDate), date))
.ifPresent(predicates::add);
Optional.ofNullable(query.deletedAfter())
.map(date -> criteriaBuilder.greaterThanOrEqualTo(source.get(MCRObjectInfoEntity_.deleteDate), date))
.ifPresent(predicates::add);
Optional.ofNullable(query.deletedBefore())
.map(date -> criteriaBuilder.lessThanOrEqualTo(source.get(MCRObjectInfoEntity_.deleteDate), date))
.ifPresent(predicates::add);
Optional.of(query.numberGreater())
.filter(numberBiggerThan -> numberBiggerThan > -1)
.map(numberBiggerThan -> criteriaBuilder.greaterThan(source.get(MCRObjectInfoEntity_.objectNumber),
numberBiggerThan))
.ifPresent(predicates::add);
Optional.of(query.numberLess())
.filter(numberLess -> numberLess > -1)
.map(numberLess -> criteriaBuilder.lessThan(source.get(MCRObjectInfoEntity_.objectNumber), numberLess))
.ifPresent(predicates::add);
Optional.ofNullable(query.status())
.map(state -> criteriaBuilder.equal(source.get(MCRObjectInfoEntity_.state), state))
.ifPresent(predicates::add);
/*
per default, we only query not deleted objects, but if the use queries one of the deleted fields
then deleted objects are included
*/
if (Optional.ofNullable(query.deletedBy()).isEmpty() &&
Optional.ofNullable(query.deletedBefore()).isEmpty() &&
Optional.ofNullable(query.deletedAfter()).isEmpty()) {
predicates.add(criteriaBuilder.isNull(source.get(MCRObjectInfoEntity_.deleteDate)));
predicates.add(criteriaBuilder.isNull(source.get(MCRObjectInfoEntity_.deletedBy)));
}
return predicates;
}
@Override
public List<MCRObjectID> getIds(MCRObjectQuery objectQuery) {
TypedQuery<MCRObjectInfoEntity> typedQuery = convertQuery(objectQuery);
return typedQuery.getResultList()
.stream()
.map(MCRObjectInfoEntity::getId)
.collect(Collectors.toList());
}
@Override
public List<MCRObjectIDDate> getIdDates(MCRObjectQuery objectQuery) {
TypedQuery<MCRObjectInfoEntity> typedQuery = convertQuery(objectQuery);
return typedQuery.getResultList()
.stream()
.map(entity -> new MCRObjectIDDateImpl(Date.from(entity.getModifyDate()), entity.getId().toString()))
.collect(Collectors.toList());
}
@Override
public List<MCRObjectInfo> getInfos(MCRObjectQuery objectQuery) {
TypedQuery<MCRObjectInfoEntity> typedQuery = convertQuery(objectQuery);
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
return typedQuery.getResultList()
.stream()
.peek(em::detach)
.collect(Collectors.toList());
}
@Override
public int count(MCRObjectQuery objectQuery) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Number> criteriaQuery = criteriaBuilder.createQuery(Number.class);
Root<MCRObjectInfoEntity> source = criteriaQuery.from(MCRObjectInfoEntity.class);
criteriaQuery.select(criteriaBuilder.count(source));
List<Predicate> filters = getFilter(objectQuery, criteriaBuilder, source);
applyClassificationFilter(objectQuery, criteriaBuilder, criteriaQuery, source, filters, em);
if (filters.size() > 0) {
criteriaQuery.where(criteriaBuilder.and(filters.toArray(new Predicate[0])));
}
return em.createQuery(criteriaQuery).getSingleResult().intValue();
}
}
| 13,902 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectInfoEntity.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/objectinfo/MCRObjectInfoEntity.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa.objectinfo;
import java.time.Instant;
import org.mycore.backend.jpa.MCRObjectIDPK;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.objectinfo.MCRObjectInfo;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.IdClass;
import jakarta.persistence.Table;
@Entity
@IdClass(MCRObjectIDPK.class)
@Table(name = "MCRObject")
public class MCRObjectInfoEntity implements MCRObjectInfo {
private MCRObjectID id;
private String state;
private String createdBy;
private String modifiedBy;
private String deletedBy;
private Instant createDate;
private Instant modifyDate;
private Instant deleteDate;
@Override
@Id
public MCRObjectID getId() {
return id;
}
public void setId(MCRObjectID id) {
this.id = id;
}
@Override
@Column(name = "objectproject")
public String getObjectProject() {
return this.id.getProjectId();
}
/**
* This method does nothing and is only to satisfy JPA
* @param objectProject ignored parameter
*/
public void setObjectProject(String objectProject) {
// read only value
}
@Override
@Column(name = "objecttype")
public String getObjectType() {
return this.id.getTypeId();
}
/**
* This method does nothing and is only to satisfy JPA
* @param objectType ignored parameter
*/
public void setObjectType(String objectType) {
// read only value
}
@Column(name = "objectnumber")
public int getObjectNumber() {
return this.id.getNumberAsInteger();
}
/**
* This method does nothing and is only to satisfy JPA
* @param objectNumber ignored parameter
*/
public void setObjectNumber(int objectNumber) {
// read only value
}
@Override
@Column(name = "createdate")
public Instant getCreateDate() {
return createDate;
}
/**
* Updates the creation date of object in the Database
* @param createDate the creation date
*/
public void setCreateDate(Instant createDate) {
this.createDate = createDate;
}
@Override
@Column(name = "modifydate")
public Instant getModifyDate() {
return modifyDate;
}
/**
* Updates the last modify date of object in the Database
* @param modifyDate the last modify date
*/
public void setModifyDate(Instant modifyDate) {
this.modifyDate = modifyDate;
}
@Override
@Column(name = "modifiedby")
public String getModifiedBy() {
return modifiedBy;
}
/**
* Changes the user which last modified the object in the Database
* @param modifiedBy the user
*/
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
@Override
@Column(name = "createdby")
public String getCreatedBy() {
return createdBy;
}
/**
* Changes the user which created the object in the Database
* @param createdBy the user
*/
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
@Override
@Column(name = "deletedby")
public String getDeletedBy() {
return deletedBy;
}
/**
* Changes the user which deleted the object in the Database
* @param deletedBy the user
*/
public void setDeletedBy(String deletedBy) {
this.deletedBy = deletedBy;
}
@Override
@Column(name = "state")
public String getState() {
return state;
}
/**
* Changes the state of the object in the Database
* @param state the state classification category id
*/
public void setState(String state) {
this.state = state;
}
@Override
@Column(name = "deletedate")
public Instant getDeleteDate() {
return deleteDate;
}
/**
* changes the date when the object was deleted.
* @param deleteddate the date
*/
public void setDeleteDate(Instant deleteddate) {
this.deleteDate = deleteddate;
}
@Override
public String toString() {
return "MCRObjectInfoEntity{" +
"id=" + id +
", state='" + state + '\'' +
", createdBy='" + createdBy + '\'' +
", modifiedBy='" + modifiedBy + '\'' +
", deletedBy='" + deletedBy + '\'' +
", createDate=" + createDate +
", modifyDate=" + modifyDate +
", deleteDate=" + deleteDate +
'}';
}
}
| 5,376 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLINKHREF.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/links/MCRLINKHREF.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa.links;
import jakarta.persistence.Basic;
import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.Index;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.Table;
import jakarta.persistence.Transient;
/**
* This class implement the data sructure of the MCRLinkHref table.
*
* @author Heiko Helmbrecht
* @author Jens Kupferschmidt
*/
@Entity
@Table(indexes = {
@Index(name = "LinkFrom", columnList = "MCRFROM, MCRTYPE"),
@Index(name = "LinkTo", columnList = "MCRTO, MCRTYPE"),
})
@NamedQueries({
@NamedQuery(name = "MCRLINKHREF.getDestinations",
query = "SELECT key.mcrto FROM MCRLINKHREF WHERE key.mcrfrom=:from"),
@NamedQuery(name = "MCRLINKHREF.getDestinationsWithType",
query = "SELECT key.mcrto FROM MCRLINKHREF WHERE key.mcrfrom=:from AND key.mcrtype=:type"),
@NamedQuery(name = "MCRLINKHREF.getSources", query = "SELECT key.mcrfrom FROM MCRLINKHREF WHERE key.mcrto=:to"),
@NamedQuery(name = "MCRLINKHREF.getSourcesWithType",
query = "SELECT key.mcrfrom FROM MCRLINKHREF WHERE key.mcrto=:to AND key.mcrtype=:type"),
@NamedQuery(name = "MCRLINKHREF.group",
query = "SELECT count(key.mcrfrom), key.mcrto FROM MCRLINKHREF WHERE key.mcrto like :like GROUP BY key.mcrto")
})
public class MCRLINKHREF {
private MCRLINKHREFPK key;
private String attr;
/**
* The constructor of the class MCRLINKHREF
*/
public MCRLINKHREF() {
key = new MCRLINKHREFPK();
attr = "";
}
/**
* The constructor of the class MCRLINKHREF
*
* @param from
* The link source
* @param to
* The link target
* @param type
* The type of the link (defined by using of this class)
* @param attr
* The optional attribute of the link (defined by using of this
* class)
*/
public MCRLINKHREF(String from, String to, String type, String attr) {
key = new MCRLINKHREFPK();
key.setMcrfrom(from);
key.setMcrto(to);
key.setMcrtype(type);
if (attr != null) {
this.attr = attr;
}
}
/**
* This method returns the primary key.
*
* @return returns the primary key as class MCRLINKHREFPK.
*/
@EmbeddedId
public MCRLINKHREFPK getKey() {
return key;
}
/**
* This method set the primary key.
*
* @param key
* the primary key as instance of the class MCRLINKHREFPK
*/
public void setKey(MCRLINKHREFPK key) {
this.key = key;
}
/**
* Get the from value.
*
* @return the from value as a String.
*/
@Transient
public String getMcrfrom() {
return key.getMcrfrom();
}
/**
* Set the from value.
*
* @param mcrfrom
* the from value as a string
*/
public void setMcrfrom(String mcrfrom) {
key.setMcrfrom(mcrfrom);
}
/**
* Get the to value.
*
* @return the to value as a String.
*/
@Transient
public String getMcrto() {
return key.getMcrto();
}
/**
* Set the to value.
*
* @param mcrto
* the to value as a string
*/
public void setMcrto(String mcrto) {
key.setMcrto(mcrto);
}
/**
* Get the type value.
*
* @return the type value as a String.
*/
@Transient
public String getMcrtype() {
return key.getMcrtype();
}
/**
* Set the type value.
*
* @param mcrtype
* the type value as a string
*/
public void setMcrtype(String mcrtype) {
key.setMcrtype(mcrtype);
}
/**
* Get the attribute value.
*
* @return the attr value as a String.
*/
@Basic
@Column(length = 194, name = "MCRATTR")
public String getMcrattr() {
return attr;
}
/**
* Set the attr value.
*
* @param mcrattr
* the attr value as a string
*/
public void setMcrattr(String mcrattr) {
if (mcrattr == null) {
return;
}
attr = mcrattr;
}
}
| 5,066 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
package-info.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/links/package-info.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Classes required for persistence of {@link org.mycore.backend.hibernate.MCRHIBLinkTableStore}.
* @author Thomas Scheffler (yagee)
*/
package org.mycore.backend.jpa.links;
| 907 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLINKHREFPK.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/jpa/links/MCRLINKHREFPK.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa.links;
import java.io.Serializable;
import jakarta.persistence.Basic;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
/**
* This class hold all primary keys of MCRLINKHREF
*
* @author Heiko Helmbrecht
* @author Jens Kupferschmidt
*/
@Embeddable
public class MCRLINKHREFPK implements Serializable {
private static final long serialVersionUID = -5838803852559721772L;
private String mcrfrom;
private String mcrto;
private String mcrtype;
/**
* @param from
* the source ID of the link
* @param to
* the target ID of the link
* @param type
* the type of the link
*/
public MCRLINKHREFPK(String from, String to, String type) {
mcrfrom = from;
mcrto = to;
mcrtype = type;
}
/**
* The constructor
*/
public MCRLINKHREFPK() {
}
/**
* Get the data field from.
*
* @return Returns the mcrfrom.
*/
@Basic
@Column(length = 64, name = "MCRFROM")
public String getMcrfrom() {
return mcrfrom;
}
/**
* Set the data field from.
*
* @param mcrfrom
* The mcrfrom to set.
*/
public void setMcrfrom(String mcrfrom) {
this.mcrfrom = mcrfrom;
}
/**
* Get the data filed to.
*
* @return Returns the mcrto.
*/
@Basic
@Column(length = 194, name = "MCRTO")
public String getMcrto() {
return mcrto;
}
/**
* Set the data filed to.
*
* @param mcrto
* The mcrto to set.
*/
public void setMcrto(String mcrto) {
this.mcrto = mcrto;
}
/**
* Get the data filed type.
*
* @return Returns the mcrtype.
*/
@Basic
@Column(length = 75, name = "MCRTYPE")
public String getMcrtype() {
return mcrtype;
}
/**
* Set the data filed type.
*
* @param mcrtype
* The mcrtype to set.
*/
public void setMcrtype(String mcrtype) {
this.mcrtype = mcrtype;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((mcrfrom == null) ? 0 : mcrfrom.hashCode());
result = prime * result + ((mcrto == null) ? 0 : mcrto.hashCode());
result = prime * result + ((mcrtype == null) ? 0 : mcrtype.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MCRLINKHREFPK other = (MCRLINKHREFPK) obj;
if (mcrfrom == null) {
if (other.mcrfrom != null) {
return false;
}
} else if (!mcrfrom.equals(other.mcrfrom)) {
return false;
}
if (mcrto == null) {
if (other.mcrto != null) {
return false;
}
} else if (!mcrto.equals(other.mcrto)) {
return false;
}
if (mcrtype == null) {
return other.mcrtype == null;
} else {
return mcrtype.equals(other.mcrtype);
}
}
@Override
public String toString() {
return "MCRLINKHREFPK [mcrfrom=" + mcrfrom + ", mcrto=" + mcrto + ", mcrtype=" + mcrtype + "]";
}
}
| 4,258 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRHIBLinkTableStore.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/hibernate/MCRHIBLinkTableStore.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.hibernate;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.backend.jpa.links.MCRLINKHREF;
import org.mycore.backend.jpa.links.MCRLINKHREFPK;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.MCRUtils;
import org.mycore.datamodel.common.MCRLinkTableInterface;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
/**
* This class implements the MCRLinkTableInterface.
*
* @author Heiko Helmbrecht
* @author Jens Kupferschmidt
*/
public class MCRHIBLinkTableStore implements MCRLinkTableInterface {
// logger
static Logger LOGGER = LogManager.getLogger(MCRHIBLinkTableStore.class);
private String classname = MCRLINKHREF.class.getCanonicalName();
/**
* The constructor for the class MCRHIBLinkTableStore.
*/
public MCRHIBLinkTableStore() {
}
/**
* The method create a new item in the datastore.
*
* @param from
* a string with the link ID MCRFROM
* @param to
* a string with the link ID MCRTO
* @param type
* a string with the link ID MCRTYPE
* @param attr
* a string with the link ID MCRATTR
*/
@Override
public final void create(String from, String to, String type, String attr) {
from = checkAttributeIsNotEmpty(from, "from");
to = checkAttributeIsNotEmpty(to, "to");
type = checkAttributeIsNotEmpty(type, "type");
attr = MCRUtils.filterTrimmedNotEmpty(attr).orElse("");
EntityManager entityMananger = MCREntityManagerProvider.getCurrentEntityManager();
LOGGER.debug("Inserting {}/{}/{} into database MCRLINKHREF", from, to, type);
MCRLINKHREFPK key = getKey(from, to, type);
MCRLINKHREF linkHref = entityMananger.find(MCRLINKHREF.class, key);
if (linkHref != null) {
linkHref.setMcrattr(attr);
} else {
linkHref = new MCRLINKHREF();
linkHref.setKey(key);
linkHref.setMcrattr(attr);
entityMananger.persist(linkHref);
}
}
private static String checkAttributeIsNotEmpty(String attr, String name) {
return MCRUtils.filterTrimmedNotEmpty(attr)
.orElseThrow(() -> new MCRPersistenceException("The " + name + " value is null or empty."));
}
private static MCRLINKHREFPK getKey(String from, String to, String type) {
MCRLINKHREFPK pk = new MCRLINKHREFPK();
pk.setMcrfrom(from);
pk.setMcrto(to);
pk.setMcrtype(type);
return pk;
}
/**
* The method removes a item for the from ID from the datastore.
*
* @param from
* a string with the link ID MCRFROM
* @param to
* a string with the link ID MCRTO
* @param type
* a string with the link ID MCRTYPE
*/
@Override
public final void delete(String from, String to, String type) {
from = checkAttributeIsNotEmpty(from, "from");
StringBuilder sb = new StringBuilder();
sb.append("from ").append(classname).append(" where key.mcrfrom = '").append(from).append('\'');
MCRUtils.filterTrimmedNotEmpty(to)
.ifPresent(trimmedTo -> sb.append(" and key.mcrto = '").append(trimmedTo).append('\''));
MCRUtils.filterTrimmedNotEmpty(type)
.ifPresent(trimmedType -> sb.append(" and key.mcrtype = '").append(trimmedType).append('\''));
LOGGER.debug("Deleting {} from database MCRLINKHREF", from);
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
em.createQuery(sb.toString(), MCRLINKHREF.class)
.getResultList()
.forEach(em::remove);
}
/**
* The method count the number of references with '%from%' and 'to' and
* optional 'type' and optional 'restriction%' values of the table.
*
* @param fromtype
* a substing in the from ID as String, it can be null
* @param to
* the object ID as String, which is referenced
* @param type
* the refernce type, it can be null
* @param restriction
* a first part of the to ID as String, it can be null
* @return the number of references
*/
@Override
public final int countTo(String fromtype, String to, String type, String restriction) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
Number returns;
StringBuilder qBf = new StringBuilder(1024);
qBf.append("select count(key.mcrfrom) from ").append(classname).append(" where key.mcrto like ").append('\'')
.append(to).append('\'');
if (type != null && type.length() != 0) {
qBf.append(" and key.mcrtype = '").append(type).append('\'');
}
if (restriction != null && restriction.length() != 0) {
qBf.append(" and key.mcrto like '").append(restriction).append('\'');
}
if (fromtype != null && fromtype.length() != 0) {
qBf.append(" and key.mcrfrom like '%_").append(fromtype).append("_%'");
}
TypedQuery<Number> q = em.createQuery(qBf.toString(), Number.class);
returns = q.getSingleResult();
return returns.intValue();
}
/**
* The method returns a Map of all counted distinct references
*
* @return
*
* the result-map of (key,value)-pairs can be visualized as<br>
* select count(mcrfrom) as value, mcrto as key from
* mcrlinkclass|mcrlinkhref where mcrto like mcrtoPrefix + '%' group by
* mcrto;
*
*/
@Override
public Map<String, Number> getCountedMapOfMCRTO(String mcrtoPrefix) {
Map<String, Number> map = new HashMap<>();
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<Object[]> groupQuery = em.createNamedQuery("MCRLINKHREF.group", Object[].class);
groupQuery.setParameter("like", mcrtoPrefix + '%');
groupQuery.getResultList()
.stream()
.forEach(row -> map.put((String) row[1], (Number) row[0]));
return map;
}
/**
* Returns a List of all link sources of <code>to</code> and a special
* <code>type</code>
*
* @param to
* Destination-ID
* @param type
* Link reference type, this can be null. Current types are
* child, classid, parent, reference and derivate.
* @return List of Strings (Source-IDs)
*/
@Override
public Collection<String> getSourcesOf(String to, String type) {
boolean withType = type != null && type.trim().length() != 0;
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<String> toQuery = em.createNamedQuery(
withType ? "MCRLINKHREF.getSourcesWithType" : "MCRLINKHREF.getSources", String.class);
toQuery.setParameter("to", to);
if (withType) {
toQuery.setParameter("type", type);
}
return toQuery.getResultList();
}
/**
* Returns a List of all link destinations of <code>destination</code>
*
* @param source
* source-ID
* @param type
* Link reference type, this can be null. Current types are
* child, classid, parent, reference and derivate.
* @return List of Strings (Destination-IDs)
*/
@Override
public Collection<String> getDestinationsOf(String source, String type) {
boolean withType = type != null && type.trim().length() != 0;
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<String> toQuery = em.createNamedQuery(
withType ? "MCRLINKHREF.getDestinationsWithType" : "MCRLINKHREF.getDestinations", String.class);
toQuery.setParameter("from", source);
if (withType) {
toQuery.setParameter("type", type);
}
return toQuery.getResultList();
}
}
| 8,984 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRHibernateConfigHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/backend/hibernate/MCRHibernateConfigHelper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.hibernate;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Locale;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.hibernate.Session;
import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.metamodel.MappingMetamodel;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.persister.entity.SingleTableEntityPersister;
import org.mycore.datamodel.classifications2.impl.MCRCategoryImpl;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;
/**
* Helper class to check if EntityManagerFactory is correctly configured.
*
* @author Thomas Scheffler (yagee)
*/
public class MCRHibernateConfigHelper {
public static void checkEntityManagerFactoryConfiguration(EntityManagerFactory entityManagerFactory) {
try {
SessionFactoryImpl sessionFactoryImpl = entityManagerFactory.unwrap(SessionFactoryImpl.class);
if (PostgreSQLDialect.class
.isInstance(sessionFactoryImpl.getServiceRegistry().getService(JdbcServices.class).getDialect())) {
//fix ClassLeftUnique and ClassRightUnique, as PostgreSQL cannot evaluate them on statement level
modifyConstraints(sessionFactoryImpl);
}
} catch (PersistenceException e) {
LogManager.getLogger()
.warn("Unsupported EntityManagerFactory found: {}", entityManagerFactory.getClass().getName());
}
}
private static void modifyConstraints(SessionFactoryImpl sessionFactoryImpl) {
MappingMetamodel mappingMetamodel = sessionFactoryImpl.getMappingMetamodel();
EntityPersister entityPersister = mappingMetamodel.findEntityDescriptor(MCRCategoryImpl.class);
String qualifiedTableName = ((SingleTableEntityPersister) entityPersister).getTableName();
try (Session session = sessionFactoryImpl.openSession()) {
session.doWork(connection -> {
String updateStmt = Stream.of("ClassLeftUnique", "ClassRightUnique")
.flatMap(idx -> Stream.of("drop constraint if exists " + idx,
String.format(Locale.ROOT, "add constraint %s unique (%s) deferrable initially deferred", idx,
getUniqueColumns(MCRCategoryImpl.class, idx))))
.collect(Collectors.joining(", ", getAlterTableString(connection) + qualifiedTableName + " ", ""));
try (Statement stmt = connection.createStatement()) {
LogManager.getLogger().info("Fixing PostgreSQL Schema for {}:\n{}", qualifiedTableName, updateStmt);
stmt.execute(updateStmt);
}
});
}
}
private static String getAlterTableString(Connection connection) throws SQLException {
return connection.getMetaData().getDatabaseMinorVersion() < 2 ? "alter table " : "alter table if exists ";
}
private static String getUniqueColumns(Class<?> clazz, String name) {
return Optional.of(clazz)
.map(c -> c.getAnnotation(Table.class))
.map(Table::uniqueConstraints)
.map(Stream::of)
.flatMap(s -> s
.filter(uc -> uc.name().equals(name))
.findAny()
.map(UniqueConstraint::columnNames))
.map(Stream::of)
.map(s -> s.collect(Collectors.joining(", ")))
.get();
}
}
| 4,524 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLayoutUtilities.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/MCRLayoutUtilities.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend;
import static org.mycore.access.MCRAccessManager.PERMISSION_READ;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.filter.Filters;
import org.jdom2.output.DOMOutputter;
import org.jdom2.output.support.AbstractDOMOutputProcessor;
import org.jdom2.output.support.FormatStack;
import org.jdom2.util.NamespaceStack;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.mycore.access.MCRAccessInterface;
import org.mycore.access.MCRAccessManager;
import org.mycore.access.MCRRuleAccessInterface;
import org.mycore.access.mcrimpl.MCRAccessStore;
import org.mycore.common.MCRException;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRURLContent;
import org.mycore.common.xml.MCRURIResolver;
import org.w3c.dom.Attr;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;
import jakarta.servlet.ServletContext;
/**
*
* Xalan extention for navigation.xsl
*
*/
public class MCRLayoutUtilities {
// strategies for access verification
public static final int ALLTRUE = 1;
public static final int ONETRUE_ALLTRUE = 2;
public static final int ALL2BLOCKER_TRUE = 3;
public static final String NAV_RESOURCE = MCRConfiguration2.getString("MCR.NavigationFile")
.orElse("/config/navigation.xml");
static final String OBJIDPREFIX_WEBPAGE = "webpage:";
private static final int STANDARD_CACHE_SECONDS = 10;
private static final XPathFactory XPATH_FACTORY = XPathFactory.instance();
private static final Logger LOGGER = LogManager.getLogger(MCRLayoutUtilities.class);
private static final ServletContext SERVLET_CONTEXT = MCRURIResolver.getServletContext();
private static final boolean ACCESS_CONTROLL_ON = MCRConfiguration2
.getOrThrow("MCR.Website.ReadAccessVerification", Boolean::parseBoolean);
private static HashMap<String, Element> itemStore = new HashMap<>();
private static final LoadingCache<String, DocumentHolder> NAV_DOCUMENT_CACHE = CacheBuilder.newBuilder()
.refreshAfterWrite(STANDARD_CACHE_SECONDS, TimeUnit.SECONDS).build(new CacheLoader<>() {
Executor executor = Executors.newSingleThreadExecutor(r -> new Thread(r, "navigation.xml refresh"));
@Override
public DocumentHolder load(String key) throws Exception {
URL url = SERVLET_CONTEXT.getResource(key);
try {
return new DocumentHolder(url);
} finally {
itemStore.clear();
}
}
@Override
public ListenableFuture<DocumentHolder> reload(final String key, DocumentHolder oldValue) throws Exception {
URL url = SERVLET_CONTEXT.getResource(key);
if (oldValue.isValid(url)) {
LOGGER.debug("Keeping {} in cache", url);
return Futures.immediateFuture(oldValue);
}
ListenableFutureTask<DocumentHolder> task = ListenableFutureTask.create(() -> load(key));
executor.execute(task);
return task;
}
});
/**
* Verifies a given $webpage-ID (//item/@href) from navigation.xml on read
* permission, based on ACL-System. To be used by XSL with
* Xalan-Java-Extension-Call. $blockerWebpageID can be used as already
* verified item with read access. So, only items of the ancestor axis till
* and exclusive $blockerWebpageID are verified. Use this, if you want to
* speed up the check
*
* @param webpageID
* any item/@href from navigation.xml
* @param blockerWebpageID
* any ancestor item of webpageID from navigation.xml
* @return true if access granted, false if not
*/
public static boolean readAccess(String webpageID, String blockerWebpageID) {
if (ACCESS_CONTROLL_ON) {
long startTime = System.currentTimeMillis();
boolean access = getAccess(webpageID, PERMISSION_READ, ALL2BLOCKER_TRUE, blockerWebpageID);
LOGGER.debug("checked read access for webpageID= {} (with blockerWebpageID ={}) => {}: took {} msec.",
webpageID, blockerWebpageID, access, getDuration(startTime));
return access;
} else {
return true;
}
}
/**
* Verifies a given $webpage-ID (//item/@href) from navigation.xml on read
* permission, based on ACL-System. To be used by XSL with
* Xalan-Java-Extension-Call.
*
* @param webpageID
* any item/@href from navigation.xml
* @return true if access granted, false if not
*/
public static boolean readAccess(String webpageID) {
if (ACCESS_CONTROLL_ON) {
long startTime = System.currentTimeMillis();
boolean access = getAccess(webpageID, PERMISSION_READ, ALLTRUE);
LOGGER.debug("checked read access for webpageID= {} => {}: took {} msec.", webpageID, access,
getDuration(startTime));
return access;
} else {
return true;
}
}
/**
* Returns all labels of the ancestor axis for the given item within
* navigation.xml
*
* @param item a navigation item
* @return Label as String, like "labelRoot > labelChild >
* labelChildOfChild"
*/
public static String getAncestorLabels(Element item) {
StringBuilder label = new StringBuilder();
String lang = MCRSessionMgr.getCurrentSession().getCurrentLanguage().trim();
XPathExpression<Element> xpath;
Element ic = null;
xpath = XPATH_FACTORY.compile("//.[@href='" + getWebpageID(item) + "']", Filters.element());
ic = xpath.evaluateFirst(getNavi());
while (ic.getName().equals("item")) {
ic = ic.getParentElement();
String webpageID = getWebpageID(ic);
Element labelEl = null;
xpath = XPATH_FACTORY.compile("//.[@href='" + webpageID + "']/label[@xml:lang='" + lang + "']",
Filters.element());
labelEl = xpath.evaluateFirst(getNavi());
if (labelEl != null) {
if (label.length() == 0) {
label = new StringBuilder(labelEl.getTextTrim());
} else {
label.insert(0, labelEl.getTextTrim() + " > ");
}
}
}
return label.toString();
}
/**
* Verifies, if an item of navigation.xml has a given $permission.
*
* @param webpageID
* item/@href
* @param permission
* permission to look for
* @param strategy
* ALLTRUE => all ancestor items of webpageID must have the
* permission, ONETRUE_ALLTRUE => only 1 ancestor item must have
* the permission
* @return true, if access, false if no access
*/
public static boolean getAccess(String webpageID, String permission, int strategy) {
Element item = getItem(webpageID);
// check permission according to $strategy
boolean access = strategy == ALLTRUE;
if (strategy == ALLTRUE) {
while (item != null && access) {
access = itemAccess(permission, item, access);
item = item.getParentElement();
}
} else if (strategy == ONETRUE_ALLTRUE) {
while (item != null && !access) {
access = itemAccess(permission, item, access);
item = item.getParentElement();
}
}
return access;
}
/**
* Verifies, if an item of navigation.xml has a given $permission with a
* stop item ($blockerWebpageID)
*
* @param webpageID
* item/@href
* @param permission
* permission to look for
* @param strategy
* ALL2BLOCKER_TRUE => all ancestor items of webpageID till and
* exlusiv $blockerWebpageID must have the permission
* @param blockerWebpageID
* any ancestor item of webpageID from navigation.xml
* @return true, if access, false if no access
*/
public static boolean getAccess(String webpageID, String permission, int strategy, String blockerWebpageID) {
Element item = getItem(webpageID);
// check permission according to $strategy
boolean access = false;
if (strategy == ALL2BLOCKER_TRUE) {
access = true;
String itemHref;
do {
access = itemAccess(permission, item, access);
item = item.getParentElement();
itemHref = getWebpageID(item);
} while (item != null && access && !(itemHref != null && itemHref.equals(blockerWebpageID)));
}
return access;
}
/**
* Returns a Element presentation of an item[@href=$webpageID]
*/
private static Element getItem(String webpageID) {
Element item = itemStore.get(webpageID);
if (item == null) {
XPathExpression<Element> xpath = XPATH_FACTORY.compile("//.[@href='" + webpageID + "']", Filters.element());
item = xpath.evaluateFirst(getNavi());
itemStore.put(webpageID, item);
}
return item;
}
/**
* Verifies a single item on access according to $permission Falls back to version without query
* if no rule for exact query string exists.
*
* @param permission an ACL permission
* @param item element to check
* @param access
* initial value
*/
public static boolean itemAccess(String permission, Element item, boolean access) {
return webpageAccess(permission, getWebpageID(item), access);
}
/**
* Verifies a single webpage on access according to $permission. Falls back to version without query
* if no rule for exact query string exists.
*
* @param permission an ACL permission
* @param webpageId webpage to check
* @param access
* initial value
*/
public static boolean webpageAccess(String permission, String webpageId, boolean access) {
List<String> ruleIDs = getAllWebpageACLIDs(webpageId);
return ruleIDs.stream()
.filter(objID -> MCRAccessManager.hasRule(objID, permission))
.findFirst()
.map(objID -> MCRAccessManager.checkPermission(objID, permission))
.orElse(access);
}
private static List<String> getAllWebpageACLIDs(String webpageID) {
String webpageACLID = getWebpageACLID(webpageID);
List<String> webpageACLIDs = new ArrayList<>(2);
webpageACLIDs.add(webpageACLID);
int queryIndex = webpageACLID.indexOf('?');
if (queryIndex != -1) {
String baseWebpageACLID = webpageACLID.substring(0, queryIndex);
webpageACLIDs.add(baseWebpageACLID);
}
return webpageACLIDs;
}
public static String getWebpageACLID(String webpageID) {
return OBJIDPREFIX_WEBPAGE + webpageID;
}
private static String getWebpageID(Element item) {
return item == null ? null : item.getAttributeValue("href", item.getAttributeValue("dir"));
}
/**
* Returns the navigation.xml as org.jdom2.document, using a cache the
* enhance loading time.
*
* @return navigation.xml as org.jdom2.document
*/
public static Document getNavi() {
return NAV_DOCUMENT_CACHE.getUnchecked(NAV_RESOURCE).parsedDocument;
}
/**
* Returns the navigation.xml as File.
* This file may not exist yet as navigation.xml may be served as a web resource.
* Use {@link #getNavigationURL()} to get access to the actual web resource.
*/
public static File getNavigationFile() {
String realPath = SERVLET_CONTEXT.getRealPath(NAV_RESOURCE);
if (realPath == null) {
return null;
}
return new File(realPath);
}
/**
* Returns the navigation.xml as URL.
*
* Use this method if you need to parse it on your own.
*/
public static URL getNavigationURL() {
try {
return SERVLET_CONTEXT.getResource(NAV_RESOURCE);
} catch (MalformedURLException e) {
throw new MCRException("Error while resolving navigation.xml", e);
}
}
public static org.w3c.dom.Document getPersonalNavigation() throws JDOMException, XPathExpressionException {
Document navi = getNavi();
DOMOutputter accessCleaner = new DOMOutputter(new AccessCleaningDOMOutputProcessor());
org.w3c.dom.Document personalNavi = accessCleaner.output(navi);
XPath xpath = javax.xml.xpath.XPathFactory.newInstance().newXPath();
NodeList emptyGroups = (NodeList) xpath.evaluate("/navigation/menu/group[not(item)]", personalNavi,
XPathConstants.NODESET);
for (int i = 0; i < emptyGroups.getLength(); ++i) {
org.w3c.dom.Element group = (org.w3c.dom.Element) emptyGroups.item(i);
group.getParentNode().removeChild(group);
}
NodeList emptyMenu = (NodeList) xpath.evaluate("/navigation/menu[not(item or group)]", personalNavi,
XPathConstants.NODESET);
for (int i = 0; i < emptyMenu.getLength(); ++i) {
org.w3c.dom.Element menu = (org.w3c.dom.Element) emptyMenu.item(i);
menu.getParentNode().removeChild(menu);
}
NodeList emptyNodes = (NodeList) xpath.evaluate("//text()[normalize-space(.) = '']", personalNavi,
XPathConstants.NODESET);
for (int i = 0; i < emptyNodes.getLength(); ++i) {
Node emptyTextNode = emptyNodes.item(i);
emptyTextNode.getParentNode().removeChild(emptyTextNode);
}
NodeList userNameNodes = (NodeList) xpath.evaluate("//@href[contains(.,'{CurrentUser}')]", personalNavi,
XPathConstants.NODESET);
for (int i = 0; i < userNameNodes.getLength(); i++) {
Attr href = (Attr) userNameNodes.item(i);
String userID = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID();
if (userID.equals(MCRSystemUserInformation.getGuestInstance().getUserID())) {
//remove item if user is not logged in
org.w3c.dom.Element item = href.getOwnerElement();
item.getParentNode().removeChild(item);
} else {
href.setValue(href.getValue().replace("{CurrentUser}", userID));
}
}
personalNavi.normalizeDocument();
if (LOGGER.isDebugEnabled()) {
try {
String encoding = "UTF-8";
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
ByteArrayOutputStream bout = new ByteArrayOutputStream();
transformer.transform(new DOMSource(personalNavi), new StreamResult(bout));
LOGGER.debug("personal navigation: {}", bout.toString(encoding));
} catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException
| UnsupportedEncodingException e) {
LOGGER.warn("Error while getting debug information.", e);
}
}
return personalNavi;
}
public static long getDuration(long startTime) {
return System.currentTimeMillis() - startTime;
}
public static String getWebpageObjIDPrefix() {
return OBJIDPREFIX_WEBPAGE;
}
public static boolean hasRule(String permission, String webpageID) {
MCRAccessInterface am = MCRAccessManager.getAccessImpl();
if (am instanceof MCRRuleAccessInterface ruleAccessInterface) {
return ruleAccessInterface.hasRule(getWebpageACLID(webpageID), permission);
} else {
return true;
}
}
public static String getRuleID(String permission, String webpageID) {
MCRAccessStore as = MCRAccessStore.getInstance();
String ruleID = as.getRuleID(getWebpageACLID(webpageID), permission);
return Objects.requireNonNullElse(ruleID, "");
}
public static String getRuleDescr(String permission, String webpageID) {
MCRAccessInterface am = MCRAccessManager.getAccessImpl();
String ruleDes = null;
if (am instanceof MCRRuleAccessInterface ruleAccessInterface) {
ruleDes = ruleAccessInterface.getRuleDescription(getWebpageACLID(webpageID), permission);
}
return Objects.requireNonNullElse(ruleDes, "");
}
public static String getPermission2ReadWebpage() {
return PERMISSION_READ;
}
private static class DocumentHolder {
URL docURL;
Document parsedDocument;
long lastModified;
DocumentHolder(URL url) throws JDOMException, IOException {
docURL = url;
parseDocument();
}
public boolean isValid(URL url) throws IOException {
return docURL.equals(url) && lastModified == getLastModified();
}
private void parseDocument() throws JDOMException, IOException {
lastModified = getLastModified();
LOGGER.info("Parsing: {}", docURL);
MCRURLContent urlContent = new MCRURLContent(docURL);
parsedDocument = urlContent.asXML();
}
private long getLastModified() throws IOException {
URLConnection urlConnection = docURL.openConnection();
return urlConnection.getLastModified();
}
}
private static class AccessCleaningDOMOutputProcessor extends AbstractDOMOutputProcessor {
@Override
protected org.w3c.dom.Element printElement(FormatStack fstack, NamespaceStack nstack,
org.w3c.dom.Document basedoc, Element element) {
Attribute href = element.getAttribute("href");
return (href == null || itemAccess(PERMISSION_READ, element, true)) ? super.printElement(fstack, nstack,
basedoc, element) : null;
}
}
}
| 20,845 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFrontendUtil.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/MCRFrontendUtil.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend;
import java.io.File;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.frontend.servlets.MCRServletJob;
import org.mycore.services.i18n.MCRTranslation;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Servlet/Jersey Resource utility class.
*/
public class MCRFrontendUtil {
private static final String PROXY_HEADER_HOST = "X-Forwarded-Host";
private static final String PROXY_HEADER_SCHEME = "X-Forwarded-Proto";
private static final String PROXY_HEADER_PORT = "X-Forwarded-Port";
private static final String PROXY_HEADER_PATH = "X-Forwarded-Path";
private static final String PROXY_HEADER_REMOTE_IP = "X-Forwarded-For";
public static final String BASE_URL_ATTRIBUTE = "org.mycore.base.url";
public static final String SESSION_NETMASK_IPV4_STRING = MCRConfiguration2
.getString("MCR.Servlet.Session.NetMask.IPv4").orElse("255.255.255.255");
public static final String SESSION_NETMASK_IPV6_STRING = MCRConfiguration2
.getString("MCR.Servlet.Session.NetMask.IPv6").orElse("FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF");
private static String BASE_URL;
private static String BASE_HOST_IP;
private static Logger LOGGER = LogManager.getLogger();
public static byte[] SESSION_NETMASK_IPV4;
public static byte[] SESSION_NETMASK_IPV6;
private static final ThreadLocal<Map.Entry<String, MCRServletJob>> CURRENT_SERVLET_JOB = new ThreadLocal<>();
static {
try {
SESSION_NETMASK_IPV4 = InetAddress.getByName(MCRFrontendUtil.SESSION_NETMASK_IPV4_STRING).getAddress();
} catch (UnknownHostException e) {
throw new MCRConfigurationException("MCR.Servlet.Session.NetMask.IPv4 is not a correct IPv4 network mask.",
e);
}
try {
SESSION_NETMASK_IPV6 = InetAddress.getByName(MCRFrontendUtil.SESSION_NETMASK_IPV6_STRING).getAddress();
} catch (UnknownHostException e) {
throw new MCRConfigurationException("MCR.Servlet.Session.NetMask.IPv6 is not a correct IPv6 network mask.",
e);
}
prepareBaseURLs(""); // getBaseURL() etc. may be called before any HTTP Request
addSessionListener();
}
/** The IP addresses of trusted web proxies */
protected static final Set<String> TRUSTED_PROXIES = getTrustedProxies();
/** returns the base URL of the mycore system */
public static String getBaseURL() {
if (MCRSessionMgr.hasCurrentSession()) {
MCRSession session = MCRSessionMgr.getCurrentSession();
Object value = session.get(BASE_URL_ATTRIBUTE);
if (value != null) {
LOGGER.debug("Returning BaseURL {} from user session.", value);
return value.toString();
}
}
return BASE_URL;
}
public static String getHostIP() {
return BASE_HOST_IP;
}
/**
* returns the base URL of the mycore system. This method uses the request to 'calculate' the right baseURL.
* Generally it is sufficent to use {@link #getBaseURL()} instead.
*/
public static String getBaseURL(ServletRequest req) {
HttpServletRequest request = (HttpServletRequest) req;
String scheme = req.getScheme();
String host = req.getServerName();
int serverPort = req.getServerPort();
String path = request.getContextPath() + "/";
if (TRUSTED_PROXIES.contains(req.getRemoteAddr())) {
scheme = Optional.ofNullable(request.getHeader(PROXY_HEADER_SCHEME)).orElse(scheme);
host = Optional.ofNullable(request.getHeader(PROXY_HEADER_HOST)).orElse(host);
serverPort = Optional.ofNullable(request.getHeader(PROXY_HEADER_PORT))
.map(Integer::parseInt)
.orElse(serverPort);
path = Optional.ofNullable(request.getHeader(PROXY_HEADER_PATH)).orElse(path);
if (!path.endsWith("/")) {
path += "/";
}
}
StringBuilder webappBase = new StringBuilder(scheme);
webappBase.append("://");
webappBase.append(host);
if (!(Objects.equals(scheme, "http") && serverPort == 80
|| Objects.equals(scheme, "https") && serverPort == 443)) {
webappBase.append(':').append(serverPort);
}
webappBase.append(path);
return webappBase.toString();
}
public static synchronized void prepareBaseURLs(String baseURL) {
BASE_URL = MCRConfiguration2.getString("MCR.baseurl").orElse(baseURL);
if (!BASE_URL.endsWith("/")) {
BASE_URL = BASE_URL + "/";
}
try {
URI baseUri = new URI(BASE_URL);
InetAddress baseHost = InetAddress.getByName(baseUri.getHost());
BASE_HOST_IP = baseHost.getHostAddress();
} catch (URISyntaxException e) {
LOGGER.error("Can't create URI from String {}", BASE_URL);
} catch (UnknownHostException e) {
LOGGER.error("Can't find host IP for URL {}", BASE_URL);
}
}
public static void configureSession(MCRSession session, HttpServletRequest request, HttpServletResponse response) {
final MCRServletJob servletJob = new MCRServletJob(request, response);
setAsCurrent(session, servletJob);
// language
getProperty(request, "lang")
.filter(MCRTranslation.getAvailableLanguages()::contains)
.ifPresent(session::setCurrentLanguage);
// Set the IP of the current session
if (session.getCurrentIP().length() == 0) {
session.setCurrentIP(getRemoteAddr(request));
}
// set BASE_URL_ATTRIBUTE to MCRSession
if (request.getAttribute(BASE_URL_ATTRIBUTE) != null) {
session.put(BASE_URL_ATTRIBUTE, request.getAttribute(BASE_URL_ATTRIBUTE));
}
// Store XSL.*.SESSION parameters to MCRSession
putParamsToSession(request);
}
/**
* @param request current request to get property from
* @param name of request {@link HttpServletRequest#getAttribute(String) attribute} or
* {@link HttpServletRequest#getParameter(String) parameter}
* @return an Optional that is either empty or contains a trimmed non-empty String that is either
* the value of the request attribute or a parameter (in that order) with the given <code>name</code>.
*/
public static Optional<String> getProperty(HttpServletRequest request, String name) {
return Stream.<Supplier<Object>>of(
() -> request.getAttribute(name),
() -> request.getParameter(name))
.map(Supplier::get)
.filter(Objects::nonNull)
.map(Object::toString)
.map(String::trim)
.filter(s -> !s.isEmpty())
.findFirst();
}
/**
* Returns the IP address of the client that made the request. When a trusted proxy server was used, e. g. a local
* Apache mod_proxy in front of Tomcat, the value of the last entry in the HTTP header X_FORWARDED_FOR is returned,
* otherwise the REMOTE_ADDR is returned. The list of trusted proxy IPs can be configured using the property
* MCR.Request.TrustedProxies, which is a List of IP addresses separated by blanks and/or comma.
*/
public static String getRemoteAddr(HttpServletRequest req) {
String remoteAddress = req.getRemoteAddr();
if (TRUSTED_PROXIES.contains(remoteAddress)) {
String xff = getXForwardedFor(req);
if (xff != null) {
remoteAddress = xff;
}
}
return remoteAddress;
}
/**
* Saves this instance as the 'current' servlet job.
*
* Can be retrieved afterwards by {@link #getCurrentServletJob()}.
* @throws IllegalStateException if {@link MCRSessionMgr#hasCurrentSession()} returns false
*/
private static void setAsCurrent(MCRSession session, MCRServletJob job) throws IllegalStateException {
session.setFirstURI(() -> URI.create(job.getRequest().getRequestURI()));
CURRENT_SERVLET_JOB.set(Map.entry(session.getID(), job));
}
/**
* Returns the instance saved for the current thread via
* {@link #configureSession(MCRSession, HttpServletRequest, HttpServletResponse)}.
* @return {@link Optional#empty()} if no servlet job is available for the current {@link MCRSession}
*/
public static Optional<MCRServletJob> getCurrentServletJob() {
final Map.Entry<String, MCRServletJob> servletJob = CURRENT_SERVLET_JOB.get();
final Optional<MCRServletJob> rv = Optional.ofNullable(servletJob)
.filter(job -> MCRSessionMgr.hasCurrentSession())
.filter(job -> MCRSessionMgr.getCurrentSession().getID().equals(job.getKey()))
.map(Map.Entry::getValue);
if (rv.isEmpty()) {
CURRENT_SERVLET_JOB.remove();
}
return rv;
}
/**
* Get header to check if request comes in via a proxy. There are two possible header names
*/
private static String getXForwardedFor(HttpServletRequest req) {
String xff = req.getHeader(PROXY_HEADER_REMOTE_IP);
if ((xff == null) || xff.trim().isEmpty()) {
xff = req.getHeader(PROXY_HEADER_REMOTE_IP);
}
if ((xff == null) || xff.trim().isEmpty()) {
return null;
}
// X_FORWARDED_FOR can be comma separated list of hosts,
// if so, take last entry, all others are not reliable because
// any client may have set the header to any value.
LOGGER.debug("{} complete: {}", PROXY_HEADER_REMOTE_IP, xff);
StringTokenizer st = new StringTokenizer(xff, " ,;");
while (st.hasMoreTokens()) {
xff = st.nextToken().trim();
}
LOGGER.debug("{} last: {}", PROXY_HEADER_REMOTE_IP, xff);
return xff;
}
private static void putParamsToSession(HttpServletRequest request) {
MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
for (Enumeration<String> e = request.getParameterNames(); e.hasMoreElements();) {
String name = e.nextElement();
if (name.startsWith("XSL.") && name.endsWith(".SESSION")) {
String key = name.substring(0, name.length() - 8);
// parameter is not empty -> store
if (!request.getParameter(name).trim().equals("")) {
mcrSession.put(key, request.getParameter(name));
LOGGER.debug("Found HTTP-Req.-Parameter {}={} that should be saved in session, safed {}={}", name,
request.getParameter(name), key, request.getParameter(name));
} else {
// paramter is empty -> do not store and if contained in
// session, remove from it
if (mcrSession.get(key) != null) {
mcrSession.deleteObject(key);
}
}
}
}
for (Enumeration<String> e = request.getAttributeNames(); e.hasMoreElements();) {
String name = e.nextElement();
if (name.startsWith("XSL.") && name.endsWith(".SESSION")) {
String key = name.substring(0, name.length() - 8);
// attribute is not empty -> store
if (!request.getAttribute(name).toString().trim().equals("")) {
mcrSession.put(key, request.getAttribute(name));
LOGGER.debug("Found HTTP-Req.-Attribute {}={} that should be saved in session, safed {}={}", name,
request.getParameter(name), key, request.getParameter(name));
} else {
// attribute is empty -> do not store and if contained in
// session, remove from it
if (mcrSession.get(key) != null) {
mcrSession.deleteObject(key);
}
}
}
}
}
/**
* Builds a list of trusted proxy IPs from MCR.Request.TrustedProxies. The IP address of the local host is
* automatically added to this list.
*
*/
private static TreeSet<String> getTrustedProxies() {
// Always trust the local host
return Stream
.concat(Stream.of("localhost", URI.create(getBaseURL()).getHost()), MCRConfiguration2
.getString("MCR.Request.TrustedProxies").map(MCRConfiguration2::splitValue).orElse(Stream.empty()))
.distinct()
.peek(proxy -> LOGGER.debug("Trusted proxy: {}", proxy))
.map(host -> {
try {
return InetAddress.getAllByName(host);
} catch (UnknownHostException e) {
LOGGER.warn("Unknown host: {}", host);
return null;
}
}).filter(Objects::nonNull)
.flatMap(Stream::of)
.map(InetAddress::getHostAddress)
.collect(Collectors.toCollection(TreeSet::new));
}
/**
* Sets cache-control, last-modified and expires parameter to the response header.
* Use this method when the client should cache the response data.
*
* @param response the response data to cache
* @param cacheTime how long to cache
* @param lastModified when the data was last modified
* @param useExpire true if 'Expire' header should be set
*/
public static void writeCacheHeaders(HttpServletResponse response, long cacheTime, long lastModified,
boolean useExpire) {
response.setHeader("Cache-Control", "public, max-age=" + cacheTime);
response.setDateHeader("Last-Modified", lastModified);
if (useExpire) {
Date expires = new Date(System.currentTimeMillis() + cacheTime * 1000);
LOGGER.debug("Last-Modified: {}, expire on: {}", new Date(lastModified), expires);
response.setDateHeader("Expires", expires.getTime());
}
}
public static Optional<File> getWebAppBaseDir(ServletContext ctx) {
return Optional.ofNullable(ctx.getRealPath("/")).map(File::new);
}
/**
* Checks if the <code>newIP</code> address matches the session of <code>lastIP</code> address.
*
* Usually this is only <code>true</code> if both addresses are equal by {@link InetAddress#equals(Object)}.
* This method is called to detect if a session is stolen by a 3rd party.
* There are two properties (with their default value) to modify this behavior and specify netmasks:
* <pre>
* MCR.Servlet.Session.NetMask.IPv4=255.255.255.255
* MCR.Servlet.Session.NetMask.IPv6=FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF
* </pre>
*
* @param lastIP IP address from former request
* @param newIP IP address from current request
* @throws UnknownHostException if <code>lastIP</code> or <code>newIP</code> are not valid IP addresses.
*/
public static boolean isIPAddrAllowed(String lastIP, String newIP) throws UnknownHostException {
InetAddress lastIPAddress = InetAddress.getByName(lastIP);
InetAddress newIPAddress = InetAddress.getByName(newIP);
byte[] lastIPMask = decideNetmask(lastIPAddress);
byte[] newIPMask = decideNetmask(newIPAddress);
lastIPAddress = InetAddress.getByAddress(filterIPByNetmask(lastIPAddress.getAddress(), lastIPMask));
newIPAddress = InetAddress.getByAddress(filterIPByNetmask(newIPAddress.getAddress(), newIPMask));
if (lastIPAddress.equals(newIPAddress)) {
return true;
}
String hostIP = getHostIP();
InetAddress hostIPAddress = InetAddress.getByName(hostIP);
byte[] hostIPMask = decideNetmask(hostIPAddress);
hostIPAddress = InetAddress.getByAddress(filterIPByNetmask(hostIPAddress.getAddress(), hostIPMask));
return newIPAddress.equals(hostIPAddress);
}
private static byte[] filterIPByNetmask(final byte[] ip, final byte[] mask) {
for (int i = 0; i < ip.length; i++) {
ip[i] = (byte) (ip[i] & mask[i]);
}
return ip;
}
private static byte[] decideNetmask(InetAddress ip) throws MCRException {
if (hasIPVersion(ip, 4)) {
return SESSION_NETMASK_IPV4;
} else if (hasIPVersion(ip, 6)) {
return SESSION_NETMASK_IPV6;
} else {
throw new MCRException("Unknown or unidentifiable version of ip: " + ip);
}
}
private static Boolean hasIPVersion(InetAddress ip, int version) {
int byteLength = switch (version) {
case 4 -> 4;
case 6 -> 16;
default -> throw new IndexOutOfBoundsException("Unknown ip version: " + version);
};
return ip.getAddress().length == byteLength;
}
private static void addSessionListener() {
MCRSessionMgr.addSessionListener(event -> {
switch (event.getType()) {
case passivated, destroyed -> CURRENT_SERVLET_JOB.remove();
default -> {
}
}
});
}
}
| 18,805 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWebsiteWriteProtection.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/MCRWebsiteWriteProtection.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.DOMOutputter;
import org.jdom2.output.XMLOutputter;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.config.MCRConfiguration2;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public final class MCRWebsiteWriteProtection {
private static final String FS = System.getProperty("file.separator");
private static final String CONFIG_FOLDER_PATH = MCRConfiguration2.getStringOrThrow("MCR.datadir") + FS
+ "config";
private static final String CONFIG_FILE_PATH = CONFIG_FOLDER_PATH + FS + "config-writeProtectionWebsite.xml";
private static final File CONFIG_FILE = new File(CONFIG_FILE_PATH);
private static long cacheInitTime = 0;
private static Element configCache = null;
private MCRWebsiteWriteProtection() {
//do not allow instantiation
}
/**
* Checks if website protection is currently active.
* If current user is super user this method always returns false.
*
* @return true if write access is currently active, false if not
*/
public static boolean isActive() {
// if superuser is online, return false
String superUser = MCRSystemUserInformation.getSuperUserInstance().getUserID();
if (MCRSessionMgr.getCurrentSession().getUserInformation().getUserID().equals(superUser)) {
return false;
}
// init, if impossible return false
Element config = getConfiguration();
if (config == null) {
return false;
}
// return value contained in config
String protection = config.getChildTextTrim("protectionEnabled");
return Boolean.parseBoolean(protection);
}
public static org.w3c.dom.Document getMessage() throws JDOMException {
Element config = getConfiguration();
if (config == null) {
return new DOMOutputter().output(new Document());
} else {
Element messageElem = config.getChild("message");
Document message = new Document(messageElem.clone());
return new DOMOutputter().output(message);
}
}
private static Element getConfiguration() {
// try to get file
File configFolder = new File(CONFIG_FOLDER_PATH);
if (!configFolder.exists()) {
configFolder.mkdirs();
}
// file exist?, return it's content
if (CONFIG_FILE.exists()) {
Element config = null;
// try to get from cache
if (cacheValid()) {
config = configCache;
} else {
SAXBuilder builder = new SAXBuilder();
try {
config = builder.build(CONFIG_FILE).getRootElement();
// update cache
updateCache(config);
} catch (JDOMException | IOException e) {
e.printStackTrace();
return null;
}
}
return config;
} else {
// create XML
Element config = configToJDOM(false, " ");
setConfiguration(config);
return config;
}
}
private static void setConfiguration(Element configXML) {
try {
// save
XMLOutputter xmlOut = new XMLOutputter();
FileOutputStream fos = new FileOutputStream(CONFIG_FILE);
xmlOut.output(configXML, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
updateCache(configXML);
}
private static void updateCache(Element configXML) {
configCache = configXML;
cacheInitTime = System.currentTimeMillis();
}
private static Element configToJDOM(boolean protection, String message) {
Element xml = new Element("config-writeProtectionWebsite");
xml.addContent(new Element("protectionEnabled").setText(Boolean.toString(protection)));
xml.addContent(new Element("message").setText(message));
return xml;
}
// to be used by cli
public static void activate() {
// create file, set param in file to true, add message to file
Element config = getConfiguration();
config.getChild("protectionEnabled").setText("true");
setConfiguration(config);
}
// to be used by cli
public static void activate(String message) {
// create file, set param in file to true, add message to file
Element config = getConfiguration();
config.getChild("protectionEnabled").setText("true");
config.getChild("message").setText(message);
setConfiguration(config);
}
// to be used by cli
public static void deactivate() {
// set param in file to false
Element config = getConfiguration();
config.getChild("protectionEnabled").setText("false");
setConfiguration(config);
}
public static boolean printInfoPageIfNoAccess(HttpServletRequest request, HttpServletResponse response,
String baseURL) throws IOException {
if (MCRWebsiteWriteProtection.isActive()) {
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
String pageURL = baseURL + MCRConfiguration2.getStringOrThrow("MCR.WriteProtectionWebsite.ErrorPage");
response.sendRedirect(response.encodeRedirectURL(pageURL));
return true;
}
return false;
}
/**
* Verifies if the cache of configuration is valid.
*
* @return true if valid, false if note
*/
private static boolean cacheValid() {
return !(configCache == null || cacheInitTime < CONFIG_FILE.lastModified());
}
}
| 6,823 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.