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
MCRURL.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/MCRURL.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.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * * @author Matthias Eichner */ public class MCRURL { static Logger LOGGER = LogManager.getLogger(MCRURL.class); private URL url; private Map<String, List<String>> parameterMap; public MCRURL(String url) throws MalformedURLException { try { this.url = new URI(url).toURL(); } catch (URISyntaxException e) { throw new MalformedURLException(e.getMessage()); } } public Map<String, List<String>> getParameterMap() { if (this.parameterMap == null) { this.parameterMap = buildParameterMap(this.url); } return parameterMap; } private Map<String, List<String>> buildParameterMap(URL url) { Map<String, List<String>> p = new HashMap<>(); String queryString = url.getQuery(); if (queryString == null) { return p; } for (String pair : queryString.split("&")) { int eq = pair.indexOf("="); String key = eq >= 0 ? pair.substring(0, eq) : pair; String value = eq >= 0 ? pair.substring(eq + 1) : ""; if (p.containsKey(key)) { p.get(key).add(value); } else { List<String> valueList = new ArrayList<>(); valueList.add(value); p.put(key, valueList); } } return p; } private String buildQueryString(Map<String, List<String>> parameterMap) { StringBuilder queryBuilder = new StringBuilder(); for (Entry<String, List<String>> entrySet : parameterMap.entrySet()) { String name = entrySet.getKey(); for (String value : entrySet.getValue()) { queryBuilder.append(name).append('=').append(value).append('&'); } } String queryString = queryBuilder.toString(); return queryString.length() > 0 ? queryString.substring(0, queryString.length() - 1) : ""; } private void rebuild() { String query = buildQueryString(this.parameterMap); try { URI uri = this.url.toURI(); StringBuilder urlBuffer = new StringBuilder(); urlBuffer.append( new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null, null)); if (query != null) { urlBuffer.append('?').append(query); } if (uri.getFragment() != null) { urlBuffer.append('#').append(uri.getFragment()); } this.url = new URI(urlBuffer.toString()).toURL(); if (this.parameterMap != null) { // rebuild parameter map this.parameterMap = buildParameterMap(this.url); } } catch (Exception exc) { LOGGER.error("unable to rebuild url {}", this.url); } } public String getParameter(String name) { List<String> valueList = getParameterMap().get(name); return valueList != null ? valueList.get(0) : null; } public List<String> getParameterValues(String name) { List<String> valueList = getParameterMap().get(name); return valueList != null ? valueList : new ArrayList<>(); } public MCRURL addParameter(String name, String value) { StringBuilder urlBuffer = new StringBuilder(this.url.toString()); urlBuffer.append(this.url.getQuery() == null ? "?" : "&"); urlBuffer.append(name).append('=').append(value); try { this.url = new URI(urlBuffer.toString()).toURL(); if (this.parameterMap != null) { // rebuild parameter map this.parameterMap = buildParameterMap(this.url); } } catch (MalformedURLException | URISyntaxException exc) { LOGGER.error("unable to add parameter ({}={}) to url{}", name, value, this.url); } return this; } public MCRURL removeParameter(String name) { this.getParameterMap().remove(name); rebuild(); return this; } public MCRURL removeParameterValue(String name, String value) { List<String> values = this.getParameterMap().get(name); if (values != null) { boolean removed = false; while (values.remove(value)) { removed = true; } if (removed) { rebuild(); } } return this; } public URL getURL() { return this.url; } @Override public String toString() { return this.url.toString(); } }
5,721
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJerseyResourceConfig.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/MCRJerseyResourceConfig.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.jersey; import org.apache.logging.log4j.LogManager; import org.glassfish.jersey.server.ResourceConfig; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; /** * Entry point for mycore jersey configuration. Loads the {@link MCRJerseyConfiguration} defined in * 'MCR.Jersey.Configuration' or the default {@link MCRJerseyDefaultConfiguration}. * * @author Matthias Eichner */ public class MCRJerseyResourceConfig extends ResourceConfig { public MCRJerseyResourceConfig() { super(); LogManager.getLogger().info("Loading jersey resource config..."); MCRJerseyConfiguration configuration; try { configuration = MCRConfiguration2.<MCRJerseyDefaultConfiguration>getInstanceOf("MCR.Jersey.Configuration") .orElseGet(MCRJerseyDefaultConfiguration::new); } catch (MCRConfigurationException exc) { LogManager.getLogger().error("Unable to initialize jersey.", exc); return; } try { configuration.configure(this); } catch (Exception exc) { LogManager.getLogger().error("Unable to configure jersey.", exc); } } }
1,977
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJerseyUtil.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/MCRJerseyUtil.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.jersey; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.glassfish.jersey.server.ResourceConfig; import org.jdom2.Document; import org.mycore.access.MCRAccessManager; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.content.transformer.MCRContentTransformer; import org.mycore.common.content.transformer.MCRParameterizedTransformer; import org.mycore.common.xml.MCRLayoutService; import org.mycore.common.xsl.MCRParameterCollector; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.frontend.jersey.resources.MCRJerseyExceptionMapper; import jakarta.servlet.http.HttpServletRequest; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.Application; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.core.UriInfo; /** * Contains some jersey utility methods. * * @author Matthias Eichner */ public abstract class MCRJerseyUtil { public static final String APPLICATION_JSON_UTF8 = MediaType.APPLICATION_JSON + ";charset=utf-8"; public static final String APPLICATION_XML_UTF8 = MediaType.APPLICATION_XML + ";charset=utf-8"; /** * Transforms a jdom document to a <code>MCRContent</code> via the <code>MCRLayoutService</code>. * * @param document * the document to transform * @param request * the http request */ public static MCRContent transform(Document document, HttpServletRequest request) throws Exception { MCRParameterCollector parameter = new MCRParameterCollector(request); MCRContent result; MCRJDOMContent source = new MCRJDOMContent(document); MCRContentTransformer transformer = MCRLayoutService.getContentTransformer(source.getDocType(), parameter); if (transformer instanceof MCRParameterizedTransformer parameterizedTransformer) { result = parameterizedTransformer.transform(source, parameter); } else { result = transformer.transform(source); } return result; } /** * Returns the mycore id. Throws a web application exception if the id is invalid or not found. * * @param id * id as string * @return mycore object id */ public static MCRObjectID getID(String id) { MCRObjectID mcrId = null; try { mcrId = MCRObjectID.getInstance(id); if (!MCRMetadataManager.exists(mcrId)) { throw new WebApplicationException(Status.NOT_FOUND); } } catch (MCRException mcrExc) { throwException(Status.BAD_REQUEST, "invalid mycore id '" + id + "'"); } return mcrId; } /** * Checks if the current user has the given permission. Throws an unauthorized exception otherwise. * * @param id * mycore object id * @param permission * permission to check */ public static void checkPermission(MCRObjectID id, String permission) { if (!MCRAccessManager.checkPermission(id, permission)) { throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); } } /** * Checks if the current user has the read permission on the given derivate content. * Throws an unauthorized exception otherwise. * * @param id * mycore object id * @see MCRAccessManager#checkDerivateContentPermission(MCRObjectID, String) */ public static void checkDerivateReadPermission(MCRObjectID id) { if (!MCRAccessManager.checkDerivateContentPermission(id, MCRAccessManager.PERMISSION_READ)) { throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); } } /** * Checks if the current user has the given permission. Throws an unauthorized exception otherwise. * * @param id * mycore object id * @param permission * permission to check */ public static void checkPermission(String id, String permission) { if (!MCRAccessManager.checkPermission(id, permission)) { throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); } } /** * Checks if the current user has the given permission. Throws an unauthorized exception otherwise. * * @param permission * permission to check */ public static void checkPermission(String permission) { if (!MCRAccessManager.checkPermission(permission)) { throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); } } /** * Throws a {@link WebApplicationException} with status and message. * This exception will be handled by the {@link MCRJerseyExceptionMapper}. * See <a href="http://stackoverflow.com/questions/29414041/exceptionmapper-for-webapplicationexceptions-thrown-with-entity">stackoverflow</a>. * * @param status the http return status * @param message the message to print */ public static void throwException(Status status, String message) { throw new WebApplicationException(new MCRException(message), status); } /** * Returns a human readable message of a http status code. * * @param statusCode * http status code * @return human readable string */ public static String fromStatusCode(int statusCode) { Status status = Response.Status.fromStatusCode(statusCode); return status != null ? status.getReasonPhrase() : "Unknown Error"; } /** * Returns the base URL of the mycore system. * * @param info the UriInfo * * @return base URL of the mycore system as string */ public static String getBaseURL(UriInfo info, Application app) { String baseURL = info.getBaseUri().toString(); List<String> applicationPaths = MCRConfiguration2 .getOrThrow("MCR.Jersey.Resource.ApplicationPaths", MCRConfiguration2::splitValue) .collect(Collectors.toList()); for (String path : applicationPaths) { baseURL = removeAppPath(baseURL, path); } Optional<String> appPath = Optional.ofNullable(app) .map(a -> a instanceof ResourceConfig ? ((ResourceConfig) a).getApplication() : a) .map(Application::getClass) .map(c -> c.getAnnotation(ApplicationPath.class)) .map(ApplicationPath::value) .map(s -> s.startsWith("/") ? s.substring(1) : s); if (appPath.isPresent()) { baseURL = removeAppPath(baseURL, appPath.get()); } return baseURL; } private static String removeAppPath(String baseURL, String path) { if (baseURL.endsWith("/" + path + "/")) { return baseURL.substring(0, baseURL.indexOf(path)); } return baseURL; } }
8,047
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJWTUtil.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/MCRJWTUtil.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.jersey; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Date; import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.mycore.common.MCRSession; import org.mycore.common.MCRUserInformation; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationDir; import org.mycore.common.config.MCRConfigurationException; import org.mycore.common.events.MCRStartupHandler; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTCreator; import com.auth0.jwt.algorithms.Algorithm; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import jakarta.servlet.ServletContext; import jakarta.ws.rs.core.Response; public class MCRJWTUtil implements MCRStartupHandler.AutoExecutable { public static final String JWT_CLAIM_ROLES = "mcr:roles"; public static final String JWT_CLAIM_IP = "mcr:ip"; public static final String JWT_USER_ATTRIBUTE_PREFIX = "mcr:ua:"; public static final String JWT_SESSION_ATTRIBUTE_PREFIX = "mcr:sa:"; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final String ROLES_PROPERTY = "MCR.Rest.JWT.Roles"; private static Algorithm SHARED_SECRET; public static JWTCreator.Builder getJWTBuilder(MCRSession mcrSession) { return getJWTBuilder(mcrSession, null, null); } public static JWTCreator.Builder getJWTBuilder(MCRSession mcrSession, String[] userAttributes, String[] sessionAttributes) { MCRUserInformation userInformation = mcrSession.getUserInformation(); String[] roles = MCRConfiguration2.getOrThrow(ROLES_PROPERTY, MCRConfiguration2::splitValue) .filter(userInformation::isUserInRole) .toArray(String[]::new); String subject = userInformation.getUserID(); String email = userInformation.getUserAttribute(MCRUserInformation.ATT_EMAIL); String name = userInformation.getUserAttribute(MCRUserInformation.ATT_REAL_NAME); JWTCreator.Builder builder = JWT.create() .withIssuedAt(new Date()) .withSubject(subject) .withArrayClaim("mcr:roles", roles) .withClaim("email", email) .withClaim("name", name); if (userAttributes != null) { for (String userAttribute : userAttributes) { String value = userInformation.getUserAttribute(userAttribute); if (value != null) { builder.withClaim(JWT_USER_ATTRIBUTE_PREFIX + userAttribute, value); } } } if (sessionAttributes != null) { for (String sessionAttribute : sessionAttributes) { Object object = mcrSession.get(sessionAttribute); Optional.ofNullable(object).map(Object::toString) .ifPresent((value) -> builder.withClaim(JWT_SESSION_ATTRIBUTE_PREFIX + sessionAttribute, value)); } } return builder; } public static Algorithm getJWTAlgorithm() { return SHARED_SECRET; } public static Response getJWTLoginSuccessResponse(String jwt) throws IOException { ObjectNode response = OBJECT_MAPPER.createObjectNode(); response.put("login_success", true); response.put("access_token", jwt); response.put("token_type", "Bearer"); return Response.status(Response.Status.OK) .header("Authorization", "Bearer " + jwt) .entity(response) .build(); } public static Response getJWTRenewSuccessResponse(String jwt) throws IOException { ObjectNode response = OBJECT_MAPPER.createObjectNode(); response.put("executed", true); response.put("access_token", jwt); response.put("token_type", "Bearer"); return Response.status(Response.Status.OK) .header("Authorization", "Bearer " + jwt) .entity(response) .build(); } public static Response getJWTLoginErrorResponse(String errorDescription) throws IOException { ObjectNode response = OBJECT_MAPPER.createObjectNode(); response.put("login_success", false); response.put("error", "login_failed"); response.put("error_description", errorDescription); return Response.status(Response.Status.FORBIDDEN) .entity(response) .build(); } @Override public String getName() { return "JSON WebToken Services"; } @Override public int getPriority() { return 0; } @Override public void startUp(ServletContext servletContext) { if (servletContext != null) { File sharedSecretFile = MCRConfigurationDir.getConfigFile("jwt.secret"); byte[] secret; if (!sharedSecretFile.isFile()) { secret = new byte[4096]; try { LogManager.getLogger().warn( "Creating shared secret file ({}) for JSON Web Token." + " This may take a while. Please wait...", sharedSecretFile); SecureRandom.getInstanceStrong().nextBytes(secret); Files.write(sharedSecretFile.toPath(), secret, StandardOpenOption.CREATE_NEW); } catch (NoSuchAlgorithmException | IOException e) { throw new MCRConfigurationException( "Could not create shared secret in file: " + sharedSecretFile.getAbsolutePath(), e); } } else { try { secret = Files.readAllBytes(sharedSecretFile.toPath()); } catch (IOException e) { throw new MCRConfigurationException( "Could not create shared secret in file: " + sharedSecretFile.getAbsolutePath(), e); } } SHARED_SECRET = Algorithm.HMAC512(secret); } } }
6,945
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRStaticContent.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/MCRStaticContent.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.jersey; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.mycore.frontend.jersey.feature.MCRJerseyDefaultFeature; /** * The MCRStaticContent annotation marks a resource or method to run without * a MyCoRe transaction, session or access filter. Basically it disables * the {@link MCRJerseyDefaultFeature} for the annotated element. * * <p>Use this annotation if you deliver static content.</p> * * <p>You can annotate whole resources or just single methods.</p> * * @author Matthias Eichner */ @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface MCRStaticContent { }
1,512
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCacheControl.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/MCRCacheControl.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.jersey; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.concurrent.TimeUnit; /** * Used to define the {@link jakarta.ws.rs.core.HttpHeaders#CACHE_CONTROL} header via annotation */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MCRCacheControl { /** * sets {@code private} directive * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.2.2.6">private definition</a> */ FieldArgument private_() default @FieldArgument(); /** * sets {@code no-cache} directive * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.2.2.2">no-cache definition</a> */ FieldArgument noCache() default @FieldArgument; /** * if {@link #noCache()}, sets {@code noCache} directive argument to these values * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.2.2.2">no-cache definition</a> */ String[] noCacheFields() default {}; /** * if true, sets {@code no-store} directive * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.2.2.3">no-store definition</a> */ boolean noStore() default false; /** * if true, sets {@code no-transform} directive * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.2.2.4">no-transform definition</a> */ boolean noTransform() default false; /** * if true, sets {@code must-revalidate} directive * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.2.2.1">must-revalidate definition</a> */ boolean mustRevalidate() default false; /** * if true, sets {@code proxy-revalidate} directive * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.2.2.7">proxy-revalidate definition</a> */ boolean proxyRevalidate() default false; /** * if true, sets {@code public} directive * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.2.2.5">public definition</a> */ boolean public_() default false; /** * Sets {@code max-age} directive * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.2.2.8">max-age definition</a> */ Age maxAge() default @Age(time = -1, unit = TimeUnit.SECONDS); /** * Sets {@code s-maxage} directive * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.2.2.9">s-maxage definition</a> */ Age sMaxAge() default @Age(time = -1, unit = TimeUnit.SECONDS); /** * Sets further Cache-Control Extensions * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.2.3">Cache Control Extensions</a> */ Extension[] extensions() default {}; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) @interface Age { long time(); TimeUnit unit() default TimeUnit.MINUTES; } @interface FieldArgument { /** * if true, this directive is present in header value */ boolean active() default false; /** * if {@link #active()}, sets directive argument to these values */ String[] fields() default {}; } @interface Extension { String directive(); String argument() default ""; } }
4,107
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJerseyConfiguration.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/MCRJerseyConfiguration.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.jersey; import org.glassfish.jersey.server.ResourceConfig; /** * Base interface to configure jersey in an mycore application. Used to register resource, features and so on. * * @author Matthias Eichner */ public interface MCRJerseyConfiguration { /** * Configures the application. * * @param resourceConfig the jersey resource configuration */ void configure(ResourceConfig resourceConfig); }
1,184
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJerseyDefaultConfiguration.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/MCRJerseyDefaultConfiguration.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.jersey; import org.apache.logging.log4j.LogManager; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.server.ResourceConfig; import org.mycore.common.config.MCRConfiguration2; import org.mycore.frontend.jersey.access.MCRRequestScopeACLFilter; /** * Default jersey configuration for mycore. * * <ul> * <li>adds the multipart feature</li> * <li>resolves all resource of the property 'MCR.Jersey.Resource.Packages'</li> * </ul> * */ public class MCRJerseyDefaultConfiguration implements MCRJerseyConfiguration { @Override public void configure(ResourceConfig resourceConfig) { resourceConfig.register(MCRRequestScopeACLFilter.class); // setup resources setupResources(resourceConfig); // include mcr jersey feature setupFeatures(resourceConfig); } /** * Setup the jersey resources. * * @param resourceConfig the jersey resource configuration */ protected void setupResources(ResourceConfig resourceConfig) { String propertyString = MCRConfiguration2.getString("MCR.Jersey.Resource.Packages") .orElse("org.mycore.frontend.jersey.resources"); resourceConfig.packages(propertyString.split(",")); LogManager.getLogger().info("Scanning jersey resource packages {}", propertyString); } /** * Setup features. By default the multi part feature and every mycore feature * class in "org.mycore.frontend.jersey.feature". * * @param resourceConfig the jersey resource configuration */ protected void setupFeatures(ResourceConfig resourceConfig) { // multi part resourceConfig.register(MultiPartFeature.class); // mycore features resourceConfig.packages("org.mycore.frontend.jersey.feature"); } }
2,588
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJerseyBaseFeature.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/feature/MCRJerseyBaseFeature.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.jersey.feature; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import org.mycore.common.config.MCRConfiguration2; import org.mycore.frontend.jersey.MCRStaticContent; import org.mycore.frontend.jersey.filter.access.MCRResourceAccessChecker; import org.mycore.frontend.jersey.filter.access.MCRResourceAccessCheckerFactory; import org.mycore.frontend.jersey.filter.access.MCRResourceAccessFilter; import org.mycore.frontend.jersey.filter.access.MCRRestrictedAccess; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.container.DynamicFeature; import jakarta.ws.rs.core.FeatureContext; import jakarta.ws.rs.core.Response; public abstract class MCRJerseyBaseFeature implements DynamicFeature { /** * Checks if the class/method is annotated by {@link MCRStaticContent}. * * @param resourceClass the class to check * @param resourceMethod the method to check * @return true if one of both is annotated as static */ protected boolean isStaticContent(Class<?> resourceClass, Method resourceMethod) { return resourceClass.getAnnotation(MCRStaticContent.class) != null || resourceMethod.getAnnotation(MCRStaticContent.class) != null; } /** * Returns a list of packages which will be used to scan for components. * * @return a list of java package names */ protected List<String> getPackages() { String propertyString = MCRConfiguration2.getString("MCR.Jersey.Resource.Packages") .orElse("org.mycore.frontend.jersey.resources"); return Arrays.asList(propertyString.split(",")); } /** * Register a MCRRestrictedAccess filter to the context. * * @param context the context to add the restricted access too * @param restrictedAccess the restricted access */ protected void addFilter(FeatureContext context, MCRRestrictedAccess restrictedAccess) { MCRResourceAccessChecker accessChecker; try { accessChecker = MCRResourceAccessCheckerFactory.getInstance(restrictedAccess.value()); } catch (ReflectiveOperationException e) { throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } context.register(new MCRResourceAccessFilter(accessChecker)); } }
3,091
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJerseyDefaultFeature.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/feature/MCRJerseyDefaultFeature.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.jersey.feature; import java.lang.reflect.Method; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.frontend.jersey.filter.MCRCacheFilter; import org.mycore.frontend.jersey.filter.MCRDBTransactionFilter; import org.mycore.frontend.jersey.filter.MCRSessionHookFilter; import org.mycore.frontend.jersey.filter.MCRSessionLockFilter; import org.mycore.frontend.jersey.filter.access.MCRRestrictedAccess; import jakarta.ws.rs.container.ResourceInfo; import jakarta.ws.rs.core.FeatureContext; import jakarta.ws.rs.ext.Provider; /** * Default feature for mycore. Does register a cache, transaction, session and * access filter. * * @author Matthias Eichner */ @Provider public class MCRJerseyDefaultFeature extends MCRJerseyBaseFeature { private static final Logger LOGGER = LogManager.getLogger(MCRJerseyDefaultFeature.class); @Override public void configure(ResourceInfo resourceInfo, FeatureContext context) { Class<?> resourceClass = resourceInfo.getResourceClass(); Method resourceMethod = resourceInfo.getResourceMethod(); context.register(MCRCacheFilter.class); if (isStaticContent(resourceClass, resourceMethod)) { // class or method is annotated with MCRStaticContent // -> do only register session lock filter context.register(MCRSessionLockFilter.class); return; } String packageName = resourceClass.getPackage().getName(); if (getPackages().contains(packageName)) { registerTransactionFilter(context); registerSessionHookFilter(context); registerAccessFilter(context, resourceClass, resourceMethod); } } protected void registerTransactionFilter(FeatureContext context) { context.register(MCRDBTransactionFilter.class); } protected void registerSessionHookFilter(FeatureContext context) { context.register(MCRSessionHookFilter.class); } protected void registerAccessFilter(FeatureContext context, Class<?> resourceClass, Method resourceMethod) { MCRRestrictedAccess restrictedAccessMETHOD = resourceMethod.getAnnotation(MCRRestrictedAccess.class); MCRRestrictedAccess restrictedAccessTYPE = resourceClass.getAnnotation(MCRRestrictedAccess.class); if (restrictedAccessMETHOD != null) { LOGGER.info("Access to {} is restricted by {}", resourceMethod, restrictedAccessMETHOD.value().getCanonicalName()); addFilter(context, restrictedAccessMETHOD); } else if (restrictedAccessTYPE != null) { LOGGER.info("Access to {} is restricted by {}", resourceClass.getName(), restrictedAccessTYPE.value().getCanonicalName()); addFilter(context, restrictedAccessTYPE); } } }
3,610
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJerseyResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/resources/MCRJerseyResource.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.jersey.resources; import java.net.URI; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.UriInfo; public abstract class MCRJerseyResource { @Context protected UriInfo uriInfo; protected URI getBaseURI() { return uriInfo.getBaseUri(); } public UriInfo getContext() { return this.uriInfo; } }
1,104
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJWTResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/resources/MCRJWTResource.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.jersey.resources; import java.io.IOException; import java.util.Optional; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.frontend.jersey.MCRCacheControl; import org.mycore.frontend.jersey.MCRJWTUtil; import org.mycore.frontend.jersey.MCRStaticContent; import org.mycore.frontend.servlets.MCRServlet; import com.auth0.jwt.JWT; import com.auth0.jwt.exceptions.JWTVerificationException; import jakarta.servlet.http.HttpServletRequest; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; /** * @author Thomas Scheffler (yagee) */ @Path("/jwt") public class MCRJWTResource { public static final String AUDIENCE = "mcr:session"; @Context HttpServletRequest request; @GET @Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8") @MCRStaticContent @MCRCacheControl(noTransform = true, noStore = true, private_ = @MCRCacheControl.FieldArgument(active = true), noCache = @MCRCacheControl.FieldArgument(active = true)) public Response getTokenFromSession() throws IOException { if (!Optional.ofNullable(request.getSession(false)) .map(s -> s.getAttribute(MCRServlet.ATTR_MYCORE_SESSION)) .isPresent()) { return MCRJWTUtil.getJWTLoginErrorResponse("No active MyCoRe session found."); } String[] userAttributes = request.getParameterValues("ua"); String[] sessionAttributes = request.getParameterValues("sa"); MCRSession mcrSession = MCRServlet.getSession(request); String jwt = getToken(mcrSession, userAttributes, sessionAttributes); return MCRJWTUtil.getJWTLoginSuccessResponse(jwt); } private String getToken(MCRSession mcrSession, String[] userAttributes, String[] sessionAttributes) { String issuer = request.getRequestURL().toString(); return MCRJWTUtil.getJWTBuilder(mcrSession, userAttributes, sessionAttributes) .withJWTId(mcrSession.getID()) .withIssuer(issuer) .withAudience(AUDIENCE) .withClaim(MCRJWTUtil.JWT_CLAIM_IP, mcrSession.getCurrentIP()) .sign(MCRJWTUtil.getJWTAlgorithm()); } public static void validate(String token) throws JWTVerificationException { //JWTClaims is a record that stores a session ID and a user ID record JWTClaims(String sessionId, String userId) { } if (Optional.of(JWT.require(MCRJWTUtil.getJWTAlgorithm()) .withAudience(AUDIENCE) .build().verify(token)) .map(jwt -> new JWTClaims(jwt.getId(), jwt.getSubject())) .filter(claims -> Optional.ofNullable(MCRSessionMgr.getSession(claims.sessionId)) .filter(session -> session.getUserInformation().getUserID().equals(claims.userId)).isPresent()) .isEmpty()) { throw new JWTVerificationException("MCRSession is invalid."); } } }
3,832
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJerseyExceptionMapper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/resources/MCRJerseyExceptionMapper.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.jersey.resources; import java.util.Optional; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRTransactionHelper; import org.mycore.common.content.MCRContent; import org.mycore.frontend.jersey.MCRJerseyUtil; import org.mycore.frontend.servlets.MCRErrorServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.ws.rs.InternalServerErrorException; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.core.UriInfo; import jakarta.ws.rs.ext.ExceptionMapper; import jakarta.ws.rs.ext.Provider; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.adapters.XmlAdapter; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * Handles jersey web application exceptions. By default, this class * just forwards the exception. Only if the request accepts HTML a * custom error page is generated. * * @author Matthias Eichner */ @Provider public class MCRJerseyExceptionMapper implements ExceptionMapper<Exception> { private static final Logger LOGGER = LogManager.getLogger(); @Context HttpHeaders headers; @Context HttpServletRequest request; //required for MCRParamCollector @Context UriInfo uriInfo; @Override public Response toResponse(Exception exc) { Response response = getResponse(exc); if (exc instanceof WebApplicationException && !(exc instanceof InternalServerErrorException)) { LOGGER.warn("{}: {}, {}", uriInfo.getRequestUri(), response.getStatus(), exc.getMessage()); LOGGER.debug("Exception: ", exc); } else { LOGGER.warn(() -> "Error while processing request " + uriInfo.getRequestUri(), exc); } MCRTransactionHelper.setRollbackOnly(); if (headers.getAcceptableMediaTypes().contains(MediaType.TEXT_HTML_TYPE)) { // try to return a html error page if (!MCRSessionMgr.isLocked() && !MCRTransactionHelper.isTransactionActive()) { MCRSessionMgr.getCurrentSession(); MCRTransactionHelper.beginTransaction(); } try { int status = response.getStatus(); String source = exc.getStackTrace().length > 0 ? exc.getStackTrace()[0].toString() : null; Document errorPageDocument = MCRErrorServlet.buildErrorPage(exc.getMessage(), status, uriInfo.getRequestUri().toASCIIString(), null, source, exc); MCRContent result = MCRJerseyUtil.transform(errorPageDocument, request); return Response.serverError() .entity(result.getInputStream()) .type(result.getMimeType()) .status(status) .build(); } catch (Exception transformException) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(transformException).build(); } finally { if (!MCRSessionMgr.isLocked()) { MCRTransactionHelper.commitTransaction(); } } } return response; } private Response getResponse(Exception exc) { if (exc instanceof WebApplicationException wae) { Response response = wae.getResponse(); if (response.hasEntity()) { return response; } return Response.fromResponse(response) .entity(exc.getMessage()) .type(MediaType.TEXT_PLAIN_TYPE) .build(); } Object entity = Optional.ofNullable(request.getContentType()) .map(MediaType::valueOf) .filter(t -> t.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE) || t .isCompatible(MediaType.MULTIPART_FORM_DATA_TYPE)) .map(t -> (Object) exc.getMessage()) //do not container form requests responses .orElseGet(() -> new MCRExceptionContainer(exc)); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(entity).build(); } @XmlRootElement(name = "error") private static class MCRExceptionContainer { private Exception exception; @SuppressWarnings("unused") private MCRExceptionContainer() { //required for JAXB } MCRExceptionContainer(Exception e) { this.exception = e; } @XmlElement @XmlJavaTypeAdapter(ExceptionTypeAdapter.class) public Exception getException() { return exception; } @XmlAttribute public Class<? extends Exception> getType() { return exception.getClass(); } } private static class ExceptionTypeAdapter extends XmlAdapter<RException, Exception> { @Override public Exception unmarshal(RException v) { throw new UnsupportedOperationException(); } @Override public RException marshal(Exception v) { RException ep = new RException(); ep.message = v.getMessage(); ep.stackTrace = Stream.of(v.getStackTrace()).map(RStackTraceElement::getInstance) .toArray(RStackTraceElement[]::new); Optional.ofNullable(v.getCause()) .filter(Exception.class::isInstance) .map(Exception.class::cast) .map(this::marshal) .ifPresent(c -> ep.cause = c); return ep; } } private static class RException { @XmlElement private String message; @XmlElement private RStackTraceElement[] stackTrace; @XmlElement private RException cause; } private static class RStackTraceElement { @XmlAttribute private String className; @XmlAttribute private String method; @XmlAttribute private String file; @XmlAttribute private int line; private static RStackTraceElement getInstance(StackTraceElement ste) { RStackTraceElement rste = new RStackTraceElement(); rste.className = ste.getClassName(); rste.method = ste.getMethodName(); rste.file = ste.getFileName(); rste.line = ste.getLineNumber(); return rste; } } }
7,523
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRLocaleResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/resources/MCRLocaleResource.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.jersey.resources; import java.util.Set; import org.mycore.common.MCRJSONUtils; import org.mycore.common.MCRSessionMgr; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.jersey.MCRJerseyUtil; import org.mycore.frontend.jersey.MCRStaticContent; import org.mycore.services.i18n.MCRTranslation; import jakarta.annotation.PostConstruct; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpServletResponse; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; @Path("locale") public class MCRLocaleResource { @Context private HttpServletResponse resp; @Context private ServletContext context; private long cacheTime, startUpTime; @PostConstruct public void init() { String cacheParam = context.getInitParameter("cacheTime"); cacheTime = cacheParam != null ? Long.parseLong(cacheParam) : (60 * 60 * 24); //default is one day startUpTime = System.currentTimeMillis(); } /** * Returns the current language in ISO 639 (two character) format. * * @return current language as plain text */ @GET @Produces(MediaType.TEXT_PLAIN) @Path("language") public String language() { return MCRTranslation.getCurrentLocale().getLanguage(); } /** * Returns all available languages of the application. The codes are in ISO 639 (two character) format. * * @return json array of all languages available */ @GET @Produces(MCRJerseyUtil.APPLICATION_JSON_UTF8) @Path("languages") @MCRStaticContent public String languages() { Set<String> availableLanguages = MCRTranslation.getAvailableLanguages(); return MCRJSONUtils.getJsonArray(availableLanguages).toString(); } /** * Translates a set of keys to the given language. * * @param lang desired language * @param key message key ending with an asterisk (e.g. component.classeditor.*) * @return json object containing all keys and their corresponding translation */ @GET @Produces(MCRJerseyUtil.APPLICATION_JSON_UTF8) @Path("translate/{lang}/{key: .*\\*}") @MCRStaticContent public String translateJSON(@PathParam("lang") String lang, @PathParam("key") String key) { MCRFrontendUtil.writeCacheHeaders(resp, cacheTime, startUpTime, true); return MCRJSONUtils.getTranslations(key, lang); } /** * Translates a set of keys to the current language. * * @param key message key ending with an asterisk (e.g. component.classeditor.*) * @return json object containing all keys and their corresponding translation in current language */ @GET @Produces(MCRJerseyUtil.APPLICATION_JSON_UTF8) @Path("translate/{key: .*\\*}") public String translateJSONDefault(@PathParam("key") String key) { MCRFrontendUtil.writeCacheHeaders(resp, cacheTime, startUpTime, true); return MCRJSONUtils.getTranslations(key.substring(0, key.length() - 1), MCRSessionMgr.getCurrentSession().getCurrentLanguage()); } /** * Translates a single key to the given language. * * @param lang desired language * @param key the key to translate (e.g. component.classeditor.save.successful) * @return translated plain text */ @GET @Produces(MediaType.TEXT_PLAIN) @Path("translate/{lang}/{key: [^\\*]+}") @MCRStaticContent public String translateText(@PathParam("lang") String lang, @PathParam("key") String key) { MCRFrontendUtil.writeCacheHeaders(resp, cacheTime, startUpTime, true); return MCRTranslation.translateToLocale(key, MCRTranslation.getLocale(lang)); } /** * Translates a single key to the current language. * * @param key the key to translate (e.g. component.classeditor.save.successful) * @return translated plain text */ @GET @Produces(MediaType.TEXT_PLAIN) @Path("translate/{key: [^\\*]+}") public String translateTextDefault(@PathParam("key") String key) { MCRFrontendUtil.writeCacheHeaders(resp, cacheTime, startUpTime, true); return MCRTranslation.translate(key, MCRTranslation.getCurrentLocale()); } }
5,104
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCREchoResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/resources/MCREchoResource.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.jersey.resources; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Locale; import java.util.Map; import org.mycore.frontend.jersey.MCRStaticContent; import org.mycore.frontend.jersey.access.MCRRequireLogin; import org.mycore.frontend.jersey.filter.access.MCRRestrictedAccess; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; /** * @author Thomas Scheffler (yagee) */ @Path("/echo") public class MCREchoResource { @Context HttpServletRequest request; @GET @Produces(MediaType.APPLICATION_JSON) @MCRRestrictedAccess(MCRRequireLogin.class) public String doEcho() { Gson gson = new Gson(); JsonObject jRequest = new JsonObject(); jRequest.addProperty("secure", request.isSecure()); jRequest.addProperty("authType", request.getAuthType()); jRequest.addProperty("context", request.getContextPath()); jRequest.addProperty("localAddr", request.getLocalAddr()); jRequest.addProperty("localName", request.getLocalName()); jRequest.addProperty("method", request.getMethod()); jRequest.addProperty("pathInfo", request.getPathInfo()); jRequest.addProperty("protocol", request.getProtocol()); jRequest.addProperty("queryString", request.getQueryString()); jRequest.addProperty("remoteAddr", request.getRemoteAddr()); jRequest.addProperty("remoteHost", request.getRemoteHost()); jRequest.addProperty("remoteUser", request.getRemoteUser()); jRequest.addProperty("remotePort", request.getRemotePort()); jRequest.addProperty("requestURI", request.getRequestURI()); jRequest.addProperty("scheme", request.getScheme()); jRequest.addProperty("serverName", request.getServerName()); jRequest.addProperty("servletPath", request.getServletPath()); jRequest.addProperty("serverPort", request.getServerPort()); HttpSession session = request.getSession(false); List<String> attributes = Collections.list(session.getAttributeNames()); JsonObject sessionJSON = new JsonObject(); JsonObject attributesJSON = new JsonObject(); attributes.forEach(attr -> attributesJSON.addProperty(attr, session.getAttribute(attr).toString())); sessionJSON.add("attributes", attributesJSON); sessionJSON.addProperty("id", session.getId()); sessionJSON.addProperty("creationTime", session.getCreationTime()); sessionJSON.addProperty("lastAccessedTime", session.getLastAccessedTime()); sessionJSON.addProperty("maxInactiveInterval", session.getMaxInactiveInterval()); sessionJSON.addProperty("isNew", session.isNew()); jRequest.add("session", sessionJSON); jRequest.addProperty("localPort", request.getLocalPort()); JsonArray jLocales = new JsonArray(); Enumeration<Locale> locales = request.getLocales(); while (locales.hasMoreElements()) { jLocales.add(gson.toJsonTree(locales.nextElement().toString())); } jRequest.add("locales", jLocales); JsonObject header = new JsonObject(); jRequest.add("header", header); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); String headerValue = request.getHeader(headerName); header.addProperty(headerName, headerValue); } JsonObject parameter = new JsonObject(); jRequest.add("parameter", parameter); for (Map.Entry<String, String[]> param : request.getParameterMap().entrySet()) { if (param.getValue().length == 1) { parameter.add(param.getKey(), gson.toJsonTree(param.getValue()[0])); } else { parameter.add(param.getKey(), gson.toJsonTree(param.getValue())); } } return jRequest.toString(); } @GET @Path("ping") @MCRStaticContent public Response ping() { return Response.ok("pong").build(); } }
5,190
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSessionHookFilter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/filter/MCRSessionHookFilter.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.jersey.filter; import java.io.IOException; import org.apache.commons.io.output.ProxyOutputStream; 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.MCRTransactionHelper; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.servlets.MCRServlet; import jakarta.annotation.Priority; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.ws.rs.Priorities; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerRequestFilter; import jakarta.ws.rs.container.ContainerResponseContext; import jakarta.ws.rs.container.ContainerResponseFilter; import jakarta.ws.rs.core.Context; @Priority(Priorities.AUTHENTICATION) public class MCRSessionHookFilter implements ContainerRequestFilter, ContainerResponseFilter { @Context private HttpServletRequest httpRequest; @Context private HttpServletResponse httpResponse; private static final String ATTR = MCRSessionHookFilter.class.getName() + ".session"; private static final Logger LOGGER = LogManager.getLogger(MCRSessionHookFilter.class); @Override public void filter(ContainerRequestContext request) { MCRSession session = MCRServlet.getSession(httpRequest); request.setProperty(ATTR, session); MCRSessionMgr.setCurrentSession(session); LOGGER.info("{} ip={} mcr={} user={}", request.getUriInfo().getPath(), MCRFrontendUtil.getRemoteAddr(httpRequest), session.getID(), session.getUserInformation().getUserID()); MCRFrontendUtil.configureSession(session, httpRequest, httpResponse); } @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { MCRSessionMgr.unlock(); MCRSession requestSession = (MCRSession) requestContext.getProperty(ATTR); if (responseContext.hasEntity()) { responseContext.setEntityStream(new ProxyOutputStream(responseContext.getEntityStream()) { @Override public void close() throws IOException { LOGGER.debug("Closing EntityStream"); try { super.close(); } finally { releaseSessionIfNeeded(requestSession); LOGGER.debug("Closing EntityStream done"); } } }); } else { LOGGER.debug("No Entity in response, closing MCRSession"); releaseSessionIfNeeded(requestSession); } } private static void releaseSessionIfNeeded(MCRSession requestSession) { if (MCRSessionMgr.hasCurrentSession()) { MCRSession currentSession = MCRSessionMgr.getCurrentSession(); try { if (MCRTransactionHelper.isTransactionActive()) { LOGGER.debug("Active MCRSession and JPA-Transaction found. Clearing up"); if (MCRTransactionHelper.transactionRequiresRollback()) { MCRTransactionHelper.rollbackTransaction(); } else { MCRTransactionHelper.commitTransaction(); } } else { LOGGER.debug("Active MCRSession found. Clearing up"); } } finally { MCRSessionMgr.releaseCurrentSession(); if (!currentSession.equals(requestSession)) { LOGGER.warn("Found orphaned MCRSession. Closing {} ", currentSession); currentSession.close(); //is not bound to HttpSession } LOGGER.debug("Session released."); } } } }
4,657
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSessionLockFilter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/filter/MCRSessionLockFilter.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.jersey.filter; import org.mycore.common.MCRSessionMgr; import jakarta.annotation.Priority; import jakarta.ws.rs.Priorities; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerRequestFilter; /** * Opposite of {@link MCRSessionHookFilter}. */ @Priority(Priorities.AUTHENTICATION - 1) public class MCRSessionLockFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) { MCRSessionMgr.lock(); } }
1,276
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCacheFilter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/filter/MCRCacheFilter.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.jersey.filter; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.apache.http.HttpStatus; import org.apache.logging.log4j.LogManager; import org.mycore.frontend.jersey.MCRCacheControl; import org.mycore.frontend.jersey.access.MCRRequestScopeACL; import jakarta.ws.rs.HttpMethod; import jakarta.ws.rs.Produces; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerResponseContext; import jakarta.ws.rs.container.ContainerResponseFilter; import jakarta.ws.rs.container.ResourceInfo; import jakarta.ws.rs.core.CacheControl; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.ext.RuntimeDelegate; public class MCRCacheFilter implements ContainerResponseFilter { private static final RuntimeDelegate.HeaderDelegate<CacheControl> HEADER_DELEGATE = RuntimeDelegate.getInstance() .createHeaderDelegate(CacheControl.class); @Context private ResourceInfo resourceInfo; private CacheControl getCacheConrol(MCRCacheControl cacheControlAnnotation) { CacheControl cc = new CacheControl(); if (cacheControlAnnotation != null) { cc.setMaxAge( (int) cacheControlAnnotation.maxAge().unit().toSeconds(cacheControlAnnotation.maxAge().time())); cc.setSMaxAge( (int) cacheControlAnnotation.sMaxAge().unit().toSeconds(cacheControlAnnotation.sMaxAge().time())); Optional.ofNullable(cacheControlAnnotation.private_()) .filter(MCRCacheControl.FieldArgument::active) .map(MCRCacheControl.FieldArgument::fields) .map(Stream::of) .ifPresent(s -> { cc.setPrivate(true); cc.getPrivateFields().addAll(s.collect(Collectors.toList())); }); if (cacheControlAnnotation.public_()) { cc.getCacheExtension().put("public", null); } cc.setNoTransform(cacheControlAnnotation.noTransform()); cc.setNoStore(cacheControlAnnotation.noStore()); Optional.ofNullable(cacheControlAnnotation.noCache()) .filter(MCRCacheControl.FieldArgument::active) .map(MCRCacheControl.FieldArgument::fields) .map(Stream::of) .ifPresent(s -> { cc.setNoCache(true); cc.getNoCacheFields().addAll(s.collect(Collectors.toList())); }); cc.setMustRevalidate(cacheControlAnnotation.mustRevalidate()); cc.setProxyRevalidate(cacheControlAnnotation.proxyRevalidate()); } else { cc.setNoTransform(false); //should have been default } return cc; } @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { CacheControl cc; String currentCacheControl = requestContext.getHeaderString(HttpHeaders.CACHE_CONTROL); if (currentCacheControl != null) { if (responseContext.getHeaderString(HttpHeaders.AUTHORIZATION) == null) { return; } cc = RuntimeDelegate.getInstance() .createHeaderDelegate(CacheControl.class) .fromString(currentCacheControl); } else { //from https://developer.mozilla.org/en-US/docs/Glossary/cacheable if (!requestContext.getMethod().equals(HttpMethod.GET) && !requestContext.getMethod().equals(HttpMethod.HEAD)) { return; } boolean statusCacheable = IntStream .of(HttpStatus.SC_OK, HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION, HttpStatus.SC_NO_CONTENT, HttpStatus.SC_PARTIAL_CONTENT, HttpStatus.SC_MULTIPLE_CHOICES, HttpStatus.SC_MOVED_PERMANENTLY, HttpStatus.SC_NOT_FOUND, HttpStatus.SC_METHOD_NOT_ALLOWED, HttpStatus.SC_GONE, HttpStatus.SC_REQUEST_URI_TOO_LONG, HttpStatus.SC_NOT_IMPLEMENTED) .anyMatch(i -> i == responseContext.getStatus()); if (!statusCacheable) { return; } cc = getCacheConrol(resourceInfo.getResourceMethod().getAnnotation(MCRCacheControl.class)); } MCRRequestScopeACL aclProvider = MCRRequestScopeACL.getInstance(requestContext); if (aclProvider.isPrivate()) { cc.setPrivate(true); cc.getPrivateFields().clear(); } boolean isPrivate = cc.isPrivate() && cc.getPrivateFields().isEmpty(); boolean isNoCache = cc.isNoCache() && cc.getNoCacheFields().isEmpty(); if (responseContext.getHeaderString(HttpHeaders.AUTHORIZATION) != null) { addAuthorizationHeaderException(cc, isPrivate, isNoCache); } String headerValue = HEADER_DELEGATE.toString(cc); LogManager.getLogger() .debug(() -> "Cache-Control filter: " + requestContext.getUriInfo().getPath() + " " + headerValue); responseContext.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, headerValue); if (Stream.of(resourceInfo.getResourceClass(), resourceInfo.getResourceMethod()) .map(t -> t.getAnnotation(Produces.class)) .filter(Objects::nonNull) .map(Produces::value) .flatMap(Stream::of) .distinct() .count() > 1) { //resource may produce differenct MediaTypes, we have to set Vary header List<String> varyHeaders = Optional.ofNullable(responseContext.getHeaderString(HttpHeaders.VARY)) .map(Object::toString) .map(s -> s.split(",")) .map(Stream::of) .orElseGet(Stream::empty) .collect(Collectors.toList()); if (!varyHeaders.contains(HttpHeaders.ACCEPT)) { varyHeaders.add(HttpHeaders.ACCEPT); } responseContext.getHeaders().putSingle(HttpHeaders.VARY, varyHeaders.stream().collect(Collectors.joining(","))); } } private void addAuthorizationHeaderException(CacheControl cc, boolean isPrivate, boolean isNoCache) { cc.setPrivate(true); if (!cc.getPrivateFields().contains(HttpHeaders.AUTHORIZATION) && !isPrivate) { cc.getPrivateFields().add(HttpHeaders.AUTHORIZATION); } cc.setNoCache(true); if (!cc.getNoCacheFields().contains(HttpHeaders.AUTHORIZATION) && !isNoCache) { cc.getNoCacheFields().add(HttpHeaders.AUTHORIZATION); } } }
7,509
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDBTransactionFilter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/filter/MCRDBTransactionFilter.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.jersey.filter; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRTransactionHelper; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerRequestFilter; import jakarta.ws.rs.container.ContainerResponseContext; import jakarta.ws.rs.container.ContainerResponseFilter; public class MCRDBTransactionFilter implements ContainerRequestFilter, ContainerResponseFilter { @Override public void filter(ContainerRequestContext request, ContainerResponseContext response) { MCRSession session = MCRSessionMgr.getCurrentSession(); if (MCRTransactionHelper.transactionRequiresRollback()) { MCRTransactionHelper.rollbackTransaction(); } else { MCRTransactionHelper.commitTransaction(); } } @Override public void filter(ContainerRequestContext request) { MCRSessionMgr.getCurrentSession(); MCRTransactionHelper.beginTransaction(); } }
1,773
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/frontend/jersey/filter/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/>. */ /** * @author Thomas Scheffler (yagee) * Classes for managing access permissions */ package org.mycore.frontend.jersey.filter.access;
864
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRResourceAccessCheckerFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/filter/access/MCRResourceAccessCheckerFactory.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.jersey.filter.access; import java.util.concurrent.ConcurrentHashMap; /** * @author Thomas Scheffler (yagee) * */ public class MCRResourceAccessCheckerFactory { private static ConcurrentHashMap<Class<? extends MCRResourceAccessChecker>, MCRResourceAccessChecker> implMap; static { //static block as code style requires 120 character line width implMap = new ConcurrentHashMap<>(); } public static <T extends MCRResourceAccessChecker> T getInstance(Class<T> clazz) throws ReflectiveOperationException { @SuppressWarnings("unchecked") T accessChecker = (T) implMap.get(clazz); if (accessChecker != null) { return accessChecker; } accessChecker = clazz.getDeclaredConstructor().newInstance(); implMap.put(clazz, accessChecker); return accessChecker; } }
1,624
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRResourceAccessFilter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/filter/access/MCRResourceAccessFilter.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.jersey.filter.access; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; import jakarta.annotation.Priority; import jakarta.ws.rs.Priorities; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerRequestFilter; import jakarta.ws.rs.core.Response; /** * @author Thomas Scheffler (yagee) * */ @Priority(Priorities.AUTHORIZATION) public class MCRResourceAccessFilter implements ContainerRequestFilter { private MCRResourceAccessChecker accessChecker; public MCRResourceAccessFilter(MCRResourceAccessChecker accessChecker) { this.accessChecker = accessChecker; } @Override public void filter(ContainerRequestContext requestContext) { // TODO due to ContainerRequest.getEntity() consumes InputStream, we need to keep a copy of it in memory try (InputStream in = requestContext.getEntityStream()) { ByteArrayOutputStream out = new ByteArrayOutputStream(64 * 1024); IOUtils.copy(in, out); byte[] entity = out.toByteArray(); //restore input requestContext.setEntityStream(new ByteArrayInputStream(entity)); boolean hasPermission = accessChecker.isPermitted(requestContext); if (!hasPermission) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } //restore input requestContext.setEntityStream(new ByteArrayInputStream(entity)); } catch (IOException e) { throw new WebApplicationException(e); } } }
2,491
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRResourceAccessChecker.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/filter/access/MCRResourceAccessChecker.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.jersey.filter.access; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Scanner; import jakarta.ws.rs.container.ContainerRequestContext; /** * @author Thomas Scheffler (yagee) * */ public interface MCRResourceAccessChecker { boolean isPermitted(ContainerRequestContext request); /** * http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string?answertab=votes#tab-top * * @param is the inputstream to read * @return the string */ default String convertStreamToString(InputStream is) { try (Scanner s = new Scanner(is, StandardCharsets.UTF_8)) { s.useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } } }
1,516
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRestrictedAccess.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/filter/access/MCRRestrictedAccess.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.jersey.filter.access; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Thomas Scheffler (yagee) * */ @Inherited @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface MCRRestrictedAccess { Class<? extends MCRResourceAccessChecker> value(); }
1,221
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/frontend/jersey/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/>. */ /** * @author Thomas Scheffler (yagee) * Classes for access permission checks */ package org.mycore.frontend.jersey.access;
854
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRequestScopeACL.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/access/MCRRequestScopeACL.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.jersey.access; import java.util.Objects; import java.util.function.Supplier; import org.mycore.access.MCRAccessInterface; import org.mycore.common.MCRUserInformation; import jakarta.ws.rs.container.ContainerRequestContext; public interface MCRRequestScopeACL extends MCRAccessInterface { boolean isPrivate(); static MCRRequestScopeACL getInstance(ContainerRequestContext requestContext) { Object property = requestContext.getProperty(MCRRequestScopeACLFilter.ACL_INSTANT_KEY); Objects.requireNonNull(property, "Please register " + MCRRequestScopeACLFilter.class); if (property instanceof Supplier) { @SuppressWarnings("unchecked") MCRRequestScopeACL requestScopeACL = ((Supplier<MCRRequestScopeACL>) property).get(); requestContext.setProperty(MCRRequestScopeACLFilter.ACL_INSTANT_KEY, requestScopeACL); property = requestScopeACL; } return (MCRRequestScopeACL) property; } default boolean checkPermissionForUser(String permission, MCRUserInformation userInfo) { throw new UnsupportedOperationException(); } default boolean checkPermission(String id, String permission, MCRUserInformation userInfo) { throw new UnsupportedOperationException(); } }
2,044
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRequireLogin.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/access/MCRRequireLogin.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.jersey.access; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRSystemUserInformation; import org.mycore.frontend.jersey.filter.access.MCRResourceAccessChecker; import jakarta.ws.rs.container.ContainerRequestContext; /** * @author Thomas Scheffler (yagee) * */ public class MCRRequireLogin implements MCRResourceAccessChecker { /** * Returns true if and only if the current user is logged in. */ @Override public boolean isPermitted(ContainerRequestContext request) { if (MCRSessionMgr.hasCurrentSession()) { return !MCRSessionMgr.getCurrentSession().getUserInformation().getUserID().equals( MCRSystemUserInformation.getGuestInstance().getUserID()); } return false; } }
1,530
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRequestScopeACLFilter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/access/MCRRequestScopeACLFilter.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.jersey.access; import java.util.function.Supplier; import jakarta.annotation.Priority; import jakarta.ws.rs.Priorities; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerRequestFilter; @Priority(Priorities.AUTHENTICATION - 1) public class MCRRequestScopeACLFilter implements ContainerRequestFilter { public static String ACL_INSTANT_KEY = "requestScopeACL"; private static final MCRRequestScopeACLFactory ACL_FACTORY = new MCRRequestScopeACLFactory(); @Override public void filter(ContainerRequestContext requestContext) { requestContext.setProperty(ACL_INSTANT_KEY, (Supplier<MCRRequestScopeACL>) ACL_FACTORY::provide); } }
1,459
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRequestScopeACLFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/jersey/access/MCRRequestScopeACLFactory.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.jersey.access; import org.apache.logging.log4j.LogManager; import org.glassfish.hk2.api.Factory; import org.mycore.access.MCRAccessManager; import org.mycore.common.MCRSystemUserInformation; public class MCRRequestScopeACLFactory implements Factory<MCRRequestScopeACL> { @Override public void dispose(MCRRequestScopeACL mcrRequestScopeACL) { LogManager.getLogger().debug("Disposed..."); } @Override public MCRRequestScopeACL provide() { return new MCRRequestScopeACLImpl(); } private static class MCRRequestScopeACLImpl implements MCRRequestScopeACL { public static final MCRSystemUserInformation GUEST = MCRSystemUserInformation.getGuestInstance(); private boolean isPrivate; MCRRequestScopeACLImpl() { LogManager.getLogger().debug("Constructor called"); this.isPrivate = false; } @Override public boolean checkPermission(String privilege) { if (!isPrivate()) { MCRAccessManager.checkPermission(GUEST, () -> MCRAccessManager.checkPermission(privilege)) .thenAccept(b -> { if (!b) { isPrivate = true; //not for guest user } }).join(); } if (isPrivate()) { return MCRAccessManager.checkPermission(privilege); } return true; } @Override public boolean checkPermission(String id, String permission) { if (!isPrivate()) { MCRAccessManager.checkPermission(GUEST, () -> MCRAccessManager.checkPermission(id, permission)) .thenAccept(b -> { if (!b) { isPrivate = true; LogManager.getLogger().debug("response is private"); } }).join(); } if (isPrivate()) { return MCRAccessManager.checkPermission(id, permission); } return true; } @Override public boolean isPrivate() { LogManager.getLogger().debug("isPrivate={}", isPrivate); return isPrivate; } } }
3,052
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRExportCollection.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/export/MCRExportCollection.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.export; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.Namespace; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.xml.MCRURIResolver; import org.mycore.frontend.basket.MCRBasket; import org.mycore.frontend.basket.MCRBasketEntry; import org.mycore.frontend.basket.MCRBasketXMLBuilder; /** * Represents a collection of XML data to export. * XML can be added by URI or by JDOM Element, * or the contents of a complete MCRBasket can be added. * The collected XML data is wrapped by a root element * thats name and namespace can be set. * * @author Frank Lützenkirchen */ public class MCRExportCollection { /** The collection to export */ private Element collection; private static MCRBasketXMLBuilder basketBuilder = new MCRBasketXMLBuilder(true); public MCRExportCollection() { collection = new Element("exportCollection"); new Document(collection); } /** Sets the name and namespace of the root element that wraps the collected data */ public void setRootElement(String elementName, String namespaceURI) { collection.setName(elementName); if ((namespaceURI != null) && (!namespaceURI.isEmpty())) { collection.setNamespace(Namespace.getNamespace(namespaceURI)); } } /** * Adds the contents of the given basket. */ public void add(MCRBasket basketOfMODS) { for (MCRBasketEntry entry : basketOfMODS) { collection.addContent(basketBuilder.buildXML(entry)); } } /** * Adds XML data from the given URI. */ public void add(String uri) { add(MCRURIResolver.instance().resolve(uri)); } /** * Adds the given XML element, making a clone. */ public void add(Element element) { collection.addContent(element.clone()); } /** * Returns the collected XML data as MCRJDOMContent. */ public MCRJDOMContent getContent() { return new MCRJDOMContent(collection.getDocument()); } }
2,808
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRExportServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/export/MCRExportServlet.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.export; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.content.MCRContent; import org.mycore.common.content.transformer.MCRContentTransformer; import org.mycore.frontend.basket.MCRBasket; import org.mycore.frontend.basket.MCRBasketManager; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import jakarta.servlet.http.HttpServletRequest; /** * Provides functionality to export content. * The content to export can be selected by specifying one or more * URIs to read from, or by giving the ID of a basket to export. * The selected content is collected as MCRExportCollection thats * root element name can be specified. * The content is then transformed using an MCRContentTransformer instance * and forwarded to the requesting client. * * Request Parameters: * uri=... * can be repeated to include content from one or more URIs to read XML from * basket=... * the ID of a basket to read XML from * root=... * optional, name of the root element that wraps the selected content * ns=... * optional, URI of the namespace of the root element * transformer=... * the ID of the transformer to use to export the selected content. * * @see MCRExportCollection * @see MCRContentTransformer * * @author Frank Lützenkirchen */ public class MCRExportServlet extends MCRServlet { private static final long serialVersionUID = 1L; private static final Logger LOGGER = LogManager.getLogger(MCRExportServlet.class); /** URIs beginning with these prefixes are forbidden for security reasons */ private static final String[] FORBIDDEN_URIS = { "file", "webapp", "resource" }; @Override public void doGetPost(MCRServletJob job) throws Exception { MCRExportCollection collection = createCollection(job.getRequest()); fillCollection(job.getRequest(), collection); MCRContent content2export = collection.getContent(); String filename = getProperty(job.getRequest(), "filename"); if (filename == null) { filename = "export-" + System.currentTimeMillis(); } job.getResponse().setHeader("Content-Disposition", "inline;filename=\"" + filename + "\""); String transformerID = job.getRequest().getParameter("transformer"); job.getRequest().setAttribute("XSL.Transformer", transformerID); getLayoutService().doLayout(job.getRequest(), job.getResponse(), content2export); } /** * Fills the collection with the XML data requested by URIs or basket ID. */ private void fillCollection(HttpServletRequest req, MCRExportCollection collection) { String basketID = req.getParameter("basket"); if (basketID != null) { MCRBasket basket = MCRBasketManager.getOrCreateBasketInSession(basketID); collection.add(basket); LOGGER.info("exporting basket {} via {}", basketID, req.getParameter("transformer")); } if (req.getParameter("uri") != null) { for (String uri : req.getParameterValues("uri")) { if (isAllowed(uri)) { collection.add(uri); LOGGER.info("exporting {} via {}", uri, req.getParameter("transformer")); } } } } private boolean isAllowed(String uri) { for (String prefix : FORBIDDEN_URIS) { if (uri.startsWith(prefix)) { LOGGER.warn("URI {} is not allowed for security reasons", uri); return false; } } return true; } /** * Creates a new, empty MCRExportCollection, optionally with the requested root element name and namespace. */ private MCRExportCollection createCollection(HttpServletRequest req) { MCRExportCollection collection = new MCRExportCollection(); String root = req.getParameter("root"); String ns = req.getParameter("ns"); if (!((root == null) || root.isEmpty())) { collection.setRootElement(root, ns); } return collection; } }
4,949
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/frontend/support/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 Thomas Scheffler (yagee) * */ package org.mycore.frontend.support;
811
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRLogin.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/support/MCRLogin.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.support; import java.util.ArrayList; import java.util.List; import org.mycore.common.MCRSystemUserInformation; import org.mycore.common.MCRUserInformation; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; @XmlRootElement(name = "login") @XmlType(name = "base-login") @XmlAccessorType(XmlAccessType.FIELD) public class MCRLogin { @XmlAttribute(required = true) protected String user; @XmlAttribute(required = true) protected boolean guest; @XmlElement protected Form form; public MCRLogin() { super(); } public MCRLogin(MCRUserInformation userInformation, String formAction) { this(); this.user = userInformation.getUserID(); this.guest = userInformation == MCRSystemUserInformation.getGuestInstance(); this.form = new Form(formAction); } public static JAXBContext getContext() throws JAXBException { return JAXBContext.newInstance(MCRLogin.class); } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public boolean isGuest() { return guest; } public void setGuest(boolean guest) { this.guest = guest; } public Form getForm() { return form; } public void setForm(Form form) { this.form = form; } @XmlType @XmlAccessorType(XmlAccessType.FIELD) public static class Form { @XmlAttribute String action; @XmlElement List<InputField> input; public Form() { input = new ArrayList<>(); } public Form(String formAction) { this(); action = formAction; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public List<InputField> getInput() { return input; } public void setInput(List<InputField> input) { this.input = input; } } @XmlType @XmlAccessorType(XmlAccessType.FIELD) public static class InputField { @XmlAttribute String name; @XmlAttribute String value; @XmlAttribute String label; @XmlAttribute String placeholder; @XmlAttribute boolean isPassword; @XmlAttribute boolean isHidden; public InputField() { } public InputField(String name, String value, String label, String placeholder, boolean isPassword, boolean isHidden) { this(); this.name = name; this.value = value; this.label = label; this.placeholder = placeholder; this.isPassword = isPassword; this.isHidden = isHidden; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getPlaceholder() { return placeholder; } public void setPlaceholder(String placeholder) { this.placeholder = placeholder; } public boolean isHidden() { return isHidden; } public void setHidden(boolean isHidden) { this.isHidden = isHidden; } public boolean isPassword() { return isPassword; } public void setPassword(boolean isPassword) { this.isPassword = isPassword; } } }
4,987
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAutoDeploy.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/support/MCRAutoDeploy.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.support; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.jar.JarFile; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.Namespace; import org.jdom2.input.SAXBuilder; import org.mycore.common.config.MCRComponent; import org.mycore.common.config.MCRRuntimeComponentDetector; import org.mycore.common.events.MCRStartupHandler; import jakarta.servlet.DispatcherType; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletRegistration; /** * This StartupHandler deploys web resources and register filters/servlets to web container server, * for with <code>MCR-Auto-Deploy = true</code> marked JARs. * * @author René Adler (eagle) * */ public class MCRAutoDeploy implements MCRStartupHandler.AutoExecutable { private static final Logger LOGGER = LogManager.getLogger(MCRAutoDeploy.class); private static final String HANDLER_NAME = MCRAutoDeploy.class.getName(); private static final String AUTO_DEPLOY_ATTRIB = "MCR-Auto-Deploy"; private static final String RESOURCE_DIR = "META-INF/resources"; private static final String WEB_FRAGMENT = "META-INF/web-fragment.xml"; @Override public String getName() { return HANDLER_NAME; } @Override public int getPriority() { return 2000; } @Override public void startUp(final ServletContext servletContext) { if (servletContext != null) { MCRRuntimeComponentDetector.getAllComponents().stream() .filter(cmp -> Boolean.parseBoolean(cmp.getManifestMainAttribute(AUTO_DEPLOY_ATTRIB))) .forEach(cmp -> { registerWebFragment(servletContext, cmp); deployWebResources(servletContext, cmp); }); } } private Path toNativePath(ZipEntry entry) { String nativePath; if (File.separatorChar != '/') { nativePath = entry.getName().replace('/', File.separatorChar); } else { nativePath = entry.getName(); } return Paths.get(nativePath); } private boolean isUnzipRequired(ZipEntry entry, Path target) { try { BasicFileAttributes fileAttributes = Files.readAttributes(target, BasicFileAttributes.class); //entry does not contain size when read by ZipInputStream, assume equal size and just compare last modified return !entry.isDirectory() && !(fileTimeEquals(entry.getLastModifiedTime(), fileAttributes.lastModifiedTime()) && (entry.getSize() == -1 || entry.getSize() == fileAttributes.size())); } catch (IOException e) { LOGGER.warn("Target path {} does not exist.", target); return true; } } /** * compares if two file times are equal. * * Uses seconds only instead of finer granularity to compare file times of different file systems. */ private boolean fileTimeEquals(FileTime a, FileTime b) { return a.to(TimeUnit.SECONDS) == b.to(TimeUnit.SECONDS) && a.to(TimeUnit.DAYS) == b.to(TimeUnit.DAYS); } private void deployWebResources(final ServletContext servletContext, final MCRComponent comp) { final Path webRoot = Optional.ofNullable(servletContext.getRealPath("/")).map(Paths::get).orElse(null); if (webRoot != null) { int resourceDirPathComponents = RESOURCE_DIR.split("/").length; try (InputStream fin = Files.newInputStream(comp.getJarFile().toPath()); ZipInputStream zin = new ZipInputStream(fin)) { LOGGER.info("Deploy web resources from {} to {}...", comp.getName(), webRoot); for (ZipEntry zipEntry = zin.getNextEntry(); zipEntry != null; zipEntry = zin.getNextEntry()) { if (zipEntry.getName().startsWith(RESOURCE_DIR)) { Path relativePath = toNativePath(zipEntry); if (relativePath.getNameCount() > resourceDirPathComponents) { //strip RESOURCE_DIR: relativePath = relativePath.subpath(resourceDirPathComponents, relativePath.getNameCount()); Path target = webRoot.resolve(relativePath); if (zipEntry.isDirectory()) { Files.createDirectories(target); } else if (isUnzipRequired(zipEntry, target)) { LOGGER.debug("...deploy {}", zipEntry.getName()); Files.copy(zin, target, StandardCopyOption.REPLACE_EXISTING); Files.setLastModifiedTime(target, zipEntry.getLastModifiedTime()); } } } } LOGGER.info("...done."); } catch (final IOException e) { LOGGER.error("Could not deploy web resources of " + comp.getJarFile() + "!", e); } } } private void registerWebFragment(final ServletContext servletContext, final MCRComponent comp) { if (!isHandledByServletContainer(servletContext, comp)) { try { final JarFile jar = new JarFile(comp.getJarFile()); Collections.list(jar.entries()).stream() .filter(file -> file.getName().equals(WEB_FRAGMENT)) .findFirst().ifPresent(file -> { final SAXBuilder builder = new SAXBuilder(); try { final InputStream is = jar.getInputStream(file); final Document doc = builder.build(is); final Element root = doc.getRootElement(); final Namespace ns = root.getNamespace(); final List<Element> filters = root.getChildren("filter", ns); final List<Element> fmaps = root.getChildren("filter-mapping", ns); filters.forEach(filter -> { final String name = filter.getChildText("filter-name", ns); final String className = filter.getChildText("filter-class", ns); fmaps.stream().filter(mapping -> mapping.getChildText("filter-name", ns).equals(name)) .findFirst().ifPresent(mapping -> { LOGGER.info("Register Filter {} ({})...", name, className); Optional.ofNullable(servletContext.addFilter(name, className)) .<Runnable>map(fr -> () -> { final List<Element> dispatchers = mapping .getChildren("dispatcher", ns); final EnumSet<DispatcherType> eDT = dispatchers.isEmpty() ? null : dispatchers.stream() .map(d -> DispatcherType.valueOf(d.getTextTrim())) .collect(Collectors .toCollection(() -> EnumSet.noneOf(DispatcherType.class))); final List<Element> servletNames = mapping .getChildren("servlet-name", ns); if (!servletNames.isEmpty()) { fr.addMappingForServletNames( eDT, false, servletNames.stream() .map(sn -> { LOGGER.info("...add servlet mapping: {}", sn.getTextTrim()); return sn.getTextTrim(); }) .toArray(String[]::new)); } final List<Element> urlPattern = mapping .getChildren("url-pattern", ns); if (!urlPattern.isEmpty()) { fr.addMappingForUrlPatterns(eDT, false, urlPattern.stream() .map(url -> { LOGGER.info("...add url mapping: {}", url.getTextTrim()); return url.getTextTrim(); }) .toArray(String[]::new)); } }).orElse(() -> LOGGER.warn("Filter {} already registered!", name)) .run(); }); }); final List<Element> servlets = root.getChildren("servlet", ns); final List<Element> smaps = root.getChildren("servlet-mapping", ns); servlets.forEach(servlet -> { final String name = servlet.getChildText("servlet-name", ns); final String className = servlet.getChildText("servlet-class", ns); smaps.stream() .filter(mapping -> mapping.getChildText("servlet-name", ns).equals(name)) .findFirst() .ifPresent(mapping -> { LOGGER.info("Register Servlet {} ({})...", name, className); ServletRegistration.Dynamic sr = servletContext.addServlet(name, className); if (sr != null) { mapping.getChildren("url-pattern", ns).forEach(url -> { LOGGER.info("...add url mapping: {}", url.getTextTrim()); sr.addMapping(url.getTextTrim()); }); servlet.getChildren("init-param", ns).forEach(param -> { LOGGER.info("...add init-param: {}", param.getTextTrim()); String paramName = param.getChildText("param-name", ns); String paramValue = param.getChildText("param-value", ns); sr.setInitParameter(paramName, paramValue); }); } else { LOGGER.warn("Servlet {} already registered!", name); } }); }); } catch (IOException | JDOMException e) { LOGGER.error("Couldn't parse " + WEB_FRAGMENT, e); } }); jar.close(); } catch (final IOException e) { LOGGER.error("Couldn't parse JAR!", e); } } } @SuppressWarnings("unchecked") private boolean isHandledByServletContainer(ServletContext servletContext, MCRComponent comp) { List<String> orderedLibs = (List<String>) servletContext.getAttribute(ServletContext.ORDERED_LIBS); return orderedLibs.stream().anyMatch(s -> s.equals(comp.getJarFile().getName())); } }
13,955
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRObjectIDLockTable.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/support/MCRObjectIDLockTable.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.support; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; 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 org.mycore.datamodel.metadata.MCRObjectID; public class MCRObjectIDLockTable implements MCRSessionListener { private static final MCRObjectIDLockTable SINGLETON = new MCRObjectIDLockTable(); private static Logger LOGGER = LogManager.getLogger(MCRObjectIDLockTable.class); private ConcurrentMap<MCRObjectID, MCRSession> lockMap; private static MCRObjectIDLockTable getInstance() { return SINGLETON; } private MCRObjectIDLockTable() { this.lockMap = new ConcurrentHashMap<>(); MCRSessionMgr.addSessionListener(this); } public void clearTable(MCRSession session) { for (MCRObjectID objectID : lockMap.keySet()) { lockMap.remove(objectID, session); } } public static void unlock(MCRObjectID objectId) { getInstance().lockMap.remove(objectId); } public static void lock(MCRObjectID objectId) { getInstance().lockMap.putIfAbsent(objectId, MCRSessionMgr.getCurrentSession()); } public static boolean isLockedByCurrentSession(MCRObjectID objectId) { MCRSession session = MCRSessionMgr.getCurrentSession(); return session.equals(getInstance().lockMap.get(objectId)); } public static MCRSession getLocker(MCRObjectID objectId) { return getInstance().lockMap.get(objectId); } @Override public void sessionEvent(MCRSessionEvent event) { switch (event.getType()) { case destroyed -> clearTable(event.getSession()); default -> LOGGER.debug("Skipping event: {}", event.getType()); } } public static boolean isLockedByCurrentSession(String objectId) { MCRObjectID objId = MCRObjectID.getInstance(objectId); return MCRObjectIDLockTable.isLockedByCurrentSession(objId); } public static String getLockingUserName(String objectId) { MCRObjectID objId = MCRObjectID.getInstance(objectId); MCRSession locker = MCRObjectIDLockTable.getLocker(objId); if (locker == null) { return null; } return locker.getUserInformation().getUserID(); } }
3,251
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSecureTokenV2.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/support/MCRSecureTokenV2.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.support; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Base64; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; /** * An implementation of SecureToken V2 used by "Wowza Streaming Engine". * <p> * A description of the algorithm: * </p> * <ol> * <li>A string is constructed by combining <code>contentPath</code>,'?' and all <strong>alphabetically sorted</strong> * parameters consisting of <code>ipAddress</code>, <code>sharedSecret</code> and any <code>queryParameters</code></li> * <li>Generate an <code>SHA-256</code> hash of that string builded in step 1 and {@link StandardCharsets#UTF_8}.</li> * <li>Generate a {@link Base64} encoded string of the digest of step 2.</li> * <li>replace <code>'+'</code> by <code>'-'</code> and <code>'/'</code> by <code>'_'</code> to make it a safe parameter * value.</li> * </ol> * * @author Thomas Scheffler (yagee) * @see <a href="https://mycore.atlassian.net/browse/MCR-1058">JIRA Ticket MCR-1058</a> */ public class MCRSecureTokenV2 { private String contentPath, ipAddress, sharedSecret, hash; private String[] queryParameters; public MCRSecureTokenV2(String contentPath, String ipAddress, String sharedSecret, String... queryParameters) { this.contentPath = Objects.requireNonNull(contentPath, "'contentPath' may not be null"); this.ipAddress = Objects.requireNonNull(ipAddress, "'ipAddress' may not be null"); this.sharedSecret = Objects.requireNonNull(sharedSecret, "'sharedSecret' may not be null"); this.queryParameters = queryParameters; try { this.contentPath = new URI(null, null, this.contentPath, null).getRawPath(); } catch (URISyntaxException e) { throw new RuntimeException(e); } buildHash(); } private void buildHash() { String forHashing = Stream.concat(Stream.of(ipAddress, sharedSecret), Arrays.stream(queryParameters).filter(Objects::nonNull)) //case of HttpServletRequest.getQueryString()==null .sorted() .collect(Collectors.joining("&", contentPath + "?", "")); MessageDigest digest; try { digest = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e);//should never happen for 'SHA-256' } digest.update(URI.create(forHashing).toASCIIString().getBytes(StandardCharsets.US_ASCII)); byte[] sha256 = digest.digest(); hash = Base64.getEncoder() .encodeToString(sha256) .chars() .map(x -> switch (x) { case '+' -> '-'; case '/' -> '_'; default -> x; }) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); } public String getHash() { return hash; } /** * Same as calling {@link #toURI(String, String, String)} with <code>suffix=""</code>. */ public URI toURI(String baseURL, String hashParameterName) throws URISyntaxException { return toURI(baseURL, "", hashParameterName); } /** * Constructs an URL by using all information from the * {@link MCRSecureTokenV2#MCRSecureTokenV2(String, String, String, String...) constructor} except * <code>ipAddress</code> and <code>sharedSecret</code> and the supplied parameters. * * @param baseURL * a valid and absolute base URL * @param suffix * is appended to the <code>contentPath</code> * @param hashParameterName * the name of the query parameter that holds the hash value * @return an absolute URL consisting of all elements as stated above and <code>queryParameters</code> in the * <strong>given order</strong> appended by the hash parameter and the hash value from {@link #getHash()}. * @throws URISyntaxException if baseURL is not a valid URI */ public URI toURI(String baseURL, String suffix, String hashParameterName) throws URISyntaxException { Objects.requireNonNull(suffix, "'suffix' may not be null"); Objects.requireNonNull(hashParameterName, "'hashParameterName' may not be null"); if (hashParameterName.isEmpty()) { throw new IllegalArgumentException("'hashParameterName' may not be empty"); } URI context = new URI(baseURL); return context.resolve(Stream .concat(Arrays.stream(queryParameters).filter(Objects::nonNull), Stream.of(hashParameterName + "=" + hash)) .collect(Collectors.joining("&", baseURL + contentPath + suffix + "?", ""))); } @Override public int hashCode() { return getHash().hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } MCRSecureTokenV2 other = (MCRSecureTokenV2) obj; if (!hash.equals(other.hash)) { return false; } if (!contentPath.equals(other.contentPath)) { return false; } if (!ipAddress.equals(other.ipAddress)) { return false; } if (!sharedSecret.equals(other.sharedSecret)) { return false; } return Arrays.equals(queryParameters, other.queryParameters); } }
6,494
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDerivateServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRDerivateServlet.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.servlets; import static org.mycore.access.MCRAccessManager.PERMISSION_DELETE; import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE; import java.io.IOException; import java.nio.file.Files; import java.util.Locale; import java.util.Objects; import org.mycore.access.MCRAccessException; import org.mycore.access.MCRAccessManager; import org.mycore.common.MCRException; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetaIFS; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter; import org.mycore.frontend.fileupload.MCRUploadHelper; import org.mycore.services.i18n.MCRTranslation; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author Sebastian Hofmann; Silvio Hermann; Thomas Scheffler (yagee); Sebastian Röher */ public class MCRDerivateServlet extends MCRServlet { private static final long serialVersionUID = 1L; public static final String TODO_SMOVFILE = "smovfile"; @Override protected void doGetPost(MCRServletJob job) throws Exception { HttpServletRequest request = job.getRequest(); HttpServletResponse response = job.getResponse(); checkPreConditions(request, response); if (response.isCommitted()) { return; } String derivateId = getProperty(request, "derivateid"); if (performTask(job, getProperty(request, "todo"), derivateId, getProperty(request, "file"), getProperty(request, "file2"))) { String url = request.getParameter("url"); if ((Objects.equals(url, ""))) { response.sendError(HttpServletResponse.SC_NO_CONTENT, "Parameter 'url' is set but empty!"); return; } if (url != null) { response.sendRedirect(response.encodeRedirectURL(url)); return; } toReferrer(request, response, response.encodeRedirectURL(getServletBaseURL() + "MCRFileNodeServlet/" + derivateId + "/")); } } protected void checkPreConditions(HttpServletRequest request, HttpServletResponse response) throws IOException { if (getProperty(request, "todo") == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter \"todo\" is not provided"); } else if (getProperty(request, "derivateid") == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter \"derivateid\" is not provided"); } else if (getProperty(request, "file") == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter \"file\" is not provided"); } else if (getProperty(request, "todo").equals(TODO_SMOVFILE) && getProperty(request, "file2") == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter \"file2\" is not provided"); } } private boolean performTask(MCRServletJob job, String task, String myCoreDerivateId, String file, String file2) throws IOException, MCRAccessException { switch (task) { case "ssetfile" -> setMainFile(myCoreDerivateId, file, job.getResponse()); case "sdelfile" -> deleteFile(myCoreDerivateId, file, job.getResponse()); case TODO_SMOVFILE -> moveFile(myCoreDerivateId, file, file2, job.getResponse()); default -> job.getResponse() .sendError(HttpServletResponse.SC_BAD_REQUEST, String.format(Locale.ENGLISH, "The task \"%s\" is not supported.", task)); } return !job.getResponse().isCommitted(); } /** * The method set the main file of a derivate object that is stored in the * server. The method use the input parameter: <b>type</b>,<b>step</b> * <b>se_mcrid</b> and <b>re_mcrid</b>. Access rights must be 'writedb'. */ private void setMainFile(String derivateId, String file, HttpServletResponse response) throws IOException, MCRAccessException { if (MCRAccessManager.checkPermission(derivateId, PERMISSION_WRITE)) { MCRObjectID mcrid = MCRObjectID.getInstance(derivateId); MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(mcrid); der.getDerivate().getInternals().setMainDoc(file); MCRMetadataManager.update(der); } else { response.sendError(HttpServletResponse.SC_FORBIDDEN, String.format(Locale.ENGLISH, "User has not the \"" + PERMISSION_WRITE + "\" permission on object %s.", derivateId)); } } /** * The method delete a file from a derivate object that is stored in the * server. The method use the input parameter: <b>type</b>,<b>step</b> * <b>se_mcrid</b> and <b>re_mcrid</b>. Access rights must be 'deletedb'. */ private void deleteFile(String derivateId, String file, HttpServletResponse response) throws IOException { if (MCRAccessManager.checkPermission(derivateId, PERMISSION_DELETE)) { MCRPath pathToFile = MCRPath.getPath(derivateId, file); if (!Files.isDirectory(pathToFile)) { Files.delete(pathToFile); } else { Files.walkFileTree(pathToFile, MCRRecursiveDeleter.instance()); } } else { response.sendError(HttpServletResponse.SC_FORBIDDEN, String.format(Locale.ENGLISH, "User has not the \"" + PERMISSION_DELETE + "\" permission on object %s.", derivateId)); } } private void moveFile(String derivateIdStr, String file, String target, HttpServletResponse response) throws IOException { if (!MCRAccessManager.checkPermission(derivateIdStr, PERMISSION_DELETE)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, String.format(Locale.ENGLISH, "User has not the \"%s\" permission on object %s.", PERMISSION_DELETE, derivateIdStr)); return; } if (!MCRAccessManager.checkPermission(derivateIdStr, PERMISSION_WRITE)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, String.format(Locale.ENGLISH, "User has not the \"%s\" permission on object %s.", PERMISSION_WRITE, derivateIdStr)); return; } MCRPath pathFrom = MCRPath.getPath(derivateIdStr, file); MCRPath pathTo = MCRPath.getPath(derivateIdStr, target); if (Files.exists(pathTo)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format(Locale.ENGLISH, "The File %s already exists!", pathTo)); return; } if (Files.isDirectory(pathFrom)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format(Locale.ENGLISH, "Renaming directory %s is not supported!", pathFrom)); return; } try { MCRUploadHelper.checkPathName(pathTo.getRoot().relativize(pathTo).toString(), true); } catch (MCRException ex) { String translatedMessage = MCRTranslation.translate("IFS.invalid.fileName", pathTo.getOwnerRelativePath()); response.sendError(HttpServletResponse.SC_BAD_REQUEST, translatedMessage); return; } boolean updateMainFile = false; MCRObjectID derivateId = MCRObjectID.getInstance(derivateIdStr); // check if the main file is moved, need to be done before the move, // because the main file gets lost after the move. updateMainFile = isMainFileUpdateRequired(pathFrom, derivateId); // this should always be a MCRPath, if not then ClassCastException is okay MCRPath resultingFile = (MCRPath) Files.move(pathFrom, pathTo); if (updateMainFile) { setMainFile(derivateId, resultingFile); } } private void setMainFile(MCRObjectID derivateId, MCRPath resultingFile) { // read derivate again, because it was changed by Files.move // (The maindoc gets removed, because the file does not exist anymore) MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateId); MCRMetaIFS internals = derivate.getDerivate().getInternals(); internals.setMainDoc(resultingFile.getOwnerRelativePath()); try { MCRMetadataManager.update(derivate); } catch (MCRAccessException e) { throw new MCRException("Error while updating main file", e); } } private boolean isMainFileUpdateRequired(MCRPath pathFrom, MCRObjectID derivateId) { if (MCRMetadataManager.exists(derivateId)) { MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateId); MCRMetaIFS internals = derivate.getDerivate().getInternals(); String mainDoc = internals.getMainDoc(); // the getOwnerRelativePath() method returns with a leading slash, but the mainDoc not. return mainDoc != null && mainDoc.equals(pathFrom.getOwnerRelativePath().substring(1)); } return false; } }
10,014
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRQRCodeServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRQRCodeServlet.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.servlets; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.content.MCRContent; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.tools.MCRPNGTools; import com.google.zxing.BarcodeFormat; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author Thomas Scheffler(yagee) * */ public class MCRQRCodeServlet extends MCRContentServlet { private static final long serialVersionUID = 1L; private static final long CACHE_TIME = TimeUnit.SECONDS.convert(1000L, TimeUnit.DAYS); private static final Logger LOGGER = LogManager.getLogger(MCRQRCodeServlet.class); private static final Pattern REQUEST_PATTERN = Pattern.compile("/(\\d*)/(.*)"); private MCRPNGTools pngTools; @Override public void init() throws ServletException { super.init(); this.pngTools = new MCRPNGTools(); } @Override public void destroy() { super.destroy(); try { this.pngTools.close(); } catch (Exception e) { LOGGER.error("Error while closing PNG tools.", e); } } @Override public MCRContent getContent(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { String pathInfo = req.getPathInfo(); Matcher matcher = REQUEST_PATTERN.matcher(pathInfo); if (!matcher.matches()) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Path info does not comply to " + REQUEST_PATTERN + ": " + pathInfo); return null; } int size = Integer.parseInt(matcher.group(1)); String relativeURL = matcher.group(2); String queryString = req.getQueryString(); String url = MCRFrontendUtil.getBaseURL() + relativeURL; if (queryString != null) { url += '?' + queryString; } LOGGER.info("Generating QR CODE: {}", url); MCRContent content = getPNGContent(url, size); content.setLastModified(0); if (!"HEAD".equals(req.getMethod())) { MCRFrontendUtil.writeCacheHeaders(resp, CACHE_TIME, 0, true); } return content; } private MCRContent getPNGContent(final String url, final int size) throws IOException { QRCodeWriter writer = new QRCodeWriter(); BitMatrix matrix; try { matrix = writer.encode(url, BarcodeFormat.QR_CODE, size, size); } catch (WriterException e) { throw new IOException(e); } BufferedImage image = toBufferedImage(matrix); return pngTools.toPNGContent(image); } public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY); int onColor = Color.BLACK.getRGB(); int offColor = Color.WHITE.getRGB(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) ? onColor : offColor); } } return image; } }
4,360
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRLogoutServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRLogoutServlet.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.servlets; import java.io.IOException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; /** * Invalidates a session and sends redirect to referring page. * * @author Thomas Scheffler (yagee) */ public class MCRLogoutServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String LOGOUT_REDIRECT_URL_PARAMETER = "url"; private static final Logger LOGGER = LogManager.getLogger(MCRLogoutServlet.class); /* (non-Javadoc) * @see jakarta.servlet.http.HttpServlet#doGet(jakarta.servlet.http.HttpServletRequest, jakarta.servlet.http.HttpServletResponse) */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getUserPrincipal() != null) { req.logout(); } HttpSession session = req.getSession(false); if (session != null) { LOGGER.debug("Invalidate HTTP-Session: {}", session.getId()); session.invalidate(); } String returnURL = getReturnURL(req); LOGGER.debug("Redirect to: {}", returnURL); resp.sendRedirect(returnURL); } static String getReturnURL(HttpServletRequest req) { String returnURL = req.getParameter(LOGOUT_REDIRECT_URL_PARAMETER); if (returnURL == null) { String referer = req.getHeader("Referer"); returnURL = (referer != null) ? referer : req.getContextPath() + "/"; } return returnURL; } }
2,545
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRServletJob.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRServletJob.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.servlets; import java.net.InetAddress; import org.mycore.common.config.MCRConfigurationException; import org.mycore.frontend.MCRFrontendUtil; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * This class simply is a container for objects needed during a Servlet session * like the HttpServletRequest and HttpServeltResponse. The class provids only * get-methods to return the objects set while constructing the job object. * * @author Detlev Degenhardt */ public class MCRServletJob { /** The HttpServletRequest object */ private HttpServletRequest theRequest = null; /** The HttpServletResponse object */ private HttpServletResponse theResponse = null; /** * The constructor takes the given objects and stores them in private * objects. * * @param theRequest * the HttpServletRequest object for this servlet job * @param theResponse * the HttpServletResponse object for this servlet job */ public MCRServletJob(HttpServletRequest theRequest, HttpServletResponse theResponse) { this.theRequest = theRequest; this.theResponse = theResponse; } /** returns the HttpServletRequest object */ public HttpServletRequest getRequest() { return theRequest; } /** returns the HttpServletResponse object */ public HttpServletResponse getResponse() { return theResponse; } /** returns true if the current http request was issued from the local host * */ public boolean isLocal() { try { String serverName = theRequest.getServerName(); String serverIP = InetAddress.getByName(serverName).getHostAddress(); String remoteIP = MCRFrontendUtil.getRemoteAddr(theRequest); return remoteIP.equals(serverIP) || remoteIP.equals("127.0.0.1"); } catch (Exception ex) { String msg = "Exception while testing if http request was from local host"; throw new MCRConfigurationException(msg, ex); } } }
2,851
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRObjectServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRObjectServlet.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.servlets; import static org.mycore.access.MCRAccessManager.PERMISSION_HISTORY_READ; import static org.mycore.access.MCRAccessManager.PERMISSION_READ; import java.io.IOException; import javax.xml.transform.TransformerException; import org.mycore.access.MCRAccessManager; import org.mycore.common.MCRException; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.content.MCRContent; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.xml.sax.SAXException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Serves a given MCROBject. * <em>.../receive/{MCRObjectID}</em> * * @author Thomas Scheffler (yagee) */ public class MCRObjectServlet extends MCRContentServlet { private static final long serialVersionUID = 1L; private static final int REV_CURRENT = 0; private static final String I18N_ERROR_PREFIX = "component.base.error"; private MCRXMLMetadataManager metadataManager = null; @Override public void init() throws ServletException { super.init(); metadataManager = MCRXMLMetadataManager.instance(); } @Override public MCRContent getContent(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final MCRObjectID mcrid = getMCRObjectID(req, resp); if (mcrid == null) { return null; } if (!MCRAccessManager.checkPermission(mcrid, PERMISSION_READ)) { // check read permission for ID final MCRSession currentSession = MCRSessionMgr.getCurrentSession(); resp.sendError( HttpServletResponse.SC_UNAUTHORIZED, getErrorI18N(I18N_ERROR_PREFIX, "accessDenied", mcrid.toString(), currentSession.getUserInformation() .getUserID(), currentSession.getCurrentIP())); return null; } String rev = null; final String revision = getProperty(req, "r"); if (revision != null) { rev = revision; } MCRContent localObject = (rev == null) ? requestLocalObject(mcrid, resp) : requestVersionedObject(mcrid, resp, rev); if (localObject == null) { return null; } try { return getLayoutService().getTransformedContent(req, resp, localObject); } catch (TransformerException | SAXException e) { throw new IOException(e); } } private MCRContent requestLocalObject(MCRObjectID mcrid, final HttpServletResponse resp) throws IOException { if (MCRMetadataManager.exists(mcrid)) { return metadataManager.retrieveContent(mcrid); } resp.sendError(HttpServletResponse.SC_NOT_FOUND, getErrorI18N(I18N_ERROR_PREFIX, "notFound", mcrid)); return null; } private MCRContent requestVersionedObject(final MCRObjectID mcrid, final HttpServletResponse resp, final String rev) throws IOException { if (!MCRAccessManager.checkPermission(mcrid, PERMISSION_HISTORY_READ)) { final MCRSession currentSession = MCRSessionMgr.getCurrentSession(); resp.sendError( HttpServletResponse.SC_UNAUTHORIZED, getErrorI18N(I18N_ERROR_PREFIX, "accessToVersionDenied", mcrid.toString(), rev, currentSession.getUserInformation().getUserID(), currentSession.getCurrentIP())); return null; } MCRXMLMetadataManager xmlMetadataManager = MCRXMLMetadataManager.instance(); if (xmlMetadataManager.listRevisions(mcrid) != null) { MCRContent content = xmlMetadataManager.retrieveContent(mcrid, rev); if (content != null) { return content; } resp.sendError(HttpServletResponse.SC_NOT_FOUND, getErrorI18N(I18N_ERROR_PREFIX, "revisionNotFound", rev, mcrid)); return null; } resp.sendError(HttpServletResponse.SC_BAD_REQUEST, getErrorI18N(I18N_ERROR_PREFIX, "noVersions", mcrid)); return null; } private MCRObjectID getMCRObjectID(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final String pathInfo = req.getPathInfo(); final String id = pathInfo == null ? null : pathInfo.substring(1); MCRObjectID mcrid = null; if (id != null) { try { mcrid = MCRObjectID.getInstance(id); // create Object with given ID, only ID syntax check performed } catch (final MCRException e) { // handle exception: invalid ID syntax, set HTTP error 400 "Invalid request" resp.sendError(HttpServletResponse.SC_BAD_REQUEST, getErrorI18N(I18N_ERROR_PREFIX, "invalidID", id)); return null; // sorry, no object to return } } return mcrid; } }
5,848
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRLockServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRLockServlet.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.servlets; import java.net.URI; import java.util.Map; import java.util.Set; 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.MCRSystemUserInformation; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.frontend.support.MCRObjectIDLockTable; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author Thomas Scheffler (yagee) * */ public class MCRLockServlet extends MCRServlet { private static final long serialVersionUID = 1L; private static final String OBJECT_ID_KEY = MCRLockServlet.class.getCanonicalName() + ".MCRObjectID"; private static final String ACTION_KEY = MCRLockServlet.class.getCanonicalName() + ".Action"; enum Action { lock, unlock } private static final Logger LOGGER = LogManager.getLogger(MCRLockServlet.class); private static final String PARAM_ACTION = "action"; private static final String PARAM_OBJECTID = "id"; private static final String PARAM_REDIRECT = "url"; @Override protected void think(MCRServletJob job) throws Exception { if (MCRSessionMgr.getCurrentSession().getUserInformation() .equals(MCRSystemUserInformation.getGuestInstance())) { job.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN); return; } String urlValue = getProperty(job.getRequest(), PARAM_REDIRECT); if (urlValue == null) { LOGGER.debug("Redirect URL is undefined, trying referrer."); URI referer = getReferer(job.getRequest()); urlValue = referer == null ? null : referer.toString(); } if (urlValue == null) { job.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST, "You must provide parameter: " + PARAM_REDIRECT); return; } String actionValue = getProperty(job.getRequest(), PARAM_ACTION); String idValue = getProperty(job.getRequest(), PARAM_OBJECTID); if (idValue == null) { job.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST, "You must provide parameter: " + PARAM_OBJECTID); return; } Action action = null; try { action = actionValue != null ? Action.valueOf(actionValue) : Action.lock; } catch (IllegalArgumentException e) { job.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported value for parameter " + PARAM_ACTION + ": " + actionValue); return; } MCRObjectID objectID = MCRObjectID.getInstance(idValue); switch (action) { case lock -> MCRObjectIDLockTable.lock(objectID); case unlock -> MCRObjectIDLockTable.unlock(objectID); } job.getRequest().setAttribute(OBJECT_ID_KEY, objectID); job.getRequest().setAttribute(ACTION_KEY, action); } @Override protected void render(MCRServletJob job, Exception ex) throws Exception { if (job.getResponse().isCommitted()) { LOGGER.info("Response allready committed"); return; } if (ex != null) { throw ex; } HttpServletRequest req = job.getRequest(); MCRObjectID objectId = (MCRObjectID) job.getRequest().getAttribute(OBJECT_ID_KEY); Action action = (Action) job.getRequest().getAttribute(ACTION_KEY); MCRSession lockingSession = MCRObjectIDLockTable.getLocker(objectId); if (MCRObjectIDLockTable.isLockedByCurrentSession(objectId) || action == Action.unlock) { String url = getProperty(job.getRequest(), PARAM_REDIRECT); if (url.startsWith("/")) { url = req.getContextPath() + url; } url = addQueryParameter(url, req); job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(url)); } else { String errorI18N = getErrorI18N("error", "lockedBy", objectId.toString(), lockingSession .getUserInformation().getUserID()); job.getResponse().sendError(HttpServletResponse.SC_CONFLICT, errorI18N); } } private String addQueryParameter(String url, HttpServletRequest req) { boolean hasQueryParameter = url.indexOf('?') != -1; StringBuilder sb = new StringBuilder(url); Set<Map.Entry<String, String[]>> entrySet = req.getParameterMap().entrySet(); for (Map.Entry<String, String[]> parameter : entrySet) { if (!(parameter.getKey().equals(PARAM_REDIRECT) || parameter.getKey().equals(PARAM_ACTION) || url .contains(parameter.getKey() + "="))) { for (String value : parameter.getValue()) { if (hasQueryParameter) { sb.append('&'); } else { sb.append('?'); hasQueryParameter = true; } sb.append(parameter.getKey()); sb.append('='); sb.append(value); } } } return sb.toString(); } }
6,074
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRErrorServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRErrorServlet.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.servlets; import java.io.IOException; import java.util.Enumeration; import java.util.Locale; import java.util.Objects; import javax.xml.transform.TransformerException; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.DocType; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.Namespace; import org.mycore.common.MCRException; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRTransactionHelper; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.xml.MCRLayoutService; import org.mycore.frontend.MCRFrontendUtil; import org.xml.sax.SAXException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; /** * @author Thomas Scheffler (yagee) * */ public class MCRErrorServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static Logger LOGGER = LogManager.getLogger(MCRErrorServlet.class); private static MCRLayoutService LAYOUT_SERVICE = MCRLayoutService.instance(); /* (non-Javadoc) * @see jakarta.servlet.http.HttpServlet#service(jakarta.servlet.http.HttpServletRequest, jakarta.servlet.http.HttpServletResponse) */ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Retrieve the possible error attributes, some may be null Integer statusCode = (Integer) req.getAttribute("jakarta.servlet.error.status_code"); String message = (String) req.getAttribute("jakarta.servlet.error.message"); @SuppressWarnings("unchecked") Class<? extends Throwable> exceptionType = (Class<? extends Throwable>) req .getAttribute("jakarta.servlet.error.exception_type"); Throwable exception = (Throwable) req.getAttribute("jakarta.servlet.error.exception"); String requestURI = (String) req.getAttribute("jakarta.servlet.error.request_uri"); String servletName = (String) req.getAttribute("jakarta.servlet.error.servletName"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Handling error {} for request ''{}'' message: {}", statusCode, requestURI, message); LOGGER.debug("Has current session: {}", MCRSessionMgr.hasCurrentSession()); } if (acceptWebPage(req)) { try { generateErrorPage(req, resp, message, exception, statusCode, exceptionType, requestURI, servletName); } catch (TransformerException | SAXException e) { LOGGER.error("Could not generate error page", e); resp.sendError(statusCode, message); } } else { LOGGER.info("Client does not accept HTML pages: {}", req.getHeader("Accept")); resp.sendError(statusCode, message); } } /** * Returns true if Accept header allows sending html pages */ private boolean acceptWebPage(HttpServletRequest req) { Enumeration<String> acceptHeader = req.getHeaders("Accept"); if (!acceptHeader.hasMoreElements()) { return true; } while (acceptHeader.hasMoreElements()) { String[] acceptValues = acceptHeader.nextElement().split(","); for (String acceptValue : acceptValues) { String[] parsed = acceptValue.split(";"); String mediaRange = parsed[0].trim(); if (mediaRange.startsWith("text/html") || mediaRange.startsWith("text/*") || mediaRange.startsWith("*/")) { float quality = 1f; //default 'q=1.0' for (int i = 1; i < parsed.length; i++) { if (parsed[i].trim().startsWith("q=")) { String qualityValue = parsed[i].trim().substring(2).trim(); quality = Float.parseFloat(qualityValue); } } if (quality > 0.5) { //firefox 18 accepts every media type when requesting images with 0.5 // but closes stream immediately when detecting text/html return true; } } } } return false; } private boolean setCurrentSession(HttpServletRequest req) { MCRSession session = getMCRSession(req); if (session != null && !MCRSessionMgr.hasCurrentSession()) { MCRSessionMgr.setCurrentSession(session); } return session != null; } private MCRSession getMCRSession(HttpServletRequest req) { HttpSession session = req.getSession(false); if (session == null) { return null; } return MCRServlet.getSession(req); } private void setWebAppBaseURL(MCRSession session, HttpServletRequest request) { if (request.getAttribute(MCRFrontendUtil.BASE_URL_ATTRIBUTE) != null) { session.put(MCRFrontendUtil.BASE_URL_ATTRIBUTE, request.getAttribute(MCRFrontendUtil.BASE_URL_ATTRIBUTE)); } } /** * Builds a jdom document containing the error parameter. * * @param msg the message of the error * @param statusCode the http status code * @param requestURI the uri of the request * @param exceptionType type of the exception * @param source source of the error * @param ex exception which is occured * * @return jdom document containing all error parameter */ public static Document buildErrorPage(String msg, Integer statusCode, String requestURI, Class<? extends Throwable> exceptionType, String source, Throwable ex) { String rootname = MCRConfiguration2.getString("MCR.Frontend.ErrorPage").orElse("mcr_error"); Element root = new Element(rootname); root.setAttribute("errorServlet", Boolean.TRUE.toString()); root.setAttribute("space", "preserve", Namespace.XML_NAMESPACE); if (msg != null) { root.setText(msg); } if (statusCode != null) { root.setAttribute("HttpError", statusCode.toString()); } if (requestURI != null) { root.setAttribute("requestURI", requestURI); } if (exceptionType != null) { root.setAttribute("exceptionType", exceptionType.getName()); } if (source != null) { root.setAttribute("source", source); } while (ex != null) { Element exception = new Element("exception"); exception.setAttribute("type", ex.getClass().getName()); Element trace = new Element("trace"); Element message = new Element("message"); trace.setText(MCRException.getStackTraceAsString(ex)); message.setText(ex.getMessage()); exception.addContent(message).addContent(trace); root.addContent(exception); ex = ex.getCause(); } return new Document(root, new DocType(rootname)); } protected void generateErrorPage(HttpServletRequest request, HttpServletResponse response, String msg, Throwable ex, Integer statusCode, Class<? extends Throwable> exceptionType, String requestURI, String servletName) throws IOException, TransformerException, SAXException { boolean exceptionThrown = ex != null; LOGGER.log(exceptionThrown ? Level.ERROR : Level.WARN, String.format(Locale.ENGLISH, "%s: Error %d occured. The following message was given: %s", requestURI, statusCode, msg), ex); String style = MCRFrontendUtil .getProperty(request, "XSL.Style") .filter("xml"::equals) .orElse("default"); request.setAttribute("XSL.Style", style); Document errorDoc = buildErrorPage(msg, statusCode, requestURI, exceptionType, servletName, ex); final String requestAttr = "MCRErrorServlet.generateErrorPage"; if (!response.isCommitted() && request.getAttribute(requestAttr) == null) { response.setStatus(Objects.requireNonNullElse(statusCode, HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); request.setAttribute(requestAttr, msg); boolean currentSessionActive = MCRSessionMgr.hasCurrentSession(); boolean sessionFromRequest = setCurrentSession(request); MCRSession session = null; try { MCRSessionMgr.unlock(); session = MCRSessionMgr.getCurrentSession(); boolean openTransaction = MCRTransactionHelper.isTransactionActive(); if (!openTransaction) { MCRTransactionHelper.beginTransaction(); } try { setWebAppBaseURL(session, request); LAYOUT_SERVICE.doLayout(request, response, new MCRJDOMContent(errorDoc)); } finally { if (!openTransaction) { MCRTransactionHelper.commitTransaction(); } } } finally { if (exceptionThrown || !currentSessionActive) { MCRSessionMgr.releaseCurrentSession(); } if (!sessionFromRequest) { //new session created for transaction session.close(); } } } else { if (request.getAttribute(requestAttr) != null) { LOGGER.warn("Could not send error page. Generating error page failed. The original message:\n{}", request.getAttribute(requestAttr)); } else { LOGGER.warn( "Could not send error page. Response allready commited. The following message was given:\n{}", msg); } } } }
10,885
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDerivateContentTransformerServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRDerivateContentTransformerServlet.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.servlets; import java.io.IOException; import java.nio.file.Files; import java.nio.file.attribute.FileTime; import javax.xml.transform.TransformerException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRPathContent; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.frontend.MCRFrontendUtil; import org.xml.sax.SAXException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * This servlet transforms and delivers xml content from a derivate. * usage: <code>servlet/derivate_id/path/to/file.xml</code> * * @author mcrshofm */ public class MCRDerivateContentTransformerServlet extends MCRContentServlet { private static final long serialVersionUID = 1L; private static final int CACHE_TIME = 24 * 60 * 60; private static final Logger LOGGER = LogManager.getLogger(MCRDerivateContentTransformerServlet.class); @Override public MCRContent getContent(HttpServletRequest req, HttpServletResponse resp) throws IOException { String pathInfo = req.getPathInfo(); if (pathInfo.startsWith("/")) { pathInfo = pathInfo.substring(1); } String[] pathTokens = pathInfo.split("/"); String derivate = pathTokens[0]; String path = pathInfo.substring(derivate.length()); LOGGER.debug("Derivate : {}", derivate); LOGGER.debug("Path : {}", path); MCRPath mcrPath = MCRPath.getPath(derivate, path); MCRContent pc = new MCRPathContent(mcrPath); FileTime lastModifiedTime = Files.getLastModifiedTime(mcrPath); MCRFrontendUtil.writeCacheHeaders(resp, CACHE_TIME, lastModifiedTime.toMillis(), true); try { return getLayoutService().getTransformedContent(req, resp, pc); } catch (TransformerException | SAXException e) { throw new IOException("could not transform content", e); } } }
2,793
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRContainerLoginServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRContainerLoginServlet.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.servlets; import java.security.Principal; 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.MCRSystemUserInformation; import org.mycore.common.MCRUserInformation; import org.mycore.frontend.MCRFrontendUtil; import jakarta.servlet.http.HttpServletRequest; /** * @author Thomas Scheffler (yagee) * */ public class MCRContainerLoginServlet extends MCRServlet { private static final long serialVersionUID = 1L; private static final Logger LOGGER = LogManager.getLogger(MCRContainerLoginServlet.class); /* (non-Javadoc) * @see org.mycore.frontend.servlets.MCRServlet#think(org.mycore.frontend.servlets.MCRServletJob) */ @Override protected void think(MCRServletJob job) throws Exception { MCRSession session = MCRSessionMgr.getCurrentSession(); session.setUserInformation(new ContainerUserInformation(session)); LOGGER.info("Logged in: {}", session.getUserInformation().getUserID()); } /* (non-Javadoc) * @see org.mycore.frontend.servlets.MCRServlet#render(org.mycore.frontend.servlets.MCRServletJob, java.lang.Exception) */ @Override protected void render(MCRServletJob job, Exception ex) throws Exception { String backToUrl = getProperty(job.getRequest(), "url"); if (backToUrl == null) { String referer = job.getRequest().getHeader("Referer"); backToUrl = (referer != null) ? referer : MCRFrontendUtil.getBaseURL(); } job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(backToUrl)); } protected static class ContainerUserInformation implements MCRUserInformation { protected MCRSession session; String lastUser; public ContainerUserInformation(MCRSession session) { this.session = session; } @Override public String getUserID() { lastUser = getCurrentRequest() .flatMap(r -> Optional.ofNullable(r.getUserPrincipal())) .map(Principal::getName) .orElseGet(() -> Optional.ofNullable(lastUser) .orElseGet(MCRSystemUserInformation.getGuestInstance()::getUserID)); return lastUser; } @Override public boolean isUserInRole(String role) { return getCurrentRequest().map(r -> r.isUserInRole(role)).orElse(Boolean.FALSE); } @Override public String getUserAttribute(String attribute) { return null; } protected Optional<HttpServletRequest> getCurrentRequest() { LogManager.getLogger(getClass()).debug("Getting request from session: {}", session.getID()); return MCRFrontendUtil.getCurrentServletJob() .map(MCRServletJob::getRequest); } } }
3,716
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRConfigHelperServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRConfigHelperServlet.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.servlets; import java.io.IOException; import java.io.StringWriter; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import com.google.gson.Gson; import com.google.gson.JsonObject; import jakarta.servlet.ServletException; import jakarta.servlet.ServletOutputStream; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Servlet to map the properties defined in the init param "Properties" to a JSON object with the property name as key * and the property value as value. The properties in the init param need to be comma separated and can end with * to * match all properties which start with the string before *. */ public class MCRConfigHelperServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static final String PROPERTIES_INIT_PARAM = "Properties"; private Date lastChange; private String resultJson; @Override public void init() throws ServletException { super.init(); updateJSON(); MCRConfiguration2.addPropertyChangeEventLister((changedProperty) -> { String propertiesParameter = getPropertiesParameter(); for (String property : propertiesParameter.split(",")) { if (property.endsWith("*")) { String prefix = property.substring(0, property.length() - 1); if (changedProperty.startsWith(prefix)) { return true; } } else { if (property.equals(changedProperty)) { return true; } } } return false; }, (property, before, after) -> { try { updateJSON(); } catch (ServletException e) { throw new MCRException(e); } }); } private void updateJSON() throws ServletException { lastChange = new Date(); try { resultJson = createResultJson(); } catch (IOException e) { throw new ServletException(e); } } private String createResultJson() throws IOException { Map<String, String> propertiesMap = new LinkedHashMap<>(); String properties = getPropertiesParameter(); for (String property : properties.split(",")) { if (property.endsWith("*")) { String prefix = property.substring(0, property.length() - 1); MCRConfiguration2.getSubPropertiesMap(prefix) .forEach((key, value) -> propertiesMap.put(prefix + key, value)); } else { MCRConfiguration2.getString(property).ifPresent((p) -> propertiesMap.put(property, p)); } } JsonObject obj = new JsonObject(); propertiesMap.forEach(obj::addProperty); try (StringWriter sw = new StringWriter()) { new Gson().toJson(obj, sw); return sw.toString(); } } private String getPropertiesParameter() { String properties = getInitParameter(PROPERTIES_INIT_PARAM); if (properties == null) { throw new MCRConfigurationException( "The Servlet does not have the init Parameter '" + PROPERTIES_INIT_PARAM + "'"); } return properties; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setHeader("Cache-Control", "public"); resp.setHeader("Cache-Control", "max-age=120"); if (req.getDateHeader("If-Modified-Since") > lastChange.getTime()) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { resp.setDateHeader("Last-Modified", lastChange.getTime()); try (ServletOutputStream os = resp.getOutputStream()) { os.print(resultJson); } } } @Override protected long getLastModified(HttpServletRequest request) { return this.lastChange.getTime(); } }
5,062
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRContainerLoginFormServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRContainerLoginFormServlet.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.servlets; import java.util.Arrays; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRUserInformation; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJAXBContent; import org.mycore.frontend.support.MCRLogin; import org.mycore.services.i18n.MCRTranslation; /** * @author Thomas Scheffler (yagee) * */ public class MCRContainerLoginFormServlet extends MCRServlet { private static final long serialVersionUID = 1L; private static final String LOGIN_ATTR = MCRContainerLoginFormServlet.class.getCanonicalName(); /* (non-Javadoc) * @see org.mycore.frontend.servlets.MCRServlet#think(org.mycore.frontend.servlets.MCRServletJob) */ @Override protected void think(MCRServletJob job) throws Exception { MCRSession mcrSession = MCRSessionMgr.getCurrentSession(); MCRUserInformation userInformation = mcrSession.getUserInformation(); MCRLogin login = new MCRLogin(userInformation, getFormAction()); login.getForm().getInput().addAll(Arrays.asList(getUserNameField(), getPasswordField())); job.getRequest().setAttribute(LOGIN_ATTR, new MCRJAXBContent<>(MCRLogin.getContext(), login)); } private String getFormAction() { return "j_security_check"; } private MCRLogin.InputField getUserNameField() { String userNameText = MCRTranslation.translate("component.user2.login.form.userName"); return new MCRLogin.InputField("j_username", null, userNameText, userNameText, false, false); } private MCRLogin.InputField getPasswordField() { String passwordText = MCRTranslation.translate("component.user2.login.form.password"); return new MCRLogin.InputField("j_password", null, passwordText, passwordText, true, false); } /* (non-Javadoc) * @see org.mycore.frontend.servlets.MCRServlet#render(org.mycore.frontend.servlets.MCRServletJob, java.lang.Exception) */ @Override protected void render(MCRServletJob job, Exception ex) throws Exception { if (ex != null) { throw ex; } MCRContent source = (MCRContent) job.getRequest().getAttribute(LOGIN_ATTR); getLayoutService().doLayout(job.getRequest(), job.getResponse(), source); } }
3,072
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDerivateLinkServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRDerivateLinkServlet.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.servlets; import java.util.Collection; import java.util.Map; import org.jdom2.Element; import org.mycore.common.content.MCRJDOMContent; import org.mycore.datamodel.common.MCRLinkTableManager; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.frontend.MCRFrontendUtil; /** * This servlet is used to display all parents of an mycore object and their * containing derivates. It returns a xml document which will be transformed * by derivateLinks-parentList.xsl. * * @author Matthias Eichner */ public class MCRDerivateLinkServlet extends MCRServlet { private static final long serialVersionUID = 1L; protected static String derivateLinkErrorPage = "error_derivatelink.xml"; @Override protected void doGetPost(MCRServletJob job) throws Exception { Map<String, String[]> pMap = job.getRequest().getParameterMap(); String webpage = pMap.get("subselect.webpage")[0]; String mcrId = getSubParameterValueOfBrowserAddressParameter(webpage, "mcrid"); String parentId = getSubParameterValueOfBrowserAddressParameter(webpage, "parentID"); // create a new root element Element rootElement = new Element("derivateLinks-parentList"); MCRObjectID objId = MCRObjectID.getInstance(mcrId); if (MCRMetadataManager.exists(objId)) { /* mcr object exists in datastore -> add all parent with their * derivates to the jdom tree */ addParentsToElement(rootElement, objId); } else if (parentId != null && MCRMetadataManager.exists(MCRObjectID.getInstance(parentId))) { /* mcr object doesnt exists in datastore -> use the parent id * to create the content */ Element firstParent = getMyCoReObjectElement(MCRObjectID.getInstance(parentId)); if (firstParent != null) { rootElement.addContent(firstParent); } addParentsToElement(rootElement, MCRObjectID.getInstance(parentId)); } // check if root element has content -> if not, show an error page if (rootElement.getContentSize() == 0) { job.getResponse().sendRedirect( job.getResponse().encodeRedirectURL(MCRFrontendUtil.getBaseURL() + derivateLinkErrorPage)); return; } // set some important attributes to the root element rootElement.setAttribute("session", pMap.get("subselect.session")[0]); rootElement.setAttribute("varpath", pMap.get("subselect.varpath")[0]); rootElement.setAttribute("webpage", webpage); // transform & display the generated xml document getLayoutService().doLayout(job.getRequest(), job.getResponse(), new MCRJDOMContent(rootElement)); } /** * This method adds all parents and their derivates * iterative to the given element. * * @param toElement the element where the parents and derivates will be added * @param objId the source object id */ private void addParentsToElement(Element toElement, MCRObjectID objId) { MCRObjectID pId = objId; while ((pId = getParentId(pId)) != null) { Element parentElement = getMyCoReObjectElement(pId); if (parentElement != null) { toElement.addContent(parentElement); } } } /** * Returns the parent object id of an mcr object. * * @param objectId from which id * @return the parent id */ private MCRObjectID getParentId(MCRObjectID objectId) { MCRObject obj = MCRMetadataManager.retrieveMCRObject(objectId); return obj.getStructure().getParentID(); } /** * Creates a new mcrobject jdom element which contains all * derivates with their ids as children. * * @param objectId id of the mcr object * @return a new jdom element */ private Element getMyCoReObjectElement(MCRObjectID objectId) { Collection<String> derivates = MCRLinkTableManager.instance().getDestinationOf(objectId, "derivate"); if (derivates.size() <= 0) { return null; } Element objElement = new Element("mycoreobject"); objElement.setAttribute("id", objectId.toString()); for (String derivate : derivates) { Element derElement = new Element("derivate"); derElement.setAttribute("id", derivate); objElement.addContent(derElement); } return objElement; } /** * Returns the value of a parameter which is embedded in a parameter * of the browser address. * * @param browserAddressParameter the separated parameter from the browser address * @param subParameter the sub parameter to search * @return the value of the sub parameter */ private String getSubParameterValueOfBrowserAddressParameter(String browserAddressParameter, String subParameter) { String value = null; int index = browserAddressParameter.indexOf(subParameter); if (index != -1) { int startIndex = index + subParameter.length() + 1; int endIndex = browserAddressParameter.indexOf("&", index + 1); if (endIndex == -1) { endIndex = browserAddressParameter.length(); } value = browserAddressParameter.substring(startIndex, endIndex); } return value; } }
6,291
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDisplayHideDerivateServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRDisplayHideDerivateServlet.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.servlets; import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE; 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.mycore.access.MCRAccessManager; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.frontend.MCRFrontendUtil; import jakarta.servlet.http.HttpServletResponse; /** * @author shermann */ public class MCRDisplayHideDerivateServlet extends MCRServlet { private static final long serialVersionUID = 1L; private static final Logger LOGGER = LogManager.getLogger(MCRDisplayHideDerivateServlet.class); @Override protected void doGetPost(MCRServletJob job) throws Exception { String derivate = job.getRequest().getParameter("derivate"); if (derivate == null || (!derivate.contains("_derivate_"))) { LOGGER.error("Cannot toogle display attribute. No derivate id provided."); job.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST, "You must provide a proper derivate id"); return; } if (!MCRAccessManager.checkPermission(MCRObjectID.getInstance(derivate), PERMISSION_WRITE)) { job.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN, "You have to be logged in."); return; } LOGGER.info("Toggling display attribute of {}", derivate); MCRDerivate obj = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(derivate)); toggleDisplay(obj); String url = MCRFrontendUtil.getBaseURL() + "receive/" + getParentHref(obj); job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(url)); } private String getParentHref(MCRDerivate obj) { return obj.getDerivate().getMetaLink().getXLinkHref(); } /** * Toggles the display attribute value of the derivate element. */ private void toggleDisplay(MCRDerivate derObj) throws Exception { Document xml = derObj.createXML(); Element derivateNode = xml.getRootElement().getChild("derivate"); Attribute displayAttr = derivateNode.getAttribute("display"); if (displayAttr == null) { /* the attributs is not existing, user wants to hide derivate */ displayAttr = new Attribute("display", "false"); derivateNode.setAttribute(displayAttr); } else { /* attribute exists, thus toggle the attribute value */ String oldVal = displayAttr.getValue(); String newVal = oldVal.equals(String.valueOf(true)) ? String.valueOf(false) : String.valueOf(true); displayAttr.setValue(newVal); LOGGER.info("Setting display attribute of derivate with id {} to {}", derObj.getId(), newVal); } MCRDerivate updated = new MCRDerivate(xml); MCRMetadataManager.update(updated); } }
3,808
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRServlet.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.servlets; import static org.mycore.frontend.MCRFrontendUtil.BASE_URL_ATTRIBUTE; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.text.MessageFormat; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Enumeration; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Properties; import javax.xml.transform.TransformerException; 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.MCRSessionResolver; import org.mycore.common.MCRTransactionHelper; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationBase; import org.mycore.common.config.MCRConfigurationDirSetup; import org.mycore.common.xml.MCRLayoutService; import org.mycore.common.xsl.MCRErrorListener; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.services.i18n.MCRTranslation; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import jakarta.servlet.ServletConfig; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletException; import jakarta.servlet.UnavailableException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; /** * This is the superclass of all MyCoRe servlets. It provides helper methods for logging and managing the current * session data. Part of the code has been taken from MilessServlet.java written by Frank Lützenkirchen. * * @author Detlev Degenhardt * @author Frank Lützenkirchen * @author Thomas Scheffler (yagee) */ public class MCRServlet extends HttpServlet { public static final String ATTR_MYCORE_SESSION = "mycore.session"; public static final String CURRENT_THREAD_NAME_KEY = "currentThreadName"; public static final String INITIAL_SERVLET_NAME_KEY = "currentServletName"; private static final long serialVersionUID = 1L; private static Logger LOGGER = LogManager.getLogger(); private static String SERVLET_URL; private static final boolean ENABLE_BROWSER_CACHE = MCRConfiguration2.getBoolean("MCR.Servlet.BrowserCache.enable") .orElse(false); private static MCRLayoutService LAYOUT_SERVICE; private static String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin"; public static MCRLayoutService getLayoutService() { return LAYOUT_SERVICE; } @Override public void init() throws ServletException { super.init(); if (LAYOUT_SERVICE == null) { LAYOUT_SERVICE = MCRLayoutService.instance(); } } @Override public void init(ServletConfig config) throws ServletException { super.init(config); String servletName = config.getServletName(); boolean disabled = MCRConfiguration2.getBoolean("MCR.Servlet." + servletName + ".Disabled") .orElse(false); if (disabled) { throw new UnavailableException("Servlet " + servletName + " is disabled in configuration."); } } /** * Returns the servlet base URL of the mycore system **/ public static String getServletBaseURL() { MCRSession session = MCRSessionMgr.getCurrentSession(); Object value = session.get(BASE_URL_ATTRIBUTE); if (value != null) { LOGGER.debug("Returning BaseURL {}servlets/ from user session.", value); return value + "servlets/"; } return SERVLET_URL != null ? SERVLET_URL : MCRFrontendUtil.getBaseURL() + "servlets/"; } /** * Initialisation of the static values for the base URL and servlet URL of the mycore system. */ private static synchronized void prepareBaseURLs(ServletContext context, HttpServletRequest req) { String contextPath = req.getContextPath() + "/"; String requestURL = req.getRequestURL().toString(); int pos = requestURL.indexOf(contextPath, 9); String baseURLofRequest = requestURL.substring(0, pos) + contextPath; prepareBaseURLs(baseURLofRequest); } private static void prepareBaseURLs(String baseURLofRequest) { MCRFrontendUtil.prepareBaseURLs(baseURLofRequest); SERVLET_URL = MCRFrontendUtil.getBaseURL() + "servlets/"; } // The methods doGet() and doPost() simply call the private method // doGetPost(), // i.e. GET- and POST requests are handled by one method only. @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { doGetPost(req, res); } catch (SAXException | TransformerException e) { throwIOException(e); } } private void throwIOException(Exception e) throws IOException { if (e instanceof IOException ioe) { throw ioe; } if (e instanceof TransformerException tfe) { TransformerException te = MCRErrorListener.unwrapException(tfe); String myMessageAndLocation = MCRErrorListener.getMyMessageAndLocation(te); throw new IOException("Error while XSL Transformation: " + myMessageAndLocation, e); } if (e instanceof SAXParseException spe) { String id = spe.getSystemId() != null ? spe.getSystemId() : spe.getPublicId(); int line = spe.getLineNumber(); int column = spe.getColumnNumber(); String msg = new MessageFormat("Error on {0}:{1} while parsing {2}", Locale.ROOT) .format(new Object[] { line, column, id }); throw new IOException(msg, e); } throw new IOException(e); } protected void doGet(MCRServletJob job) throws Exception { doGetPost(job); } @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { doGetPost(req, res); } catch (SAXException | TransformerException e) { throwIOException(e); } } protected void doPost(MCRServletJob job) throws Exception { doGetPost(job); } public static MCRSession getSession(HttpServletRequest req) { boolean reusedSession = req.isRequestedSessionIdValid(); HttpSession theSession = req.getSession(true); if (reusedSession) { LOGGER.debug(() -> "Reused HTTP session: " + theSession.getId() + ", created: " + LocalDateTime .ofInstant(Instant.ofEpochMilli(theSession.getCreationTime()), ZoneId.systemDefault())); } else { LOGGER.info(() -> "Created new HTTP session: " + theSession.getId()); } MCRSession session = null; MCRSession fromHttpSession = Optional .ofNullable((MCRSessionResolver) theSession.getAttribute(ATTR_MYCORE_SESSION)) .flatMap(MCRSessionResolver::resolveSession) .orElse(null); MCRSessionMgr.unlock(); if (fromHttpSession != null && fromHttpSession.getID() != null) { // Take session from HttpSession with servlets session = fromHttpSession; String lastIP = session.getCurrentIP(); String newIP = MCRFrontendUtil.getRemoteAddr(req); try { if (!MCRFrontendUtil.isIPAddrAllowed(lastIP, newIP)) { LOGGER.warn("Session steal attempt from IP {}, previous IP was {}. Session: {}", newIP, lastIP, session); MCRSessionMgr.releaseCurrentSession(); session.close(); //MCR-1409 do not leak old session MCRSessionMgr.unlock();//due to release above session = MCRSessionMgr.getCurrentSession(); session.setCurrentIP(newIP); } } catch (UnknownHostException e) { throw new MCRException("Wrong transformation of IP address for this session.", e); } } else { // Create a new session session = MCRSessionMgr.getCurrentSession(); } // Store current session in HttpSession theSession.setAttribute(ATTR_MYCORE_SESSION, new MCRSessionResolver(session)); // store the HttpSession ID in MCRSession if (session.put("http.session", theSession.getId()) == null) { //first request //for MCRTranslation.getAvailableLanguages() MCRTransactionHelper.beginTransaction(); try { String acceptLanguage = req.getHeader("Accept-Language"); if (acceptLanguage != null) { List<Locale.LanguageRange> languageRanges = Locale.LanguageRange.parse(acceptLanguage); LOGGER.debug("accept languages: {}", languageRanges); MCRSession finalSession = session; Optional .ofNullable(Locale.lookupTag(languageRanges, MCRTranslation.getAvailableLanguages())) .ifPresent(selectedLanguage -> { LOGGER.debug("selected language: {}", selectedLanguage); finalSession.setCurrentLanguage(selectedLanguage); }); } } catch (IllegalArgumentException e) { //from Locale.LanguageRange.parse(...) //error example (found in tomcat logs): "range=no;en-us" //do nothing = same behaviour as with no Accept-Language-Header set } finally { if (MCRTransactionHelper.transactionRequiresRollback()) { MCRTransactionHelper.rollbackTransaction(); } MCRTransactionHelper.commitTransaction(); } } // Forward MCRSessionID to XSL Stylesheets req.setAttribute("XSL.MCRSessionID", session.getID()); return session; } private static void bindSessionToRequest(HttpServletRequest req, String servletName, MCRSession session) { if (!isSessionBoundToRequest(req)) { // Bind current session to this thread: MCRSessionMgr.setCurrentSession(session); req.setAttribute(CURRENT_THREAD_NAME_KEY, Thread.currentThread().getName()); req.setAttribute(INITIAL_SERVLET_NAME_KEY, servletName); } } private static boolean isSessionBoundToRequest(HttpServletRequest req) { String currentThread = getProperty(req, CURRENT_THREAD_NAME_KEY); // check if this is request passed the same thread before // (RequestDispatcher) return currentThread != null && currentThread.equals(Thread.currentThread().getName()); } /** * This private method handles both GET and POST requests and is invoked by doGet() and doPost(). * * @param req * the HTTP request instance * @param res * the HTTP response instance * @exception IOException * for java I/O errors. * @exception ServletException * for errors from the servlet engine. */ private void doGetPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, SAXException, TransformerException { initializeMCRSession(req, getServletName()); if (SERVLET_URL == null) { prepareBaseURLs(getServletContext(), req); } MCRServletJob job = new MCRServletJob(req, res); @SuppressWarnings("unused") MCRSession session = MCRSessionMgr.getCurrentSession(); try { // transaction around 1st phase of request Exception thinkException = processThinkPhase(job); // first phase completed, start rendering phase processRenderingPhase(job, thinkException); } catch (Error error) { if (getProperty(req, INITIAL_SERVLET_NAME_KEY).equals(getServletName())) { // current Servlet not called via RequestDispatcher MCRTransactionHelper.rollbackTransaction(); } throw error; } catch (ServletException | IOException | SAXException | TransformerException | RuntimeException ex) { if (isHandleExceptionComplete(req, ex)) { return; } throw ex; } catch (Exception ex) { if (isHandleExceptionComplete(req, ex)) { return; } throw new RuntimeException(ex); } finally { cleanupMCRSession(req, getServletName()); } } private boolean isHandleExceptionComplete(HttpServletRequest req, Exception ex) { if (getProperty(req, INITIAL_SERVLET_NAME_KEY).equals(getServletName())) { // current Servlet not called via RequestDispatcher MCRTransactionHelper.rollbackTransaction(); } if (isBrokenPipe(ex)) { LOGGER.info("Ignore broken pipe."); return true; } if (ex.getMessage() == null) { LOGGER.error("Exception while in rendering phase.", ex); } else { LOGGER.error("Exception while in rendering phase: {}", ex.getMessage()); } return false; } /** * Code to initialize a MyCoRe Session * may be reused in ServletFilter, MVC controller, etc. * * @param req - the HTTP request * @param servletName - the servletName */ public static void initializeMCRSession(HttpServletRequest req, String servletName) throws IOException { // Try to set encoding of form values String reqCharEncoding = req.getCharacterEncoding(); if (reqCharEncoding == null) { // Set default to UTF-8 reqCharEncoding = MCRConfiguration2.getString("MCR.Request.CharEncoding").orElse("UTF-8"); req.setCharacterEncoding(reqCharEncoding); LOGGER.debug("Setting ReqCharEncoding to: {}", reqCharEncoding); } if ("true".equals(req.getParameter("reload.properties"))) { MCRConfigurationDirSetup setup = new MCRConfigurationDirSetup(); setup.startUp(req.getServletContext()); } if (getProperty(req, INITIAL_SERVLET_NAME_KEY) == null) { MCRSession session = getSession(req); bindSessionToRequest(req, servletName, session); } } /** * Code to cleanup a MyCoRe Session * may be reused in ServletFilter, MVC controller, etc. * @param req - the HTTP Request * @param servletName - the Servlet name */ public static void cleanupMCRSession(HttpServletRequest req, String servletName) { // Release current MCRSession from current Thread, // in case that Thread pooling will be used by servlet engine if (getProperty(req, INITIAL_SERVLET_NAME_KEY).equals(servletName)) { // current Servlet not called via RequestDispatcher MCRSessionMgr.releaseCurrentSession(); } } private static boolean isBrokenPipe(Throwable throwable) { String message = throwable.getMessage(); if (message != null && throwable instanceof IOException && message.contains("Broken pipe")) { return true; } return throwable.getCause() != null && isBrokenPipe(throwable.getCause()); } private void configureSession(MCRServletJob job) { MCRSession session = MCRSessionMgr.getCurrentSession(); String longName = getClass().getName(); final String shortName = longName.substring(longName.lastIndexOf(".") + 1); LOGGER.info(() -> String .format(Locale.ROOT, "%s ip=%s mcr=%s path=%s", shortName, MCRFrontendUtil.getRemoteAddr(job.getRequest()), session.getID(), job.getRequest().getPathInfo())); MCRFrontendUtil.configureSession(session, job.getRequest(), job.getResponse()); } private Exception processThinkPhase(MCRServletJob job) { @SuppressWarnings("unused") MCRSession session = MCRSessionMgr.getCurrentSession(); try { if (getProperty(job.getRequest(), INITIAL_SERVLET_NAME_KEY).equals(getServletName())) { // current Servlet not called via RequestDispatcher MCRTransactionHelper.beginTransaction(); } configureSession(job); think(job); if (getProperty(job.getRequest(), INITIAL_SERVLET_NAME_KEY).equals(getServletName())) { // current Servlet not called via RequestDispatcher MCRTransactionHelper.commitTransaction(); } } catch (Exception ex) { if (getProperty(job.getRequest(), INITIAL_SERVLET_NAME_KEY).equals(getServletName())) { // current Servlet not called via RequestDispatcher LOGGER.warn("Exception occurred, performing database rollback."); MCRTransactionHelper.rollbackTransaction(); } else { LOGGER.warn("Exception occurred, cannot rollback database transaction right now."); } return ex; } return null; } /** * 1st phase of doGetPost. This method has a seperate transaction. Per default id does nothing as a fallback to the * old behaviour. * * @see #render(MCRServletJob, Exception) */ protected void think(MCRServletJob job) throws Exception { // not implemented by default } private void processRenderingPhase(MCRServletJob job, Exception thinkException) throws Exception { if (allowCrossDomainRequests() && !job.getResponse().containsHeader(ACCESS_CONTROL_ALLOW_ORIGIN)) { job.getResponse().setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); } @SuppressWarnings("unused") MCRSession session = MCRSessionMgr.getCurrentSession(); if (getProperty(job.getRequest(), INITIAL_SERVLET_NAME_KEY).equals(getServletName())) { // current Servlet not called via RequestDispatcher MCRTransactionHelper.beginTransaction(); } render(job, thinkException); if (getProperty(job.getRequest(), INITIAL_SERVLET_NAME_KEY).equals(getServletName())) { // current Servlet not called via RequestDispatcher MCRTransactionHelper.commitTransaction(); } } /** * Returns true if this servlet allows Cross-domain requests. The default value defined by {@link MCRServlet} is * <code>false</code>. */ protected boolean allowCrossDomainRequests() { return false; } /** * 2nd phase of doGetPost This method has a seperate transaction and gets the same MCRServletJob from the first * phase (think) and any exception that occurs at the first phase. By default this method calls * doGetPost(MCRServletJob) as a fallback to the old behaviour. * * @param job * same instance as of think(MCRServlet job) * @param ex * any exception thrown by think(MCRServletJob) or transaction commit * @throws Exception * if render could not handle <code>ex</code> to produce a nice user page */ protected void render(MCRServletJob job, Exception ex) throws Exception { // no info here how to handle if (ex != null) { throw ex; } if (job.getRequest().getMethod().equals("POST")) { doPost(job); } else { doGet(job); } } /** * This method should be overwritten by other servlets. As a default response we indicate the HTTP 1.1 status code * 501 (Not Implemented). */ protected void doGetPost(MCRServletJob job) throws Exception { job.getResponse().sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); } /** Handles an exception by reporting it and its embedded exception */ protected void handleException(Exception ex) { try { reportException(ex); } catch (Exception ignored) { LOGGER.error(ignored); } } /** Reports an exception to the log */ protected void reportException(Exception ex) { String cname = this.getClass().getName(); String servlet = cname.substring(cname.lastIndexOf(".") + 1); LOGGER.warn("Exception caught in : {}", servlet, ex); } /** * This method builds a URL that can be used to redirect the client browser to another page, thereby including http * request parameters. The request parameters will be encoded as http get request. * * @param baseURL * the base url of the target webpage * @param parameters * the http request parameters */ protected String buildRedirectURL(String baseURL, Properties parameters) { StringBuilder redirectURL = new StringBuilder(baseURL); boolean first = true; for (Enumeration<?> e = parameters.keys(); e.hasMoreElements();) { if (first) { redirectURL.append('?'); first = false; } else { redirectURL.append('&'); } String name = (String) e.nextElement(); String value = null; value = URLEncoder.encode(parameters.getProperty(name), StandardCharsets.UTF_8); redirectURL.append(name).append('=').append(value); } LOGGER.debug("Sending redirect to {}", redirectURL); return redirectURL.toString(); } /** * allows browser to cache requests. This method is usefull as it allows browsers to cache content that is not * changed. Please overwrite this method in every Servlet that depends on "remote" data. */ @Override protected long getLastModified(HttpServletRequest request) { if (ENABLE_BROWSER_CACHE) { // we can cache every (local) request long lastModified = MCRSessionMgr.getCurrentSession().getLoginTime() > MCRConfigurationBase .getSystemLastModified() ? MCRSessionMgr.getCurrentSession().getLoginTime() : MCRConfigurationBase.getSystemLastModified(); LOGGER.info("LastModified: {}", lastModified); return lastModified; } return -1; // time is not known } public static String getProperty(HttpServletRequest request, String name) { return MCRFrontendUtil.getProperty(request, name).orElse(null); } /** * returns a translated error message for the current Servlet. I18N keys are of form * {prefix}'.'{SimpleServletClassName}'.'{subIdentifier} * * @param prefix * a prefix of the message property like component.base.error * @param subIdentifier * last part of I18n key * @param args * any arguments that should be passed to {@link MCRTranslation#translate(String, Object...)} */ protected String getErrorI18N(String prefix, String subIdentifier, Object... args) { String key = new MessageFormat("{0}.{1}.{2}", Locale.ROOT) .format(new Object[] { prefix, getClass().getSimpleName(), subIdentifier }); return MCRTranslation.translate(key, args); } /** * Returns the referer of the given request. */ protected URI getReferer(HttpServletRequest request) { String referer; referer = request.getHeader("Referer"); if (referer == null) { return null; } try { return new URI(referer); } catch (URISyntaxException e) { //should not happen LOGGER.error("Referer is not a valid URI: {}", referer, e); return null; } } /** * If a referrer is available this method redirects to the url given by the referrer otherwise method redirects to * the application base url. */ protected void toReferrer(HttpServletRequest request, HttpServletResponse response) throws IOException { URI referrer = getReferer(request); if (referrer != null) { response.sendRedirect(response.encodeRedirectURL(referrer.toString())); } else { LOGGER.warn("Could not get referrer, returning to the application's base url"); response.sendRedirect(response.encodeRedirectURL(MCRFrontendUtil.getBaseURL())); } } /** * If a referrer is available this method redirects to the url given by the referrer otherwise method redirects to * the alternative-url. */ protected void toReferrer(HttpServletRequest request, HttpServletResponse response, String altURL) throws IOException { URI referrer = getReferer(request); if (referrer != null) { response.sendRedirect(response.encodeRedirectURL(referrer.toString())); } else { LOGGER.warn("Could not get referrer, returning to {}", altURL); response.sendRedirect(response.encodeRedirectURL(altURL)); } } }
26,263
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRContentServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRContentServlet.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.servlets; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.NoSuchFileException; import java.util.Locale; import java.util.Objects; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.util.Supplier; import org.mycore.common.content.MCRContent; import org.mycore.common.content.util.MCRServletContentHelper; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author Thomas Scheffler (yagee) * */ public abstract class MCRContentServlet extends MCRServlet { private static final long serialVersionUID = 1L; private static Logger LOGGER = LogManager.getLogger(MCRContentServlet.class); private MCRServletContentHelper.Config config; /** * Returns MCRContent matching current request. */ public abstract MCRContent getContent(HttpServletRequest req, HttpServletResponse resp) throws IOException; @Override public void init() throws ServletException { super.init(); this.config = MCRServletContentHelper.buildConfig(getServletConfig()); } /** * Handles a HEAD request for the specified content. */ @Override protected void doHead(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { request.setAttribute(MCRServletContentHelper.ATT_SERVE_CONTENT, Boolean.FALSE); super.doGet(request, response); } @Override protected void doOptions(final HttpServletRequest req, final HttpServletResponse resp) { resp.setHeader("Allow", "GET, HEAD, POST, OPTIONS"); } @Override protected void render(final MCRServletJob job, final Exception ex) throws Exception { if (ex != null) { throw ex; } final HttpServletRequest request = job.getRequest(); final HttpServletResponse response = job.getResponse(); final MCRContent content = getContent(request, response); boolean serveContent = MCRServletContentHelper.isServeContent(request); try { MCRServletContentHelper.serveContent(content, request, response, getServletContext(), getConfig(), serveContent); } catch (NoSuchFileException | FileNotFoundException e) { LOGGER.info("Catched {}:", e.getClass().getSimpleName(), e); response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage()); return; } final Supplier<Object> getResourceName = () -> { String id = ""; if (Objects.nonNull(content.getSystemId())) { id = content.getSystemId(); } else if (Objects.nonNull(content.getName())) { id = content.getName(); } return String.format(Locale.ROOT, "Finished serving resource:%s", id); }; LOGGER.debug(getResourceName); } public MCRServletContentHelper.Config getConfig() { return config; } }
3,867
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRStaticXMLFileServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/MCRStaticXMLFileServlet.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.servlets; import java.io.IOException; import java.net.URL; import java.nio.file.Path; import java.util.Optional; import javax.xml.transform.TransformerException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.JDOMException; import org.mycore.common.MCRDeveloperTools; import org.mycore.common.MCRException; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRURLContent; import org.mycore.frontend.MCRLayoutUtilities; import org.xml.sax.SAXException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * This servlet displays static *.xml files stored in the web application by sending them to MCRLayoutService. * * @author Frank Lützenkirchen */ public class MCRStaticXMLFileServlet extends MCRServlet { private static final String READ_WEBPAGE_PERMISSION = MCRLayoutUtilities.getPermission2ReadWebpage(); private static final long serialVersionUID = -9213353868244605750L; protected static final Logger LOGGER = LogManager.getLogger(MCRStaticXMLFileServlet.class); @Override public void doGetPost(MCRServletJob job) throws java.io.IOException, MCRException, SAXException, JDOMException, TransformerException { String webpageID = getWebpageId(job.getRequest()); boolean hasAccess = MCRLayoutUtilities.webpageAccess(READ_WEBPAGE_PERMISSION, webpageID, true); if (!hasAccess) { job.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN); return; } URL resource = resolveResource(job); if (resource != null) { HttpServletRequest request = job.getRequest(); HttpServletResponse response = job.getResponse(); setXSLParameters(resource, request); MCRContent content = getResourceContent(request, response, resource); getLayoutService().doLayout(request, response, content); } } private String getWebpageId(HttpServletRequest request) { String servletPath = request.getServletPath(); String queryString = request.getQueryString(); StringBuilder builder = new StringBuilder(servletPath); if (queryString != null && !queryString.isEmpty()) { builder.append('?').append(queryString); } return builder.toString(); } private void setXSLParameters(URL resource, HttpServletRequest request) { String path = resource.getProtocol().equals("file") ? resource.getPath() : resource.toExternalForm(); int lastPathElement = path.lastIndexOf('/') + 1; String fileName = path.substring(lastPathElement); String parent = path.substring(0, lastPathElement); request.setAttribute("XSL.StaticFilePath", request.getServletPath().substring(1)); request.setAttribute("XSL.DocumentBaseURL", parent); request.setAttribute("XSL.FileName", fileName); request.setAttribute("XSL.FilePath", path); } private URL resolveResource(MCRServletJob job) throws IOException { String requestedPath = job.getRequest().getServletPath(); LOGGER.info("MCRStaticXMLFileServlet {}", requestedPath); if (MCRDeveloperTools.overrideActive()) { final Optional<Path> overriddenFilePath = MCRDeveloperTools .getOverriddenFilePath(requestedPath, true); if (overriddenFilePath.isPresent()) { return overriddenFilePath.get().toUri().toURL(); } } URL resource = getServletContext().getResource(requestedPath); if (resource != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Resolved to {}", resource); } return resource; } String msg = "Could not find file " + requestedPath; job.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, msg); return null; } protected MCRContent getResourceContent(HttpServletRequest request, HttpServletResponse response, URL resource) throws IOException, JDOMException, SAXException { return new MCRURLContent(resource); } }
4,962
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDeleteDerivateServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/persistence/MCRDeleteDerivateServlet.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.servlets.persistence; import java.io.IOException; import org.mycore.access.MCRAccessException; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.frontend.cli.MCRDerivateCommands; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Handles DELTE operation on {@link MCRDerivate}. * @author Thomas Scheffler (yagee) * */ public class MCRDeleteDerivateServlet extends MCRPersistenceServlet { private static final long serialVersionUID = 1581063299429224344L; @Override void handlePersistenceOperation(HttpServletRequest request, HttpServletResponse response) throws MCRAccessException { MCRDerivateCommands.delete(getProperty(request, "id")); } @Override void displayResult(HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendRedirect(response.encodeRedirectURL(getReferer(request).toString())); } }
1,725
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/frontend/servlets/persistence/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/>. */ /** * Servlets handling C(R)UD operations on MCRObject and MCRDerivate * @author Thomas Scheffler (yagee) * */ package org.mycore.frontend.servlets.persistence;
892
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPersistenceServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/persistence/MCRPersistenceServlet.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.servlets.persistence; import java.io.IOException; import java.util.Locale; import java.util.Properties; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.JDOMException; import org.mycore.access.MCRAccessException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.common.MCRActiveLinkException; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.MCRWebsiteWriteProtection; import org.mycore.frontend.fileupload.MCRUploadHandlerIFS; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.xml.sax.SAXParseException; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Acts as a base class for all other servlets in this package * @author Thomas Scheffler (yagee) * */ abstract class MCRPersistenceServlet extends MCRServlet { private static final long serialVersionUID = -6776941436009193613L; protected static final String OBJECT_ID_KEY = MCRPersistenceServlet.class.getCanonicalName() + ".MCRObjectID"; private static final Logger LOGGER = LogManager.getLogger(); private String uploadPage; @Override public void init() throws ServletException { super.init(); String configuredPage = MCRConfiguration2.getStringOrThrow("MCR.FileUpload.WebPage"); uploadPage = MCRPersistenceHelper.getWebPage(getServletContext(), configuredPage, "fileupload_commit.xml"); } @Override protected void think(MCRServletJob job) throws Exception { //If admin mode, do not change any data if (MCRWebsiteWriteProtection.printInfoPageIfNoAccess(job.getRequest(), job.getResponse(), MCRFrontendUtil.getBaseURL())) { return; } handlePersistenceOperation(job.getRequest(), job.getResponse()); } @Override protected void render(MCRServletJob job, Exception ex) throws Exception { if (job.getResponse().isCommitted()) { LOGGER.info("Response allready committed"); return; } if (ex != null) { if (ex instanceof MCRAccessException) { job.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); return; } if (ex instanceof MCRActiveLinkException linkException) { String msg = linkException .getActiveLinks() .values() .iterator() .next() .stream() .collect(Collectors.joining(String.format(Locale.ROOT, "%n - "), String.format(Locale.ROOT, "%s%n - ", ex.getMessage()), String.format(Locale.ROOT, "%nPlease remove links before trying again."))); throw new ServletException(msg, ex); } throw ex; } displayResult(job.getRequest(), job.getResponse()); } abstract void handlePersistenceOperation(HttpServletRequest request, HttpServletResponse response) throws MCRAccessException, ServletException, MCRActiveLinkException, SAXParseException, JDOMException, IOException; abstract void displayResult(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; protected void redirectToUploadForm(ServletContext context, HttpServletRequest request, HttpServletResponse response, String objectId, String derivateId) throws IOException { MCRUploadHandlerIFS fuh = new MCRUploadHandlerIFS(objectId, derivateId, MCRPersistenceHelper.getCancelUrl(request)); String fuhid = fuh.getID(); String base = MCRFrontendUtil.getBaseURL() + uploadPage; Properties params = new Properties(); params.put("uploadId", fuhid); params.put("parentObjectID", objectId); if (derivateId != null) { params.put("derivateID", derivateId); } params.put("cancelUrl", MCRPersistenceHelper.getCancelUrl(request)); response.sendRedirect(response.encodeRedirectURL(buildRedirectURL(base, params))); } }
5,129
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUpdateDerivateServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/persistence/MCRUpdateDerivateServlet.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.servlets.persistence; import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE; import static org.mycore.common.MCRConstants.XLINK_NAMESPACE; import static org.mycore.common.MCRConstants.XSI_NAMESPACE; import java.io.IOException; import java.util.Properties; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.mycore.access.MCRAccessException; import org.mycore.access.MCRAccessManager; import org.mycore.common.content.MCRJDOMContent; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.frontend.MCRFrontendUtil; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Handles UPDATE operation on {@link MCRDerivate}. * @author Thomas Scheffler (yagee) * */ public class MCRUpdateDerivateServlet extends MCRPersistenceServlet { private static final long serialVersionUID = -8005685456830013040L; @Override void handlePersistenceOperation(HttpServletRequest request, HttpServletResponse response) throws MCRAccessException, ServletException, JDOMException, IOException { Document editorSubmission = MCRPersistenceHelper.getEditorSubmission(request, false); if (editorSubmission != null) { MCRObjectID objectID = updateDerivateXML(editorSubmission); request.setAttribute(OBJECT_ID_KEY, objectID); } else { //access checks String objectID = getProperty(request, "objectid"); MCRObjectID derivateID = MCRObjectID.getInstance(getProperty(request, "id")); request.setAttribute("id", derivateID.toString()); if (!MCRAccessManager.checkPermission(derivateID, PERMISSION_WRITE)) { throw MCRAccessException.missingPermission("Change derivate title.", derivateID.toString(), PERMISSION_WRITE); } if (objectID != null) { //Load additional files MCRObjectID mcrObjectID = MCRObjectID.getInstance(objectID); request.setAttribute("objectid", mcrObjectID.toString()); if (!MCRAccessManager.checkPermission(mcrObjectID, PERMISSION_WRITE)) { throw MCRAccessException.missingPermission("Change derivate title.", mcrObjectID.toString(), PERMISSION_WRITE); } } } } @Override void displayResult(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { MCRObjectID returnID = (MCRObjectID) request.getAttribute(OBJECT_ID_KEY); if (returnID == null) { //calculate redirect to title change form or add files form redirectToUpdateDerivate(request, response); } else { response.sendRedirect( response.encodeRedirectURL(MCRFrontendUtil.getBaseURL() + "receive/" + returnID)); } } /** * Updates derivate xml in the persistence backend * @param editorSubmission * MyCoRe derivate as XML * @return * MCRObjectID of the MyCoRe object */ private MCRObjectID updateDerivateXML(Document editorSubmission) throws JDOMException, IOException, MCRAccessException { Element root = editorSubmission.getRootElement(); root.setAttribute("noNamespaceSchemaLocation", "datamodel-derivate.xsd", XSI_NAMESPACE); root.addNamespaceDeclaration(XLINK_NAMESPACE); root.addNamespaceDeclaration(XSI_NAMESPACE); byte[] xml = new MCRJDOMContent(editorSubmission).asByteArray(); MCRDerivate der = new MCRDerivate(xml, true); MCRMetadataManager.update(der); return der.getOwnerID(); } /** * Redirects to either add files to derivate upload form or change derivate title form. * * At least "id" HTTP parameter is required to succeed. * <dl> * <dt>id</dt> * <dd>derivate ID(required)</dd> * <dt>objectid</dt> * <dd>object ID of the parent mycore object</dd> * </dl> * If the "objectid" parameter is given, upload form is presented. * If not than the user is redirected to the title change form. * */ private void redirectToUpdateDerivate(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String objectID = getProperty(request, "objectid"); String derivateID = getProperty(request, "id"); if (objectID != null) { //Load additional files redirectToUploadForm(getServletContext(), request, response, objectID, derivateID); } else { //set derivate title Properties params = new Properties(); params.put("sourceUri", "xslStyle:mycorederivate-editor:mcrobject:" + derivateID); params.put("cancelUrl", MCRPersistenceHelper.getCancelUrl(request)); String page = MCRPersistenceHelper.getWebPage(getServletContext(), "editor_form_derivate.xed", "editor_form_derivate.xml"); String redirectURL = MCRFrontendUtil.getBaseURL() + page; response .sendRedirect(response.encodeRedirectURL(buildRedirectURL(redirectURL, params))); } } }
6,203
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPersistenceHelper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/persistence/MCRPersistenceHelper.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.servlets.persistence; import java.io.IOException; import java.io.StringWriter; import java.net.MalformedURLException; import java.util.Map; import java.util.Properties; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.mycore.common.MCRException; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.metadata.validator.MCREditorOutValidator; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.servlets.MCRServlet; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; /** * Helper methods for various servlets. * @author Thomas Scheffler (yagee) * */ class MCRPersistenceHelper { private static final Logger LOGGER = LogManager.getLogger(); static Properties getXSLProperties(HttpServletRequest request) { Properties params = new Properties(); params.putAll( request .getParameterMap() .entrySet() .stream() .filter(e -> e.getKey().startsWith("XSL.") && e.getValue().length != 0) .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()[0]))); return params; } static String getCancelUrl(HttpServletRequest request) { String cancelURL = request.getParameter("cancelURL"); if (cancelURL != null && !cancelURL.isEmpty()) { return cancelURL; } String referer = request.getHeader("Referer"); if (referer == null || referer.equals("")) { referer = MCRFrontendUtil.getBaseURL(); } LOGGER.debug("Referer: {}", referer); return referer; } /** * returns a jdom document representing the output of a mycore editor form. * @param failOnMissing * if not editor submission is present, should we throw an exception (true) or just return null (false) * @return * editor submission or null if editor submission is not present and failOnMissing==false * @throws ServletException * if failOnMissing==true and no editor submission is present */ static Document getEditorSubmission(HttpServletRequest request, boolean failOnMissing) throws ServletException { Document inDoc = (Document) request.getAttribute("MCRXEditorSubmission"); if (inDoc == null) { if (failOnMissing) { throw new ServletException("No MCREditorSubmission"); } return null; } if (inDoc.getRootElement().getAttribute("ID") == null) { String mcrID = MCRServlet.getProperty(request, "mcrid"); LOGGER.info("Adding MCRObjectID from request: {}", mcrID); inDoc.getRootElement().setAttribute("ID", mcrID); } return inDoc; } /** * creates a MCRObject instance on base of JDOM document * @param doc * MyCoRe object as XML. * @throws JDOMException * exception from underlying {@link MCREditorOutValidator} * @throws IOException * exception from underlying {@link MCREditorOutValidator} or {@link XMLOutputter} */ static MCRObject getMCRObject(Document doc) throws JDOMException, IOException, MCRException { String id = doc.getRootElement().getAttributeValue("ID"); MCRObjectID objectID = MCRObjectID.getInstance(id); MCREditorOutValidator ev = new MCREditorOutValidator(doc, objectID); Document validMyCoReObject = ev.generateValidMyCoReObject(); if (ev.getErrorLog().size() > 0 && LOGGER.isDebugEnabled()) { XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); StringWriter swOrig = new StringWriter(); xout.output(doc, swOrig); LOGGER.debug("Input document \n{}", swOrig); for (String logMsg : ev.getErrorLog()) { LOGGER.debug(logMsg); } StringWriter swClean = new StringWriter(); xout.output(validMyCoReObject, swClean); LOGGER.debug("Results in \n{}", swClean); } return new MCRObject(validMyCoReObject); } protected static String getWebPage(ServletContext context, String modernPage, String deprecatedPage) throws ServletException { try { if (context.getResource("/" + modernPage) == null && context.getResource("/" + deprecatedPage) != null) { LogManager.getLogger() .warn("Could not find {} in webapp root, using deprecated {} instead.", modernPage, deprecatedPage); return deprecatedPage; } } catch (MalformedURLException e) { throw new ServletException(e); } return modernPage; //even if it does not exist: nice 404 helps the user } }
5,874
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCreateObjectServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/persistence/MCRCreateObjectServlet.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.servlets.persistence; import java.io.IOException; import java.util.Enumeration; import java.util.Properties; import org.jdom2.Document; import org.jdom2.JDOMException; import org.mycore.access.MCRAccessException; import org.mycore.common.MCRException; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.frontend.MCRFrontendUtil; import org.xml.sax.SAXParseException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Handles CREATE operation on {@link MCRObject}. * @author Thomas Scheffler (yagee) * */ public class MCRCreateObjectServlet extends MCRPersistenceServlet { private static final long serialVersionUID = 4143057048219690238L; private boolean appendDerivate = false; @Override public void init() throws ServletException { super.init(); String appendDerivate = getInitParameter("appendDerivate"); if (appendDerivate != null) { this.appendDerivate = true; } } @Override void handlePersistenceOperation(HttpServletRequest request, HttpServletResponse response) throws MCRAccessException, ServletException, SAXParseException, JDOMException, IOException { Document editorSubmission = MCRPersistenceHelper.getEditorSubmission(request, false); MCRObjectID objectID; if (editorSubmission != null) { objectID = createObject(editorSubmission); } else { //editorSubmission is null, when editor input is absent (redirect to editor form in render phase) String projectID = getProperty(request, "project"); String type = getProperty(request, "type"); String formattedId = MCRObjectID.formatID(projectID + "_" + type, 0); objectID = MCRObjectID.getInstance(formattedId); MCRMetadataManager.checkCreatePrivilege(objectID); } request.setAttribute(OBJECT_ID_KEY, objectID); } @Override void displayResult(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //return to object itself if created, else call editor form MCRObjectID returnID = (MCRObjectID) request.getAttribute(OBJECT_ID_KEY); if (returnID.getNumberAsInteger() == 0) { redirectToCreateObject(request, response); } else { Properties params = MCRPersistenceHelper.getXSLProperties(request); if (this.appendDerivate) { params.put("id", returnID.toString()); params.put("cancelURL", MCRFrontendUtil.getBaseURL() + "receive/" + returnID); response.sendRedirect( response.encodeRedirectURL( buildRedirectURL(MCRFrontendUtil.getBaseURL() + "servlets/derivate/create", params))); } else { response.sendRedirect(response .encodeRedirectURL( buildRedirectURL(MCRFrontendUtil.getBaseURL() + "receive/" + returnID, params))); } } } /** * Adds a new mycore object to the persistence backend. * @param doc * MyCoRe object as XML * @return * MCRObjectID of the newly created object. * @throws JDOMException * from {@link MCRPersistenceHelper#getMCRObject(Document)} * @throws IOException * from {@link MCRPersistenceHelper#getMCRObject(Document)} */ private MCRObjectID createObject(Document doc) throws JDOMException, IOException, MCRException, MCRAccessException { MCRObject mcrObject = MCRPersistenceHelper.getMCRObject(doc); MCRMetadataManager.create(mcrObject); return mcrObject.getId(); } /** * redirects to new mcrobject form. * * At least "type" HTTP parameter is required to succeed. * <dl> * <dt>type</dt> * <dd>object type of the new object (required)</dd> * <dt>project</dt> * <dd>project ID part of object ID (required)</dd> * <dt>layout</dt> * <dd>special editor form layout</dd> * </dl> */ private void redirectToCreateObject(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { MCRObjectID objectID = (MCRObjectID) request.getAttribute(OBJECT_ID_KEY); StringBuilder sb = new StringBuilder(); sb.append("editor_form_author").append('-').append(objectID.getTypeId()); String layout = getProperty(request, "layout"); if (layout != null && layout.length() != 0) { sb.append('-').append(layout); } String baseName = sb.toString(); String form = MCRPersistenceHelper.getWebPage(getServletContext(), baseName + ".xed", baseName + ".xml"); Properties params = new Properties(); params.put("cancelUrl", MCRPersistenceHelper.getCancelUrl(request)); params.put("mcrid", objectID.toString()); Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); String value = request.getParameter(name); params.put(name, value); } response .sendRedirect(response.encodeRedirectURL(buildRedirectURL(MCRFrontendUtil.getBaseURL() + form, params))); } }
6,277
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCreateDerivateServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/persistence/MCRCreateDerivateServlet.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.servlets.persistence; import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE; import java.io.IOException; import org.mycore.access.MCRAccessException; import org.mycore.access.MCRAccessManager; import org.mycore.datamodel.metadata.MCRDerivate; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Handles CREATE operation on {@link MCRDerivate}. * @author Thomas Scheffler (yagee) * */ public class MCRCreateDerivateServlet extends MCRPersistenceServlet { private static final long serialVersionUID = 4735574336094275787L; @Override void handlePersistenceOperation(HttpServletRequest request, HttpServletResponse response) throws MCRAccessException { String objectID = getObjectId(request); if (!MCRAccessManager.checkPermission(objectID, PERMISSION_WRITE)) { throw MCRAccessException.missingPermission("Add derivate.", objectID, PERMISSION_WRITE); } } /** * redirects to new derivate upload form. * * At least "id" HTTP parameter is required to succeed. * <dl> * <dt>id</dt> * <dd>object ID of the parent mycore object (required)</dd> * </dl> */ @Override void displayResult(HttpServletRequest request, HttpServletResponse response) throws IOException { redirectToUploadForm(getServletContext(), request, response, getObjectId(request), null); } private String getObjectId(HttpServletRequest request) { return getProperty(request, "id"); } }
2,317
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDeleteObjectServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/persistence/MCRDeleteObjectServlet.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.servlets.persistence; import java.io.IOException; import org.mycore.access.MCRAccessException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.common.MCRActiveLinkException; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.cli.MCRObjectCommands; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Handles DELETE operation on {@link MCRObject}. * @author Thomas Scheffler (yagee) * */ public class MCRDeleteObjectServlet extends MCRPersistenceServlet { private static final long serialVersionUID = 3148314720092349972L; @Override void handlePersistenceOperation(HttpServletRequest request, HttpServletResponse response) throws MCRAccessException, MCRActiveLinkException { MCRObjectCommands.delete(getProperty(request, "id")); } @Override void displayResult(HttpServletRequest request, HttpServletResponse response) throws IOException { String deletedRedirect = MCRConfiguration2.getStringOrThrow("MCR.Persistence.PageDelete"); response.sendRedirect(response.encodeRedirectURL(MCRFrontendUtil.getBaseURL() + deletedRedirect)); } }
2,009
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUpdateObjectServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/servlets/persistence/MCRUpdateObjectServlet.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.servlets.persistence; import java.io.IOException; import org.apache.logging.log4j.LogManager; import org.jdom2.Document; import org.jdom2.JDOMException; import org.mycore.access.MCRAccessException; import org.mycore.common.MCRException; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.support.MCRObjectIDLockTable; import org.xml.sax.SAXParseException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Handles UPDATE operation on {@link MCRObject}. * @author Thomas Scheffler (yagee) * */ public class MCRUpdateObjectServlet extends MCRPersistenceServlet { private static final long serialVersionUID = -7507356414480350102L; @Override void handlePersistenceOperation(HttpServletRequest request, HttpServletResponse response) throws MCRAccessException, ServletException, SAXParseException, JDOMException, IOException { MCRObjectID objectID = updateObject(MCRPersistenceHelper.getEditorSubmission(request, true)); request.setAttribute(OBJECT_ID_KEY, objectID); } @Override void displayResult(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { MCRObjectID returnID = (MCRObjectID) request.getAttribute(OBJECT_ID_KEY); if (returnID == null) { throw new ServletException("No MCRObjectID given."); } else { response.sendRedirect( response.encodeRedirectURL(buildRedirectURL( MCRFrontendUtil.getBaseURL() + "receive/" + returnID, MCRPersistenceHelper.getXSLProperties(request)))); } } /** * Updates a mycore object in the persistence backend. * @param doc * MyCoRe object as XML * @return * MCRObjectID of the newly created object. * @throws JDOMException * from {@link MCRPersistenceHelper#getMCRObject(Document)} * @throws IOException * from {@link MCRPersistenceHelper#getMCRObject(Document)} */ private MCRObjectID updateObject(Document doc) throws JDOMException, IOException, MCRException, MCRAccessException { MCRObject mcrObject = MCRPersistenceHelper.getMCRObject(doc); LogManager.getLogger().info("ID: {}", mcrObject.getId()); try { MCRMetadataManager.update(mcrObject); return mcrObject.getId(); } finally { MCRObjectIDLockTable.unlock(mcrObject.getId()); } } }
3,466
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIDMapper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/idmapper/MCRIDMapper.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.idmapper; import java.util.Optional; import org.mycore.datamodel.metadata.MCRObjectID; /** * Interface for an object id mapper * It is used in rest api and elsewhere to retrieve * the MCRObjectID of an object or derivate for a given id string * * This feature can be used to retrieve information on MyCoRe objects * by their alternative identifiers like DOI or URN. * * @author Robert Stephan * */ public interface MCRIDMapper { String MCR_PROPERTY_CLASS = "MCR.Object.IDMapper.Class"; /** * Detection of the MyCoRe object id * @param mcrid - the id string that should be evaluated * @return a MCRObjectID instance for the object id */ Optional<MCRObjectID> mapMCRObjectID(String mcrid); /** * Detection of the MyCoRe derivate id * @param mcrObjId - the MCRObjectID of the MyCoRe object to which the derivate should belong to * @param derid - the id string that should be evaluated * @return a MCRObjectID instance for the derivate id */ Optional<MCRObjectID> mapMCRDerivateID(MCRObjectID mcrObjId, String derid); }
1,857
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDefaultIDMapper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/idmapper/MCRDefaultIDMapper.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.idmapper; import java.util.Optional; import org.mycore.datamodel.metadata.MCRObjectID; /** * Default implementation of an MCRIDMapper * * It simply take the id string and tries to create the MCRObjectID from it. * * @author Robert Stephan */ public class MCRDefaultIDMapper implements MCRIDMapper { /** * {@inheritDoc} */ @Override public Optional<MCRObjectID> mapMCRObjectID(String mcrid) { if (MCRObjectID.isValid(mcrid)) { return Optional.of(MCRObjectID.getInstance(mcrid)); } return Optional.empty(); } /** * {@inheritDoc} */ @Override public Optional<MCRObjectID> mapMCRDerivateID(MCRObjectID mcrObjId, String derid) { if (MCRObjectID.isValid(derid)) { return Optional.of(MCRObjectID.getInstance(derid)); } return Optional.empty(); } }
1,634
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUploadHandlerManager.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/fileupload/MCRUploadHandlerManager.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.fileupload; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRCache; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRUsageException; import org.mycore.common.processing.MCRProcessableCollection; import org.mycore.common.processing.MCRProcessableDefaultCollection; import org.mycore.common.processing.MCRProcessableRegistry; /** * @author Frank Lützenkirchen * @author Harald Richter * @author Jens Kupferschmidt * */ public class MCRUploadHandlerManager { private static Logger LOGGER = LogManager.getLogger(MCRUploadHandlerManager.class); /** Cache of currently active upload handler sessions */ protected static MCRCache<String, MCRUploadHandlerCacheEntry> HANDLERS; protected static MCRProcessableCollection COLLECTION; static { HANDLERS = new MCRCache<>(100, "UploadHandlerManager UploadHandlers"); COLLECTION = new MCRProcessableDefaultCollection("Upload Manager"); MCRProcessableRegistry registry = MCRProcessableRegistry.getSingleInstance(); registry.register(COLLECTION); } static void register(MCRUploadHandler handler) { LOGGER.debug("Registering {} with upload ID {}", handler.getClass().getName(), handler.getID()); String sessionID = MCRSessionMgr.getCurrentSession().getID(); HANDLERS.put(handler.getID(), new MCRUploadHandlerCacheEntry(sessionID, handler)); COLLECTION.add(handler); } public static MCRUploadHandler getHandler(String uploadID) { long yesterday = System.currentTimeMillis() - 86400000; MCRUploadHandlerCacheEntry entry = HANDLERS.getIfUpToDate(uploadID, yesterday); if (entry == null) { throw new MCRUsageException("Upload session " + uploadID + " timed out"); } String sessionID = entry.getSessionID(); if (!sessionID.equals(MCRSessionMgr.getCurrentSessionID())) { MCRSession session = MCRSessionMgr.getSession(sessionID); if (session != null) { MCRSessionMgr.setCurrentSession(session); } } return entry.getUploadHandler(); } public static void unregister(String uploadID) { MCRUploadHandlerCacheEntry cacheEntry = HANDLERS.get(uploadID); HANDLERS.remove(uploadID); COLLECTION.remove(cacheEntry.handler); } /** Represents a cache entry of currently active upload handler session */ private static class MCRUploadHandlerCacheEntry { /** The ID of the MCRSession this upload is associated with */ private String sessionID; /** The MCRUploadHander instance to be used */ private MCRUploadHandler handler; MCRUploadHandlerCacheEntry(String sessionID, MCRUploadHandler handler) { this.sessionID = sessionID; this.handler = handler; } public String getSessionID() { return sessionID; } public MCRUploadHandler getUploadHandler() { return handler; } } }
3,885
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUploadServletDeployer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/fileupload/MCRUploadServletDeployer.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.fileupload; import java.io.IOException; import java.nio.file.Files; import java.nio.file.NotDirectoryException; import java.nio.file.Path; import java.nio.file.Paths; import org.apache.logging.log4j.LogManager; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import org.mycore.common.events.MCRStartupHandler.AutoExecutable; import jakarta.servlet.MultipartConfigElement; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletRegistration.Dynamic; /** * Uses <code>mycore.properties</code> to configure {@link MCRUploadViaFormServlet}. * @author Thomas Scheffler (yagee) * */ public class MCRUploadServletDeployer implements AutoExecutable { private static final String MCR_FILE_UPLOAD_TEMP_STORAGE_PATH = "MCR.FileUpload.TempStoragePath"; /* (non-Javadoc) * @see org.mycore.common.events.MCRStartupHandler.AutoExecutable#getName() */ @Override public String getName() { return MCRUploadViaFormServlet.class.getSimpleName() + " Deployer"; } /* (non-Javadoc) * @see org.mycore.common.events.MCRStartupHandler.AutoExecutable#getPriority() */ @Override public int getPriority() { return 0; } /* (non-Javadoc) * @see org.mycore.common.events.MCRStartupHandler.AutoExecutable#startUp(jakarta.servlet.ServletContext) */ @Override public void startUp(ServletContext servletContext) { if (servletContext != null) { String servletName = "MCRUploadViaFormServlet"; MultipartConfigElement multipartConfig = getMultipartConfig(); try { checkTempStoragePath(multipartConfig.getLocation()); } catch (IOException e) { throw new MCRConfigurationException("Could not setup " + servletName + "!", e); } Dynamic uploadServlet = servletContext.addServlet(servletName, MCRUploadViaFormServlet.class); uploadServlet.addMapping("/servlets/MCRUploadViaFormServlet"); uploadServlet.setMultipartConfig(multipartConfig); } } private void checkTempStoragePath(String location) throws IOException { Path targetDir = Paths.get(location); if (!targetDir.isAbsolute()) { throw new MCRConfigurationException( "'" + MCR_FILE_UPLOAD_TEMP_STORAGE_PATH + "=" + location + "' must be an absolute path!"); } if (Files.notExists(targetDir)) { LogManager.getLogger().info("Creating directory: {}", targetDir); Files.createDirectories(targetDir); } if (!Files.isDirectory(targetDir)) { throw new NotDirectoryException(targetDir.toString()); } } private MultipartConfigElement getMultipartConfig() { String location = MCRConfiguration2.getStringOrThrow(MCR_FILE_UPLOAD_TEMP_STORAGE_PATH); long maxFileSize = MCRConfiguration2.getLong("MCR.FileUpload.MaxSize").orElse(5000000L); int fileSizeThreshold = MCRConfiguration2.getInt("MCR.FileUpload.MemoryThreshold").orElse(1000000); LogManager.getLogger() .info(() -> MCRUploadViaFormServlet.class.getSimpleName() + " accept files and requests up to " + maxFileSize + " bytes and uses " + location + " as tempory storage for files larger " + fileSizeThreshold + " bytes."); return new MultipartConfigElement(location, maxFileSize, maxFileSize, fileSizeThreshold); } }
4,291
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPostUploadFileProcessor.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/fileupload/MCRPostUploadFileProcessor.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.fileupload; import java.io.IOException; import java.nio.file.Path; import java.util.function.Supplier; /** * Modifies a uploaded file before it will be written to the destination Derivate. */ public abstract class MCRPostUploadFileProcessor { /** * Checks a file if it is processable. * @param path to the temp file * @return true if this {@link MCRPostUploadFileProcessor} can process this file */ public abstract boolean isProcessable(String path); /** * * @param path the actual relative path in the derivate * @param tempFileContent the actual path to the temporary file * @param tempFileSupplier a supplier which creates a new temporary file which can be used for processing. * @return the {@link Path} of the final file, which was provided by the tempFileSupplier * @throws IOException if the processing failed */ public abstract Path processFile(String path, Path tempFileContent, Supplier<Path> tempFileSupplier) throws IOException; }
1,783
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUploadViaFormServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/fileupload/MCRUploadViaFormServlet.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.fileupload; import java.io.InputStream; import java.util.Collection; import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; 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.MCRTransactionHelper; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.streams.MCRNotClosingInputStream; import org.mycore.frontend.MCRWebsiteWriteProtection; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import jakarta.persistence.EntityTransaction; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.Part; /** * This servlet handles form based file upload. * * @author Frank Lützenkirchen * @author Thomas Scheffler (yagee) * * * @see MCRUploadHandler * @see MCRUploadServletDeployer */ public final class MCRUploadViaFormServlet extends MCRServlet { private static final long serialVersionUID = 1L; private static final Logger LOGGER = LogManager.getLogger(MCRUploadViaFormServlet.class); @Override public void doGetPost(MCRServletJob job) throws Exception { guardWebsiteCurrentlyReadOnly(); Optional<MCRUploadHandler> uh = getUploadHandler(job); if (!uh.isPresent()) { job.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter 'uploadId' is missing!"); return; } MCRUploadHandler handler = uh.get(); LOGGER.info("UploadHandler form based file upload for ID {}", handler.getID()); handleUploadedFiles(handler, job.getRequest().getParts()); job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(handler.getRedirectURL())); handler.finishUpload(); handler.unregister(); } private void guardWebsiteCurrentlyReadOnly() { if (MCRWebsiteWriteProtection.isActive()) { throw new RuntimeException("System is currently in read-only mode"); } } private Optional<MCRUploadHandler> getUploadHandler(MCRServletJob job) { return Optional.ofNullable(job.getRequest().getParameter("uploadId")).map(MCRUploadHandlerManager::getHandler); } private void handleUploadedFiles(MCRUploadHandler handler, Collection<Part> files) throws Exception { int numFiles = (int) files.stream().map(Part::getSubmittedFileName).filter(Objects::nonNull).count(); LOGGER.info("UploadHandler uploading {} file(s)", numFiles); handler.startUpload(numFiles); MCRSession session = MCRSessionMgr.getCurrentSession(); MCRTransactionHelper.commitTransaction(); for (Part file : files) { try { handleUploadedFile(handler, file); } finally { file.delete(); } } MCRTransactionHelper.beginTransaction(); } private void handleUploadedFile(MCRUploadHandler handler, Part file) throws Exception { String submitted = file.getSubmittedFileName(); if (submitted == null || Objects.equals(submitted, "")) { return; } try (InputStream in = file.getInputStream()) { String path = MCRUploadHelper.getFileName(submitted); if (requireDecompressZip(path)) { handleZipFile(handler, in); } else { handleUploadedFile(handler, file.getSize(), path, in); } } } private boolean requireDecompressZip(String path) { return MCRConfiguration2.getBoolean("MCR.FileUpload.DecompressZip").orElse(true) && path.toLowerCase(Locale.ROOT).endsWith(".zip"); } private void handleUploadedFile(MCRUploadHandler handler, long size, String path, InputStream in) throws Exception { LOGGER.info("UploadServlet uploading {}", path); MCRUploadHelper.checkPathName(path); EntityTransaction tx = MCRUploadHelper.startTransaction(); try { handler.receiveFile(path, in, size, null); MCRUploadHelper.commitTransaction(tx); } catch (Exception exc) { MCRUploadHelper.rollbackAnRethrow(tx, exc); } } private void handleZipFile(MCRUploadHandler handler, InputStream in) throws Exception { ZipInputStream zis = new ZipInputStream(in); MCRNotClosingInputStream nis = new MCRNotClosingInputStream(zis); for (ZipEntry entry = zis.getNextEntry(); entry != null; entry = zis.getNextEntry()) { String path = convertAbsolutePathToRelativePath(entry.getName()); if (entry.isDirectory()) { LOGGER.debug("UploadServlet skipping ZIP entry {}, is a directory", path); } else { handler.incrementNumFiles(); handleUploadedFile(handler, entry.getSize(), path, nis); } } handler.decrementNumFiles(); //ZIP file does not count nis.reallyClose(); } private String convertAbsolutePathToRelativePath(String path) { int pos = path.indexOf(":"); if (pos >= 0) { path = path.substring(pos + 1); } while (path.startsWith("\\") || path.startsWith("/")) { path = path.substring(1); } return path; } }
6,224
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUploadHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/fileupload/MCRUploadHandler.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.fileupload; import java.io.InputStream; import org.mycore.common.MCRException; import org.mycore.common.processing.MCRAbstractProcessable; import org.mycore.frontend.MCRWebsiteWriteProtection; /** * This class does the server-side of uploading files from a client browser, * which runs the upload applet. This is an abstract base class that must be * subclassed to implement the storage of files at the server side for miless, * MyCoRe or other usages of the upload framework. Every instance of * MCRUploadHandler handles one singe upload session with the applet. * * @author Harald Richter * @author Frank Lützenkirchen * * * @see MCRUploadHandlerManager */ public abstract class MCRUploadHandler extends MCRAbstractProcessable { /** The unique ID of this upload session * */ protected String uploadID; /** The url where to go after upload is finished. * */ protected String url; private int numFiles; /** Creates a new upload handler and registers it at the handler manager * */ protected MCRUploadHandler() { if (MCRWebsiteWriteProtection.isActive()) { throw new MCRException("System is currently in read-only mode"); } uploadID = Long.toString(System.currentTimeMillis(), 36); MCRUploadHandlerManager.register(this); this.setName(uploadID); } /** Returns the unique ID of this upload session * */ public final String getID() { return uploadID; } /** Returns the url where to go after upload is finished * */ public String getRedirectURL() { return url; } /** * Starts the upload session. * * @param numberOfFiles * the number of files that will be uploaded */ public void startUpload(int numberOfFiles) { this.numFiles = numberOfFiles; } /** * Increments the uploaded number of files. Use this method with care! * In general a fixed number of files to upload should be set with * {@link #startUpload(int)}. * * @return the new number of files to upload */ public int incrementNumFiles() { return ++this.numFiles; } /** * Decrements the uploaded number of files. Use this method with care! * In general a fixed number of files to upload should be set with * {@link #startUpload(int)}. * * @return the new number of files to upload */ public int decrementNumFiles() { return --this.numFiles; } /** * Returns the number of files which will be uploaded * * @return number of files to upload */ public int getNumFiles() { return this.numFiles; } /** * This method is called to ask if this * file should be uploaded and will be accepted by the server. The default * implementation always returns true (always upload file), but subclasses * should overwrite this method to decide whether the file's content must be * uploaded. Decision can be based on the MD5 checksum, so unchanged files do not have to be * uploaded again. * * @param path * the path and filename of the file * @param checksum * the MD5 checksum computed at the client side * @param length * the length of the file in bytes (file size) * @return true, if the file should be uploaded, false if the file should be * skipped */ public boolean acceptFile(String path, String checksum, long length) throws Exception { return true; } /** * This method is called so that the * UploadHandler subclass can store the file on the server side. * When the UploadHandler could read less than length bytes from the * InputStream at the time the InputStream has no data any more, the user * at the remote side canceled upload during file transfer. The UploadHandler * then can decide to delete the file, but must return the number of * bytes stored. The UploadHandler can also compare the MD5 checksum calculated * at the client side with its own checksum, to detect magical transfer errors. * * This method requires a database transaction. * * @param path * the path and filename of the file * @param in * the inputstream to read the content of the file from * @param length * the total file size as number of bytes. This may be 0, * meaning that the file is empty or the file size is not known. * @param md5 * the md5 checksum calculated at the client side. This * may be null, meaning that the md5 checksum is not known. * @return * the number of bytes that have been stored. */ public abstract long receiveFile(String path, InputStream in, long length, String md5) throws Exception; /** * After finishing uploading all files, this method is called so * that the UploadHandler subclass can finish work and commit all saved * files. * */ public abstract void finishUpload() throws Exception; /** * This method is called so that the UploadHandler subclass can finish * or cancel work. The implementation is optional, by default finishUpload() * is called * */ public void cancelUpload() throws Exception { finishUpload(); } /** * Automatically unregister this upload handler from the * UploadHandlerManager. */ public void unregister() { MCRUploadHandlerManager.unregister(uploadID); } }
6,422
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUploadHandlerIFS.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/fileupload/MCRUploadHandlerIFS.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.fileupload; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.file.DirectoryStream; import java.nio.file.FileSystemException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; 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.access.MCRAccessException; import org.mycore.access.MCRAccessInterface; import org.mycore.access.MCRAccessManager; import org.mycore.access.MCRRuleAccessInterface; import org.mycore.common.MCRPersistenceException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.processing.MCRProcessableStatus; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetaIFS; import org.mycore.datamodel.metadata.MCRMetaLinkID; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectDerivate; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRFileAttributes; import org.mycore.datamodel.niofs.MCRPath; /** * handles uploads and store files directly into the IFS. * * @author Thomas Scheffler (yagee) * @author Frank Lützenkirchen * @see MCRUploadHandler */ public class MCRUploadHandlerIFS extends MCRUploadHandler { private static final Logger LOGGER = LogManager.getLogger(MCRUploadHandlerIFS.class); private static final String ID_TYPE = "derivate"; private static final String FILE_PROCESSOR_PROPERTY = "MCR.MCRUploadHandlerIFS.FileProcessors"; private static final List<MCRPostUploadFileProcessor> FILE_PROCESSORS = initProcessorList(); protected String documentID; protected String derivateID; protected MCRDerivate derivate; protected MCRPath rootDir; private int filesUploaded; public MCRUploadHandlerIFS(String documentID, String derivateID) { super(); this.documentID = Objects.requireNonNull(documentID, "Document ID may not be 'null'."); this.derivateID = derivateID; this.setName(this.derivateID); } public MCRUploadHandlerIFS(String documentID, String derivateID, String returnURL) { this(documentID, derivateID); this.url = Objects.requireNonNull(returnURL, "Return URL may not be 'null'."); } private static List<MCRPostUploadFileProcessor> initProcessorList() { return MCRConfiguration2.getString(FILE_PROCESSOR_PROPERTY) .map(MCRConfiguration2::splitValue) .orElseGet(Stream::empty) .map(MCRConfiguration2::<MCRPostUploadFileProcessor>instantiateClass) .collect(Collectors.toList()); } @Override public void startUpload(int numFiles) { super.startUpload(numFiles); this.filesUploaded = 0; this.setStatus(MCRProcessableStatus.processing); this.setProgress(0); this.setProgressText("start upload..."); } private synchronized void prepareUpload() throws MCRPersistenceException, MCRAccessException, IOException { if (this.derivate != null) { return; } LOGGER.debug("upload starting, expecting {} files", getNumFiles()); MCRObjectID derivateID = getOrCreateDerivateID(); if (MCRMetadataManager.exists(derivateID)) { this.derivate = MCRMetadataManager.retrieveMCRDerivate(derivateID); } else { this.derivate = createDerivate(derivateID); } getOrCreateRootDirectory(); LOGGER.debug("uploading into {} of {}", this.derivateID, this.documentID); } private MCRObjectID getOrCreateDerivateID() { if (derivateID == null) { String projectID = MCRObjectID.getInstance(this.documentID).getProjectId(); MCRObjectID oid = MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(projectID + '_' + ID_TYPE); this.derivateID = oid.toString(); return oid; } else { return MCRObjectID.getInstance(derivateID); } } private MCRDerivate createDerivate(MCRObjectID derivateID) throws MCRPersistenceException, MCRAccessException { MCRDerivate derivate = new MCRDerivate(); derivate.setId(derivateID); String schema = MCRConfiguration2.getString("MCR.Metadata.Config.derivate") .orElse("datamodel-derivate.xml") .replaceAll(".xml", ".xsd"); derivate.setSchema(schema); MCRMetaLinkID linkId = new MCRMetaLinkID(); linkId.setSubTag("linkmeta"); linkId.setReference(documentID, null, null); derivate.getDerivate().setLinkMeta(linkId); MCRMetaIFS ifs = new MCRMetaIFS(); ifs.setSubTag("internal"); ifs.setSourcePath(null); derivate.getDerivate().setInternals(ifs); LOGGER.debug("Creating new derivate with ID {}", this.derivateID); MCRMetadataManager.create(derivate); setDefaultPermissions(derivateID); return derivate; } protected void setDefaultPermissions(MCRObjectID derivateID) { if (MCRConfiguration2.getBoolean("MCR.Access.AddDerivateDefaultRule").orElse(true)) { MCRAccessInterface accessImpl = MCRAccessManager.getAccessImpl(); if (accessImpl instanceof MCRRuleAccessInterface ruleAccessImpl) { Collection<String> configuredPermissions = ruleAccessImpl.getAccessPermissionsFromConfiguration(); for (String permission : configuredPermissions) { MCRAccessManager.addRule(derivateID, permission, MCRAccessManager.getTrueRule(), "default derivate rule"); } } } } private void getOrCreateRootDirectory() throws FileSystemException { this.rootDir = MCRPath.getPath(derivateID, "/"); if (Files.notExists(rootDir)) { rootDir.getFileSystem().createRoot(derivateID); } } @Override public boolean acceptFile(String path, String checksum, long length) throws Exception { LOGGER.debug("incoming acceptFile request: {} {} {} bytes", path, checksum, length); boolean shouldAcceptFile = true; if (rootDir != null) { MCRPath child = MCRPath.toMCRPath(rootDir.resolve(path)); if (Files.isRegularFile(child)) { @SuppressWarnings("rawtypes") MCRFileAttributes attrs = Files.readAttributes(child, MCRFileAttributes.class); shouldAcceptFile = attrs.size() != length || !(checksum.equals(attrs.md5sum()) && child.getFileSystem().verifies(child, attrs)); } } LOGGER.debug("Should the client send this file? {}", shouldAcceptFile); return shouldAcceptFile; } @Override public synchronized long receiveFile(String path, InputStream in, long length, String checksum) throws IOException, MCRPersistenceException, MCRAccessException { LOGGER.debug("incoming receiveFile request: {} {} {} bytes", path, checksum, length); this.setProgressText(path); List<Path> tempFiles = new ArrayList<>(); Supplier<Path> tempFileSupplier = () -> { try { Path tempFile = Files.createTempFile(derivateID + "-" + path.hashCode(), ".upload"); tempFiles.add(tempFile); return tempFile; } catch (IOException e) { throw new UncheckedIOException("Error while creating temp File!", e); } }; try (InputStream fIn = preprocessInputStream(path, in, length, tempFileSupplier)) { if (rootDir == null) { //MCR-1376: Create derivate only if at least one file was successfully uploaded prepareUpload(); } MCRPath file = getFile(path); LOGGER.info("Creating file {}.", file); Files.copy(fIn, file, StandardCopyOption.REPLACE_EXISTING); return tempFiles.isEmpty() ? length : Files.size(tempFiles.stream().reduce((a, b) -> b).get()); } finally { tempFiles.stream().filter(Files::exists).forEach((tempFilePath) -> { try { Files.delete(tempFilePath); } catch (IOException e) { LOGGER.error("Could not delete temp file {}", tempFilePath); } }); this.filesUploaded++; int progress = (int) (((float) this.filesUploaded / (float) getNumFiles()) * 100f); this.setProgress(progress); } } private InputStream preprocessInputStream(String path, InputStream in, long length, Supplier<Path> tempFileSupplier) throws IOException { List<MCRPostUploadFileProcessor> activeProcessors = FILE_PROCESSORS.stream().filter(p -> p.isProcessable(path)) .collect(Collectors.toList()); if (activeProcessors.isEmpty()) { return in; } Path currentTempFile = tempFileSupplier.get(); try (InputStream initialIS = in) { Files.copy(initialIS, currentTempFile, StandardCopyOption.REPLACE_EXISTING); } long myLength = Files.size(currentTempFile); if (length >= 0 && length != myLength) { throw new IOException("Length of transmitted data does not match promised length: " + myLength + "!=" + length); } for (MCRPostUploadFileProcessor pufp : activeProcessors) { currentTempFile = pufp.processFile(path, currentTempFile, tempFileSupplier); } return Files.newInputStream(currentTempFile); } private MCRPath getFile(String path) throws IOException { MCRPath pathToFile = MCRPath.toMCRPath(rootDir.resolve(path)); MCRPath parentDirectory = pathToFile.getParent(); if (!Files.isDirectory(parentDirectory)) { Files.createDirectories(parentDirectory); } return pathToFile; } @Override public synchronized void finishUpload() throws IOException, MCRAccessException { if (this.derivate == null) { return; } try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(rootDir)) { if (dirStream.iterator().hasNext()) { updateMainFile(); } else { throw new IllegalStateException( "No files were uploaded, delete entry in database for " + derivate.getId() + "!"); } } this.setStatus(MCRProcessableStatus.successful); } private void updateMainFile() throws IOException, MCRAccessException { String mainFile = derivate.getDerivate().getInternals().getMainDoc(); MCRObjectDerivate der = MCRMetadataManager.retrieveMCRDerivate(getOrCreateDerivateID()).getDerivate(); boolean hasNoMainFile = ((der.getInternals().getMainDoc() == null) || (der.getInternals().getMainDoc().trim() .isEmpty())); if ((mainFile == null) || mainFile.trim().isEmpty() && hasNoMainFile) { mainFile = getPathOfMainFile(); LOGGER.debug("Setting main file to {}", mainFile); derivate.getDerivate().getInternals().setMainDoc(mainFile); MCRMetadataManager.update(derivate); } } protected String getPathOfMainFile() throws IOException { MainFileFinder mainFileFinder = new MainFileFinder(); Files.walkFileTree(rootDir, mainFileFinder); Path mainFile = mainFileFinder.getMainFile(); return mainFile == null ? "" : mainFile.subpath(0, mainFile.getNameCount()).toString(); } public String getDerivateID() { return derivateID; } public String getDocumentID() { return documentID; } private static class MainFileFinder extends SimpleFileVisitor<Path> { private Path mainFile; @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (mainFile != null) { if (mainFile.getFileName().compareTo(file.getFileName()) > 0) { mainFile = file; } } else { mainFile = file; } return super.visitFile(file, attrs); } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { FileVisitResult result = super.postVisitDirectory(dir, exc); if (mainFile != null) { return FileVisitResult.TERMINATE; } return result; } public Path getMainFile() { return mainFile; } } }
13,898
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUploadHelper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/fileupload/MCRUploadHelper.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.fileupload; import java.io.File; import java.io.IOException; import java.nio.CharBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.access.MCRAccessException; import org.mycore.access.MCRAccessManager; import org.mycore.access.MCRRuleAccessInterface; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRException; import org.mycore.common.MCRPersistenceException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.classifications2.MCRCategoryDAO; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetaClassification; import org.mycore.datamodel.metadata.MCRMetaIFS; import org.mycore.datamodel.metadata.MCRMetaLinkID; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.datamodel.niofs.utils.MCRFileCollectingFileVisitor; import jakarta.persistence.EntityTransaction; /** * Common helper class for all services handling file upload. * * @author Frank Lützenkirchen * */ public abstract class MCRUploadHelper { private static final Logger LOGGER = LogManager.getLogger(MCRUploadHelper.class); private static final Pattern PATH_SEPERATOR = Pattern.compile(Pattern.quote(File.separator.replace('\\', '/'))); public static final String FILE_NAME_PATTERN_PROPERTY = "MCR.FileUpload.FileNamePattern"; public static final String FILE_NAME_PATTERN = MCRConfiguration2.getStringOrThrow(FILE_NAME_PATTERN_PROPERTY); public static final Predicate<String> FILE_NAME_PREDICATE = Pattern.compile(FILE_NAME_PATTERN).asMatchPredicate(); public static final String IGNORE_MAINFILE_PROPERTY = "MCR.Upload.NotPreferredFiletypeForMainfile"; /** * reserved URI characters should not be in uploaded filenames. See RFC3986, * Section 2.2 and 7.3 */ private static final String RESERVERD_CHARACTERS = new String( new char[] { ':', '?', '%', '#', '[', ']', '@', '!', '$', '&', '\'', '(', ')', '*', ',', ';', '=', '\'', '+', '\\' }); private static final String WINDOWS_RESERVED_CHARS = "<>:\"|?*"; private static final String[] RESERVED_NAMES = { "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "con", "nul", "prn", "aux" }; private static final int SAVE_LENGTH = Stream.of(RESERVED_NAMES).mapToInt(String::length).max().getAsInt(); /** * checks if path contains reserved URI characters or path starts or ends with whitespace. There are some characters * that are maybe allowed in file names but are reserved in URIs. * * @see <a href="http://tools.ietf.org/html/rfc3986#section-2.2">RFC3986, Section 2.2</a> * @param path * complete path name * @param checkFilePattern * checks if the last path element matches the pattern * defined in the property {@link #FILE_NAME_PATTERN_PROPERTY} * @throws MCRException * if path contains reserved character */ public static void checkPathName(String path, boolean checkFilePattern) throws MCRException { List<String> pathParts = splitPath(path).collect(Collectors.toList()); pathParts.forEach(pathElement -> { checkNotEmpty(path, pathElement); checkOnlyDots(path, pathElement); checkTrimmed(pathElement); checkEndsWithDot(pathElement); checkReservedNames(pathElement); checkInvalidCharacters(pathElement); }); String actualFileName = pathParts.get(pathParts.size() - 1); if (checkFilePattern && !FILE_NAME_PREDICATE.test(actualFileName)) { throw new MCRException( "File name does not match " + FILE_NAME_PATTERN + " defined in " + FILE_NAME_PATTERN_PROPERTY + "!"); } } /** * see {@link #checkPathName(String, boolean)} checkFilePattern=true */ public static void checkPathName(String path) throws MCRException { checkPathName(path, true); } private static Stream<String> splitPath(String path) { return PATH_SEPERATOR.splitAsStream(path); } private static void checkNotEmpty(String path, String pathElement) { if (pathElement.isEmpty()) { throw new MCRException("Path " + path + " contains empty path elements."); } } private static void checkOnlyDots(String path, String pathElement) { if (!pathElement.chars().filter(c -> c != '.').findAny().isPresent()) { throw new MCRException("Path " + path + " contains invalid path element: " + pathElement); } } private static void checkTrimmed(String pathElement) { if (pathElement.trim().length() != pathElement.length()) { throw new MCRException( "Path element '" + pathElement + "' may not start or end with whitespace character."); } } private static void checkEndsWithDot(String pathElement) { if (pathElement.charAt(pathElement.length() - 1) == '.') { throw new MCRException("Path element " + pathElement + " may not end with '.'"); } } private static void checkReservedNames(String pathElement) { if (pathElement.length() <= SAVE_LENGTH) { String lcPathElement = pathElement.toLowerCase(Locale.ROOT); if (Stream.of(RESERVED_NAMES).anyMatch(lcPathElement::equals)) { throw new MCRException("Path element " + pathElement + " is an illegal Windows file name."); } } } private static void checkInvalidCharacters(String pathElement) { if (getOSIllegalCharacterStream(pathElement).findAny().isPresent()) { throw new MCRException("Path element " + pathElement + " contains illegal characters: " + getOSIllegalCharacterStream(pathElement) .mapToObj(Character::toChars) .map(CharBuffer::wrap) .collect(Collectors.joining("', '", "'", "'"))); } } private static IntStream getOSIllegalCharacterStream(String path) { //https://msdn.microsoft.com/en-us/library/aa365247.aspx return path .chars() .filter( c -> c < '\u0020' || WINDOWS_RESERVED_CHARS.indexOf(c) != -1 || RESERVERD_CHARACTERS.indexOf(c) != -1); } static String getFileName(String path) { int pos = Math.max(path.lastIndexOf('\\'), path.lastIndexOf("/")); return path.substring(pos + 1); } static EntityTransaction startTransaction() { LOGGER.debug("Starting transaction"); final EntityTransaction transaction = MCREntityManagerProvider.getCurrentEntityManager().getTransaction(); transaction.begin(); return transaction; } static void commitTransaction(EntityTransaction tx) { LOGGER.debug("Committing transaction"); if (tx != null) { tx.commit(); } else { LOGGER.error("Cannot commit transaction. Transaction is null."); } } static void rollbackAnRethrow(EntityTransaction tx, Exception e) throws Exception { LOGGER.debug("Rolling back transaction"); if (tx != null) { tx.rollback(); } else { LOGGER.error("Error while rolling back transaction. Transaction is null."); } throw e; } public static MCRObjectID getNewCreateDerivateID(MCRObjectID objId) { String projectID = objId.getProjectId(); return MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(projectID + "_derivate"); } /** * Detects the main file of a derivate. The main file is the first file that is not in the ignore list. * @param rootPath the root path of the derivate * @return the main file * @throws IOException if an I/O error is thrown by a visitor method. */ public static Optional<MCRPath> detectMainFile(MCRPath rootPath) throws IOException { List<String> ignoreMainfileList = MCRConfiguration2.getString(IGNORE_MAINFILE_PROPERTY) .map(MCRConfiguration2::splitValue) .map(s -> s.collect(Collectors.toList())) .orElseGet(Collections::emptyList); MCRFileCollectingFileVisitor<Path> visitor = new MCRFileCollectingFileVisitor<>(); Files.walkFileTree(rootPath, visitor); //sort files by name ArrayList<Path> paths = visitor.getPaths(); if(paths.isEmpty()) { return Optional.empty(); } paths.sort(Comparator.comparing(Path::getNameCount) .thenComparing(Path::getFileName)); //extract first file, before filtering MCRPath firstPath = MCRPath.toMCRPath(paths.get(0)); //filter files, remove files that should be ignored for mainfile return paths.stream() .map(MCRPath.class::cast) .filter(p -> ignoreMainfileList.stream().noneMatch(p.getOwnerRelativePath()::endsWith)) .findFirst() .or(() -> Optional.of(firstPath)); } public static MCRDerivate createDerivate(MCRObjectID objectID, List<MCRMetaClassification> classifications) throws MCRPersistenceException, MCRAccessException { MCRObjectID derivateID = getNewCreateDerivateID(objectID); MCRDerivate derivate = new MCRDerivate(); derivate.setId(derivateID); derivate.getDerivate().getClassifications().addAll(classifications); String schema = MCRConfiguration2.getString("MCR.Metadata.Config.derivate") .orElse("datamodel-derivate.xml") .replaceAll(".xml", ".xsd"); derivate.setSchema(schema); MCRMetaLinkID linkId = new MCRMetaLinkID(); linkId.setSubTag("linkmeta"); linkId.setReference(objectID, null, null); derivate.getDerivate().setLinkMeta(linkId); MCRMetaIFS ifs = new MCRMetaIFS(); ifs.setSubTag("internal"); ifs.setSourcePath(null); derivate.getDerivate().setInternals(ifs); MCRMetadataManager.create(derivate); setDefaultPermissions(derivateID); return derivate; } public static void setDefaultPermissions(MCRObjectID derivateID) { if (MCRConfiguration2.getBoolean("MCR.Access.AddDerivateDefaultRule").orElse(true)) { MCRRuleAccessInterface aclImpl = MCRAccessManager.getAccessImpl(); Collection<String> configuredPermissions = aclImpl.getAccessPermissionsFromConfiguration(); for (String permission : configuredPermissions) { MCRAccessManager.addRule(derivateID, permission, MCRAccessManager.getTrueRule(), "default derivate rule"); } } } /** * Gets the classifications from the given string. * @param classifications the string * @return the classifications */ public static List<MCRMetaClassification> getClassifications(String classifications) { if (classifications == null || classifications.isBlank()) { return Collections.emptyList(); } final MCRCategoryDAO dao = MCRCategoryDAOFactory.getInstance(); final List<MCRCategoryID> categoryIDS = Stream.of(classifications) .filter(Objects::nonNull) .filter(Predicate.not(String::isBlank)) .flatMap(c -> Stream.of(c.split(","))) .filter(Predicate.not(String::isBlank)) .filter(cv -> cv.contains(":")) .map(classValString -> { final String[] split = classValString.split(":"); return new MCRCategoryID(split[0], split[1]); }).collect(Collectors.toList()); if (!categoryIDS.stream().allMatch(dao::exist)) { final String parsedIDS = categoryIDS.stream().map(Object::toString).collect(Collectors.joining(",")); throw new MCRException(String.format(Locale.ROOT, "One of the Categories \"%s\" was not found", parsedIDS)); } return categoryIDS.stream() .map(category -> new MCRMetaClassification("classification", 0, null, category.getRootID(), category.getId())) .collect(Collectors.toList()); } }
13,788
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRExternalProcess.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRExternalProcess.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.cli; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UncheckedIOException; import java.nio.charset.Charset; import java.util.Optional; import java.util.concurrent.CompletableFuture; 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.MCRByteContent; import org.mycore.common.content.MCRContent; public class MCRExternalProcess { private static final Logger LOGGER = LogManager.getLogger(); private final InputStream stdin; private String[] command; private int exitValue; private CompletableFuture<MCRByteContent> output; private CompletableFuture<MCRByteContent> errors; public MCRExternalProcess(String... command) { this(null, command); } public MCRExternalProcess(String command) { this(command.split("\\s+")); } public MCRExternalProcess(InputStream stdin, String... command) { this.stdin = stdin; this.command = command; } public int run() throws IOException, InterruptedException { LOGGER.debug(() -> Stream.of(command) .collect(Collectors.joining(" "))); ProcessBuilder pb = new ProcessBuilder(command); Process p = pb.start(); CompletableFuture<Void> input = MCRStreamSucker.writeAllBytes(stdin, p); output = MCRStreamSucker.readAllBytesAsync(p.getInputStream()).thenApply(MCRStreamSucker::toContent); errors = MCRStreamSucker.readAllBytesAsync(p.getErrorStream()).thenApply(MCRStreamSucker::toContent); try { exitValue = p.waitFor(); } catch (InterruptedException e) { p.destroy(); throw e; } CompletableFuture.allOf(input, output, errors) .whenComplete((Void, ex) -> MCRStreamSucker.destroyProcess(p, ex)); return exitValue; } public int getExitValue() { return exitValue; } public String getErrors() { return new String(errors.join().asByteArray(), Charset.defaultCharset()); } public MCRContent getOutput() { return output.join(); } private static class MCRStreamSucker { private static final Logger LOGGER = LogManager.getLogger(); private static CompletableFuture<byte[]> readAllBytesAsync(InputStream is) { return CompletableFuture.supplyAsync(() -> readAllBytes(is)); } private static byte[] readAllBytes(InputStream is) throws UncheckedIOException { try { return is.readAllBytes(); } catch (IOException e) { throw new UncheckedIOException(e); } } private static MCRByteContent toContent(byte[] data) { return new MCRByteContent(data, System.currentTimeMillis()); } private static void destroyProcess(Process p, Throwable ex) { if (ex != null) { LOGGER.warn("Error while sucking stdout or stderr streams.", ex); } LOGGER.debug("Destroy process {}", p.pid()); p.destroy(); } public static CompletableFuture<Void> writeAllBytes(InputStream stdin, Process p) throws UncheckedIOException { return Optional.ofNullable(stdin) .map(in -> CompletableFuture.runAsync(() -> { try { try (OutputStream stdinPipe = p.getOutputStream()) { in.transferTo(stdinPipe); } } catch (IOException e) { throw new UncheckedIOException(e); } })) .orElseGet(CompletableFuture::allOf); } } }
4,603
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAccessCommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRAccessCommands.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.cli; import static org.mycore.common.MCRConstants.DEFAULT_ENCODING; import static org.mycore.common.MCRConstants.XLINK_NAMESPACE; import static org.mycore.common.MCRConstants.XSI_NAMESPACE; import java.io.File; import java.io.FileOutputStream; import java.util.Collection; import java.util.List; import java.util.Objects; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.mycore.access.MCRAccessManager; import org.mycore.access.MCRRuleAccessInterface; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRFileContent; import org.mycore.common.xml.MCRURIResolver; import org.mycore.common.xml.MCRXMLParserFactory; import org.mycore.frontend.MCRWebsiteWriteProtection; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; /** * This class provides a set of commands for the org.mycore.access management * which can be used by the command line interface. * * @author Heiko Helmbrecht * @author Jens Kupferschmidt */ @MCRCommandGroup(name = "Access Commands") public class MCRAccessCommands extends MCRAbstractCommands { /** The logger */ private static Logger LOGGER = LogManager.getLogger(MCRAccessCommands.class.getName()); /** * Check the file name * * @param filename * the filename of the user data input * @return true if the file name is okay */ private static boolean checkFilename(String filename) { if (!filename.endsWith(".xml")) { LOGGER.warn("{} ignored, does not end with *.xml", filename); return false; } if (!new File(filename).isFile()) { LOGGER.warn("{} ignored, is not a file.", filename); return false; } return true; } /** * This method sets the new permissions given in a certain file * * @param filename * the filename of the file that contains the mcrpermissions * */ public static void createPermissionsFromFile(String filename) throws Exception { MCRRuleAccessInterface accessImpl = MCRAccessManager.requireRulesInterface(); if (!checkFilename(filename)) { return; } LOGGER.info("Reading file {} ...", filename); Document doc = MCRXMLParserFactory.getValidatingParser().parseXML(new MCRFileContent(filename)); Element rootelm = doc.getRootElement(); if (!rootelm.getName().equals("mcrpermissions")) { throw new MCRException("The data are not for mcrpermissions."); } List<Element> listelm = rootelm.getChildren("mcrpermission"); for (Element mcrpermission : listelm) { String permissionName = mcrpermission.getAttributeValue("name").trim(); String ruleDescription = mcrpermission.getAttributeValue("ruledescription"); if (ruleDescription == null) { ruleDescription = ""; } Element rule = mcrpermission.getChild("condition").clone(); String objectid = mcrpermission.getAttributeValue("objectid"); if (objectid == null) { accessImpl.addRule(permissionName, rule, ruleDescription); } else { accessImpl.addRule(objectid, permissionName, rule, ruleDescription); } } } /** * This method deletes the old permissions (if given any) and sets the new * permissions given in a certain file * * @param filename * the filename of the file that contains the mcrpermissions * @see #createPermissionsFromFile(String) */ @MCRCommand(syntax = "load permissions data from file {0}", help = "The command loads the permissions data of the access control system with data from the file {0}.", order = 10) public static void loadPermissionsFromFile(String filename) throws Exception { createPermissionsFromFile(filename); } /** * delete all permissions */ @MCRCommand(syntax = "delete all permissions", help = "Remove all permission entries from the Access Control System.", order = 40) public static void deleteAllPermissions() { MCRRuleAccessInterface accessImpl = MCRAccessManager.requireRulesInterface(); for (String permission : accessImpl.getPermissions()) { accessImpl.removeRule(permission); } } /** * delete the permission {0} * * @param permission * the name of the permission */ @MCRCommand(syntax = "delete permission {0}", help = "Remove a named permission entriy from the Access Control System.", order = 30) public static void deletePermission(String permission) { MCRRuleAccessInterface accessImpl = MCRAccessManager.requireRulesInterface(); accessImpl.removeRule(permission); } /** * This method invokes MCRUserMgr.getAllPrivileges() and retrieves a * ArrayList of all privileges stored in the persistent datastore. */ @MCRCommand(syntax = "list all permissions", help = "List all permission entries.", order = 20) public static void listAllPermissions() throws MCRException { MCRRuleAccessInterface accessImpl = MCRAccessManager.requireRulesInterface(); Collection<String> permissions = accessImpl.getPermissions(); boolean noPermissionsDefined = true; for (String permission : permissions) { noPermissionsDefined = false; String description = accessImpl.getRuleDescription(permission); if (description.equals("")) { description = "No description"; } Element rule = accessImpl.getRule(permission); LOGGER.info(" {}", permission); LOGGER.info(" {}", description); if (rule != null) { XMLOutputter o = new XMLOutputter(); LOGGER.info(" {}", o.outputString(rule)); } } if (noPermissionsDefined) { LOGGER.warn("No permissions defined"); } LOGGER.info(""); } /** * This method just export the permissions to a file * * @param filename * the file written to */ @MCRCommand(syntax = "export all permissions to file {0}", help = "Export all permissions from the Access Control System to the file {0}.", order = 50) public static void exportAllPermissionsToFile(String filename) throws Exception { MCRRuleAccessInterface accessImpl = MCRAccessManager.requireRulesInterface(); Element mcrpermissions = new Element("mcrpermissions"); mcrpermissions.addNamespaceDeclaration(XSI_NAMESPACE); mcrpermissions.addNamespaceDeclaration(XLINK_NAMESPACE); mcrpermissions.setAttribute("noNamespaceSchemaLocation", "MCRPermissions.xsd", XSI_NAMESPACE); Document doc = new Document(mcrpermissions); Collection<String> permissions = accessImpl.getPermissions(); for (String permission : permissions) { Element mcrpermission = new Element("mcrpermission"); mcrpermission.setAttribute("name", permission); String ruleDescription = accessImpl.getRuleDescription(permission); if (!ruleDescription.equals("")) { mcrpermission.setAttribute("ruledescription", ruleDescription); } Element rule = accessImpl.getRule(permission); mcrpermission.addContent(rule); mcrpermissions.addContent(mcrpermission); } File file = new File(filename); if (file.exists()) { LOGGER.warn("File {} yet exists, overwrite.", filename); } FileOutputStream fos = new FileOutputStream(file); LOGGER.info("Writing to file {} ...", filename); String mcrEncoding = MCRConfiguration2.getString("MCR.Metadata.DefaultEncoding").orElse(DEFAULT_ENCODING); XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setEncoding(mcrEncoding)); out.output(doc, fos); } private static String filenameToUri(String filename) { return new File(filename).toURI().toString(); } private static Element getRuleFromUri(String uri) { Element rule = MCRURIResolver.instance().resolve(uri); if (rule == null || !Objects.equals(rule.getName(), "condition")) { LOGGER.warn("ROOT element is not valid, a valid rule would be for example:"); LOGGER.warn("<condition format=\"xml\"><boolean operator=\"true\" /></condition>"); return null; } return rule; } /** * updates the permission for a given id and a given permission type with a * given rule * * @param permission * String type of permission like read, writedb, etc. * @param id * String the URI of to the XML resource, that contains the rule * @param ruleUri * String the path to the xml file, that contains the rule */ @MCRCommand(syntax = "update permission {0} for id {1} with rule {2}", help = "The command updates access rule for a given id of a given permission with a given special rule", order = 70) public static void permissionUpdateForID(String permission, String id, String ruleUri) { permissionUpdateForID(permission, id, ruleUri, ""); } /** * updates the permission for a given id and a given permission type with a * given rule * * @param permission * String type of permission like read, writedb, etc. * @param id * String the URI of to the XML resource, that contains the rule * @param strFileRule * String the path to the xml file, that contains the rule */ @MCRCommand(syntax = "update permission {0} for id {1} with rulefile {2}", help = "The command updates access rule for a given id of a given permission with a given special rule", order = 71) public static void permissionFileUpdateForID(String permission, String id, String strFileRule) { permissionUpdateForID(permission, id, filenameToUri(strFileRule)); } /** * updates the permission for a given id and a given permission type with a * given rule * * @param permission * String type of permission like read, writedb, etc. * @param id * String the id of the object the rule is assigned to * @param ruleUri * String the URI of to the XML resource, that contains the rule * @param description * String give a special description, if the semantics of your * rule is multiple used */ @MCRCommand(syntax = "update permission {0} for id {1} with rule {2} described by {3}", help = "The command updates access rule for a given id of a given permission with a given special rule", order = 60) public static void permissionUpdateForID(String permission, String id, String ruleUri, String description) { MCRRuleAccessInterface accessImpl = MCRAccessManager.requireRulesInterface(); Element rule = getRuleFromUri(ruleUri); if (rule == null) { return; } accessImpl.addRule(id, permission, rule, description); } /** * updates the permission for a given id and a given permission type with a * given rule * * @param permission * String type of permission like read, writedb, etc. * @param id * String the id of the object the rule is assigned to * @param strFileRule * String the path to the xml file, that contains the rule * @param description * String give a special description, if the semantics of your * rule is multiple used */ @MCRCommand(syntax = "update permission {0} for id {1} with rulefile {2} described by {3}", help = "The command updates access rule for a given id of a given permission with a given special rule", order = 61) public static void permissionFileUpdateForID(String permission, String id, String strFileRule, String description) { permissionUpdateForID(permission, id, filenameToUri(strFileRule), description); } /** * updates the permissions for all ids of a given MCRObjectID-Type with a * given rule and a given permission * * @param permission * String type of permission like read, writedb, etc. * @param ruleUri * String the URI of the rule XML resource, that contains the rule */ @MCRCommand( syntax = "update permission {0} for selected with rule {1}", help = "The command updates access rule for a given permission and all ids " + "of a given MCRObject-Type with a given special rule", order = 90) public static void permissionUpdateForSelected(String permission, String ruleUri) { permissionUpdateForSelected(permission, ruleUri, ""); } /** * updates the permissions for all ids of a given MCRObjectID-Type with a * given rule and a given permission * * @param permission * String type of permission like read, writedb, etc. * @param strFileRule * String the path to the xml file, that contains the rule */ @MCRCommand( syntax = "update permission {0} for selected with rulefile {1}", help = "The command updates access rule for a given permission and all ids " + "of a given MCRObject-Type with a given special rule", order = 91) public static void permissionFileUpdateForSelected(String permission, String strFileRule) { permissionUpdateForSelected(permission, filenameToUri(strFileRule)); } /** * updates the permissions for all ids of a given MCRObjectID-Type and for a * given permission type with a given rule * * @param permission * String type of permission like read, writedb, etc. * @param ruleUri * String the URI of the rule XML resource, that contains the rule * @param description * String give a special description, if the semantics of your * rule is multiple used */ @MCRCommand( syntax = "update permission {0} for selected with rule {1} described by {2}", help = "The command updates access rule for a given permission and all ids " + "of a given MCRObject-Type with a given special rule", order = 80) public static void permissionUpdateForSelected(String permission, String ruleUri, String description) { MCRRuleAccessInterface accessImpl = MCRAccessManager.requireRulesInterface(); Element rule = getRuleFromUri(ruleUri); if (rule == null) { return; } for (String id : MCRObjectCommands.getSelectedObjectIDs()) { accessImpl.addRule(id, permission, rule, description); } } /** * updates the permissions for all ids of a given MCRObjectID-Type and for a * given permission type with a given rule * * @param permission * String type of permission like read, writedb, etc. * @param strFileRule * String the path to the xml file, that contains the rule * @param description * String give a special description, if the semantics of your * rule is multiple used */ @MCRCommand( syntax = "update permission {0} for selected with rulefile {1} described by {2}", help = "The command updates access rule for a given permission and all ids " + "of a given MCRObject-Type with a given special rule", order = 80) public static void permissionFileUpdateForSelected(String permission, String strFileRule, String description) { permissionUpdateForSelected(permission, filenameToUri(strFileRule), description); } /** * delete a given permission for a given id * * @param permission * String type of permission like read, writedb, etc. * @param id * String the id of the object the rule is assigned to */ @MCRCommand(syntax = "delete permission {0} for id {1}", help = "The command delete access rule for a given id of a given permission", order = 110) public static void permissionDeleteForID(String permission, String id) { MCRRuleAccessInterface accessImpl = MCRAccessManager.requireRulesInterface(); accessImpl.removeRule(id, permission); } /** * delete all permissions for a given id * * @param id * String the id of the object the rule is assigned to */ @MCRCommand(syntax = "delete all permissions for id {1}", help = "The command delete all access rules for a given id", order = 120) public static void permissionDeleteAllForID(String id) { MCRRuleAccessInterface accessImpl = MCRAccessManager.requireRulesInterface(); accessImpl.removeAllRules(id); } /** * delete all permissions for all selected objects * * @param permission * String type of permission like read, writedb, etc. * @see MCRObjectCommands#getSelectedObjectIDs() */ @MCRCommand(syntax = "delete permission {0} for selected", help = "The command delete access rule for a query selected set of object ids of a given permission", order = 130) public static void permissionDeleteForSelected(String permission) { MCRRuleAccessInterface accessImpl = MCRAccessManager.requireRulesInterface(); for (String id : MCRObjectCommands.getSelectedObjectIDs()) { accessImpl.removeRule(id, permission); } } /** * delete all permissions for all selected objects * * @see MCRObjectCommands#getSelectedObjectIDs() */ @MCRCommand(syntax = "delete all permissions for selected", help = "The command delete all access rules for a query selected set of object ids", order = 140) public static void permissionDeleteAllForSelected() { MCRRuleAccessInterface accessImpl = MCRAccessManager.requireRulesInterface(); for (String id : MCRObjectCommands.getSelectedObjectIDs()) { accessImpl.removeAllRules(id); } } @MCRCommand( syntax = "set website read only {0}", help = "This command set the whole website into read only mode and provides the given message to users. " + "Nobody, except super user can write on system, using web frontend. Parameter {0} specifies a message " + "to be displayed", order = 150) public static void setWebsiteReadOnly(String message) { MCRWebsiteWriteProtection.activate(message); } @MCRCommand( syntax = "set website read only", help = "This command set the whole website into read only mode. " + "An already configurated message will be displayed to users. " + "Nobody, except super user can write on system, using web frontend", order = 160) public static void setWebsiteReadOnly() { MCRWebsiteWriteProtection.activate(); } @MCRCommand( syntax = "unset website read only", help = "This command removes the write protection (read only) from website. " + "After unsetting anybody can write as usual, using web frontend", order = 170) public static void unsetWebsiteReadOnly() { MCRWebsiteWriteProtection.deactivate(); } }
20,847
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCommand.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRCommand.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.cli; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.text.Format; import java.text.MessageFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.StringTokenizer; import org.apache.commons.lang3.ClassUtils; 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.MCRConfigurationException; /** * Represents a command understood by the command line interface. A command has an external input syntax that the user * uses to invoke the command and points to a method in a class that implements the command. * * @see MCRCommandLineInterface * @author Frank Lützenkirchen * @author Jens Kupferschmidt */ public class MCRCommand { private static final Logger LOGGER = LogManager.getLogger(MCRCommand.class); /** The input format used for invoking this command */ protected MessageFormat messageFormat; /** The java method that implements this command */ private Method method; /** The types of the invocation parameters */ protected Class<?>[] parameterTypes; /** The class providing the implementation method */ protected String className; /** The method implementing this command */ protected String methodName; /** The beginning of the message format up to the first parameter */ protected String suffix; /** The help text String */ protected String help; /** * use this to overwrite this class. */ protected MCRCommand() { } /** * Creates a new MCRCommand. * * @param format * the command syntax, e.g. "save document {0} to directory {1}" * @param methodSignature * the method to invoke, e.g. "miless.commandline.DocumentCommands.saveDoc int String" * @param helpText * the helpt text for this command */ public MCRCommand(String format, String methodSignature, String helpText) { StringTokenizer st = new StringTokenizer(methodSignature, " "); String token = st.nextToken(); int point = token.lastIndexOf("."); className = token.substring(0, point); methodName = token.substring(point + 1); int numParameters = st.countTokens(); parameterTypes = new Class<?>[numParameters]; messageFormat = new MessageFormat(format, Locale.ROOT); for (int i = 0; i < numParameters; i++) { token = st.nextToken(); Format f = null; switch (token) { case "int" -> { parameterTypes[i] = Integer.TYPE; f = NumberFormat.getIntegerInstance(Locale.ROOT); } case "long" -> { parameterTypes[i] = Long.TYPE; f = NumberFormat.getIntegerInstance(Locale.ROOT); } //CSOFF: InnerAssignment case "String" -> parameterTypes[i] = String.class; //CSON: InnerAssignment default -> unsupportedArgException(methodSignature, token); } messageFormat.setFormat(i, f); } int pos = format.indexOf("{"); suffix = pos == -1 ? format : format.substring(0, pos); help = Objects.requireNonNullElse(helpText, "No help text available for this command"); } private void unsupportedArgException(String methodSignature, String token) { throw new MCRConfigurationException("Error while parsing command definitions for command line interface:\n" + "Unsupported argument type '" + token + "' in command " + methodSignature); } public MCRCommand(Method cmd) { className = cmd.getDeclaringClass().getName(); methodName = cmd.getName(); parameterTypes = cmd.getParameterTypes(); org.mycore.frontend.cli.annotation.MCRCommand cmdAnnotation = cmd .getAnnotation(org.mycore.frontend.cli.annotation.MCRCommand.class); help = cmdAnnotation.help(); messageFormat = new MessageFormat(cmdAnnotation.syntax(), Locale.ROOT); setMethod(cmd); for (int i = 0; i < parameterTypes.length; i++) { Class<?> paramtype = parameterTypes[i]; if (ClassUtils.isAssignable(paramtype, Integer.class, true) || ClassUtils.isAssignable(paramtype, Long.class, true)) { messageFormat.setFormat(i, NumberFormat.getIntegerInstance(Locale.ROOT)); } else if (!String.class.isAssignableFrom(paramtype)) { unsupportedArgException(className + "." + methodName, paramtype.getName()); } } int pos = cmdAnnotation.syntax().indexOf("{"); suffix = pos == -1 ? cmdAnnotation.syntax() : cmdAnnotation.syntax().substring(0, pos); } private void initMethod(ClassLoader classLoader) throws ClassNotFoundException, NoSuchMethodException { if (method == null) { setMethod(Class.forName(className, true, classLoader).getMethod(methodName, parameterTypes)); } } /** * The method return the helpt text of this command. * * @return the help text as String */ public String getHelpText() { return help; } /** * Parses an input string and tries to match it with the message format used to invoke this command. * * @param commandLine * The input from the command line * @return null, if the input does not match the message format; otherwise an array holding the parameter values * from the command line */ protected Object[] parseCommandLine(String commandLine) { try { return messageFormat.parse(commandLine); } catch (ParseException ex) { return null; } } /** * Transforms the parameters found by the MessageFormat parse method into such that can be used to invoke the method * implementing this command * * @param commandParameters * The parameters as returned by the <code>parseCommandLine</code> method */ private void prepareInvocationParameters(Object[] commandParameters) { for (int i = 0; i < commandParameters.length; i++) { if (parameterTypes[i] == Integer.TYPE) { commandParameters[i] = ((Number) commandParameters[i]).intValue(); } } } /** * Tries to invoke the method that implements the behavior of this command given the user input from the command * line. This is only done when the command line syntax matches the syntax used by this command. * * @return null, if the command syntax did not match and the command was not invoked, otherwise a List of commands * is returned which may be empty or otherwise contains commands that should be processed next * @param input * The command entered by the user at the command prompt * @throws IllegalAccessException * when the method can not be invoked * @throws InvocationTargetException * when an exception is thrown by the invoked method * @throws ClassNotFoundException * when the class providing the method could not be found * @throws NoSuchMethodException * when the method specified does not exist */ public List<String> invoke(String input) throws IllegalAccessException, InvocationTargetException, ClassNotFoundException, NoSuchMethodException { return invoke(input, MCRClassTools.getClassLoader()); } @SuppressWarnings({ "unchecked", "rawtypes" }) public List<String> invoke(String input, ClassLoader classLoader) throws IllegalAccessException, InvocationTargetException, ClassNotFoundException, NoSuchMethodException { if (!input.startsWith(suffix)) { return null; } Object[] commandParameters = parseCommandLine(input); if (commandParameters == null) { LOGGER.info("No match for syntax: {}", getSyntax()); return null; } LOGGER.info("Syntax matched (executed): {}", getSyntax()); initMethod(classLoader); prepareInvocationParameters(commandParameters); Object result = method.invoke(null, commandParameters); if (result instanceof List resultList && !resultList.isEmpty() && resultList.get(0) instanceof String) { return (List<String>) result; } else { return new ArrayList<>(); } } /** * Returns the input syntax to be used for invoking this command from the command prompt. * * @return the input syntax for this command */ public final String getSyntax() { return messageFormat.toPattern(); } public void outputHelp() { MCRCommandLineInterface.output(getSyntax()); MCRCommandLineInterface.output(" " + getHelpText()); MCRCommandLineInterface.output(""); } /** * @param method * the method to set */ public void setMethod(Method method) { if (!Modifier.isStatic(method.getModifiers())) { throw new MCRException("MCRCommand method needs to be static: " + method); } this.method = method; } }
10,387
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAbstractCommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRAbstractCommands.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.cli; import java.util.ArrayList; /** * This class is an abstract for the implementation of command classes for the * MyCoRe commandline system. * * @author Jens Kupferschmidt */ public abstract class MCRAbstractCommands implements MCRExternalCommandInterface { /** The array holding all known commands */ protected ArrayList<MCRCommand> command = null; private String displayName; /** * The constructor. */ protected MCRAbstractCommands() { init(); } private void init() { setCommand(new ArrayList<>()); } /** * @param displayName * a human readable name for this collection of commands */ protected MCRAbstractCommands(String displayName) { init(); this.displayName = displayName; } /** * The method return the list of possible commands of this class. Each * command has TWO Strings, a String of the user command syntax and a String * of the called method. * * @return a ascending sorted command pair ArrayList */ public ArrayList<MCRCommand> getPossibleCommands() { return this.command; } @Override public String getDisplayName() { return this.displayName == null ? this.getClass().getSimpleName() : this.displayName; } @Override public void setDisplayName(String s) { this.displayName = s; } public void addCommand(MCRCommand cmd) { if (this.command == null) { init(); } this.command.add(cmd); } private void setCommand(ArrayList<MCRCommand> command) { this.command = command; } }
2,420
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRExternalCommandInterface.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRExternalCommandInterface.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.cli; import java.util.ArrayList; /** * This interface is designed to incude external application commands. * * @author Jens Kupferschmidt */ public interface MCRExternalCommandInterface { /** * The method return the list of possible commands of this class. Each * command has TWO Strings, a String of the user command syntax and a String * of the called method. * * @return a command pair ArrayList */ ArrayList<MCRCommand> getPossibleCommands(); /** * Returns the display name of the external commands. If the display name * has not been set the simple class name is returned * * @return the display name of the external commands */ String getDisplayName(); /** * Sets the display name. */ void setDisplayName(String s); }
1,579
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRClassification2Commands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRClassification2Commands.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.cli; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.stream.StreamResult; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.jdom2.transform.JDOMSource; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRConstants; import org.mycore.common.MCRException; import org.mycore.common.content.MCRSourceContent; import org.mycore.common.content.MCRURLContent; import org.mycore.common.xml.MCRXMLParserFactory; import org.mycore.common.xml.MCRXSLTransformerUtils; 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.classifications2.MCRUnmappedCategoryRemover; import org.mycore.datamodel.classifications2.impl.MCRCategoryDAOImpl; import org.mycore.datamodel.classifications2.impl.MCRCategoryImpl; import org.mycore.datamodel.classifications2.utils.MCRCategoryTransformer; import org.mycore.datamodel.classifications2.utils.MCRXMLTransformer; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; import jakarta.persistence.EntityManager; /** * Commands for the classification system. * * @author Thomas Scheffler (yagee) */ @MCRCommandGroup(name = "Classification Commands") public class MCRClassification2Commands extends MCRAbstractCommands { private static Logger LOGGER = LogManager.getLogger(); private static final MCRCategoryDAO DAO = MCRCategoryDAOFactory.getInstance(); /** Default transformer script */ public static final String DEFAULT_STYLE = "save-classification.xsl"; /** Static compiled transformer stylesheets */ private static final Map<String, Transformer> TRANSFORMER_CACHE = new HashMap<>(); /** * Deletes a classification * * @param classID classification ID * @see MCRCategoryDAO#deleteCategory(MCRCategoryID) */ @MCRCommand(syntax = "delete classification {0}", help = "The command remove the classification with MCRObjectID {0} from the system.", order = 30) public static void delete(String classID) { DAO.deleteCategory(MCRCategoryID.rootID(classID)); } /** * Counts the classification categories on top level * * @param classID classification ID */ @MCRCommand(syntax = "count classification children of {0}", help = "The command count the categoies of the classification with MCRObjectID {0} in the system.", order = 80) public static void countChildren(String classID) { MCRCategory category = DAO.getCategory(MCRCategoryID.rootID(classID), 1); System.out.printf(Locale.ROOT, "%s has %d children", category.getId(), category.getChildren().size()); } /** * Adds a classification. * * Classification is built from a file. * * @param filename * file in mcrclass xml format * @see MCRCategoryDAO#addCategory(MCRCategoryID, MCRCategory) */ @MCRCommand(syntax = "load classification from file {0}", help = "The command adds a new classification from file {0} to the system.", order = 10) public static List<String> loadFromFile(String filename) throws MCRException, IOException { String fileURL = Paths.get(filename).toAbsolutePath().normalize().toUri().toURL().toString(); return Collections.singletonList("load classification from url " + fileURL); } @MCRCommand(syntax = "load classification from url {0}", help = "The command adds a new classification from URL {0} to the system.", order = 15) public static void loadFromURL(String fileURL) throws IOException, URISyntaxException, JDOMException { Document xml = MCRXMLParserFactory.getParser().parseXML(new MCRURLContent(new URI(fileURL).toURL())); MCRCategory category = MCRXMLTransformer.getCategory(xml); DAO.addCategory(null, category); } @MCRCommand(syntax = "load classification from uri {0}", help = "The command adds a new classification from URI {0} to the system.", order = 17) public static void loadFromURI(String fileURI) throws URISyntaxException, TransformerException, IOException, JDOMException { Document xml = MCRXMLParserFactory.getParser().parseXML(MCRSourceContent.getInstance(fileURI)); MCRCategory category = MCRXMLTransformer.getCategory(xml); DAO.addCategory(null, category); } /** * Replaces a classification with a new version * * @param filename * file in mcrclass xml format * @see MCRCategoryDAO#replaceCategory(MCRCategory) */ @MCRCommand(syntax = "update classification from file {0}", help = "The command updates a classification from file {0} to the system.", order = 20) public static List<String> updateFromFile(String filename) throws MCRException, IOException { String fileURL = Paths.get(filename).toAbsolutePath().normalize().toUri().toURL().toString(); return Collections.singletonList("update classification from url " + fileURL); } @MCRCommand(syntax = "update classification from url {0}", help = "The command updates a classification from URL {0} to the system.", order = 25) public static void updateFromURL(String fileURL) throws IOException, URISyntaxException, JDOMException { Document xml = MCRXMLParserFactory.getParser().parseXML(new MCRURLContent(new URI(fileURL).toURL())); MCRCategory category = MCRXMLTransformer.getCategory(xml); if (DAO.exist(category.getId())) { DAO.replaceCategory(category); } else { // add if classification does not exist DAO.addCategory(null, category); } } @MCRCommand(syntax = "update classification from uri {0}", help = "The command updates a classification from URI {0} to the system.", order = 27) public static void updateFromURI(String fileURI) throws URISyntaxException, TransformerException, IOException, JDOMException { Document xml = MCRXMLParserFactory.getParser().parseXML(MCRSourceContent.getInstance(fileURI)); MCRCategory category = MCRXMLTransformer.getCategory(xml); if (DAO.exist(category.getId())) { DAO.replaceCategory(category); } else { // add if classification does not exist DAO.addCategory(null, category); } } /** * Loads MCRClassification from all XML files in a directory. * * @param directory * the directory containing the XML files */ @MCRCommand(syntax = "load all classifications from directory {0}", help = "The command add all classifications in the directory {0} to the system.", order = 40) public static List<String> loadFromDirectory(String directory) { return processFromDirectory(directory, false); } /** * Updates MCRClassification from all XML files in a directory. * * @param directory * the directory containing the XML files */ @MCRCommand(syntax = "update all classifications from directory {0}", help = "The command update all classifications in the directory {0} to the system.", order = 50) public static List<String> updateFromDirectory(String directory) { return processFromDirectory(directory, true); } /** * Loads or updates MCRClassification from all XML files in a directory. * * @param directory * the directory containing the XML files * @param update * if true, classification will be updated, else Classification * is created */ private static List<String> processFromDirectory(String directory, boolean update) { File dir = new File(directory); if (!dir.isDirectory()) { LOGGER.warn("{} ignored, is not a directory.", directory); return null; } String[] list = dir.list(); if (list.length == 0) { LOGGER.warn("No files found in directory {}", directory); return null; } return Arrays.stream(list) .filter(file -> file.endsWith(".xml")) .map(file -> (update ? "update" : "load") + " classification from file " + new File( dir, file).getAbsolutePath()) .collect(Collectors.toList()); } /** * Save a MCRClassification. * * @param id * the ID of the MCRClassification to save. * @param dirname * the directory to export the classification to * @param style * the name of the stylesheet, prefix of <em>style</em>-classification.xsl */ @MCRCommand(syntax = "export classification {0} to directory {1} with stylesheet {2}", help = "Stores the classification with MCRObjectID {0} as xml file to directory {1} " + "with the stylesheet {2}-classification.xsl. For {2}, the default is xsl/save.", order = 60) public static void export(String id, String dirname, String style) throws Exception { File dir = new File(dirname); if (!dir.isDirectory()) { LOGGER.error("{} is not a directory.", dirname); return; } MCRCategory cl = DAO.getCategory(MCRCategoryID.rootID(id), -1); Document classDoc = MCRCategoryTransformer.getMetaDataDocument(cl, false); Transformer trans = getTransformer(style != null ? style + "-classification" : null); String extension = MCRXSLTransformerUtils.getFileExtension(trans, "xml"); File xmlOutput = new File(dir, id + "." + extension); FileOutputStream out = new FileOutputStream(xmlOutput); if (trans != null) { StreamResult sr = new StreamResult(out); trans.transform(new JDOMSource(classDoc), sr); } else { XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); xout.output(classDoc, out); out.flush(); } LOGGER.info("Classifcation {} saved to {}.", id, xmlOutput.getCanonicalPath()); } /** * This method searches for the stylesheet <em>style</em>.xsl and builds the transformer. Default is * <em>save-classification.xsl</em> if no stylesheet is given or the stylesheet couldn't be resolved. * * @param style * the name of the style to be used when resolving the stylesheet * @return the transformer */ private static Transformer getTransformer(String style) { return MCRCommandUtils.getTransformer(style, DEFAULT_STYLE, TRANSFORMER_CACHE); } /** * Save all MCRClassifications. * * @param dirname * the directory name to store all classifications * @param style * the name of the stylesheet, prefix of <em>style</em>-classification.xsl * @return a list of export commands, one for each classification */ @MCRCommand(syntax = "export all classifications to directory {0} with stylesheet {1}", help = "The command store all classifications to the directory with name {0} with the stylesheet " + "{1}-classification.xsl. For {1}, the default is xsl/save.", order = 70) public static List<String> exportAll(String dirname, String style) throws Exception { return DAO.getRootCategoryIDs().stream() .map(id -> "export classification " + id + " to directory " + dirname + " with stylesheet " + style) .collect(Collectors.toList()); } /** * List all IDs of all classifications stored in the database */ @MCRCommand(syntax = "list all classifications", help = "The command list all classification stored in the database.", order = 100) public static void listAllClassifications() { List<MCRCategoryID> allClassIds = DAO.getRootCategoryIDs(); for (MCRCategoryID id : allClassIds) { LOGGER.info(id.getRootID()); } LOGGER.info(""); } /** * List a MCRClassification. * * @param classid * the MCRObjectID of the classification */ @MCRCommand(syntax = "list classification {0}", help = "The command list the classification with MCRObjectID {0}.", order = 90) public static void listClassification(String classid) { MCRCategoryID clid = MCRCategoryID.rootID(classid); MCRCategory cl = DAO.getCategory(clid, -1); LOGGER.info(classid); if (cl != null) { listCategory(cl); } else { LOGGER.error("Can't find classification {}", classid); } } private static void listCategory(MCRCategory categ) { int level = categ.getLevel(); String space = " ".repeat(level * 2); if (categ.isCategory()) { LOGGER.info("{} ID : {}", space, categ.getId().getId()); } for (MCRLabel label : categ.getLabels()) { LOGGER.info("{} Label : ({}) {}", space, label.getLang(), label.getText()); } List<MCRCategory> children = categ.getChildren(); for (MCRCategory child : children) { listCategory(child); } } @MCRCommand(syntax = "repair category with empty labels", help = "fixes all categories with no labels (adds a label with categid as @text for default lang)", order = 110) public static void repairEmptyLabels() { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); String deleteEmptyLabels = "delete from {h-schema}MCRCategoryLabels where text is null or trim(text) = ''"; int affected = em.createNativeQuery(deleteEmptyLabels).executeUpdate(); LOGGER.info("Deleted {} labels.", affected); String sqlQuery = "select cat.classid,cat.categid from {h-schema}MCRCategory cat " + "left outer join {h-schema}MCRCategoryLabels label on cat.internalid = label.category where " + "label.text is null"; @SuppressWarnings("unchecked") List<Object[]> list = em.createNativeQuery(sqlQuery).getResultList(); for (Object resultList : list) { Object[] arrayOfResults = (Object[]) resultList; String classIDString = (String) arrayOfResults[0]; String categIDString = (String) arrayOfResults[1]; MCRCategoryID mcrCategID = new MCRCategoryID(classIDString, categIDString); MCRLabel mcrCategLabel = new MCRLabel(MCRConstants.DEFAULT_LANG, categIDString, null); MCRCategoryDAOFactory.getInstance().setLabel(mcrCategID, mcrCategLabel); LOGGER.info("fixing category with class ID \"{}\" and category ID \"{}\"", classIDString, categIDString); } LOGGER.info("Fixing category labels completed!"); } @MCRCommand(syntax = "repair position in parent", help = "fixes all categories gaps in position in parent", order = 120) @SuppressWarnings("unchecked") public static void repairPositionInParent() { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); // this SQL-query find missing numbers in positioninparent String sqlQuery = "select parentid, min(cat1.positioninparent+1) from {h-schema}MCRCategory cat1 " + "where cat1.parentid is not null and not exists" + "(select 1 from {h-schema}MCRCategory cat2 " + "where cat2.parentid=cat1.parentid and cat2.positioninparent=(cat1.positioninparent+1))" + "and cat1.positioninparent not in " + "(select max(cat3.positioninparent) from {h-schema}MCRCategory cat3 " + "where cat3.parentid=cat1.parentid) group by cat1.parentid"; for (List<Object[]> parentWithErrorsList = em.createNativeQuery(sqlQuery).getResultList(); !parentWithErrorsList .isEmpty(); parentWithErrorsList = em.createNativeQuery(sqlQuery).getResultList()) { for (Object[] parentWithErrors : parentWithErrorsList) { Number parentID = (Number) parentWithErrors[0]; Number firstErrorPositionInParent = (Number) parentWithErrors[1]; LOGGER.info("Category {} has the missing position {} ...", parentID, firstErrorPositionInParent); repairCategoryWithGapInPos(parentID, firstErrorPositionInParent); LOGGER.info("Fixed position {} for category {}.", firstErrorPositionInParent, parentID); } } sqlQuery = "select parentid, min(cat1.positioninparent-1) from {h-schema}MCRCategory cat1 " + "where cat1.parentid is not null and not exists" + "(select 1 from {h-schema}MCRCategory cat2 " + "where cat2.parentid=cat1.parentid and cat2.positioninparent=(cat1.positioninparent-1))" + "and cat1.positioninparent not in " + "(select max(cat3.positioninparent) from {h-schema}MCRCategory cat3 " + "where cat3.parentid=cat1.parentid) and cat1.positioninparent > 0 group by cat1.parentid"; while (true) { List<Object[]> parentWithErrorsList = em.createNativeQuery(sqlQuery).getResultList(); if (parentWithErrorsList.isEmpty()) { break; } for (Object[] parentWithErrors : parentWithErrorsList) { Number parentID = (Number) parentWithErrors[0]; Number wrongStartPositionInParent = (Number) parentWithErrors[1]; LOGGER.info("Category {} has the the starting position {} ...", parentID, wrongStartPositionInParent); repairCategoryWithWrongStartPos(parentID, wrongStartPositionInParent); LOGGER.info("Fixed position {} for category {}.", wrongStartPositionInParent, parentID); } } LOGGER.info("Repair position in parent finished!"); } public static void repairCategoryWithWrongStartPos(Number parentID, Number wrongStartPositionInParent) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); String sqlQuery = "update {h-schema}MCRCategory set positioninparent= positioninparent -" + wrongStartPositionInParent + "-1 where parentid=" + parentID + " and positioninparent > " + wrongStartPositionInParent; em.createNativeQuery(sqlQuery).executeUpdate(); } private static void repairCategoryWithGapInPos(Number parentID, Number firstErrorPositionInParent) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); // the query decrease the position in parent with a rate. // eg. posInParent: 0 1 2 5 6 7 // at 3 the position get faulty, 5 is the min. of the position greather // 3 // so the reate is 5-3 = 2 String sqlQuery = "update {h-schema}MCRCategory " + "set positioninparent=(positioninparent - (select min(positioninparent) from " + "{h-schema}MCRCategory where parentid=" + parentID + " and positioninparent > " + firstErrorPositionInParent + ")+" + firstErrorPositionInParent + ") where parentid=" + parentID + " and positioninparent > " + firstErrorPositionInParent; em.createNativeQuery(sqlQuery).executeUpdate(); } @MCRCommand(syntax = "repair left right values for classification {0}", help = "fixes all left and right values in the given classification", order = 130) public static void repairLeftRightValue(String classID) { if (DAO instanceof MCRCategoryDAOImpl categoryDAO) { categoryDAO.repairLeftRightValue(classID); } else { LOGGER.error("Command not compatible with {}", DAO.getClass().getName()); return; } } @MCRCommand(syntax = "check all classifications", help = "checks if all redundant information are stored without conflicts", order = 140) public static List<String> checkAllClassifications() { List<MCRCategoryID> classifications = MCRCategoryDAOFactory.getInstance().getRootCategoryIDs(); List<String> commands = new ArrayList<>(classifications.size()); for (MCRCategoryID id : classifications) { commands.add("check classification " + id.getRootID()); } return commands; } @MCRCommand(syntax = "check classification {0}", help = "checks if all redundant information are stored without conflicts", order = 150) public static void checkClassification(String id) { LOGGER.info("Checking classifcation {}", id); ArrayList<String> log = new ArrayList<>(); LOGGER.info("{}: checking for missing parentID", id); checkMissingParent(id, log); LOGGER.info("{}: checking for empty labels", id); checkEmptyLabels(id, log); if (log.isEmpty()) { MCRCategoryImpl category = (MCRCategoryImpl) MCRCategoryDAOFactory.getInstance().getCategory( MCRCategoryID.rootID(id), -1); LOGGER.info("{}: checking left, right and level values and for non-null children", id); checkLeftRightAndLevel(category, 0, 0, log); } if (log.size() > 0) { LOGGER.error("Some errors occured on last test, report will follow"); StringBuilder sb = new StringBuilder(); for (String msg : log) { sb.append(msg).append('\n'); } LOGGER.error("Error report for classification {}\n{}", id, sb); } else { LOGGER.info("Classifcation {} has no errors.", id); } } @MCRCommand(syntax = "remove unmapped categories from classification {0}", help = "Deletes all Categories of classification {0} which can not be mapped from all other classifications!", order = 160) public static void filterClassificationWithMapping(String id) { new MCRUnmappedCategoryRemover(id).filter(); } private static int checkLeftRightAndLevel(MCRCategoryImpl category, int leftStart, int levelStart, List<String> log) { int curValue = leftStart; final int nextLevel = levelStart + 1; if (leftStart != category.getLeft()) { log.add("LEFT of " + category.getId() + " is " + category.getLeft() + " should be " + leftStart); } if (levelStart != category.getLevel()) { log.add("LEVEL of " + category.getId() + " is " + category.getLevel() + " should be " + levelStart); } int position = 0; for (MCRCategory child : category.getChildren()) { if (child == null) { log.add("NULL child of parent " + category.getId() + " on position " + position); continue; } LOGGER.debug(child.getId()); curValue = checkLeftRightAndLevel((MCRCategoryImpl) child, ++curValue, nextLevel, log); position++; } ++curValue; if (curValue != category.getRight()) { log.add("RIGHT of " + category.getId() + " is " + category.getRight() + " should be " + curValue); } return curValue; } private static void checkEmptyLabels(String classID, List<String> log) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); String sqlQuery = "select cat.categid from {h-schema}MCRCategory cat " + "left outer join {h-schema}MCRCategoryLabels label on cat.internalid = label.category where " + "cat.classid='" + classID + "' and (label.text is null or trim(label.text) = '')"; @SuppressWarnings("unchecked") List<String> list = em.createNativeQuery(sqlQuery).getResultList(); for (String categIDString : list) { log.add("EMPTY lables for category " + new MCRCategoryID(classID, categIDString)); } } private static void checkMissingParent(String classID, List<String> log) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); String sqlQuery = "select cat.categid from {h-schema}MCRCategory cat WHERE cat.classid='" + classID + "' and cat.level > 0 and cat.parentID is NULL"; @SuppressWarnings("unchecked") List<String> list = em.createNativeQuery(sqlQuery).getResultList(); for (String categIDString : list) { log.add("parentID is null for category " + new MCRCategoryID(classID, categIDString)); } } @MCRCommand(syntax = "repair missing parent for classification {0}", help = "restores parentID from information in the given classification, if left right values are correct", order = 130) public static void repairMissingParent(String classID) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); String sqlQuery = "update {h-schema}MCRCategory cat set cat.parentID=(select parent.internalID from " + "{h-schema}MCRCategory parent WHERE parent.classid='" + classID + "' and parent.leftValue<cat.leftValue and parent.rightValue>cat.rightValue and " + "parent.level=(cat.level-1)) WHERE cat.classid='" + classID + "' and cat.level > 0 and cat.parentID is NULL"; int updates = em.createNativeQuery(sqlQuery).executeUpdate(); LOGGER.info(() -> "Repaired " + updates + " parentID columns for classification " + classID); } @MCRCommand(syntax = "clear classification export transformer cache", help = "Clears the classification export transformer cache", order = 200) public static void clearExportTransformerCache() { TRANSFORMER_CACHE.clear(); } }
27,493
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCommandStatistics.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRCommandStatistics.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.cli; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * Collects statistics on number of invocations and total time needed for each command invoked. * * @see org.mycore.frontend.cli.MCRBasicCommands for integration in MyCoRe CLI * * @author Frank Lützenkirchen */ public class MCRCommandStatistics { private static Map<MCRCommand, StatisticsEntry> entries = new HashMap<>(); private static StatisticsEntry getEntry(MCRCommand command) { return entries.computeIfAbsent(command, k -> new StatisticsEntry()); } public static void commandInvoked(MCRCommand command, long timeNeeded) { StatisticsEntry entry = getEntry(command); entry.numInvocations++; entry.totalTimeNeeded += timeNeeded; } /** * Shows statistics on number of invocations and time needed for each * command successfully executed. */ public static void showCommandStatistics() { System.out.println(); for (Entry<MCRCommand, StatisticsEntry> entry : entries.entrySet()) { System.out.println(entry.getKey().getSyntax()); System.out.println(entry.getValue()); } } } class StatisticsEntry { /** Stores total number of invocations for each command */ int numInvocations = 0; /** Stores total time needed for all executions of the given command */ long totalTimeNeeded = 0; long getAverage() { return totalTimeNeeded / numInvocations; } public String toString() { return " total=" + totalTimeNeeded + " ms, average=" + getAverage() + " ms, " + numInvocations + " invocations."; } }
2,431
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRBatchEditorCommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRBatchEditorCommands.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.cli; import java.io.IOException; import java.text.MessageFormat; import java.util.Collection; import java.util.List; import java.util.Locale; import org.jaxen.JaxenException; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.Namespace; import org.jdom2.filter.Filter; import org.jdom2.filter.Filters; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.access.MCRAccessException; import org.mycore.common.MCRConstants; import org.mycore.common.MCRPersistenceException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.xml.MCRNodeBuilder; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; /** * Commands to batch add/remove/replace values * like identifiers, categories, tags, flags etc. within XML. * Supported fields are completely configurable using XPath expressions. * * @author Frank Lützenkirchen */ @MCRCommandGroup(name = "Batch Editor") public class MCRBatchEditorCommands extends MCRAbstractCommands { private static final Collection<Namespace> NS = MCRConstants.getStandardNamespaces(); private static final Filter<Element> FE = Filters.element(); private static final String CFG_PREFIX = "MCR.BatchEditor."; private static final String CFG_PREFIX_BASE = CFG_PREFIX + "BaseLevel."; private static final String CFG_SUFFIX_REMOVE = ".Path2Remove"; private static final String CFG_SUFFIX_ADD = ".Path2Add"; private enum Action { ADD, ADD_IF, REMOVE, REMOVE_IF, REPLACE } @MCRCommand(syntax = "edit {0} at {1} add {2} {3}", help = "Edit XML elements in object {0} at level {1} in object {1}, add field {2} with value {3}", order = 2) public static void batchAdd(String oid, String level, String field, String value) throws JaxenException, MCRPersistenceException, MCRAccessException, IOException { edit(oid, level, Action.ADD, field, value, null, null); } @MCRCommand(syntax = "edit {0} at {1} if {2} {3} add {4} {5}", help = "Edit XML elements in object {0} at level {1}, if there is a field {2} with value {3}, " + "add field {4} with value {5}") public static void batchAddIf(String oid, String level, String fieldIf, String valueIf, String field2Add, String value2Add) throws JaxenException, MCRPersistenceException, MCRAccessException, IOException { edit(oid, level, Action.ADD_IF, fieldIf, valueIf, field2Add, value2Add); } @MCRCommand(syntax = "edit {0} at {1} remove {2} {3}", help = "Edit XML elements at in object {0} at level {1}, remove field {2} where value is {3}", order = 2) public static void batchRemove(String oid, String level, String field, String value) throws MCRPersistenceException, MCRAccessException, JaxenException, IOException { edit(oid, level, Action.REMOVE, field, value, null, null); } @MCRCommand(syntax = "edit {0} at {1} if {2} {3} remove {4} {5}", help = "Edit XML elements in object {0} at level {1}, if there is a field {2} with value {3}, " + "remove field {4} where value is {5}") public static void batchRemoveIf(String oid, String level, String fieldIf, String valueIf, String field2Rem, String value2Rem) throws MCRPersistenceException, MCRAccessException, JaxenException, IOException { edit(oid, level, Action.REMOVE_IF, fieldIf, valueIf, field2Rem, value2Rem); } @MCRCommand(syntax = "edit {0} at {1} replace {2} {3} with {4} {5}", help = "Edit XML elements in object {0} at level {1}, replace field {2} value {3} by field {4} with value {5}") public static void batchReplace(String oid, String level, String oldField, String oldValue, String newField, String newValue) throws JaxenException, MCRPersistenceException, MCRAccessException, IOException { edit(oid, level, Action.REPLACE, oldField, oldValue, newField, newValue); } public static void edit(String oid, String level, Action a, String field1, String value1, String field2, String value2) throws JaxenException, MCRPersistenceException, MCRAccessException, IOException { Document xmlOld = getObjectXML(oid); Document xmlNew = xmlOld.clone(); for (Element base : getlevelElements(xmlNew, level)) { if (a == Action.ADD) { add(base, field1, value1); } else if (a == Action.REMOVE) { find(base, field1, value1).forEach(Element::detach); } else if (a == Action.REPLACE) { List<Element> found = find(base, field1, value1); found.forEach(Element::detach); if (!found.isEmpty()) { add(base, field2, value2); } } else if (a == Action.ADD_IF) { if (!find(base, field1, value1).isEmpty()) { add(base, field2, value2); } } else if (a == Action.REMOVE_IF) { if (!find(base, field1, value1).isEmpty()) { find(base, field2, value2).forEach(Element::detach); } } } saveIfModified(xmlOld, xmlNew); } private static Document getObjectXML(String objectID) { MCRObjectID oid = MCRObjectID.getInstance(objectID); MCRObject obj = MCRMetadataManager.retrieveMCRObject(oid); return obj.createXML(); } private static void saveIfModified(Document xmlOld, Document xmlNew) throws MCRAccessException, IOException { String oldData = new MCRJDOMContent(xmlOld).asString(); String newData = new MCRJDOMContent(xmlNew).asString(); if (!oldData.equals(newData)) { MCRObject obj = new MCRObject(xmlNew); MCRMetadataManager.update(obj); } } private static List<Element> getlevelElements(Document xml, String level) { String path = MCRConfiguration2.getStringOrThrow(CFG_PREFIX_BASE + level); XPathExpression<Element> xPath = XPathFactory.instance().compile(path, FE, null, NS); return xPath.evaluate(xml); } private static void add(Element base, String field, String value) throws JaxenException { String path = MCRConfiguration2.getStringOrThrow(CFG_PREFIX + field + CFG_SUFFIX_ADD); path = new MessageFormat(path, Locale.ROOT).format(new String[] { value }); new MCRNodeBuilder().buildNode(path, null, base); } private static List<Element> find(Element base, String field, String value) { String path = MCRConfiguration2.getStringOrThrow(CFG_PREFIX + field + CFG_SUFFIX_REMOVE); path = new MessageFormat(path, Locale.ROOT).format(new String[] { value }); XPathExpression<Element> fPath = XPathFactory.instance().compile(path, FE, null, NS); List<Element> selected = fPath.evaluate(base); return selected; } }
7,978
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDeveloperCommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRDeveloperCommands.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.cli; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.xml.MCRURIResolver; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; import org.mycore.services.i18n.MCRTranslation; /** * This class contains commands that may be helpful during development. * * @author Torsten Krause */ @MCRCommandGroup(name = "Developer Commands") public class MCRDeveloperCommands { private static final Logger LOGGER = LogManager.getLogger(MCRDeveloperCommands.class); @MCRCommand( syntax = "show message {0} for {1}", help = "Show message with key {0} for locale {1}", order = 10) public static void showMessage(String key, String lang) { String value = MCRTranslation.translate(key, MCRTranslation.getLocale(lang)); if (value == null || (value.startsWith("???") && value.endsWith("???"))) { LOGGER.info("Found no message for key {}", key); } else { LOGGER.info("Found message for key {}: {}", key, value); } } @MCRCommand( syntax = "show messages {0} for {1}", help = "Show messages with key prefix {0} for locale {1}", order = 20) public static void showMessages(String keyPrefix, String lang) { Map<String, String> values = MCRTranslation.translatePrefixToLocale(keyPrefix, MCRTranslation.getLocale(lang)); if (values.isEmpty()) { LOGGER.info("Found no messages for key prefix {}", keyPrefix); } else { values.forEach((key, value) -> LOGGER.info("Found message for key {}: {}", key, value)); } } @MCRCommand( syntax = "show all messages for {0}", help = "Show all messages for locale {0}", order = 30) public static void showMessages(String lang) { Map<String, String> values = MCRTranslation.translatePrefixToLocale("", MCRTranslation.getLocale(lang)); if (values.isEmpty()) { LOGGER.info("Found no messages"); } else { values.forEach((key, value) -> LOGGER.info("Found message for key {}: {}", key, value)); } } @MCRCommand( syntax = "show property {0}", help = "Show configuration property with key {0}", order = 40) public static void showProperty(String key) { String value = MCRConfiguration2.getPropertiesMap().get(key); if (value == null) { LOGGER.info("Found no value for key {}", key); } else { LOGGER.info("Found value for key {}: {}", key, value); } } @MCRCommand( syntax = "show properties {0}", help = "Show configuration properties starting with key prefix {0}", order = 50) public static void showProperties(String keyPrefix) { Map<String, String> values = MCRConfiguration2.getSubPropertiesMap(keyPrefix); if (values.isEmpty()) { LOGGER.info("Found no values for key prefix {}", keyPrefix); } else { values.forEach((key, value) -> LOGGER.info("Found value for key {}: {}", keyPrefix + key, value)); } } @MCRCommand( syntax = "show all properties", help = "Show all configuration properties", order = 60) public static void showAllProperties() { Map<String, String> values = MCRConfiguration2.getPropertiesMap(); if (values.isEmpty()) { LOGGER.info("Found no values"); } else { values.forEach((key, value) -> LOGGER.info("Found value for key {}: {}", key, value)); } } @MCRCommand( syntax = "show resource {0}", help = "Show resource with uri {0}", order = 70) public static void showResource(String uri) { try { Element resource = MCRURIResolver.instance().resolve(uri); String xmlText = new XMLOutputter(Format.getPrettyFormat()).outputString(resource); LOGGER.info("Resolved resource for uri {}:\n{}", uri, xmlText); } catch (Exception e) { LOGGER.info("Failed to resolve resource for uri " + uri, e); } } @MCRCommand( syntax = "touch object {0}", help = "Load and update object with id {0} without making any modifications", order = 80) public static void touchObject(String id) { try { MCRObjectID objectId = MCRObjectID.getInstance(id); MCRObject object = MCRMetadataManager.retrieveMCRObject(objectId); MCRMetadataManager.update(object); LOGGER.info("Touched object with id {}", id); } catch (Exception e) { LOGGER.info("Failed to touch object with id " + id, e); } } @MCRCommand( syntax = "touch derivate {0}", help = "Load and update derivate with id {0} without making any modifications", order = 90) public static void touchDerivate(String id) { try { MCRObjectID derivateId = MCRObjectID.getInstance(id); MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateId); MCRMetadataManager.update(derivate); LOGGER.info("Touched derivate with id {}", id); } catch (Exception e) { LOGGER.info("Failed to touch derivate with id " + id, e); } } }
6,537
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCLIExceptionHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRCLIExceptionHandler.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.cli; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRException; import org.mycore.datamodel.common.MCRActiveLinkException; /** * Shows details about an exception that occured during command processing * * @author Frank Lützenkirchen */ public class MCRCLIExceptionHandler { private static final Logger LOGGER = LogManager.getLogger(MCRCLIExceptionHandler.class); public static void handleException(InvocationTargetException ex) { handleException(ex.getTargetException()); } public static void handleException(ExceptionInInitializerError ex) { handleException(ex.getCause()); } public static void handleException(MCRActiveLinkException ex) { showActiveLinks(ex); showException(ex); } private static void showActiveLinks(MCRActiveLinkException activeLinks) { MCRCommandLineInterface .output("There are links active preventing the commit of work, see error message for details."); MCRCommandLineInterface.output("The following links where affected:"); Map<String, Collection<String>> links = activeLinks.getActiveLinks(); for (String curDest : links.keySet()) { LOGGER.debug("Current Destination: {}", curDest); Collection<String> sources = links.get(curDest); for (String source : sources) { MCRCommandLineInterface.output(source + " ==> " + curDest); } } } public static void handleException(Throwable ex) { showException(ex); } private static void showException(Throwable ex) { MCRCommandLineInterface.output(""); MCRCommandLineInterface.output("Exception occured: " + ex.getClass().getName()); MCRCommandLineInterface.output("Exception message: " + ex.getLocalizedMessage()); MCRCommandLineInterface.output(""); showStackTrace(ex); showCauseOf(ex); } private static void showStackTrace(Throwable ex) { String trace = MCRException.getStackTraceAsString(ex); if (LOGGER.isDebugEnabled()) { LOGGER.debug(trace); } else { MCRCommandLineInterface.output(trace); } } private static void showCauseOf(Throwable ex) { ex = ex.getCause(); if (ex == null) { return; } MCRCommandLineInterface.output(""); MCRCommandLineInterface.output("This exception was caused by:"); handleException(ex); } }
3,415
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCommandLineInterface.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRCommandLineInterface.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.cli; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Vector; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import org.apache.commons.text.StringSubstitutor; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import org.mycore.common.MCRClassTools; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRSystemUserInformation; import org.mycore.common.MCRTransactionHelper; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.events.MCRStartupHandler; import org.mycore.common.xml.MCRURIResolver; /** * The main class implementing the MyCoRe command line interface. With the * command line interface, you can import, export, update and delete documents * and other data from/to the filesystem. Metadata is imported from and exported * to XML files. The command line interface is for administrative purposes and * to be used on the server side. It implements an interactive command prompt * and understands a set of commands. Each command is an instance of the class * <code>MCRCommand</code>. * * @see MCRCommand * * @author Frank Lützenkirchen * @author Detlev Degenhardt * @author Jens Kupferschmidt * @author Thomas Scheffler (yagee) */ public class MCRCommandLineInterface { private static final Logger LOGGER = LogManager.getLogger(); /** The name of the system */ private static String system = null; /** A queue of commands waiting to be executed */ protected static Vector<String> commandQueue = new Vector<>(); protected static Vector<String> failedCommands = new Vector<>(); private static boolean interactiveMode = true; private static boolean SKIP_FAILED_COMMAND = false; private static MCRCommandManager knownCommands; private static ThreadLocal<String> sessionId = new ThreadLocal<>(); /** * The main method that either shows up an interactive command prompt or * reads a file containing a list of commands to be processed */ public static void main(String[] args) { if (!(MCRCommandLineInterface.class.getClassLoader() instanceof URLClassLoader)) { System.out.println("Current ClassLoader is not extendable at runtime. Using workaround."); Thread.currentThread().setContextClassLoader(new CLIURLClassLoader(new URL[0])); } MCRStartupHandler.startUp(null/*no servlet context here*/); system = MCRConfiguration2.getStringOrThrow("MCR.CommandLineInterface.SystemName") + ":"; initSession(); MCRSession session = MCRSessionMgr.getSession(sessionId.get()); MCRSessionMgr.setCurrentSession(session); try { output(""); output("Command Line Interface."); output(""); output("Initializing..."); knownCommands = new MCRCommandManager(); output("Initialization done."); output("Type 'help' to list all commands!"); output(""); } finally { MCRSessionMgr.releaseCurrentSession(); } readCommandFromArguments(args); String command = null; MCRCommandPrompt prompt = new MCRCommandPrompt(system); while (true) { if (commandQueue.isEmpty()) { if (interactiveMode) { command = prompt.readCommand(); } else if (MCRConfiguration2.getString("MCR.CommandLineInterface.unitTest").orElse("false") .equals("true")) { break; } else { exit(); } } else { command = commandQueue.firstElement(); commandQueue.removeElementAt(0); System.out.println(system + "> " + command); } processCommand(command); } } private static void readCommandFromArguments(String[] args) { if (args.length > 0) { interactiveMode = false; String line = readLineFromArguments(args); addCommands(line); } } private static void addCommands(String line) { Stream.of(line.split(";;")) .map(String::trim) .filter(s -> !s.isEmpty()) .forEachOrdered(commandQueue::add); } private static String readLineFromArguments(String[] args) { StringBuilder sb = new StringBuilder(); for (String arg : args) { sb.append(arg).append(' '); } return sb.toString(); } private static void initSession() { MCRSessionMgr.unlock(); MCRSession session = MCRSessionMgr.getCurrentSession(); session.setCurrentIP("127.0.0.1"); session.setUserInformation(MCRSystemUserInformation.getSuperUserInstance()); MCRSessionMgr.setCurrentSession(session); sessionId.set(session.getID()); MCRSessionMgr.releaseCurrentSession(); } /** * Processes a command entered by searching a matching command in the list * of known commands and executing its method. * * @param command * The command string to be processed */ protected static void processCommand(String command) { MCRSession session = MCRSessionMgr.getSession(sessionId.get()); MCRSessionMgr.setCurrentSession(session); try { MCRTransactionHelper.beginTransaction(); List<String> commandsReturned = knownCommands.invokeCommand(expandCommand(command)); MCRTransactionHelper.commitTransaction(); addCommandsToQueue(commandsReturned); } catch (Exception ex) { MCRCLIExceptionHandler.handleException(ex); rollbackTransaction(session); if (SKIP_FAILED_COMMAND) { saveFailedCommand(command); } else { saveQueue(command); if (!interactiveMode) { System.exit(1); } commandQueue.clear(); } } finally { MCRSessionMgr.releaseCurrentSession(); } } /** * Expands variables in a command. * Replaces any variables in form ${propertyName} to the value defined by * {@link MCRConfiguration2#getString(String)}. * If the property is not defined no variable replacement takes place. * @param command a CLI command that should be expanded * @return expanded command */ public static String expandCommand(final String command) { StringSubstitutor strSubstitutor = new StringSubstitutor(MCRConfiguration2.getPropertiesMap()); String expandedCommand = strSubstitutor.replace(command); if (!expandedCommand.equals(command)) { LOGGER.info("{} --> {}", command, expandedCommand); } return expandedCommand; } private static void rollbackTransaction(MCRSession session) { output("Command failed. Performing transaction rollback..."); if (MCRTransactionHelper.isTransactionActive()) { try { MCRTransactionHelper.rollbackTransaction(); } catch (Exception ex2) { MCRCLIExceptionHandler.handleException(ex2); } } } private static void addCommandsToQueue(List<String> commandsReturned) { if (commandsReturned.size() > 0) { output("Queueing " + commandsReturned.size() + " commands to process"); for (int i = 0; i < commandsReturned.size(); i++) { commandQueue.insertElementAt(commandsReturned.get(i), i); } } } protected static void saveQueue(String lastCommand) { output(""); output("The following command failed:"); output(lastCommand); if (!commandQueue.isEmpty()) { System.out.printf(Locale.ROOT, "%s There are %s other commands still unprocessed.%n", system, commandQueue.size()); } else if (interactiveMode) { return; } commandQueue.add(0, lastCommand); saveCommandQueueToFile(commandQueue, "unprocessed-commands.txt"); } private static void saveCommandQueueToFile(final Vector<String> queue, String fname) { output("Writing unprocessed commands to file " + fname); try (PrintWriter pw = new PrintWriter(new File(fname), Charset.defaultCharset())) { for (String command : queue) { pw.println(command); } } catch (IOException ex) { MCRCLIExceptionHandler.handleException(ex); } } protected static void saveFailedCommand(String lastCommand) { output(""); output("The following command failed:"); output(lastCommand); if (!commandQueue.isEmpty()) { System.out.printf(Locale.ROOT, "%s There are %s other commands still unprocessed.%n", system, commandQueue.size()); } failedCommands.add(lastCommand); } protected static void handleFailedCommands() { if (failedCommands.size() > 0) { System.err.println(system + " Several command failed."); saveCommandQueueToFile(failedCommands, "failed-commands.txt"); } } /** * Show contents of a local text file, including line numbers. * * @param fname * the filename */ public static void show(String fname) throws Exception { AtomicInteger ln = new AtomicInteger(); System.out.println(); Files.readAllLines(Paths.get(fname), Charset.defaultCharset()) .forEach(l -> System.out.printf(Locale.ROOT, "%04d: %s", ln.incrementAndGet(), l)); System.out.println(); } /** * Reads XML content from URIResolver and sends output to a local file. */ public static void getURI(String uri, String file) throws Exception { Element resolved = MCRURIResolver.instance().resolve(uri); Element cloned = resolved.clone(); new MCRJDOMContent(cloned).sendTo(new File(file)); } /** * Reads a file containing a list of commands to be executed and adds them * to the commands queue for processing. This method implements the * "process ..." command. * * @param file * The file holding the commands to be processed * @throws IOException * when the file could not be read * @throws FileNotFoundException * when the file was not found */ public static List<String> readCommandsFile(String file) throws IOException { try (BufferedReader reader = Files.newBufferedReader(new File(file).toPath(), Charset.defaultCharset())) { output("Reading commands from file " + file); return readCommandsFromBufferedReader(reader); } } public static List<String> readCommandsRessource(String resource) throws IOException { final URL resourceURL = MCRClassTools.getClassLoader().getResource(resource); if (resourceURL == null) { throw new IOException("Resource URL is null!"); } try (InputStream is = resourceURL.openStream(); InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8); BufferedReader reader = new BufferedReader(isr)) { output("Reading commands from resource " + resource); return readCommandsFromBufferedReader(reader); } } private static List<String> readCommandsFromBufferedReader(BufferedReader reader) throws IOException { String line; List<String> list = new ArrayList<>(); while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("#") || line.isEmpty()) { continue; } list.add(line); } return list; } /** * Executes simple shell commands from inside the command line interface and * shows their output. This method implements commands entered beginning * with exclamation mark, like "! ls -l /temp" * * @param command * the shell command to be executed * @throws IOException * when an IO error occured while catching the output returned * by the command * @throws SecurityException * when the command could not be executed for security reasons */ public static void executeShellCommand(String command) throws Exception { MCRExternalProcess process = new MCRExternalProcess(command); process.run(); output(process.getOutput().asString()); output(process.getErrors()); } /** * Prints out the current user. */ public static void whoami() { MCRSession session = MCRSessionMgr.getCurrentSession(); String userName = session.getUserInformation().getUserID(); output("You are user " + userName); } public static void cancelOnError() { SKIP_FAILED_COMMAND = false; } public static void skipOnError() { SKIP_FAILED_COMMAND = true; } /** * Exits the command line interface. This method implements the "exit" and * "quit" commands. */ public static void exit() { showSessionDuration(); handleFailedCommands(); System.exit(0); } private static void showSessionDuration() { MCRSessionMgr.unlock(); MCRSession session = MCRSessionMgr.getCurrentSession(); long duration = System.currentTimeMillis() - session.getLoginTime(); output("Session duration: " + duration + " ms"); MCRSessionMgr.releaseCurrentSession(); session.close(); } static void output(String message) { System.out.println(system + " " + message); } private static class CLIURLClassLoader extends URLClassLoader { CLIURLClassLoader(URL[] urls) { super(urls); } @Override protected void addURL(URL url) { //make this callable via reflection later; super.addURL(url); } } }
15,565
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDerivateCommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRDerivateCommands.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.cli; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.stream.StreamResult; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.output.XMLOutputter; import org.jdom2.transform.JDOMSource; import org.mycore.access.MCRAccessException; import org.mycore.access.MCRAccessInterface; import org.mycore.access.MCRAccessManager; import org.mycore.access.MCRRuleAccessInterface; import org.mycore.common.MCRException; import org.mycore.common.MCRPersistenceException; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRPathContent; import org.mycore.common.content.transformer.MCRXSLTransformer; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventManager; import org.mycore.common.xml.MCRXMLHelper; import org.mycore.common.xml.MCRXSLTransformerUtils; import org.mycore.datamodel.classifications2.MCRCategoryDAO; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetaClassification; import org.mycore.datamodel.metadata.MCRMetaEnrichedLinkID; import org.mycore.datamodel.metadata.MCRMetaEnrichedLinkIDFactory; 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.niofs.MCRAbstractFileSystem; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.datamodel.niofs.utils.MCRDerivateUtil; import org.mycore.datamodel.niofs.utils.MCRTreeCopier; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; /** * Provides static methods that implement commands for the MyCoRe command line * interface. * * @author Jens Kupferschmidt * @author Frank Lützenkirchen */ @MCRCommandGroup(name = "Derivate Commands") public class MCRDerivateCommands extends MCRAbstractCommands { /** The logger */ private static Logger LOGGER = LogManager.getLogger(MCRDerivateCommands.class); /** The ACL interface */ private static final MCRAccessInterface ACCESS_IMPL = MCRAccessManager.getAccessImpl(); /** Default transformer script */ public static final String DEFAULT_STYLE = "save-derivate.xsl"; /** Static compiled transformer stylesheets */ private static final Map<String, Transformer> TRANSFORMER_CACHE = new HashMap<>(); /** * deletes all MCRDerivate from the datastore. */ @MCRCommand(syntax = "delete all derivates", help = "Removes all derivates from the repository", order = 10) public static List<String> deleteAllDerivates() { return MCRCommandUtils.getIdsForType("derivate") .map(id -> "delete derivate " + id) .collect(Collectors.toList()); } /** * Delete an MCRDerivate from the datastore. * * @param id * the ID of the MCRDerivate that should be deleted * @throws MCRAccessException see {@link MCRMetadataManager#delete(MCRDerivate)} */ @MCRCommand(syntax = "delete derivate {0}", help = "The command remove a derivate with the MCRObjectID {0}", order = 30) public static void delete(String id) throws MCRPersistenceException, MCRAccessException { MCRObjectID objectID = MCRObjectID.getInstance(id); MCRMetadataManager.deleteMCRDerivate(objectID); LOGGER.info("{} deleted.", objectID); } /** * Delete MCRDerivates form ID to ID from the datastore. * * @param idFrom * the start ID for deleting the MCRDerivate * @param idTo * the stop ID for deleting the MCRDerivate */ @MCRCommand(syntax = "delete derivate from {0} to {1}", help = "The command remove derivates in the number range between the MCRObjectID {0} and {1}.", order = 20) public static List<String> delete(String idFrom, String idTo) throws MCRPersistenceException { return MCRCommandUtils.getIdsFromIdToId(idFrom, idTo) .map(id -> "delete derivate " + id) .collect(Collectors.toList()); } /** * Loads MCRDerivates from all XML files in a directory. * * @param directory * the directory containing the XML files */ @MCRCommand(syntax = "load all derivates from directory {0}", help = "Loads all MCRDerivates from the directory {0} to the system. " + "If the numerical part of a provided ID is zero, a new ID with the same project ID and type is assigned.", order = 60) public static List<String> loadFromDirectory(String directory) { return processFromDirectory(directory, false); } /** * Updates MCRDerivates from all XML files in a directory. * * @param directory * the directory containing the XML files */ @MCRCommand(syntax = "update all derivates from directory {0}", help = "The command update all derivates form the directory {0} in the system.", order = 70) public static List<String> updateFromDirectory(String directory) { return processFromDirectory(directory, true); } /** * Loads or updates MCRDerivates from all XML files in a directory. * * @param directory * the directory containing the XML files * @param update * if true, object will be updated, else object is created */ private static List<String> processFromDirectory(String directory, boolean update) { File dir = new File(directory); if (!dir.isDirectory()) { LOGGER.warn("{} ignored, is not a directory.", directory); return null; } File[] list = dir.listFiles(); if (list.length == 0) { LOGGER.warn("No files found in directory {}", directory); return null; } List<String> cmds = new ArrayList<>(); for (File file : list) { String name = file.getName(); if (!(name.endsWith(".xml") && name.contains("derivate"))) { continue; } name = name.substring(0, name.length() - 4); // remove ".xml" File contentDir = new File(dir, name); if (!(contentDir.exists() && contentDir.isDirectory())) { continue; } cmds.add((update ? "update" : "load") + " derivate from file " + file.getAbsolutePath()); } return cmds; } /** * Loads an MCRDerivates from an XML file. * * @param file * the location of the xml file * @throws MCRAccessException see {@link MCRMetadataManager#create(MCRDerivate)} */ @MCRCommand(syntax = "load derivate from file {0}", help = "Loads an MCRDerivate from the file {0} to the system. " + "If the numerical part of the provided ID is zero, a new ID with the same project ID and type is assigned.", order = 40) public static boolean loadFromFile(String file) throws IOException, MCRPersistenceException, MCRAccessException, JDOMException { return loadFromFile(file, true); } /** * Loads an MCRDerivates from an XML file. * * @param file * the location of the xml file * @param importMode * if true, servdates are taken from xml file * @throws MCRAccessException see {@link MCRMetadataManager#create(MCRDerivate)} */ public static boolean loadFromFile(String file, boolean importMode) throws IOException, MCRPersistenceException, MCRAccessException, JDOMException { return processFromFile(new File(file), false, importMode); } /** * Updates an MCRDerivates from an XML file. * * @param file * the location of the xml file * @throws MCRAccessException see {@link MCRMetadataManager#update(MCRDerivate)} */ @MCRCommand(syntax = "update derivate from file {0}", help = "The command update a derivate form the file {0} in the system.", order = 50) public static boolean updateFromFile(String file) throws IOException, MCRPersistenceException, MCRAccessException, JDOMException { return updateFromFile(file, true); } /** * Updates an MCRDerivates from an XML file. * * @param file * the location of the xml file * @param importMode * if true, servdates are taken from xml file * @throws MCRAccessException see {@link MCRMetadataManager#update(MCRDerivate)} */ public static boolean updateFromFile(String file, boolean importMode) throws IOException, MCRPersistenceException, MCRAccessException, JDOMException { return processFromFile(new File(file), true, importMode); } /** * Load or update an MCRDerivate from an XML file. If the numerical part of the contained ID is zero, * a new ID with the same project ID and type is assigned. * * @param file * the location of the xml file * @param update * if true, derivate will be updated, else derivate is created * @param importMode * if true, servdates are taken from xml file * @throws MCRAccessException see {@link MCRMetadataManager#update(MCRDerivate)} */ private static boolean processFromFile(File file, boolean update, boolean importMode) throws IOException, MCRPersistenceException, MCRAccessException, JDOMException { if (!file.getName().endsWith(".xml")) { LOGGER.warn("{} ignored, does not end with *.xml", file); return false; } if (!file.isFile()) { LOGGER.warn("{} ignored, is not a file.", file); return false; } LOGGER.info("Reading file {} ...", file); MCRDerivate derivate = new MCRDerivate(file.toURI()); derivate.setImportMode(importMode); // Replace relative path with absolute path of files if (derivate.getDerivate().getInternals() != null) { String path = derivate.getDerivate().getInternals().getSourcePath(); if (path == null) { path = ""; } else { path = path.replace('/', File.separatorChar).replace('\\', File.separatorChar); } if (path.trim().length() <= 1) { // the path is the path name plus the name of the derivate - path = derivate.getId().toString(); } File sPath = new File(path); if (!sPath.isAbsolute()) { // only change path to absolute path when relative String prefix = file.getParent(); if (prefix != null) { path = prefix + File.separator + path; } } derivate.getDerivate().getInternals().setSourcePath(path); LOGGER.info("Source path --> {}", path); } if (update) { MCRMetadataManager.update(derivate); LOGGER.info("{} updated.", derivate.getId()); } else { MCRMetadataManager.create(derivate); LOGGER.info("{} loaded.", derivate.getId()); } return true; } /** * Export an MCRDerivate to a file named <em>MCRObjectID</em>.xml in a * directory named <em>dirname</em> and store the derivate files in a * nested directory named <em>MCRObjectID</em>. The IFS-Attribute of the * derivate files aren't saved, for reloading purpose after deleting a * derivate in the datastore * * @param id * the ID of the MCRDerivate to be save. * @param dirname * the dirname to store the derivate */ @MCRCommand(syntax = "show loadable derivate of {0} to directory {1}", help = "The command store the derivate with the MCRObjectID {0} to the directory {1}, without ifs-metadata", order = 130) public static void show(String id, String dirname) { exportWithStylesheet(id, id, dirname, "save"); } /** * Export an MCRDerivate to a file named <em>MCRObjectID</em>.xml in a directory named <em>dirname</em> * and store the derivate files in a nested directory named <em>MCRObjectID</em>. * The method uses the converter stylesheet <em>style</em>.xsl. * * @param id * the ID of the MCRDerivate to save. * @param dirname * the dirname to store the derivate * @param style * the name of the stylesheet, prefix of <em>style</em>-derivate.xsl */ @MCRCommand( syntax = "export derivate {0} to directory {1} with stylesheet {2}", help = "Stores the derivate with the MCRObjectID {0} to the directory {1}" + " with the stylesheet {2}-derivate.xsl. For {2}, the default is xsl/save.", order = 90) public static void exportWithStylesheet(String id, String dirname, String style) { exportWithStylesheet(id, id, dirname, style); } /** * Export any MCRDerivate's to files named <em>MCRObjectID</em>.xml in a directory named <em>dirname</em> * and the derivate files in nested directories named <em>MCRObjectID</em>. * Exporting starts with <em>fromID</em> and ends with <em>toID</em>. IDs that aren't found will be skipped. * The method use the converter stylesheet <em>style</em>.xsl. * * @param fromID * the first ID of the MCRDerivate to save. * @param toID * the last ID of the MCRDerivate to save. * @param dirname * the filename to store the object * @param style * the name of the stylesheet, prefix of <em>style</em>-derivate.xsl */ @MCRCommand(syntax = "export derivates from {0} to {1} to directory {2} with stylesheet {3}", help = "Stores all derivates with MCRObjectID's between {0} and {1} to the directory {2}" + " with the stylesheet {3}-derivate.xsl. For {3}, the default is xsl/save.", order = 80) public static void exportWithStylesheet(String fromID, String toID, String dirname, String style) { // check fromID MCRObjectID fid; try { fid = MCRObjectID.getInstance(fromID); } catch (Exception ex) { LOGGER.error("FromID : {}", ex.getMessage()); return; } // check toID MCRObjectID tid; try { tid = MCRObjectID.getInstance(toID); } catch (Exception ex) { LOGGER.error("ToID : {}", ex.getMessage()); return; } // check dirname File dir = new File(dirname); if (!dir.isDirectory()) { LOGGER.error("{} is not a directory.", dirname); return; } Transformer trans = getTransformer(style != null ? style + "-derivate" : null); String extension = MCRXSLTransformerUtils.getFileExtension(trans, "xml"); int k = 0; try { for (int i = fid.getNumberAsInteger(); i < tid.getNumberAsInteger() + 1; i++) { String id = MCRObjectID.formatID(fid.getProjectId(), fid.getTypeId(), i); exportDerivate(dir, trans, extension, id); k++; } } catch (Exception ex) { LOGGER.error("Exception while storing derivate to " + dir.getAbsolutePath(), ex); return; } LOGGER.info("{} Object's stored under {}.", k, dir.getAbsolutePath()); } /** * This command looks for all derivates in the application and builds export * commands. * * @param dirname * the filename to store the object * @param style * the name of the stylesheet, prefix of <em>style</em>-derivate.xsl * @return a list of export commands, one for each derivate */ @MCRCommand(syntax = "export all derivates to directory {0} with stylesheet {1}", help = "Stores all derivates to the directory {0} with the stylesheet {1}-derivate.xsl." + " For {1}, the default is xsl/save.", order = 100) public static List<String> exportAllDerivatesWithStylesheet(String dirname, String style) { return MCRCommandUtils.getIdsForType("derivate") .map(id -> "export derivate " + id + " to directory " + dirname + " with stylesheet " + style) .collect(Collectors.toList()); } /** * This command looks for all derivates starting with project name in the * application and builds export commands. * * @param dirname * the filename to store the object * @param style * the name of the stylesheet, prefix of <em>style</em>-derivate.xsl * @return a list of export commands, one for each derivate */ @MCRCommand(syntax = "export all derivates of project {0} to directory {1} with stylesheet {2}", help = "Stores all derivates of project {0} to the directory {1} with the stylesheet {2}-derivate.xsl." + " For {2}, the default is xsl/save.", order = 110) public static List<String> exportAllDerivatesOfProjectWithStylesheet(String project, String dirname, String style) { return MCRCommandUtils.getIdsForProjectAndType(project, "derivate") .map(id -> "export derivate " + id + " to directory " + dirname + " with stylesheet " + style) .collect(Collectors.toList()); } private static void exportDerivate(File dir, Transformer trans, String extension, String nid) throws TransformerException, IOException { // store the XML file Document xml = null; MCRDerivate obj; MCRObjectID derivateID = MCRObjectID.getInstance(nid); try { obj = MCRMetadataManager.retrieveMCRDerivate(derivateID); String path = obj.getDerivate().getInternals().getSourcePath(); // reset from the absolute to relative path, for later reload LOGGER.info("Old Internal Path ====>{}", path); obj.getDerivate().getInternals().setSourcePath(nid); LOGGER.info("New Internal Path ====>{}", nid); // add ACL's if (ACCESS_IMPL instanceof MCRRuleAccessInterface ruleAccessInterface) { Collection<String> l = ruleAccessInterface.getPermissionsForID(nid); for (String permission : l) { Element rule = ruleAccessInterface.getRule(nid, permission); obj.getService().addRule(permission, rule); } } // build JDOM xml = obj.createXML(); } catch (MCRException ex) { LOGGER.warn("Could not read {}, continue with next ID", nid); return; } File xmlOutput = new File(dir, derivateID + "." + extension); FileOutputStream out = new FileOutputStream(xmlOutput); dir = new File(dir, derivateID.toString()); if (trans != null) { trans.setParameter("dirname", dir.getPath()); StreamResult sr = new StreamResult(out); trans.transform(new JDOMSource(xml), sr); } else { new XMLOutputter().output(xml, out); out.flush(); out.close(); } LOGGER.info("Object {} stored under {}.", nid, xmlOutput); // store the derivate file under dirname if (!dir.isDirectory()) { dir.mkdir(); } MCRPath rootPath = MCRPath.getPath(derivateID.toString(), "/"); Files.walkFileTree(rootPath, new MCRTreeCopier(rootPath, dir.toPath())); LOGGER.info("Derivate {} saved under {} and {}.", nid, dir, xmlOutput); } /** * This method searches for the stylesheet <em>style</em>.xsl and builds the transformer. Default is * <em>save-derivate.xsl</em> if no stylesheet is given or the stylesheet couldn't be resolved. * * @param style * the name of the style to be used when resolving the stylesheet * @return the transformer */ private static Transformer getTransformer(String style) { return MCRCommandUtils.getTransformer(style, DEFAULT_STYLE, TRANSFORMER_CACHE); } /** * The method start the repair the content search index for all derivates. */ @MCRCommand(syntax = "repair derivate search of type derivate", help = "The command read the Content store and reindex the derivate search stores.", order = 140) public static List<String> repairDerivateSearch() { LOGGER.info("Start the repair for type derivate."); return MCRCommandUtils.getIdsForType("derivate") .map(id -> "repair derivate search of ID " + id) .collect(Collectors.toList()); } /** * Repairing the content search index for all derivates in project {0}. * * @param project * the project part of a MCRObjectID e.g. *DocPortal*_derivate */ @MCRCommand(syntax = "repair derivate search of project {0}", help = "Reads the Content store for project {0} and reindexes the derivate search stores.", order = 141) public static List<String> repairDerivateSearchForBase(String project) { LOGGER.info("Start the repair for project {}.", project); return MCRCommandUtils.getIdsForProjectAndType(project, "derivate") .map(id -> "repair derivate search of ID " + id) .collect(Collectors.toList()); } /** * The method start the repair the content search index for one. * * @param id * the MCRObjectID as String */ @MCRCommand(syntax = "repair derivate search of ID {0}", help = "The command read the Content store for MCRObjectID {0} and reindex the derivate search store.", order = 150) public static void repairDerivateSearchForID(String id) throws IOException { LOGGER.info("Start the repair for the ID {}", id); doForChildren(MCRPath.getPath(id, "/")); LOGGER.info("Repaired {}", id); } /** * This is a recursive method to start an event handler for each file. * * @param rootPath * a IFS node (file or directory) */ private static void doForChildren(Path rootPath) throws IOException { Files.walkFileTree(rootPath, new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // handle events MCREvent evt = new MCREvent(MCREvent.ObjectType.PATH, MCREvent.EventType.REPAIR); evt.put(MCREvent.PATH_KEY, file); evt.put(MCREvent.FILEATTR_KEY, attrs); MCREventManager.instance().handleEvent(evt); LOGGER.debug("repaired file {}", file); return super.visitFile(file, attrs); } }); } /** * The method start the repair the content search index for all derivates. */ @MCRCommand(syntax = "synchronize all derivates", help = "The command read each derivate and synchronize the xlink:label with " + "the derivate entry of the mycoreobject.", order = 160) public static List<String> synchronizeAllDerivates() { LOGGER.info("Start the synchronization for derivates."); return MCRCommandUtils.getIdsForType("derivate") .map(id -> "synchronize derivate with ID " + id) .collect(Collectors.toList()); } /** * Links the given derivate to the given object. */ @MCRCommand(syntax = "link derivate {0} to {1}", help = "links the given derivate {0} to the given mycore object {1}", order = 180) public static void linkDerivateToObject(String derivateId, String objectId) throws Exception { if (derivateId == null || objectId == null) { LOGGER.error("Either derivate id or object id is null. Derivate={}, object={}", derivateId, objectId); return; } MCRObjectID derID = MCRObjectID.getInstance(derivateId); MCRObjectID objID = MCRObjectID.getInstance(objectId); if (!MCRMetadataManager.exists(objID)) { throw new Exception("The object with id " + objID + " does not exist"); } if (!MCRMetadataManager.exists(derID)) { throw new Exception("The derivate with id " + derID + " does not exist"); } MCRDerivate derObj = MCRMetadataManager.retrieveMCRDerivate(derID); MCRMetaLinkID oldDerivateToObjectLink = derObj.getDerivate().getMetaLink(); MCRObjectID oldOwnerId = oldDerivateToObjectLink.getXLinkHrefID(); /* set link to new parent in the derivate object */ LOGGER.info("Setting {} as parent for derivate {}", objID, derID); derObj.getDerivate().getMetaLink() .setReference(objID, oldDerivateToObjectLink.getXLinkLabel(), oldDerivateToObjectLink.getXLinkTitle()); MCRMetadataManager.update(derObj); /* set link to derivate in the new parent */ MCRObject oldOwner = MCRMetadataManager.retrieveMCRObject(oldOwnerId); List<MCRMetaEnrichedLinkID> derivates = oldOwner.getStructure().getDerivates(); MCRMetaLinkID oldObjectToDerivateLink = null; for (MCRMetaLinkID derivate : derivates) { if (derivate.getXLinkHrefID().equals(derID)) { oldObjectToDerivateLink = derivate; } } if (oldObjectToDerivateLink == null) { oldObjectToDerivateLink = new MCRMetaLinkID(); } LOGGER.info("Linking derivate {} to {}", derID, objID); MCRMetaEnrichedLinkID derivateLink = MCRMetaEnrichedLinkIDFactory.getInstance().getDerivateLink(derObj); MCRMetadataManager.addOrUpdateDerivateToObject(objID, derivateLink, derObj.isImportMode()); /* removing link from old parent */ boolean flag = oldOwner.getStructure().removeDerivate(derID); LOGGER.info("Unlinking derivate {} from object {}. Success={}", derID, oldOwnerId, flag); MCRMetadataManager.fireUpdateEvent(oldOwner); } /** * Check the object links in derivates of MCR base ID for existing. * It looks to the XML store on the disk to get all object IDs. * * @param baseId * the base part of a MCRObjectID e.g. DocPortal_derivate */ @MCRCommand(syntax = "check object entries in derivates for base {0}", help = "check in all derivates of MCR base ID {0} for existing linked objects", order = 400) public static void checkObjectsInDerivates(String baseId) { if (baseId == null || baseId.length() == 0) { LOGGER.error("Base ID missed for check object entries in derivates for base {0}"); return; } int projectPartPosition = baseId.indexOf('_'); if (projectPartPosition == -1) { LOGGER.error("The given base ID {} has not the syntax of project_type", baseId); return; } MCRXMLMetadataManager mgr = MCRXMLMetadataManager.instance(); List<String> idList = mgr.listIDsForBase(baseId.substring(0, projectPartPosition + 1) + "derivate"); int counter = 0; int maxresults = idList.size(); for (String derid : idList) { counter++; LOGGER.info("Processing dataset {} from {} with ID: {}", counter, maxresults, derid); // get from data MCRObjectID mcrderid = MCRObjectID.getInstance(derid); MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(mcrderid); MCRObjectID objid = der.getOwnerID(); if (!mgr.exists(objid)) { LOGGER.error(" !!! Missing object {} in database for derivate ID {}", objid, mcrderid); } } LOGGER.info("Check done for {} entries", Integer.toString(counter)); } @MCRCommand(syntax = "transform xml matching file name pattern {0} in derivate {1} with stylesheet {2}", help = "Finds all files in Derivate {1} which match the pattern {0} " + "(the complete path with regex: or glob:*.xml syntax) and transforms them with stylesheet {2}") public static void transformXMLMatchingPatternWithStylesheet(String pattern, String derivate, String stylesheet) throws IOException { MCRXSLTransformer transformer = new MCRXSLTransformer(stylesheet); MCRPath derivateRoot = MCRPath.getPath(derivate, "/"); PathMatcher matcher = derivateRoot.getFileSystem().getPathMatcher(pattern); Files.walkFileTree(derivateRoot, new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (matcher.matches(file)) { LOGGER.info("The file {} matches the pattern {}", file, pattern); MCRContent sourceContent = new MCRPathContent(file); MCRContent resultContent = transformer.transform(sourceContent); try { Document source = sourceContent.asXML(); Document result = resultContent.asXML(); LOGGER.info("Transforming complete!"); if (!MCRXMLHelper.deepEqual(source, result)) { LOGGER.info("Writing result.."); resultContent.sendTo(file, StandardCopyOption.REPLACE_EXISTING); } else { LOGGER.info("Result and Source is the same.."); } } catch (JDOMException e) { throw new IOException("Error while processing file : " + file, e); } } return FileVisitResult.CONTINUE; } }); } @MCRCommand(syntax = "set main file of {0} to {1}", help = "Sets the main file of the derivate with the id {0} to " + "the file with the path {1}") public static void setMainFile(final String derivateIDString, final String filePath) throws MCRAccessException { if (!MCRObjectID.isValid(derivateIDString)) { LOGGER.error("{} is not valid. ", derivateIDString); return; } // check for derivate exist final MCRObjectID derivateID = MCRObjectID.getInstance(derivateIDString); if (!MCRMetadataManager.exists(derivateID)) { LOGGER.error("{} does not exist!", derivateIDString); return; } // remove leading slash String cleanPath = filePath; if (filePath.startsWith(String.valueOf(MCRAbstractFileSystem.SEPARATOR))) { cleanPath = filePath.substring(1); } // check for file exist final MCRPath path = MCRPath.getPath(derivateID.toString(), cleanPath); if (!Files.exists(path)) { LOGGER.error("File {} does not exist!", cleanPath); return; } final MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateID); derivate.getDerivate().getInternals().setMainDoc(cleanPath); MCRMetadataManager.update(derivate); LOGGER.info("The main file of {} is now '{}'!", derivateIDString, cleanPath); } @MCRCommand(syntax = "rename files from derivate {0} with {1} to {2}", help = "Renames multiple files in one Derivate with the ID {0} the given RegEx pattern {1} and the replacement" + " {2}. You can try out your pattern with the command: 'test rename file {0} with {1} to {2}'.") public static void renameFiles(String derivate, String pattern, String newName) throws IOException { MCRDerivateUtil.renameFiles(derivate, pattern, newName); } @MCRCommand(syntax = "test rename file {0} with {1} to {2}", help = "Tests the rename pattern {1} on one file {0} and replaces it with {2}, so you can try the rename" + " before renaming all files. This command does not change any files.") public static void testRenameFile(String filename, String pattern, String newName) { MCRDerivateUtil.testRenameFile(filename, pattern, newName); } @MCRCommand(syntax = "set order of derivate {0} to {1}", help = "Sets the order of derivate {0} to the number {1} see also MCR-2003") public static void setOrderOfDerivate(String derivateIDStr, String orderStr) throws MCRAccessException { final int order = Integer.parseInt(orderStr); final MCRObjectID derivateID = MCRObjectID.getInstance(derivateIDStr); if (!MCRMetadataManager.exists(derivateID)) { throw new MCRException("The derivate " + derivateIDStr + " does not exist!"); } final MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateID); derivate.setOrder(order); MCRMetadataManager.update(derivate); } @MCRCommand(syntax = "set classification of derivate {0} to {1}", help = "Sets the classification of derivate {0} to the categories {1} (comma separated) " + "of classification 'derivate_types' or any fully qualified category, removing any previous definition.") public static void setClassificationOfDerivate(String derivateIDStr, String categoriesCommaList) throws MCRAccessException { final MCRCategoryDAO categoryDAO = MCRCategoryDAOFactory.getInstance(); final List<MCRCategoryID> derivateTypes = Stream.of(categoriesCommaList.split(",")) .map(String::trim) .map(category -> category.contains(":") ? MCRCategoryID.fromString(category) : new MCRCategoryID("derivate_types", category)) .collect(Collectors.toList()); final String nonExistingCategoriesCommaList = derivateTypes.stream() .filter(Predicate.not(categoryDAO::exist)) .map(MCRCategoryID::getId) .collect(Collectors.joining(", ")); if (!nonExistingCategoriesCommaList.isEmpty()) { throw new MCRPersistenceException("Categories do not exist: " + nonExistingCategoriesCommaList); } final MCRObjectID derivateID = MCRObjectID.getInstance(derivateIDStr); final MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateID); derivate.getDerivate().getClassifications().clear(); derivate.getDerivate().getClassifications() .addAll( derivateTypes.stream() .map(categoryID -> new MCRMetaClassification("classification", 0, null, categoryID.getRootID(), categoryID.getId())) .collect(Collectors.toList())); MCRMetadataManager.update(derivate); } @MCRCommand(syntax = "clear derivate export transformer cache", help = "Clears the derivate export transformer cache", order = 200) public static void clearExportTransformerCache() { TRANSFORMER_CACHE.clear(); } }
37,064
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCommandManager.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRCommandManager.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.cli; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeMap; 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.MCRClassTools; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import org.mycore.frontend.cli.annotation.MCRCommandGroup; /** * Manages all commands for the Command Line Interface and WebCLI. * * @author Frank Lützenkirchen * @author Robert Stephan */ public class MCRCommandManager { private static final Logger LOGGER = LogManager.getLogger(MCRCommandManager.class); protected static TreeMap<String, List<MCRCommand>> knownCommands = new TreeMap<>(); public MCRCommandManager() { try { initBuiltInCommands(); initCommands(); } catch (Exception ex) { handleInitException(ex); } } @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("DM_EXIT") protected void handleInitException(Exception ex) { MCRCLIExceptionHandler.handleException(ex); System.exit(1); } public static TreeMap<String, List<MCRCommand>> getKnownCommands() { return knownCommands; } protected void initBuiltInCommands() { addAnnotatedCLIClass(MCRBasicCommands.class); } protected void initCommands() { // load build-in commands initConfiguredCommands("Internal"); initConfiguredCommands("External"); } /** Read internal and/or external commands */ protected void initConfiguredCommands(String type) { String prefix = "MCR.CLI.Classes." + type; Stream<Map.Entry<String, String>> propsWithPrefix = MCRConfiguration2.getPropertiesMap() .entrySet() .stream() .filter(e -> e.getKey().startsWith(prefix)); Stream<String> classNames = propsWithPrefix .map(Map.Entry::getValue) .flatMap(MCRConfiguration2::splitValue) .filter(s -> !s.isEmpty()); classNames.forEach(this::loadCommandClass); } private void loadCommandClass(String commandClassName) { LOGGER.debug("Will load commands from the {} class {}", commandClassName, commandClassName); try { Class<?> cliClass = MCRClassTools.forName(commandClassName); if (cliClass.isAnnotationPresent(MCRCommandGroup.class)) { addAnnotatedCLIClass(cliClass); } else { addDefaultCLIClass(commandClassName); } } catch (ClassNotFoundException cnfe) { LOGGER.error("MyCoRe Command Class {} not found.", commandClassName); } } protected void addAnnotatedCLIClass(Class<?> cliClass) { String groupName = Optional.ofNullable(cliClass.getAnnotation(MCRCommandGroup.class)) .map(MCRCommandGroup::name) .orElse(cliClass.getSimpleName()); final Class<org.mycore.frontend.cli.annotation.MCRCommand> mcrCommandAnnotation; mcrCommandAnnotation = org.mycore.frontend.cli.annotation.MCRCommand.class; ArrayList<MCRCommand> commands = Arrays.stream(cliClass.getMethods()) .filter(method -> method.getDeclaringClass().equals(cliClass)) .filter(method -> Modifier.isStatic(method.getModifiers()) && Modifier.isPublic(method.getModifiers())) .filter(method -> method.isAnnotationPresent(mcrCommandAnnotation)) .sorted(Comparator.comparingInt(m -> m.getAnnotation(mcrCommandAnnotation).order())) .map(MCRCommand::new) .collect(Collectors.toCollection(ArrayList::new)); addCommandGroup(groupName, commands); } //fixes MCR-1594 deep in the code private List<MCRCommand> addCommandGroup(String groupName, ArrayList<MCRCommand> commands) { return knownCommands.put(groupName, Collections.unmodifiableList(commands)); } protected void addDefaultCLIClass(String className) { Object obj = buildInstanceOfClass(className); MCRExternalCommandInterface commandInterface = (MCRExternalCommandInterface) obj; ArrayList<MCRCommand> commandsToAdd = commandInterface.getPossibleCommands(); addCommandGroup(commandInterface.getDisplayName(), commandsToAdd); } private Object buildInstanceOfClass(String className) { try { return MCRClassTools.forName(className).getDeclaredConstructor().newInstance(); } catch (Exception ex) { String msg = "Could not instantiate class " + className; throw new MCRConfigurationException(msg, ex); } } public List<String> invokeCommand(String command) throws Exception { if (command.trim().startsWith("#")) { //ignore comment return new ArrayList<>(); } for (List<MCRCommand> commands : knownCommands.values()) { for (MCRCommand currentCommand : commands) { long start = System.currentTimeMillis(); List<String> commandsReturned = currentCommand.invoke(command); long end = System.currentTimeMillis(); if (commandsReturned != null) { long timeNeeded = end - start; MCRCommandLineInterface.output("Command processed (" + timeNeeded + " ms)"); MCRCommandStatistics.commandInvoked(currentCommand, timeNeeded); return commandsReturned; } } } MCRCommandLineInterface.output("Command not understood:" + command); MCRCommandLineInterface.output("Enter 'help' to get a list of commands."); return new ArrayList<>(); } }
6,737
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCommandUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRCommandUtils.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.cli; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; 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.MCRUsageException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.xml.MCRURIResolver; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; /** * Utilities intended to reduce redundant code when writing variants of CLI commands. * * @author Christoph Neidahl (OPNA2608) * */ public class MCRCommandUtils { private static final Logger LOGGER = LogManager.getLogger(); /** * Get a stream of MCRObjectIDs found for a type. * * @param type * The type to look in the store for. * @return A (parallel) stream with found IDs. (may be empty if none were found) * @throws MCRUsageException * If no type was given or the type could not be found. * Not thrown if type exists but has no values. */ public static Stream<String> getIdsForType(final String type) throws MCRUsageException { if (type == null || type.length() == 0) { throw new MCRUsageException("Type required to enumerate IDs!"); } List<String> idList = MCRXMLMetadataManager.instance().listIDsOfType(type); if (idList.isEmpty()) { LOGGER.warn("No IDs found for type {}.", type); } return idList.stream(); } /** * Get a stream of MCRObjectIDs found for a project &amp; type combination. * * @param project * The project to look in the store for. * @param type * The type to look in the store for. * @return A (parallel) stream with found IDs. (may be empty if none were found) * @throws MCRUsageException * If no project was given, no type was given or the base (${project}_${base}) could not be found. * Not thrown if the base exists but has no values. */ public static Stream<String> getIdsForProjectAndType(final String project, final String type) throws MCRUsageException { if (project == null || project.length() == 0) { throw new MCRUsageException("Project required to enumerate IDs!"); } if (type == null || type.length() == 0) { throw new MCRUsageException("Type required to enumerate IDs!"); } return getIdsForBaseId(project + "_" + type); } /** * Get a stream of MCRObjectIDs found for a base. * * @param base * The base to look in the store for. * @return A (parallel) stream with found IDs. (may be empty if none were found) * @throws MCRUsageException * If no base was given or the base could not be found. * Not thrown if the base exists but has no values. */ public static Stream<String> getIdsForBaseId(final String base) throws MCRUsageException { if (MCRObjectID.getIDParts(base).length != 2) { throw new MCRUsageException("Base ID ({project}_{type}) required to enumerate IDs!"); } List<String> idList = MCRXMLMetadataManager.instance().listIDsForBase(base); if (idList.isEmpty()) { LOGGER.warn("No IDs found for base {}.", base); } return idList.stream(); } /** * Get a stream of MCRObjectIDs found in range between two IDs, incrementing/decrementing by 1. * * @param startId * The first ID to start iterating from. * @param endId * The last ID to iterate towards. * @return A (parallel) stream with generated IDs that exist in the store. (may be empty if none exist) * @throws MCRUsageException * If the supplied IDs are missing, invalid or have different base IDs, or if an error * occurred while getting the store responsible for their base. The latter *may* occur if there does not * yet exist a store for this base. * Not thrown if the base exists but has no values. */ public static Stream<String> getIdsFromIdToId(final String startId, final String endId) throws MCRUsageException { if (startId == null || startId.length() == 0) { throw new MCRUsageException("Start-ID required to enumerate IDs!"); } if (endId == null || endId.length() == 0) { throw new MCRUsageException("End-ID required to enumerate IDs!"); } MCRObjectID from = MCRObjectID.getInstance(startId); MCRObjectID to = MCRObjectID.getInstance(endId); String fromBase = from.getBase(); String toBase = to.getBase(); if (!fromBase.equals(toBase)) { throw new MCRUsageException( startId + " and " + endId + " have different base IDs (" + fromBase + " and " + toBase + "), same base required to enumerate IDs!"); } int fromID = from.getNumberAsInteger(); int toID = to.getNumberAsInteger(); int lowerBound = fromID < toID ? fromID : toID; int upperBound = fromID < toID ? toID : fromID; List<String> idList = IntStream.rangeClosed(lowerBound, upperBound).boxed().parallel() .map(n -> MCRObjectID.formatID(fromBase, n)) .filter(id -> MCRMetadataManager.exists(MCRObjectID.getInstance(id))) .collect(Collectors.toCollection(ArrayList::new)); if (idList.isEmpty()) { LOGGER.warn("No IDs found in range [{} -> {}].", from, to); } return idList.stream(); } /** * This method search for the stylesheet <em>style</em>.xsl and builds a transformer. A fallback is * used if no stylesheet is given or the stylesheet couldn't be resolved. * * @param style * the name of the style to be used when resolving the stylesheet. * @param defaultStyle * the name of the default style, ending with <em>.xsl</em> to be used when resolving the stylesheet. * A corresponding file [MCR.Layout.Transformer.Factory.XSLFolder]/<em>defaultStyle</em> must exist. * @param cache * The transformer cache to be used. * @return the transformer */ public static Transformer getTransformer(String style, String defaultStyle, Map<String, Transformer> cache) { String xslFilePath = defaultStyle; if (style != null && style.trim().length() != 0) { xslFilePath = style.trim() + ".xsl"; } Transformer transformer = cache.get(style); if (transformer != null) { return transformer; } Element element = MCRURIResolver.instance().resolve("resource:" + xslFilePath); if (element == null) { LOGGER.warn("Couldn't find resource {} for style {}, using default.", xslFilePath, style); final String xslFolder = MCRConfiguration2.getStringOrThrow("MCR.Layout.Transformer.Factory.XSLFolder"); xslFilePath = xslFolder + "/" + defaultStyle; element = MCRURIResolver.instance().resolve("resource:" + xslFilePath); } try { if (element != null) { TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setURIResolver(MCRURIResolver.instance()); transformer = transformerFactory.newTransformer(new JDOMSource(element)); cache.put(style, transformer); LOGGER.info("Loaded transformer from resource {} for style {}.", xslFilePath, style); return transformer; } else { LOGGER.warn("Couldn't load transformer from resource {} for style {}.", xslFilePath, style); } } catch (Exception e) { LOGGER.warn("Error while loading transformer from resource " + xslFilePath + " for style " + style + ".", e); } return null; } }
9,074
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCommandPrompt.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRCommandPrompt.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.cli; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; /** * Reads the next command entered at the stdin prompt. * * @author Frank Lützenkirchen */ public class MCRCommandPrompt { private BufferedReader console; private String systemName; public MCRCommandPrompt(String systemName) { this.systemName = systemName; this.console = new BufferedReader(new InputStreamReader(System.in, Charset.defaultCharset())); } public String readCommand() { String line = ""; do { line = readLine(); } while (line.isEmpty()); return line; } private String readLine() { System.out.print(systemName + "> "); try { String input = console.readLine(); if (input != null) { return input.trim().replaceAll("\\s+", " "); } else { /* input stream closed (EOF), shutdown */ System.out.println("quit"); return "quit"; } } catch (IOException ignored) { return ""; } } }
1,935
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRBasicCommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRBasicCommands.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.cli; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Comment; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.Namespace; import org.jdom2.filter.Filters; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.mycore.common.MCRClassTools; import org.mycore.common.config.MCRComponent; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationDir; import org.mycore.common.config.MCRRuntimeComponentDetector; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRFileContent; import org.mycore.common.xml.MCRXMLParserFactory; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; /** * This class contains the basic commands for MyCoRe Command Line and WebCLI. * * @author Robert Stephan */ @MCRCommandGroup(name = "Basic Commands") public class MCRBasicCommands { private static Logger LOGGER = LogManager.getLogger(MCRBasicCommands.class); // default value as defined in src/main/resources/configdir.template/resources/META-INF/persistence.xml private static final String PERSISTENCE_DEFAULT_H2_URL = "jdbc:h2:file:/path/to/.mycore/myapp/data/h2/mycore;AUTO_SERVER=TRUE"; /** * Shows a list of commands understood by the command line interface and * shows their input syntax. This method implements the "help" command */ @MCRCommand(syntax = "help", help = "List all possible commands.", order = 20) public static void listKnownCommands() { MCRCommandLineInterface.output("The following commands can be used:"); MCRCommandLineInterface.output(""); MCRCommandManager .getKnownCommands().entrySet().stream().forEach(e -> { outputGroup(e.getKey()); e.getValue().forEach(org.mycore.frontend.cli.MCRCommand::outputHelp); }); } /** * Shows the help text for one or more commands. * * @param pattern * the command, or a fragment of it */ @MCRCommand(syntax = "help {0}", help = "Show the help text for the commands beginning with {0}.", order = 10) public static void listKnownCommandsBeginningWithPrefix(String pattern) { TreeMap<String, List<org.mycore.frontend.cli.MCRCommand>> matchingCommands = MCRCommandManager .getKnownCommands().entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream() .filter(cmd -> cmd.getSyntax().contains(pattern) || cmd.getHelpText().contains(pattern)) .collect(Collectors.toList()), (k, v) -> k, TreeMap::new)); matchingCommands.entrySet().removeIf(e -> e.getValue().isEmpty()); if (matchingCommands.isEmpty()) { MCRCommandLineInterface.output("Unknown command:" + pattern); } else { MCRCommandLineInterface.output(""); matchingCommands.forEach((grp, cmds) -> { outputGroup(grp); cmds.forEach(org.mycore.frontend.cli.MCRCommand::outputHelp); }); } } private static void outputGroup(String group) { MCRCommandLineInterface.output(group); MCRCommandLineInterface.output(new String(new char[70]).replace("\0", "-")); MCRCommandLineInterface.output(""); } @MCRCommand(syntax = "process resource {0}", help = "Execute the commands listed in the resource file {0}.", order = 20) public static List<String> readCommandsResource(String resource) throws IOException { return MCRCommandLineInterface.readCommandsRessource(resource); } @MCRCommand(syntax = "process {0}", help = "Execute the commands listed in the text file {0}.", order = 30) public static List<String> readCommandsFile(String file) throws IOException { return MCRCommandLineInterface.readCommandsFile(file); } @MCRCommand(syntax = "exit", help = "Stop and exit the commandline tool.", order = 40) public static void exit() { MCRCommandLineInterface.exit(); } @MCRCommand(syntax = "quit", help = "Stop and exit the commandline tool.", order = 50) public static void quit() { MCRCommandLineInterface.exit(); } @MCRCommand(syntax = "! {0}", help = "Execute the shell command {0}, for example '! ls' or '! cmd /c dir'", order = 60) public static void executeShellCommand(String command) throws Exception { MCRCommandLineInterface.executeShellCommand(command); } @MCRCommand(syntax = "show file {0}", help = "Show contents of local file {0}", order = 70) public static void show(String file) throws Exception { MCRCommandLineInterface.show(file); } @MCRCommand(syntax = "whoami", help = "Print the current user.", order = 80) public static void whoami() { MCRCommandLineInterface.whoami(); } @MCRCommand(syntax = "show command statistics", help = "Show statistics on number of commands processed and execution time needed per command", order = 90) public static void showCommandStatistics() { MCRCommandStatistics.showCommandStatistics(); } @MCRCommand(syntax = "cancel on error", help = "Cancel execution of further commands in case of error", order = 100) public static void cancelonError() { MCRCommandLineInterface.cancelOnError(); } @MCRCommand(syntax = "skip on error", help = "Skip execution of failed command in case of error", order = 110) public static void skipOnError() { MCRCommandLineInterface.skipOnError(); } @MCRCommand(syntax = "get uri {0} to file {1}", help = "Get XML content from URI {0} and save it to a local file {1}", order = 120) public static void getURI(String uri, String file) throws Exception { MCRCommandLineInterface.getURI(uri, file); } @MCRCommand(syntax = "create configuration directory", help = "Creates the MCRConfiguration directory if it does not exist.", order = 130) public static void createConfigurationDirectory() throws IOException { File configurationDirectory = MCRConfigurationDir.getConfigurationDirectory(); ArrayList<File> directories = new ArrayList<>(3); directories.add(configurationDirectory); for (String dir : MCRConfiguration2.getString("MCR.ConfigurationDirectory.template.directories").orElse("") .split(",")) { if (!dir.trim().isEmpty()) { directories.add(new File(configurationDirectory, dir.trim())); } } for (File directory : directories) { if (!createDirectory(directory)) { break; } } for (String f : MCRConfiguration2.getString("MCR.ConfigurationDirectory.template.files").orElse("") .split(",")) { if (!f.trim().isEmpty()) { createSampleConfigFile(f.trim()); } } } private static boolean createDirectory(File directory) { if (directory.exists()) { LOGGER.warn("Directory {} already exists.", directory.getAbsolutePath()); return true; } if (directory.mkdirs()) { LOGGER.info("Successfully created directory: {}", directory.getAbsolutePath()); return true; } else { LOGGER.warn("Due to unknown error the directory could not be created: {}", directory.getAbsolutePath()); return false; } } private static void createSampleConfigFile(String path) throws IOException { ClassLoader classLoader = MCRClassTools.getClassLoader(); File configurationDirectory = MCRConfigurationDir.getConfigurationDirectory(); File targetFile = new File(configurationDirectory, path); if (targetFile.exists()) { LOGGER.warn("File {} already exists.", targetFile.getAbsolutePath()); return; } if (!targetFile.getParentFile().exists() && !targetFile.getParentFile().mkdirs()) { throw new IOException("Could not create directory for file: " + targetFile); } try (InputStream templateResource = classLoader.getResourceAsStream("configdir.template/" + path); FileOutputStream fout = new FileOutputStream(targetFile)) { if (templateResource == null) { throw new IOException("Could not find template for " + path); } IOUtils.copy(templateResource, fout); LOGGER.info("Created template for {} in {}", path, configurationDirectory); } } @MCRCommand(syntax = "reload mappings in jpa configuration file", help = "retrieves the mapping files from MyCoRe jars and adds them to the jpa configuration file.", order = 140) public static void reloadJPAMappings() throws IOException, JDOMException { File persistenceXMLFile = MCRConfigurationDir.getConfigFile("resources/META-INF/persistence.xml"); if (Files.exists(persistenceXMLFile.toPath())) { SAXBuilder sb = new SAXBuilder(); Document persistenceDoc = sb.build(persistenceXMLFile); // attention: non-short-circuit OR operators to execute left and right side of OR expression boolean modified = updatePersistenceMappings(persistenceDoc) | updatePersistenceH2JdbcUrl(persistenceDoc); if (modified) { LOGGER.warn("Updating " + persistenceXMLFile + " with new mappings."); XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); try (BufferedWriter bw = Files.newBufferedWriter(persistenceXMLFile.toPath())) { out.output(persistenceDoc, bw); } } } else { LOGGER.warn("The config file '" + persistenceXMLFile + "' does not exist yet!"); } } /** * changes an unconfigured H2 JDBC URL, * that the database files are created in the current MYCORE_HOME directory * * @param persistenceDoc the persistence.xml as JDOM2 document * @return true if the Jdbc URL was change */ private static boolean updatePersistenceH2JdbcUrl(Document persistenceDoc) { Namespace nsPersistence = persistenceDoc.getRootElement().getNamespace(); Element ePersistenceUnit = persistenceDoc.getRootElement().getChild("persistence-unit", nsPersistence); List<Element> properties = ePersistenceUnit.getChild("properties", nsPersistence) .getContent(Filters.element("property", nsPersistence)); for (Element p : properties) { if ("jakarta.persistence.jdbc.url".equals(p.getAttributeValue("name")) && PERSISTENCE_DEFAULT_H2_URL.equals(p.getAttributeValue("value"))) { File databaseFile = MCRConfigurationDir.getConfigFile("data/h2/mycore"); if (databaseFile != null) { p.setAttribute("value", "jdbc:h2:file:" + databaseFile.getAbsolutePath() + ";AUTO_SERVER=TRUE"); return true; } } } return false; } /** * adds or removes mapping entries in persistence.xml, * that they match the defined JPA-mappings in the currently available MyCoRe components * * @param persistenceDoc - the persistence.xml as JDOM2 document * @return true, if the mappings changed * @throws IOException */ private static boolean updatePersistenceMappings(Document persistenceDoc) throws IOException { Namespace nsPersistence = persistenceDoc.getRootElement().getNamespace(); Element ePersistenceUnit = persistenceDoc.getRootElement().getChild("persistence-unit", nsPersistence); List<Element> mappingElements = ePersistenceUnit .getContent(Filters.element("mapping-file", nsPersistence)); List<String> oldMappings = mappingElements.stream() .map(Element::getTextNormalize) .collect(Collectors.toList()); boolean modified = mappingElements .removeIf(e -> e.getTextNormalize().endsWith("-mappings.xml") && MCRBasicCommands.class.getResource( (e.getTextNormalize().startsWith("/") ? "" : "/") + e.getTextNormalize()) == null); if (modified) { LOGGER.warn((oldMappings.size() - mappingElements.size()) + " unknown mapping files removed."); } List<String> newMappings = new ArrayList<>(); for (MCRComponent cmp : MCRRuntimeComponentDetector.getAllComponents()) { try (ZipInputStream zip = new ZipInputStream(Files.newInputStream(cmp.getJarFile().toPath()))) { ZipEntry ze; while ((ze = zip.getNextEntry()) != null) { String zeName = ze.getName(); if (zeName.startsWith("META-INF/") && zeName.endsWith("-mappings.xml") && !oldMappings.contains(zeName)) { newMappings.add(zeName); } } } } if (!newMappings.isEmpty()) { Comment c = new Comment( " mapping files, added by command 'reload mappings in jpa configuration file' "); ePersistenceUnit.getContent(Filters.comment()).removeIf(x -> x.getText().equals(c.getText())); ePersistenceUnit.addContent(0, c); int pos = 0; for (String mappingFile : newMappings) { Element eMappingFile = new Element("mapping-file", nsPersistence).setText(mappingFile); ePersistenceUnit.addContent(++pos, eMappingFile); } LOGGER.warn(newMappings.size() + " mapping files added."); modified = true; } return modified; } /** * The method parse and check an XML file. * * @param fileName * the location of the xml file */ @MCRCommand(syntax = "check file {0}", help = "Checks the data file {0} against the XML Schema.", order = 160) public static boolean checkXMLFile(String fileName) throws IOException, JDOMException { if (!fileName.endsWith(".xml")) { LOGGER.warn("{} ignored, does not end with *.xml", fileName); return false; } File file = new File(fileName); if (!file.isFile()) { LOGGER.warn("{} ignored, is not a file.", fileName); return false; } LOGGER.info("Reading file {} ...", file); MCRContent content = new MCRFileContent(file); MCRXMLParserFactory.getParser().parseXML(content); LOGGER.info("The file has no XML errors."); return true; } }
16,179
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRObjectCommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRObjectCommands.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.cli; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UncheckedIOException; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.commons.lang3.function.FailableBiConsumer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.filter.Filters; import org.jdom2.transform.JDOMResult; import org.jdom2.transform.JDOMSource; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.access.MCRAccessException; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRConstants; import org.mycore.common.MCRException; import org.mycore.common.MCRPersistenceException; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRStreamUtils; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRBaseContent; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.content.MCRSourceContent; import org.mycore.common.content.transformer.MCRContentTransformer; import org.mycore.common.content.transformer.MCRContentTransformerFactory; import org.mycore.common.xml.MCREntityResolver; import org.mycore.common.xml.MCRLayoutTransformerFactory; 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.datamodel.common.MCRAbstractMetadataVersion; import org.mycore.datamodel.common.MCRActiveLinkException; import org.mycore.datamodel.common.MCRFileBaseCacheObjectIDGenerator; import org.mycore.datamodel.common.MCRLinkTableManager; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetaEnrichedLinkID; 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.MCRObjectUtils; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; import org.mycore.tools.MCRTopologicalSort; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import jakarta.persistence.EntityManager; import jakarta.persistence.TypedQuery; /** * Provides static methods that implement commands for the MyCoRe command line interface. Robert: Ideas for clean-up - * "transform ..." and "xslt..." do the same thing and should thereform be named uniquely - "transformm ...." - * "delete by Query ..." can be deleted - "select ..." and "delete selected ..." supply the same behaviour in 2 commands * - "list objects matching ..." can be deleted - "select ..." and "list selected" supply the same behaviour in 2 * commands * * @author Jens Kupferschmidt * @author Frank Lützenkirchen * @author Robert Stephan */ @MCRCommandGroup(name = "Object Commands") public class MCRObjectCommands extends MCRAbstractCommands { private static final String EXPORT_OBJECT_TO_DIRECTORY_WITH_STYLESHEET_COMMAND = "export object {0} to directory {1} with stylesheet {2}"; /** The logger */ private static final Logger LOGGER = LogManager.getLogger(MCRObjectCommands.class); /** Default transformer script */ public static final String DEFAULT_STYLE = "save-object.xsl"; /** Static compiled transformer stylesheets */ private static final Map<String, Transformer> TRANSFORMER_CACHE = new HashMap<>(); public static void setSelectedObjectIDs(List<String> selected) { LOGGER.info("{} objects selected", selected.size()); MCRSessionMgr.getCurrentSession().put("mcrSelectedObjects", selected); } @SuppressWarnings("unchecked") public static List<String> getSelectedObjectIDs() { final List<String> list = (List<String>) MCRSessionMgr.getCurrentSession().get("mcrSelectedObjects"); if (list == null) { return Collections.EMPTY_LIST; } return list; } @MCRCommand( syntax = "select objects with xpath {0}", help = "Selects MCRObjects with XPath {0}, if that XPath evaluates to a non-empty result list" + " (this command may take a while, use with care in case of a large number of objects)", order = 10) public static void selectObjectsWithXpath(String xPath) { XPathExpression<Object> xPathExpression = XPathFactory .instance() .compile(xPath, Filters.fpassthrough(), null, MCRConstants.getStandardNamespaces()); List<String> selectedObjectIds = MCRXMLMetadataManager .instance() .listIDs() .stream() .filter(id -> !id.contains("_derivate_")) .map(MCRObjectID::getInstance) .map(MCRMetadataManager::retrieveMCRObject) .filter(mcrObject -> !xPathExpression.evaluate(mcrObject.createXML()).isEmpty()) .map(MCRObject::getId) .map(MCRObjectID::toString) .collect(Collectors.toList()); MCRObjectCommands.setSelectedObjectIDs(selectedObjectIds); } @MCRCommand( syntax = "select descendants of object {0}", help = "Selects MCRObjects that are descendants of {0} (children, grandchildren, ...) and {0} itself.", order = 15) public static void selectDescendantObjects(String id) { List<String> descendants = new ArrayList<>(); if (MCRMetadataManager.exists(MCRObjectID.getInstance(id))) { fillWithDescendants(id, descendants); } MCRObjectCommands.setSelectedObjectIDs(descendants); } private static void fillWithDescendants(String mcrObjID, List<String> descendants) { descendants.add(mcrObjID); //add child objects for (String childID : MCRLinkTableManager.instance().getSourceOf(mcrObjID, MCRLinkTableManager.ENTRY_TYPE_PARENT)) { descendants.add(childID); fillWithDescendants(childID, descendants); } } /** * Delete all MCRObject from the datastore for a given type. * * @param type * the type of the MCRObjects that should be deleted */ @MCRCommand( syntax = "delete all objects of type {0}", help = "Removes MCRObjects of type {0}.", order = 20) public static List<String> deleteAllObjects(String type) { return MCRCommandUtils.getIdsForType(type) .map(id -> "delete object " + id) .collect(Collectors.toList()); } /** * Delete all MCRObjects from the datastore in topological order * */ @MCRCommand( syntax = "delete all objects in topological order", help = "Removes all MCRObjects in topological order.", order = 25) public static List<String> deleteTopologicalAllObjects() { final List<String> objectIds = MCRXMLMetadataManager.instance().listIDs(); String[] objects = objectIds.stream().filter(id -> !id.contains("_derivate_")).toArray(String[]::new); MCRTopologicalSort<String> ts = new MCRTopologicalSort<>(); MCRTopologicalSort.prepareMCRObjects(ts, objects); int[] order = ts.doTopoSort(); List<String> cmds = new ArrayList<>(objectIds.size()); if (order != null) { //delete in reverse order for (int o = order.length - 1; o >= 0; o--) { cmds.add("delete object " + ts.getNodeName(order[o])); } } return cmds; } @MCRCommand( syntax = "check for circles in topological order", help = "Checks if there are circular dependencies in the parent child relationships of MCRObjects.", order = 25) public static void checkForCircles() { final List<String> objectIds = MCRXMLMetadataManager.instance().listIDs(); String[] objects = objectIds.stream().filter(id -> !id.contains("_derivate_")).toArray(String[]::new); MCRTopologicalSort<String> ts = new MCRTopologicalSort<>(); MCRTopologicalSort.prepareMCRObjects(ts, objects); int[] order = ts.doTopoSort(); if (order != null) { LOGGER.info("OK - No circles detected!"); } } /** * Delete a MCRObject from the datastore. * * @param id * the id of the MCRObject that should be deleted * @throws MCRPersistenceException if a persistence problem is occurred * @throws MCRAccessException see {@link MCRMetadataManager#deleteMCRObject(MCRObjectID)} * @throws MCRActiveLinkException if object is referenced by other objects */ @MCRCommand( syntax = "delete object {0}", help = "Removes a MCRObject with the MCRObjectID {0}", order = 40) public static void delete(String id) throws MCRPersistenceException, MCRActiveLinkException, MCRAccessException { MCRObjectID mcrId = MCRObjectID.getInstance(id); MCRMetadataManager.deleteMCRObject(mcrId); LOGGER.info("{} deleted.", mcrId); } /** * Runs though all mycore objects which are linked with the given object and removes its link. This includes * parent/child relations and all {@link MCRMetaLinkID} in the metadata section. * * @param id * the id of the MCRObject that should be deleted * @throws MCRPersistenceException if a persistence problem is occurred */ @MCRCommand( syntax = "clear links of object {0}", help = "removes all links of this object, including parent/child relations" + " and all MetaLinkID's in the metadata section", order = 45) public static void clearLinks(String id) throws MCRPersistenceException { final MCRObjectID mcrId = MCRObjectID.getInstance(id); AtomicInteger counter = new AtomicInteger(0); MCRObjectUtils.removeLinks(mcrId).forEach(linkedObject -> { try { LOGGER.info("removing link '{}' of '{}'.", mcrId, linkedObject.getId()); MCRMetadataManager.update(linkedObject); counter.incrementAndGet(); } catch (Exception exc) { LOGGER.error(String.format(Locale.ROOT, "Unable to update object '%s'", linkedObject), exc); } }); LOGGER.info("{} link(s) removed of {}.", counter.get(), mcrId); } /** * Delete MCRObject's form ID to ID from the datastore. * * @param idFrom * the start ID for deleting the MCRObjects * @param idTo * the stop ID for deleting the MCRObjects * @return list of delete commands */ @MCRCommand( syntax = "delete object from {0} to {1}", help = "Removes MCRObjects in the number range between the MCRObjectID {0} and {1}.", order = 30) public static List<String> deleteFromTo(String idFrom, String idTo) { return MCRCommandUtils.getIdsFromIdToId(idFrom, idTo) .map(id -> "delete object " + id) .collect(Collectors.toList()); } /** * Load MCRObject's from all XML files in a directory in proper order (respecting parent-child-relationships). * * @param directory * the directory containing the XML files */ @MCRCommand( syntax = "load all objects in topological order from directory {0}", help = "Loads all MCRObjects form the directory {0} to the system " + "respecting the order of parents and children.", order = 75) public static List<String> loadTopologicalFromDirectory(String directory) { return processFromDirectory(true, directory, false); } /** * Update MCRObject's from all XML files in a directory in proper order (respecting parent-child-relationships). * * @param directory * the directory containing the XML files */ @MCRCommand( syntax = "update all objects in topological order from directory {0}", help = "Updates all MCRObjects from the directory {0} in the system " + "respecting the order of parents and children.", order = 95) public static List<String> updateTopologicalFromDirectory(String directory) { return processFromDirectory(true, directory, true); } /** * Load MCRObject's from all XML files in a directory. * * @param directory * the directory containing the XML files */ @MCRCommand( syntax = "load all objects from directory {0}", help = "Loads all MCRObjects from the directory {0} to the system. " + "If the numerical part of a provided ID is zero, a new ID with the same project ID and type is assigned.", order = 70) public static List<String> loadFromDirectory(String directory) { return processFromDirectory(false, directory, false); } /** * Update MCRObject's from all XML files in a directory. * * @param directory * the directory containing the XML files */ @MCRCommand( syntax = "update all objects from directory {0}", help = "Updates all MCRObjects from the directory {0} in the system.", order = 90) public static List<String> updateFromDirectory(String directory) { return processFromDirectory(false, directory, true); } /** * Load or update MCRObject's from all XML files in a directory. * * @param topological * if true, the dependencies of parent and child objects will be respected * @param directory * the directory containing the XML files * @param update * if true, object will be updated, else object is created */ private static List<String> processFromDirectory(boolean topological, String directory, boolean update) { File dir = new File(directory); if (!dir.isDirectory()) { LOGGER.warn("{} ignored, is not a directory.", directory); return null; } String[] list = dir.list(); if (list == null || list.length == 0) { LOGGER.warn("No files found in directory {}", directory); return null; } Predicate<String> isMetaXML = file -> file.endsWith(".xml") && !file.contains("derivate"); Function<String, String> cmdFromFile = file -> (update ? "update" : "load") + " object from file " + new File(dir, file).getAbsolutePath(); if (topological) { MCRTopologicalSort<String> ts = new MCRTopologicalSort<>(); MCRTopologicalSort.prepareData(ts, list, dir.toPath()); return Optional.ofNullable(ts.doTopoSort()) .map(Arrays::stream) .map(is -> is.mapToObj(i -> list[i])) .orElse(Stream.empty()) .filter(isMetaXML) .map(cmdFromFile) .collect(Collectors.toList()); } else { return Arrays.stream(list) .filter(isMetaXML) .sorted() .map(cmdFromFile) .collect(Collectors.toList()); } } /** * Load a MCRObjects from an XML file. * * @param file * the location of the xml file * @throws MCRAccessException see {@link MCRMetadataManager#create(MCRObject)} */ @MCRCommand( syntax = "load object from file {0}", help = "Loads an MCRObject from the file {0} to the system. " + "If the numerical part of the provided ID is zero, a new ID with the same project ID and type is assigned.", order = 60) public static boolean loadFromFile(String file) throws MCRException, IOException, MCRAccessException, JDOMException { return loadFromFile(file, true) != null; } /** * Load a MCRObjects from an XML file. * * @param file * the location of the xml file * @param importMode * if true, servdates are taken from xml file * @throws MCRAccessException see {@link MCRMetadataManager#update(MCRObject)} */ public static MCRObject loadFromFile(String file, boolean importMode) throws MCRException, IOException, MCRAccessException, JDOMException { return processFromFile(new File(file), false, importMode); } /** * Update a MCRObject's from an XML file. * * @param file * the location of the xml file * @throws MCRAccessException see {@link MCRMetadataManager#update(MCRObject)} */ @MCRCommand( syntax = "update object from file {0}", help = "Updates a MCRObject from the file {0} in the system.", order = 80) public static boolean updateFromFile(String file) throws MCRException, IOException, MCRAccessException, JDOMException { return updateFromFile(file, true) != null; } /** * Update a MCRObject's from an XML file. * * @param file * the location of the xml file * @param importMode * if true, servdates are taken from xml file * @throws MCRAccessException see {@link MCRMetadataManager#update(MCRObject)} * @return the updated object */ public static MCRObject updateFromFile(String file, boolean importMode) throws MCRException, IOException, MCRAccessException, JDOMException { return processFromFile(new File(file), true, importMode); } /** * Load or update an MCRObject from an XML file. If the numerical part of the contained ID is zero, * a new ID with the same project ID and type is assigned. * * @param file * the location of the xml file * @param update * if true, object will be updated, else object is created * @param importMode * if true, servdates are taken from xml file * @throws SAXParseException * unable to build the mycore object from the file's URI * @throws MCRException * the parent of the given object does not exists * @throws MCRAccessException * if write permission is missing * @return the created or updated object */ private static MCRObject processFromFile(File file, boolean update, boolean importMode) throws MCRException, IOException, MCRAccessException, JDOMException { if (!file.getName().endsWith(".xml")) { LOGGER.warn("{} ignored, does not end with *.xml", file); return null; } if (!file.isFile()) { LOGGER.warn("{} ignored, is not a file.", file); return null; } LOGGER.info("Reading file {} ...", file); MCRObject mcrObject = new MCRObject(file.toURI()); if (mcrObject.hasParent()) { MCRObjectID parentID = mcrObject.getStructure().getParentID(); if (!MCRMetadataManager.exists(mcrObject.getStructure().getParentID())) { throw new MCRException("The parent object " + parentID + "does not exist for " + mcrObject + "."); } } mcrObject.setImportMode(importMode); LOGGER.debug("Label --> {}", mcrObject.getLabel()); if (update) { MCRMetadataManager.update(mcrObject); LOGGER.info("{} updated.", mcrObject.getId()); } else { MCRMetadataManager.create(mcrObject); LOGGER.info("{} loaded.", mcrObject.getId()); } return mcrObject; } /** * Shows the next free MCRObjectIDs. * * @param base * the base String of the MCRObjectID */ public static void showNextID(String base) { try { LOGGER.info("The next free ID is {}", MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(base)); } catch (MCRException ex) { LOGGER.error(ex.getMessage()); } } /** * Shows the last used MCRObjectIDs. * * @param base * the base String of the MCRObjectID */ public static void showLastID(String base) { try { LOGGER.info("The last used ID is {}", MCRMetadataManager.getMCRObjectIDGenerator().getLastID(base)); } catch (MCRException ex) { LOGGER.error(ex.getMessage()); } } /** * Export an MCRObject to a file named <em>MCRObjectID</em>.xml in a directory named <em>dirname</em>. * The method uses the converter stylesheet <em>style</em>.xsl. * * @param id * the id of the MCRObject to save. * @param dirname * the dirname to store the object * @param style * the name of the stylesheet, prefix of <em>style</em>-object.xsl */ @MCRCommand( syntax = EXPORT_OBJECT_TO_DIRECTORY_WITH_STYLESHEET_COMMAND, help = "Stores the object with the MCRObjectID {0} to the directory {1}" + " with the stylesheet {2}-object.xsl. For {2}, the default is xsl/save.", order = 110) public static void exportWithStylesheet(String id, String dirname, String style) { exportWithStylesheet(id, id, dirname, style); } /** * Export an MCRObject to a file named <em>MCRObjectID</em>.xml in a directory named <em>dirname</em>. * The method use the content transformer <em>transname</em>xsl. * * @param id * the id of the MCRObject to save. * @param dirname * the dirname to store the object * @param transname * the name of the transformer */ @MCRCommand( syntax = "export object {0} to directory {1} with transformer {2}", help = "Stores the object with the MCRObjectID {0} to the directory {1}" + " with the transformer {2}.", order = 110) public static void exportWithTransformer(String id, String dirname, String transname) { exportWithTransformer(id, id, dirname, transname); } /** * Export any MCRObject's to files named <em>MCRObjectID</em>.xml in a directory named <em>dirname</em>. * Exporting starts with <em>fromID</em> and ends with <em>toID</em>. IDs that aren't found will be skipped. * The method uses the converter stylesheet <em>style</em>.xsl. * * @param fromID * the first ID of the MCRObjects to save. * @param toID * the last ID of the MCRObjects to save. * @param dirname * the filename to store the object * @param style * the name of the stylesheet, prefix of <em>style</em>-object.xsl */ @MCRCommand( syntax = "export objects from {0} to {1} to directory {2} with stylesheet {3}", help = "Stores all objects with MCRObjectID's between {0} and {1} to the directory {2} " + "with the stylesheet {3}-object.xsl. For {3}, the default is xsl/save.", order = 100) public static void exportWithStylesheet(String fromID, String toID, String dirname, String style) { Transformer transformer = getTransformer(style != null ? style + "-object" : null); String extension = MCRXSLTransformerUtils.getFileExtension(transformer, "xml"); exportWith(fromID, toID, dirname, extension, (content, out) -> { StreamResult sr = new StreamResult(out); JDOMSource doc = new JDOMSource(MCRXMLParserFactory.getNonValidatingParser().parseXML(content)); transformer.transform(doc, sr); }); } /** * Export any MCRObject's to files named <em>MCRObjectID</em>.xml in a directory named <em>dirname</em>. * Exporting starts with <em>fromID</em> and ends with <em>toID</em>. IDs that aren't found will be skipped. * The method use the content transformer <em>transname</em>xsl. * * @param fromID * the first ID of the MCRObjects to save. * @param toID * the last ID of the MCRObjects to save. * @param dirname * the filename to store the object * @param transname * the name of the transformer */ @MCRCommand( syntax = "export objects from {0} to {1} to directory {2} with transformer {3}", help = "Stores all objects with MCRObjectID's between {0} and {1} to the directory {2} " + "with the transformer {3}.", order = 100) public static void exportWithTransformer(String fromID, String toID, String dirname, String transname) { MCRContentTransformer transformer = MCRContentTransformerFactory.getTransformer(transname); exportWith(fromID, toID, dirname, getExtension(transformer), transformer::transform); } private static String getExtension(MCRContentTransformer transformer) { try { return transformer.getFileExtension(); } catch (Exception e) { throw new MCRException(e); } } private static void exportWith(String fromID, String toID, String dirname, String extension, FailableBiConsumer<MCRContent, OutputStream, Exception> trans) { // check fromID MCRObjectID fid; try { fid = MCRObjectID.getInstance(fromID); } catch (Exception ex) { LOGGER.error("FromID : {}", ex.getMessage()); return; } // check toID MCRObjectID tid; try { tid = MCRObjectID.getInstance(toID); } catch (Exception ex) { LOGGER.error("ToID : {}", ex.getMessage()); return; } // check dirname File dir = new File(dirname); if (!dir.isDirectory()) { LOGGER.error("{} is not a directory.", dirname); return; } int k = 0; try { for (int i = fid.getNumberAsInteger(); i < tid.getNumberAsInteger() + 1; i++) { String id = MCRObjectID.formatID(fid.getProjectId(), fid.getTypeId(), i); if (!MCRMetadataManager.exists(MCRObjectID.getInstance(id))) { continue; } if (!exportObject(dir, extension, trans, id)) { continue; } k++; } } catch (Exception ex) { LOGGER.error("Exception while storing object to " + dir.getAbsolutePath(), ex); return; } LOGGER.info("{} Object's stored under {}.", k, dir.getAbsolutePath()); } /** * Export all MCRObject's with data type <em>type</em> to files named <em>MCRObjectID</em>.xml in a directory * named <em>dirname</em>. The method uses the converter stylesheet <em>style</em>.xsl. * * @param type * the MCRObjectID type * @param dirname * the filename to store the object * @param style * the name of the stylesheet, prefix of <em>style</em>-object.xsl * @return a list of export commands, one for each object */ @MCRCommand( syntax = "export all objects of type {0} to directory {1} with stylesheet {2}", help = "Stores all objects of type {0} to directory {1} " + "with the stylesheet {2}-object.xsl. For {2}, the default is xsl/save.", order = 120) public static List<String> exportAllObjectsOfTypeWithStylesheet(String type, String dirname, String style) { List<String> objectIds = MCRXMLMetadataManager.instance().listIDsOfType(type); return buildExportCommands(new File(dirname), style, objectIds); } /** * Export all MCRObject's with data base <em>base</em> to files named <em>MCRObjectID</em>.xml in a directory * named <em>dirname</em>. The method uses the converter stylesheet <em>style</em>.xsl. * * @param base * the MCRObjectID base * @param dirname * the filename to store the object * @param style * the name of the stylesheet, prefix of <em>style</em>-object.xsl * @return a list of export commands, one for each object */ @MCRCommand( syntax = "export all objects of base {0} to directory {1} with stylesheet {2}", help = "Stores all objects of base {0} to directory {1} " + "with the stylesheet {2}-object.xsl. For {2}, the default is xsl/save.", order = 130) public static List<String> exportAllObjectsOfBaseWithStylesheet(String base, String dirname, String style) { List<String> objectIds = MCRXMLMetadataManager.instance().listIDsForBase(base); return buildExportCommands(new File(dirname), style, objectIds); } private static List<String> buildExportCommands(File dir, String style, List<String> objectIds) { if (dir.isFile()) { LOGGER.error("{} is not a dirctory.", dir); return Collections.emptyList(); } List<String> cmds = new ArrayList<>(objectIds.size()); for (String id : objectIds) { String command = new MessageFormat(EXPORT_OBJECT_TO_DIRECTORY_WITH_STYLESHEET_COMMAND, Locale.ROOT) .format(new Object[] { id, dir.getAbsolutePath(), style }); cmds.add(command); } return cmds; } /** * This method searches for the stylesheet <em>style</em>.xsl and builds the transformer. Default is * <em>save-object.xsl</em> if no stylesheet is given or the stylesheet couldn't be resolved. * * @param style * the name of the style to be used when resolving the stylesheet * @return the transformer */ private static Transformer getTransformer(String style) { return MCRCommandUtils.getTransformer(style, DEFAULT_STYLE, TRANSFORMER_CACHE); } /** * The method read a MCRObject and use a transformation to write the data to a file. There aren't any steps to * handel errors and save the damaged data. * <ul> * <li>Read data for object ID in the MCRObject, add ACLs and store it as checked and transformed XML. Return true. * </li> * <li>If it can't find a transformer instance (no script file found) it store the checked data with ACLs native in * the file. Warning and return true.</li> * <li>If it get an exception while build the MCRObject, it try to read the XML blob and store it without check and * ACLs to the file. Warning and return true.</li> * <li>If it get an exception while store the native data without check, ACLs and transformation it return a * warning and false.</li> * </ul> * * @param dir * the file instance to store * @param extension * the file extension to use * @param trans * the transformation * @param nid * the MCRObjectID * @return true if the store was okay (see description), else return false */ private static boolean exportObject(File dir, String extension, FailableBiConsumer<MCRContent, OutputStream, Exception> trans, String nid) throws IOException, MCRException { MCRContent content; try { // if object doesn't exist - no exception is caught! content = MCRXMLMetadataManager.instance().retrieveContent(MCRObjectID.getInstance(nid)); } catch (MCRException ex) { return false; } File xmlOutput = new File(dir, nid + "." + extension); if (trans != null) { FileOutputStream out = new FileOutputStream(xmlOutput); try { trans.accept(content, out); } catch (UncheckedIOException e) { throw e.getCause(); } catch (IOException | RuntimeException e) { throw e; } catch (Exception e) { throw new MCRException(e); } } else { content.sendTo(xmlOutput); } LOGGER.info("Object {} saved to {}.", nid, xmlOutput.getCanonicalPath()); return true; } /** * Get the next free MCRObjectID for the given MCRObjectID base. * * @param base * the MCRObjectID base string */ @MCRCommand( syntax = "get next ID for base {0}", help = "Returns the next free MCRObjectID for the ID base {0}.", order = 150) public static void getNextID(String base) { try { LOGGER.info(MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(base)); } catch (MCRException ex) { LOGGER.error(ex.getMessage()); } } /** * Get the last used MCRObjectID for the given MCRObjectID base. * * @param base * the MCRObjectID base string */ @MCRCommand( syntax = "get last ID for base {0}", help = "Returns the last used MCRObjectID for the ID base {0}.", order = 140) public static void getLastID(String base) { LOGGER.info(MCRMetadataManager.getMCRObjectIDGenerator().getLastID(base)); } /** * List all selected MCRObjects. */ @MCRCommand( syntax = "list selected", help = "Prints the id of selected objects", order = 190) public static void listSelected() { LOGGER.info("List selected MCRObjects"); if (getSelectedObjectIDs().isEmpty()) { LOGGER.info("No Resultset to work with, use command \"select objects with solr query {0} in core {1}\"" + " or \"select objects with xpath {0}\" to build one"); return; } StringBuilder out = new StringBuilder(); for (String id : getSelectedObjectIDs()) { out.append(id).append(' '); } LOGGER.info(out.toString()); } /** * List revisions of an MyCoRe Object. * * @param id * id of MyCoRe Object */ @MCRCommand( syntax = "list revisions of {0}", help = "List revisions of MCRObject.", order = 260) public static void listRevisions(String id) { MCRObjectID mcrId = MCRObjectID.getInstance(id); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT); try { StringBuilder log = new StringBuilder("Revisions:\n"); List<? extends MCRAbstractMetadataVersion<?>> revisions = MCRXMLMetadataManager.instance() .listRevisions(mcrId); for (MCRAbstractMetadataVersion<?> revision : revisions) { log.append(revision.getRevision()).append(' '); log.append(revision.getType()).append(' '); log.append(sdf.format(revision.getDate())).append(' '); log.append(revision.getUser()); log.append("\n"); } LOGGER.info(log.toString()); } catch (Exception exc) { LOGGER.error("While print revisions.", exc); } } /** * This method restores a MyCoRe Object to the selected revision. Please note that children and derivates are not * deleted or reverted! * * @param id * id of MyCoRe Object * @param revision * revision to restore */ @MCRCommand( syntax = "restore {0} to revision {1}", help = "Restores the selected MCRObject to the selected revision.", order = 270) public static void restoreToRevision(String id, String revision) { LOGGER.info("Try to restore object {} with revision {}", id, revision); MCRObjectID mcrId = MCRObjectID.getInstance(id); try { MCRObjectUtils.restore(mcrId, revision); LOGGER.info("Object {} successfully restored!", id); } catch (Exception exc) { LOGGER.error("While retrieving object {} with revision {}", id, revision, exc); } } /** * Does a xsl transform with the given mycore object. * <p> * To use this command create a new xsl file and copy following xslt code into it. * </p> * * <pre> * {@code * <?xml version="1.0" encoding="utf-8"?> * <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> * * <xsl:template match='@*|node()'> * <!-- default template: just copy --> * <xsl:copy> * <xsl:apply-templates select='@*|node()' /> * </xsl:copy> * </xsl:template> * * </xsl:stylesheet> * } * </pre> * <p> * Insert a new template match, for example: * </p> * * <pre> * {@code * <xsl:template match="metadata/mainTitle/@heritable"> * <xsl:attribute name="heritable"><xsl:value-of select="'true'"/></xsl:attribute> * </xsl:template> * } * </pre> * * @param objectId * object to transform * @param xslFilePath * path to xsl file * @throws MCRPersistenceException see {@link MCRMetadataManager#update(MCRObject)} * @throws MCRAccessException see {@link MCRMetadataManager#update(MCRObject)} */ @MCRCommand( syntax = "xslt {0} with file {1}", help = "transforms a mycore object {0} with the given file or URI {1}", order = 280) public static void xslt(String objectId, String xslFilePath) throws IOException, JDOMException, SAXException, TransformerException, MCRPersistenceException, MCRAccessException, ParserConfigurationException { xslt(objectId, xslFilePath, false); } /** * @see #xslt(String, String) * * Forces the xml to overwrite even if the root name of the original and the result differs. * * @param objectId * object to transform * @param xslFilePath * path to xsl file * @throws MCRPersistenceException see {@link MCRMetadataManager#update(MCRObject)} * @throws MCRAccessException see {@link MCRMetadataManager#update(MCRObject)} */ @MCRCommand( syntax = "force xslt {0} with file {1}", help = "transforms a mycore object {0} with the given file or URI {1}. Overwrites anyway if original " + "root name and result root name are different.", order = 285) public static void forceXSLT(String objectId, String xslFilePath) throws IOException, JDOMException, SAXException, TransformerException, MCRPersistenceException, MCRAccessException, ParserConfigurationException { xslt(objectId, xslFilePath, true); } private static void xslt(String objectId, String xslFilePath, boolean force) throws IOException, JDOMException, SAXException, TransformerException, MCRPersistenceException, MCRAccessException, ParserConfigurationException { File xslFile = new File(xslFilePath); Source xslSource; if (xslFile.exists()) { xslSource = new StreamSource(xslFile); } else { xslSource = MCRURIResolver.instance().resolve(xslFilePath, null); if (xslSource == null) { xslSource = new StreamSource(xslFilePath); } } MCRSourceContent style = new MCRSourceContent(xslSource); MCRObjectID mcrId = MCRObjectID.getInstance(objectId); Document document = MCRXMLMetadataManager.instance().retrieveXML(mcrId); // do XSL transform TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setErrorListener(MCRErrorListener.getInstance()); transformerFactory.setURIResolver(MCRURIResolver.instance()); XMLReader xmlReader = MCRXMLParserFactory.getNonValidatingParser().getXMLReader(); xmlReader.setEntityResolver(MCREntityResolver.instance()); SAXSource styleSource = new SAXSource(xmlReader, style.getInputSource()); Transformer transformer = transformerFactory.newTransformer(styleSource); for (Entry<String, String> property : MCRConfiguration2.getPropertiesMap().entrySet()) { transformer.setParameter(property.getKey(), property.getValue()); } transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "no"); JDOMResult result = new JDOMResult(); transformer.transform(new JDOMSource(document), result); Document resultDocument = Objects.requireNonNull(result.getDocument(), "Could not get transformation result"); String originalName = document.getRootElement().getName(); String resultName = resultDocument.getRootElement().getName(); if (!force && !originalName.equals(resultName)) { LOGGER.error("{}: root name '{}' does not match result name '{}'.", objectId, originalName, resultName); return; } // update on diff if (MCRXMLHelper.deepEqual(document, resultDocument)) { return; } switch (resultName) { case MCRObject.ROOT_NAME -> MCRMetadataManager.update(new MCRObject(resultDocument)); case MCRDerivate.ROOT_NAME -> MCRMetadataManager.update(new MCRDerivate(resultDocument)); default -> LOGGER.error("Unable to transform '{}' because unknown result root name '{}'.", objectId, resultName); } } @MCRCommand(syntax = "transform object {0} with transformer {1}", help = "Transforms the object with the id {0} using the transformer with the id {1} and" + " updates the object with the result") public static void transformObject(String objectIDStr, String transformer) throws IOException, JDOMException, MCRAccessException { MCRObjectID objectID = MCRObjectID.getInstance(objectIDStr); if (!MCRMetadataManager.exists(objectID)) { LOGGER.error("The object {} does not exist!", objectID); return; } MCRObject mcrObject = MCRMetadataManager.retrieveMCRObject(objectID); MCRBaseContent baseContent = new MCRBaseContent(mcrObject); MCRContent result = new MCRLayoutTransformerFactory().getTransformer(transformer).transform(baseContent); Document resultXML = result.asXML(); MCRObject resulting = new MCRObject(resultXML); if (!MCRXMLHelper.deepEqual(mcrObject.createXML(), resultXML)) { LOGGER.info("The Object changed with the transformation. Execute Update."); MCRMetadataManager.update(resulting); } else { LOGGER.info("The Object did not change with the transformation. Skip Update."); } } /** * Moves object to new parent. * * @param sourceId * object that should be attached to new parent * @param newParentId * the ID of the new parent * @throws MCRAccessException see {@link MCRMetadataManager#update(MCRObject)} */ @MCRCommand( syntax = "set parent of {0} to {1}", help = "replaces a parent of an object (first parameter) to the given new one (second parameter)", order = 300) public static void replaceParent(String sourceId, String newParentId) throws MCRPersistenceException, MCRAccessException { // child MCRObject sourceMCRObject = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance(sourceId)); // old parent MCRObjectID oldParentId = sourceMCRObject.getStructure().getParentID(); MCRObjectID newParentObjectID = MCRObjectID.getInstance(newParentId); if (newParentObjectID.equals(oldParentId)) { LOGGER.info("Object {} is already child of {}", sourceId, newParentId); return; } MCRObject oldParentMCRObject = null; if (oldParentId != null) { try { oldParentMCRObject = MCRMetadataManager.retrieveMCRObject(oldParentId); } catch (Exception exc) { LOGGER.error("Unable to get old parent object {}, its probably deleted.", oldParentId, exc); } } // change href to new parent LOGGER.info("Setting link in \"{}\" to parent \"{}\"", sourceId, newParentObjectID); MCRMetaLinkID parentLinkId = new MCRMetaLinkID("parent", 0); parentLinkId.setReference(newParentObjectID, null, null); sourceMCRObject.getStructure().setParent(parentLinkId); if (oldParentMCRObject != null) { // remove Child in old parent LOGGER.info("Remove child \"{}\" in old parent \"{}\"", sourceId, oldParentId); oldParentMCRObject.getStructure().removeChild(sourceMCRObject.getId()); LOGGER.info("Update old parent \"{}\n", oldParentId); MCRMetadataManager.update(oldParentMCRObject); } LOGGER.info("Update \"{}\" in datastore (saving new link)", sourceId); MCRMetadataManager.update(sourceMCRObject); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Structure: {}", sourceMCRObject.getStructure().isValid()); LOGGER.debug("Object: {}", sourceMCRObject.isValid()); } } /** * Check the derivate links in objects of MCR base ID for existing. It looks to the XML store on the disk to get all * object IDs. * * @param baseId * the base part of a MCRObjectID e.g. DocPortal_document */ @MCRCommand( syntax = "check derivate entries in objects for base {0}", help = "check in all objects with MCR base ID {0} for existing linked derivates", order = 400) public static void checkDerivatesInObjects(String baseId) { if (baseId == null || baseId.length() == 0) { LOGGER.error("Base ID missed for check derivate entries in objects for base {0}"); return; } MCRXMLMetadataManager mgr = MCRXMLMetadataManager.instance(); List<String> idList = mgr.listIDsForBase(baseId); int counter = 0; int maxresults = idList.size(); for (String objid : idList) { counter++; LOGGER.info("Processing dataset {} from {} with ID: {}", counter, maxresults, objid); // get from data MCRObjectID mcrobjid = MCRObjectID.getInstance(objid); MCRObject obj = MCRMetadataManager.retrieveMCRObject(mcrobjid); List<MCRMetaEnrichedLinkID> derivateEntries = obj.getStructure().getDerivates(); for (MCRMetaLinkID derivateEntry : derivateEntries) { String derid = derivateEntry.getXLinkHref(); if (!mgr.exists(MCRObjectID.getInstance(derid))) { LOGGER.error(" !!! Missing derivate {} in database for base ID {}", derid, baseId); } } } LOGGER.info("Check done for {} entries", Integer.toString(counter)); } /** * Checks objects of the specified base ID for validity against their specified schemas. * * @param baseID * the base part of a MCRObjectID e.g. DocPortal_document */ @MCRCommand( syntax = "validate object schema for base {0}", help = "Validates all objects of base {0} against their specified schema.", order = 401) public static List<String> validateObjectsOfBase(String baseID) { return MCRCommandUtils.getIdsForBaseId(baseID) .map(id -> "validate object schema for ID " + id) .collect(Collectors.toList()); } /** * Checks objects of the specified type for validity against their specified schemas. * * @param type * the type of a MCRObjectID e.g. document */ @MCRCommand( syntax = "validate object schema for type {0}", help = "Validates all object of type {0} against their specified schema.", order = 402) public static List<String> validateObjectsOfType(String type) { return MCRCommandUtils.getIdsForType(type) .map(id -> "validate object schema for ID " + id) .collect(Collectors.toList()); } /** * Check if an object validates against its specified schema. * * @param objectID * the ID of an object to check */ @MCRCommand( syntax = "validate object schema for ID {0}", help = "Checks if object {0} validates against its specified schema.", order = 404) public static void validateObject(String objectID) { validateObjectWithTransformer(objectID, null); } /** * Check if an object validates against its specified schema. * * @param objectID * the ID of an object to check * @param transformerType * the name of a stylesheet that the object should be transformed with before validation */ @MCRCommand( syntax = "validate object schema for ID {0} after transformer {1}", help = "Checks if object {0} validates against its specified schema, " + "after being transformed through {1}.xsl.", order = 403) public static void validateObjectWithTransformer(String objectID, String transformerType) { if (objectID == null || objectID.length() == 0) { throw new MCRException("ID of an object required to check its schema validity."); } LOGGER.info("validate object schema for ID " + objectID); Transformer trafo = null; if (transformerType != null) { // getTransformer with non-existent input successfully returns a working transformer // that "successfully transforms", an error would be preferable trafo = getTransformer(transformerType); LOGGER.debug("Transformer {} has been loaded.", transformerType); } MCRObjectID objID = MCRObjectID.getInstance(objectID); try { doValidateObjectAgainstSchema(objID, trafo); LOGGER.info("Object {} successfully validated.", objectID); } catch (MCRException e) { LOGGER.error("Object {} failed its validation!", objectID); throw e; } } private static void doValidateObjectAgainstSchema(MCRObjectID objID, Transformer trans) { // MCRMetadataManager -> retrieveMCRObject() -> MCRObject.createXML already validates the contents // we need to offer transformation first though, so manual talking to MCRXMLMetadataManager // for the object contents, then manually using a validating XML parser later MCRXMLMetadataManager mgr = MCRXMLMetadataManager.instance(); Document doc; try { doc = mgr.retrieveXML(objID); } catch (IOException | JDOMException e) { throw new MCRException( "Object " + objID.toString() + " could not be retrieved, unable to validate against schema!", e); } if (doc == null) { throw new MCRException("Could not get object " + objID.toString() + " from XML store"); } MCRObject object = new MCRObject(doc); try { object.validate(); } catch (MCRException e) { throw new MCRException( "Object " + objID.toString() + " does not pass basic self-validation, unable to validate against schema!", e); } String schema = object.getSchema(); if (schema == null) { throw new MCRException( "Object " + objID.toString() + " has no assigned schema, unable to validate against it!"); } if (trans != null) { JDOMResult res = new JDOMResult(); try { trans.transform(new JDOMSource(doc), res); doc = Objects.requireNonNull(res.getDocument(), "Could not get transformation result"); } catch (TransformerException | MCRException | NullPointerException e) { throw new MCRException("Object " + objID.toString() + " could not be transformed, unable to validate against schema!", e); } LOGGER.info("Object {} successfully transformed.", objID.toString()); } try { MCRXMLParserFactory.getValidatingParser().parseXML(new MCRJDOMContent(doc)); } catch (MCRException | JDOMException | IOException e) { throw new MCRException("Object " + objID.toString() + " failed to parse against its schema!", e); } } @MCRCommand( syntax = "execute for selected {0}", help = "Calls the given command multiple times for all selected objects." + " The replacement is defined by an {x}.E.g. 'execute for selected set" + " parent of {x} to myapp_container_00000001'", order = 450) public static List<String> executeForSelected(String command) { if (!command.contains("{x}")) { LOGGER.info("No replacement defined. Use the {x} variable in order to execute your command with all " + "selected objects."); return Collections.emptyList(); } return getSelectedObjectIDs().stream() .map(objID -> command.replaceAll("\\{x}", objID)) .collect(Collectors.toList()); } /** * The method start the repair of the metadata search for a given MCRObjectID type. * * @param type * the MCRObjectID type */ @MCRCommand( syntax = "repair metadata search of type {0}", help = "Scans the metadata store for MCRObjects of type {0} and restores them in the search store.", order = 170) public static List<String> repairMetadataSearch(String type) { LOGGER.info("Start the repair for type {}", type); return MCRCommandUtils.getIdsForType(type) .map(id -> "repair metadata search of ID " + id) .collect(Collectors.toList()); } /** * The method start the repair of the metadata search for a given MCRObjectID base. * * @param baseID * the base part of a MCRObjectID e.g. DocPortal_document */ @MCRCommand( syntax = "repair metadata search of base {0}", help = "Scans the metadata store for MCRObjects of base {0} and restores them in the search store.", order = 171) public static List<String> repairMetadataSearchForBase(String baseID) { LOGGER.info("Start the repair for base {}", baseID); return MCRCommandUtils.getIdsForBaseId(baseID) .map(id -> "repair metadata search of ID " + id) .collect(Collectors.toList()); } @MCRCommand( syntax = "repair shared metadata for the ID {0}", help = "Retrieves the MCRObject with the MCRObjectID {0} and repairs the shared metadata.", order = 172) public static void repairSharedMetadata(String id) throws MCRAccessException { if (!MCRObjectID.isValid(id)) { LOGGER.error("The String {} is not a MCRObjectID.", id); return; } MCRObjectID mid = MCRObjectID.getInstance(id); MCRObject obj = MCRMetadataManager.retrieveMCRObject(mid); MCRMetadataManager.repairSharedMetadata(obj); } @MCRCommand( syntax = "create object id cache", help = "Creates a cache for all object ids in the configuration directory.", order = 175) public static void createObjectIDCache() { MCRXMLMetadataManager metadataManager = MCRXMLMetadataManager.instance(); metadataManager.getObjectBaseIds().forEach(id -> { LOGGER.info("Creating cache for base {}", id); int highestStoredID = metadataManager.getHighestStoredID(id); MCRFileBaseCacheObjectIDGenerator gen = new MCRFileBaseCacheObjectIDGenerator(); gen.setNextFreeId(id, highestStoredID+1); }); } /** * The method start the repair of the metadata search for a given MCRObjectID as String. * * @param id * the MCRObjectID as String */ @MCRCommand( syntax = "repair metadata search of ID {0}", help = "Retrieves the MCRObject with the MCRObjectID {0} and restores it in the search store.", order = 180) public static void repairMetadataSearchForID(String id) { LOGGER.info("Start the repair for the ID {}", id); if (!MCRObjectID.isValid(id)) { LOGGER.error("The String {} is not a MCRObjectID.", id); return; } MCRObjectID mid = MCRObjectID.getInstance(id); MCRBase obj = MCRMetadataManager.retrieve(mid); MCRMetadataManager.fireRepairEvent(obj); LOGGER.info("Repaired {}", mid); } @MCRCommand( syntax = "repair mcrlinkhref table", help = "Runs through the whole table and checks for already deleted mcr objects and deletes them.", order = 185) public static void repairMCRLinkHrefTable() { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); TypedQuery<String> fromQuery = em.createQuery("SELECT DISTINCT m.key.mcrfrom FROM MCRLINKHREF m", String.class); TypedQuery<String> toQuery = em.createQuery("SELECT DISTINCT m.key.mcrto FROM MCRLINKHREF m", String.class); String query = "DELETE FROM MCRLINKHREF m WHERE m.key.mcrfrom IN (:invalidIds) or m.key.mcrto IN (:invalidIds)"; // open streams try (Stream<String> fromStream = fromQuery.getResultStream()) { try (Stream<String> toStream = toQuery.getResultStream()) { List<String> invalidIds = Stream.concat(fromStream, toStream) .distinct() .filter(MCRObjectID::isValid) .map(MCRObjectID::getInstance) .filter(MCRStreamUtils.not(MCRMetadataManager::exists)) .map(MCRObjectID::toString) .collect(Collectors.toList()); // delete em.createQuery(query).setParameter("invalidIds", invalidIds).executeUpdate(); } } } @MCRCommand( syntax = "rebuild mcrlinkhref table for object {0}", help = "Rebuilds (remove/create) all entries of the link href table for the given object id.", order = 188) public static void rebuildMCRLinkHrefTableForObject(String objectId) { MCRLinkTableManager.instance().update(MCRObjectID.getInstance(objectId)); } @MCRCommand(syntax = "clear object export transformer cache", help = "Clears the object export transformer cache", order = 200) public static void clearExportTransformerCache() { TRANSFORMER_CACHE.clear(); } }
60,983
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRLoggingCommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/MCRLoggingCommands.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.cli; import java.util.Objects; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.Configurator; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; /** * Use this class to change log levels of java packages and classes. * * @author shermann */ @MCRCommandGroup(name = "Logging Commands") public class MCRLoggingCommands extends MCRAbstractCommands { private static final Logger LOGGER = LogManager.getLogger(); /** * @param name * the name of the java class or java package to set the log * level for * @param logLevelToSet * the log level to set e.g. TRACE, DEBUG, INFO, WARN, ERROR and * FATAL, providing any other value will lead to DEBUG as new log * level */ @MCRCommand(syntax = "change log level of {0} to {1}", help = "{0} the package or class name for which to change the log level, {1} the log level to set.", order = 10) public static synchronized void changeLogLevel(String name, String logLevelToSet) { LOGGER.info("Setting log level for \"{}\" to \"{}\"", name, logLevelToSet); Level newLevel = Level.getLevel(logLevelToSet); if (newLevel == null) { LOGGER.error("Unknown log level \"{}\"", logLevelToSet); return; } Logger log = Objects.equals(name, "ROOT") ? LogManager.getRootLogger() : LogManager.getLogger(name); if (log == null) { LOGGER.error("Could not get logger for \"{}\"", name); return; } LOGGER.info("Change log level from {} to {}", log.getLevel(), newLevel); Configurator.setLevel(log.getName(), newLevel); } }
2,633
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCommand.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/annotation/MCRCommand.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.cli.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.text.MessageFormat; import org.mycore.frontend.cli.MCRCommandLineInterface; /** * Annotates a public static method as a command that could be executed via {@link MCRCommandLineInterface}. * @author Thomas Scheffler (yagee) */ @Retention(RetentionPolicy.RUNTIME) @Documented @Target(ElementType.METHOD) public @interface MCRCommand { /** * The syntax of the command in {@link MessageFormat} syntax */ String syntax(); /** * Help text that should be returned by <code>help</code> command. */ String help() default ""; /** * I18N key for the help text that should be returned by <code>help</code> command. */ String helpKey() default ""; /** * If {@link #syntax()} conflicts, use <code>order</code> to specify in which order the invocation should be tried. */ int order() default 1; }
1,847
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCommandGroup.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/cli/annotation/MCRCommandGroup.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.cli.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.mycore.frontend.cli.MCRCommandLineInterface; /** * Annotates a class that holds public static methods as commands they could be executed via * {@link MCRCommandLineInterface}. * * @author Thomas Scheffler (yagee) */ @Retention(RetentionPolicy.RUNTIME) @Documented @Target(ElementType.TYPE) public @interface MCRCommandGroup { /** * A name for this command group */ String name(); }
1,394
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRWebAppBaseFilter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/filter/MCRWebAppBaseFilter.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.filter; import java.io.IOException; import org.mycore.frontend.MCRFrontendUtil; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; public class MCRWebAppBaseFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // check if BASE_URL_ATTRIBUTE is present // for used proxy header use the first entry of list if (req.getAttribute(MCRFrontendUtil.BASE_URL_ATTRIBUTE) == null) { String webappBase = MCRFrontendUtil.getBaseURL(req); req.setAttribute(MCRFrontendUtil.BASE_URL_ATTRIBUTE, webappBase); } chain.doFilter(req, res); } public void destroy() { } public void init(FilterConfig arg0) { } }
1,715
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUserAgentFilter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/filter/MCRUserAgentFilter.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.filter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.regex.Pattern; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.config.MCRConfiguration2; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; /** * Automatically closes HttpSession of certain user agents. * * If the <code>User-Agent</code> header matches a regular expression * defined by the property <code>MCR.Filter.UserAgent.Pattern</code> the * HTTP session is closed after the request. * * If the <code>User-Agent</code> header is invalid a 403 FORBIDDEN response * is sent to client if not <code>MCR.Filter.UserAgent.AcceptInvalid = true</code>. * * A <code>User-Agent</code> header is considered invalid if it is not sent at all or * its value has not at least <code>MCR.Filter.UserAgent.MinLength</code> characters. * * @author Thomas Scheffler (yagee) */ public class MCRUserAgentFilter implements Filter { private static final int MIN_USER_AGENT_LENGTH = MCRConfiguration2 .getOrThrow("MCR.Filter.UserAgent.MinLength", Integer::parseInt); private static final boolean ACCEPT_INVALID_USER_AGENTS = MCRConfiguration2 .getOrThrow("MCR.Filter.UserAgent.AcceptInvalid", Boolean::parseBoolean); private static Pattern agentPattern; private static final Logger LOGGER = LogManager.getLogger(); @Override public void init(final FilterConfig arg0) { final String agentRegEx = MCRConfiguration2.getStringOrThrow("MCR.Filter.UserAgent.BotPattern"); agentPattern = Pattern.compile(agentRegEx); } @Override public void destroy() { } @Override public void doFilter(final ServletRequest sreq, final ServletResponse sres, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) sreq; final HttpServletResponse response = (HttpServletResponse) sres; final String userAgent = request.getHeader("User-Agent"); boolean invalidUserAgent = isInvalidUserAgent(userAgent); if (invalidUserAgent) { handleInvalidUserAgent(response, userAgent); if (response.isCommitted()) { return; } } final boolean newSession = request.getSession(false) == null; chain.doFilter(sreq, sres); final HttpSession session = request.getSession(false); if (session != null && newSession) { try { if (invalidUserAgent) { LOGGER.info("Closing session, invalid User-Agent: " + userAgent); session.invalidate(); } else if (agentPattern.matcher(userAgent).find()) { LOGGER.info("Closing session: {} matches {}", userAgent, agentPattern); session.invalidate(); } else { LOGGER.debug("{} does not match {}", userAgent, agentPattern); } } catch (IllegalStateException e) { LOGGER.warn("Session was allready closed"); } } } private static boolean isInvalidUserAgent(String userAgent) { return userAgent == null || userAgent.length() < MIN_USER_AGENT_LENGTH; } private void handleInvalidUserAgent(HttpServletResponse response, String userAgent) throws IOException { if (ACCEPT_INVALID_USER_AGENTS) { return; } //don't use sendError here as we do not want to trigger error handling by container response.setStatus(HttpServletResponse.SC_FORBIDDEN); try (var os = response.getOutputStream()) { byte[] msg = getInvalidMsg(userAgent).getBytes(StandardCharsets.UTF_8); response.setContentLength(msg.length); os.write(msg); } response.flushBuffer(); } private static String getInvalidMsg(String userAgent) { return userAgent == null ? "User-Agent header required." : "Invalid User-Agent: " + userAgent; } }
5,158
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSecureTokenV2Filter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/filter/MCRSecureTokenV2Filter.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.filter; import java.io.IOException; import java.net.URISyntaxException; import java.util.regex.Pattern; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.datamodel.ifs.MCRFileNodeServlet; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.support.MCRSecureTokenV2; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Filter for {@link MCRFileNodeServlet} that uses {@link MCRSecureTokenV2} to check access to specific file types. * <p> * used properties: * </p> * <dl> * <dt>MCR.SecureTokenV2.Extensions=mp4,mpeg4</dt> * <dd>List of file extension. If empty, disables this filter</dd> * <dt>MCR.SecureTokenV2.HashParameter=securetoken</dt> * <dd>Name of request parameter that holds hash value</dd> * <dt>MCR.SecureTokenV2.SharedSecret=mySharedSecret</dt> * <dd>shared secret used to calculate secure token</dd> * </dl> * <code>contentPath</code> used for {@link MCRSecureTokenV2} is the {@link HttpServletRequest#getPathInfo() path info} * without leading '/'. * * @author Thomas Scheffler (yagee) */ public class MCRSecureTokenV2Filter implements Filter { private static final Logger LOGGER = LogManager.getLogger(); private boolean filterEnabled = true; private String hashParameter; private String sharedSecret; /* (non-Javadoc) * @see jakarta.servlet.Filter#init(jakarta.servlet.FilterConfig) */ @Override public void init(FilterConfig filterConfig) { filterEnabled = MCRSecureTokenV2FilterConfig.isFilterEnabled(); hashParameter = MCRSecureTokenV2FilterConfig.getHashParameterName(); sharedSecret = MCRSecureTokenV2FilterConfig.getSharedSecret(); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterEnabled) { HttpServletRequest httpServletRequest = (HttpServletRequest) request; String pathInfo = httpServletRequest.getPathInfo(); if (pathInfo != null && MCRSecureTokenV2FilterConfig.requireHash(pathInfo)) { if (!validateSecureToken(httpServletRequest)) { ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN); LOGGER.warn("Access to {} forbidden by secure token check.", pathInfo); return; } } } chain.doFilter(request, response); } private boolean validateSecureToken(HttpServletRequest httpServletRequest) throws ServletException { String queryString = httpServletRequest.getQueryString(); if (queryString == null) { LOGGER.warn("Request contains no parameters {}.", httpServletRequest.getRequestURL()); } String hashValue = httpServletRequest.getParameter(hashParameter); if (hashValue == null) { LOGGER.warn("Could not find parameter '{}' in request {}.", hashParameter, httpServletRequest.getRequestURL().append('?').append(queryString)); return false; } String[] origParams = Pattern.compile("&").split(queryString); String[] stripParams = new String[origParams.length - 1]; for (int i = origParams.length - 1; i > -1; i--) { if (origParams[i].startsWith(hashParameter + "=")) { removeElement(origParams, stripParams, i); } } MCRSecureTokenV2 token = new MCRSecureTokenV2(httpServletRequest.getPathInfo().substring(1), MCRFrontendUtil.getRemoteAddr(httpServletRequest), sharedSecret, stripParams); try { LOGGER.info(token.toURI(MCRFrontendUtil.getBaseURL() + "servlets/MCRFileNodeServlet/", hashParameter)); } catch (URISyntaxException e) { throw new ServletException(e); } return hashValue.equals(token.getHash()); } private static void removeElement(String[] src, String[] dest, int i) { if (i == 0) { return; } System.arraycopy(src, 0, dest, 0, i - 1); if (i < src.length - 1) { System.arraycopy(src, i + 1, dest, i, src.length - 1 - i); } } @Override public void destroy() { } }
5,343
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRequestDebugFilter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/filter/MCRRequestDebugFilter.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.filter; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.URI; import java.net.URL; import java.nio.file.Path; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Collection; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.stream.Stream; import org.apache.commons.beanutils.BeanUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRStreamUtils; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; /** * @author Thomas Scheffler * */ public class MCRRequestDebugFilter implements Filter { private static final Logger LOGGER = LogManager.getLogger(); /* (non-Javadoc) * @see jakarta.servlet.Filter#init(jakarta.servlet.FilterConfig) */ @Override public void init(FilterConfig filterConfig) { } /* (non-Javadoc) * @see jakarta.servlet.Filter#doFilter(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, jakarta.servlet.FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { LOGGER.debug(() -> getLogMsg(request)); chain.doFilter(request, response); LOGGER.debug(() -> getLogMsg(request, response)); } private String getLogMsg(ServletRequest request) { HttpServletRequest req = (HttpServletRequest) request; StringBuilder sb = new StringBuilder("REQUEST (" + req.getMethod() + ") URI: " + req.getRequestURI() + " \n"); logCookies(req, sb); logRequestParameters(request, sb); logSessionAttributes(req, sb); logHeader(MCRStreamUtils.asStream(req.getHeaderNames()), s -> MCRStreamUtils.asStream(req.getHeaders(s)), sb); return sb.append("\n\n").toString(); } private String getLogMsg(ServletRequest request, ServletResponse response) { HttpServletRequest req = (HttpServletRequest) request; StringBuilder sb = new StringBuilder("RESPONSE (" + req.getMethod() + ") URI: " + req.getRequestURI() + " \n"); HttpServletResponse res = (HttpServletResponse) response; sb.append("Status: ").append(res.getStatus()).append('\n'); logHeader(res.getHeaderNames().stream(), s -> res.getHeaders(s).stream(), sb); return sb.append("\n\n").toString(); } private void logHeader(Stream<String> headerNames, Function<String, Stream<String>> headerValues, StringBuilder sb) { sb.append("Header: \n"); headerNames .sorted(String.CASE_INSENSITIVE_ORDER) .forEachOrdered(header -> headerValues .apply(header) .forEachOrdered(value -> sb .append(header) .append(": ") .append(value) .append("\n"))); sb.append("HEADERS END \n\n"); } private void logCookies(HttpServletRequest request, StringBuilder sb) { sb.append("Cookies: \n"); if (null != request.getCookies()) { for (Cookie cookie : request.getCookies()) { String description = ""; try { description = BeanUtils.describe(cookie).toString(); } catch (Exception e) { LOGGER.error("BeanUtils Exception describing cookie", e); } sb.append(' ').append(description).append('\n'); } } sb.append("COOKIES END \n\n"); } private void logSessionAttributes(HttpServletRequest request, StringBuilder sb) { sb.append("Session ") .append(request.isRequestedSessionIdFromCookie() ? "is" : "is not") .append(" requested by cookie.\n"); sb.append("Session ") .append(request.isRequestedSessionIdFromURL() ? "is" : "is not") .append(" requested by URL.\n"); sb.append("Session ").append(request.isRequestedSessionIdValid() ? "is" : "is not").append(" valid.\n"); HttpSession session = request.getSession(false); if (session != null) { sb.append("SESSION ") .append(request.getSession().getId()) .append(" created at: ") .append(LocalDateTime.ofInstant(Instant.ofEpochMilli(request.getSession().getCreationTime()), ZoneId.systemDefault())) .append("\n"); sb.append("SESSION ATTRIBUTES: \n"); MCRStreamUtils .asStream(session.getAttributeNames()) .sorted(String.CASE_INSENSITIVE_ORDER) .forEachOrdered(attrName -> sb.append(' ') .append(attrName) .append(": ") .append(getValue(attrName, Optional.ofNullable(session.getAttribute(attrName)))) .append("\n")); sb.append("SESSION ATTRIBUTES END \n\n"); } } private String getValue(String key, Optional<Object> value) { return value.map(o -> { if (!hasSafeToString(o)) { try { Map<String, String> beanDescription = BeanUtils.describe(value); if (!beanDescription.isEmpty()) { return beanDescription.toString(); } } catch (Exception e) { LOGGER.error("BeanUtils Exception describing attribute {}", key, e); } } return o.toString(); }).orElse("<null>"); } private static boolean hasSafeToString(Object o) { return o != null && Stream .of(CharSequence.class, Number.class, Boolean.class, Map.class, Collection.class, URI.class, URL.class, InetAddress.class, Throwable.class, Path.class, File.class, Class.class) .parallel() .filter(c -> c.isAssignableFrom(o.getClass())) .findAny() .isPresent(); } private void logRequestParameters(ServletRequest request, StringBuilder sb) { sb.append("REQUEST PARAMETERS:\n"); request.getParameterMap() .entrySet() .stream() .sorted((o1, o2) -> String.CASE_INSENSITIVE_ORDER.compare(o1.getKey(), o2.getKey())) .forEachOrdered(entry -> { sb.append(' ').append(entry.getKey()).append(": "); for (String s : entry.getValue()) { sb.append(s); sb.append(", "); } sb.append("\n"); }); sb.append("REQUEST PARAMETERS END \n\n"); } /* (non-Javadoc) * @see jakarta.servlet.Filter#destroy() */ @Override public void destroy() { } }
8,048
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCORSFilter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/filter/MCRCORSFilter.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.filter; import java.io.IOException; import java.util.Locale; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * This filter can be used to add a specific Access-Control-Allow-Origin header to a response. * Access-Control-Allow-Origin is processed by the browser if a ajax request was made. * If the origin from where the request was made is not contained in the Access-Control-Allow-Origin field, * then the Request will be rejected. * <p> * Parameter: * corsFilterSuffix - MCR.CORSFilter.%corsFilterSuffix% will be resolved from the mycore.properties and used as * Access-Control-Allow-Origin header field * </p> * @author Sebastian Hofmann */ public class MCRCORSFilter implements Filter { private static final String CORS_FILTER_NAME = "corsFilterSuffix"; private static final Logger LOGGER; private static final String CONFIGURATION_PREFIX = "MCR.CORSFilter"; private String allowOriginValue; static { LOGGER = LogManager.getLogger(MCRCORSFilter.class); } @Override public void init(FilterConfig filterConfig) { String filterName = filterConfig.getInitParameter(CORS_FILTER_NAME); if (filterName != null) { LOGGER.info("initializing {}", MCRCORSFilter.class.getSimpleName()); LOGGER.info(String.format(Locale.ROOT, "%s is %s", CORS_FILTER_NAME, filterName)); String propertyName = String.format(Locale.ROOT, "%s.%s", CONFIGURATION_PREFIX, filterName); this.allowOriginValue = MCRConfiguration2.getStringOrThrow(propertyName); } else { throw new MCRConfigurationException(String.format(Locale.ROOT, "No %s is set!", CORS_FILTER_NAME)); } } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // check if the request is a http request if (servletRequest instanceof HttpServletRequest && servletResponse instanceof HttpServletResponse resp) { resp.setHeader("Access-Control-Allow-Origin", this.allowOriginValue); } filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { LOGGER.info("destroying {}", MCRCORSFilter.class.getSimpleName()); } }
3,555
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSecureTokenV2FilterConfig.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/filter/MCRSecureTokenV2FilterConfig.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.filter; import java.net.URISyntaxException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRException; import org.mycore.common.MCRSessionMgr; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.ifs.MCRFileNodeServlet; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.support.MCRSecureTokenV2; public class MCRSecureTokenV2FilterConfig { private static boolean enabled; private static String hashParameter; private static String sharedSecret; private static Pattern securedExtensions; private static Logger LOGGER = LogManager.getLogger(); static { List<String> propertyValues = MCRConfiguration2.getString("MCR.SecureTokenV2.Extensions") .map(MCRConfiguration2::splitValue) .map(s -> s.collect(Collectors.toList())) .orElseGet(Collections::emptyList); if (propertyValues.isEmpty()) { enabled = false; LOGGER.info("Local MCRSecureToken2 support is disabled."); } else { enabled = true; securedExtensions = getExtensionPattern(propertyValues); LOGGER.info("SecureTokenV2 extension pattern: {}", securedExtensions); hashParameter = MCRConfiguration2.getStringOrThrow("MCR.SecureTokenV2.ParameterName"); sharedSecret = MCRConfiguration2.getStringOrThrow("MCR.SecureTokenV2.SharedSecret"); } } static Pattern getExtensionPattern(Collection<String> propertyValues) { return Pattern.compile(propertyValues .stream() .map(s -> s.toLowerCase(Locale.ROOT)) .distinct() .collect(Collectors.joining("|", "(.+(\\.(?i)(", "))$)"))); } public static boolean isFilterEnabled() { return enabled; } public static String getHashParameterName() { return hashParameter; } public static String getSharedSecret() { return sharedSecret; } public static boolean requireHash(String filename) { return enabled && securedExtensions.matcher(filename).matches(); } public static String getFileNodeServletSecured(MCRObjectID derivate, String path) { return getFileNodeServletSecured(derivate, path, MCRFrontendUtil.getBaseURL()); } public static String getFileNodeServletSecured(MCRObjectID derivate, String path, String baseURL) { String fileNodeBaseURL = baseURL + "servlets/MCRFileNodeServlet/"; if (requireHash(path)) { MCRSecureTokenV2 token = new MCRSecureTokenV2(derivate + "/" + path, MCRSessionMgr.getCurrentSession().getCurrentIP(), sharedSecret); try { return token.toURI(fileNodeBaseURL, hashParameter).toString(); } catch (URISyntaxException e) { throw new MCRException("Could not find out URL to " + MCRFileNodeServlet.class.getSimpleName(), e); } } else { return fileNodeBaseURL + derivate + "/" + path; } } }
4,076
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRequestAuthenticationFilter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/filter/MCRRequestAuthenticationFilter.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.filter; import java.io.IOException; import java.util.Optional; import org.apache.logging.log4j.LogManager; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; /** * @author Thomas Scheffler * */ public class MCRRequestAuthenticationFilter implements Filter { public static final String SESSION_KEY = "mcr.authenticateRequest"; @Override public void init(FilterConfig filterConfig) { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; Optional<HttpSession> httpSession = Optional.ofNullable(req.getSession(false)); if (httpSession.map(s -> s.getAttribute(SESSION_KEY)).isPresent() && req.getUserPrincipal() == null) { LogManager.getLogger().info("request authentication required for: {}", req.getRemoteUser()); req.authenticate((HttpServletResponse) response); } chain.doFilter(request, response); } @Override public void destroy() { } }
2,171
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRBasketManager.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/basket/MCRBasketManager.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.basket; import org.mycore.common.MCRSessionMgr; /** * Manages basket objects in the user's current MCRSession. * A session may store multiple baskets with different type IDs, * for example a basket for documents and another for an other type of entry. * * @author Frank Lützenkirchen */ public class MCRBasketManager { /** * Convenience method to get a basket of the given type. * When there already is a basket in the session, that basket is returned. * Otherwise a new basket is created and saved in the session. */ public static MCRBasket getOrCreateBasketInSession(String type) { MCRBasket basket = getBasketFromSession(type); if (basket == null) { basket = new MCRBasket(type); setBasketInSession(basket); } return basket; } /** * Returns the basket of the given type from the current session, if there is any. */ public static MCRBasket getBasketFromSession(String type) { String key = getBasketKey(type); return (MCRBasket) (MCRSessionMgr.getCurrentSession().get(key)); } /** * Stores the given basket in the current user's session */ public static void setBasketInSession(MCRBasket basket) { String key = getBasketKey(basket.getType()); MCRSessionMgr.getCurrentSession().put(key, basket); } /** * Returns the key to be used to store a basket in the current user's MCRSession */ private static String getBasketKey(String type) { return "basket." + type; } /** * Checks if a basket entry is present in the current basket * @param type basket type * @param id basket entry id * @return true if a basket of this type exist and contains basket entry with the given id */ public static boolean contains(String type, String id) { MCRBasket basket = getBasketFromSession(type); if (basket == null) { return false; } return (basket.get(id) != null); } }
2,800
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/frontend/basket/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/>. */ /** Implements a generic basket of entries and a web frontend to display/add/remove/reorder/comment entries. */ package org.mycore.frontend.basket;
875
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRBasketPersistence.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/basket/MCRBasketPersistence.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.basket; import java.io.IOException; import java.nio.file.Files; import org.jdom2.Document; import org.jdom2.output.XMLOutputter; import org.mycore.access.MCRAccessException; import org.mycore.common.MCRPersistenceException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRPathContent; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetaIFS; import org.mycore.datamodel.metadata.MCRMetaLangText; import org.mycore.datamodel.metadata.MCRMetaLinkID; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; /** * Manages basket objects in the persistent store. * A basket can be saved to and loaded from a derivate. The persistent form * of a basket is a file "basket.xml" in a derivate. * * @author Frank Lützenkirchen */ public class MCRBasketPersistence { /** * Retrieves a basket from an XML file in the given derivate. */ public static MCRBasket retrieveBasket(String derivateID) throws Exception { MCRPath file = getBasketFile(derivateID); Document xml = new MCRPathContent(file).asXML(); MCRBasket basket = new MCRBasketXMLParser().parseXML(xml); basket.setDerivateID(derivateID); return basket; } /** * Returns the MCRFile that stores the persistent data of a basket within the given derivate. */ private static MCRPath getBasketFile(String derivateID) { return MCRPath.getPath(derivateID, "/basket.xml"); } /** * Updates the basket's data in the persistent store by saving its XML representation * to a file in a derivate. The ID of the derivate is given in the basket's properties. */ public static void updateBasket(MCRBasket basket) throws Exception { String derivateID = basket.getDerivateID(); MCRObjectID derivateOID = MCRObjectID.getInstance(derivateID); MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateOID); MCRPath file = getBasketFile(derivateID); writeBasketToFile(basket, derivate, file); } /** * Creates a new derivate including a file basket.xml which stores the persistent * data of the given basket. * * @param basket the basket to store in a new file in a new derivate * @param ownerID the ID of the MCRObject owning the new derivate * @throws MCRAccessException see {@link MCRMetadataManager#create(MCRDerivate)} */ public static void createDerivateWithBasket(MCRBasket basket, MCRObjectID ownerID) throws IOException, MCRPersistenceException, MCRAccessException { String base = ownerID.getProjectId() + "_derivate"; MCRObjectID derivateOID = MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(base); String derivateID = derivateOID.toString(); MCRDerivate derivate = createNewDerivate(ownerID, derivateOID); basket.setDerivateID(derivateID); writeBasketToFile(basket, derivate, getBasketFile(derivateID)); } /** * Creates a new, empty derivate. * * @param ownerID the ID of the object owning the new derivate * @param derivateOID a free derivate ID to use for the newly created derivate * @return the empty derivate that was created. * @throws MCRAccessException see {@link MCRMetadataManager#create(MCRDerivate)} */ private static MCRDerivate createNewDerivate(MCRObjectID ownerID, MCRObjectID derivateOID) throws MCRPersistenceException, MCRAccessException { MCRDerivate derivate = new MCRDerivate(); derivate.setId(derivateOID); derivate.getDerivate().getTitles() .add(new MCRMetaLangText("title", null, null, 0, null, "Saved basket data for " + ownerID)); String schema = MCRConfiguration2.getString("MCR.Metadata.Config.derivate").orElse("datamodel-derivate.xml"); derivate.setSchema(schema.replaceAll(".xml", ".xsd")); MCRMetaIFS ifs = new MCRMetaIFS(); ifs.setSubTag("internal"); ifs.setSourcePath(null); derivate.getDerivate().setInternals(ifs); MCRMetaLinkID linkId = new MCRMetaLinkID(); linkId.setSubTag("linkmeta"); linkId.setReference(ownerID, null, null); derivate.getDerivate().setLinkMeta(linkId); MCRMetadataManager.create(derivate); return derivate; } /** * Writes the basket's content to a persistent file in the given derivate. * * @param basket the basket to save. * @param derivate the derivate holding the file * @param basketFile the file holding the basket's data. */ private static void writeBasketToFile(MCRBasket basket, MCRDerivate derivate, MCRPath basketFile) throws IOException, MCRAccessException { Document xml = new MCRBasketXMLBuilder(false).buildXML(basket); XMLOutputter xout = new XMLOutputter(); xout.output(xml, Files.newOutputStream(basketFile)); MCRMetadataManager.update(derivate); } }
5,873
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z