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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
MCRRestObjectAccessKeys.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/restapi/v2/MCRRestObjectAccessKeys.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.mcr.acl.accesskey.restapi.v2;
import static org.mycore.mcr.acl.accesskey.restapi.v2.MCRRestAccessKeyHelper.PARAM_SECRET;
import static org.mycore.mcr.acl.accesskey.restapi.v2.MCRRestAccessKeyHelper.QUERY_PARAM_SECRET_ENCODING;
import static org.mycore.restapi.v2.MCRRestAuthorizationFilter.PARAM_MCRID;
import static org.mycore.restapi.v2.MCRRestUtils.TAG_MYCORE_OBJECT;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.mcr.acl.accesskey.model.MCRAccessKey;
import org.mycore.restapi.annotations.MCRApiDraft;
import org.mycore.restapi.annotations.MCRRequireTransaction;
import org.mycore.restapi.converter.MCRObjectIDParamConverterProvider;
import org.mycore.restapi.v2.access.MCRRestAPIACLPermission;
import org.mycore.restapi.v2.annotation.MCRRestRequiredPermission;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
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.UriInfo;
@MCRApiDraft("MCRAccessKey")
@Path("/objects/{" + PARAM_MCRID + "}/accesskeys")
@Tag(name = TAG_MYCORE_OBJECT)
public class MCRRestObjectAccessKeys {
@Context
UriInfo uriInfo;
@GET
@Operation(
summary = "Lists all access keys for an object",
responses = {
@ApiResponse(responseCode = "200",
description = "List of access keys attached to this metadata object",
content = { @Content(mediaType = MediaType.APPLICATION_JSON,
array = @ArraySchema(schema = @Schema(implementation = MCRAccessKey.class))) }),
@ApiResponse(responseCode = "" + MCRObjectIDParamConverterProvider.CODE_INVALID, // 400
description = MCRObjectIDParamConverterProvider.MSG_INVALID,
content = { @Content(mediaType = MediaType.APPLICATION_JSON) }),
@ApiResponse(responseCode = "401",
description = "You do not have create permission and need to authenticate first",
content = { @Content(mediaType = MediaType.APPLICATION_JSON) }),
@ApiResponse(responseCode = "404",
description = "Object or access key does not exist",
content = { @Content(mediaType = MediaType.APPLICATION_JSON) }),
})
@Produces(MediaType.APPLICATION_JSON)
@MCRRestRequiredPermission(MCRRestAPIACLPermission.WRITE)
public Response listAccessKeysForObject(@PathParam(PARAM_MCRID) final MCRObjectID objectId,
@DefaultValue("0") @QueryParam("offset") final int offset,
@DefaultValue("128") @QueryParam("limit") final int limit) {
return MCRRestAccessKeyHelper.doListAccessKeys(objectId, offset, limit);
}
@GET
@Path("/{" + PARAM_SECRET + "}")
@Operation(
summary = "Gets access key for an object",
responses = {
@ApiResponse(responseCode = "200",
description = "Information about a specific access key",
content = @Content(mediaType = MediaType.APPLICATION_JSON,
schema = @Schema(implementation = MCRAccessKey.class))),
@ApiResponse(responseCode = "" + MCRObjectIDParamConverterProvider.CODE_INVALID, // 400
description = MCRObjectIDParamConverterProvider.MSG_INVALID,
content = { @Content(mediaType = MediaType.APPLICATION_JSON) }),
@ApiResponse(responseCode = "401",
description = "You do not have create permission and need to authenticate first",
content = { @Content(mediaType = MediaType.APPLICATION_JSON) }),
@ApiResponse(responseCode = "404",
description = "Object or access key does not exist",
content = { @Content(mediaType = MediaType.APPLICATION_JSON) }),
})
@Produces(MediaType.APPLICATION_JSON)
@MCRRestRequiredPermission(MCRRestAPIACLPermission.WRITE)
public Response getAccessKeyFromObject(@PathParam(PARAM_MCRID) final MCRObjectID objectId,
@PathParam(PARAM_SECRET) final String secret,
@QueryParam(QUERY_PARAM_SECRET_ENCODING) final String secretEncoding) {
return MCRRestAccessKeyHelper.doGetAccessKey(objectId, secret, secretEncoding);
}
@POST
@Operation(
summary = "Creates an access key for an object",
responses = {
@ApiResponse(responseCode = "201",
description = "Access key was successfully created",
headers = @Header(name = HttpHeaders.LOCATION,
schema = @Schema(type = "string", format = "uri"),
description = "Location of the new access keyO")),
@ApiResponse(responseCode = "400",
description = "Invalid ID or invalid access key",
content = { @Content(mediaType = MediaType.APPLICATION_JSON) }),
@ApiResponse(responseCode = "401",
description = "You do not have create permission and need to authenticate first",
content = { @Content(mediaType = MediaType.APPLICATION_JSON) }),
@ApiResponse(responseCode = "404",
description = "Object does not exist",
content = { @Content(mediaType = MediaType.APPLICATION_JSON) }),
})
@RequestBody(required = true,
content = @Content(mediaType = MediaType.APPLICATION_JSON,
schema = @Schema(implementation = MCRAccessKey.class)))
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@MCRRestRequiredPermission(MCRRestAPIACLPermission.WRITE)
@MCRRequireTransaction
public Response createAccessKeyForObject(@PathParam(PARAM_MCRID) final MCRObjectID objectId,
final String accessKeyJson) {
return MCRRestAccessKeyHelper.doCreateAccessKey(objectId, accessKeyJson, uriInfo);
}
@PUT
@Path("/{" + PARAM_SECRET + "}")
@Operation(
summary = "Updates an access key for an object",
responses = {
@ApiResponse(responseCode = "204", description = "Access key was successfully updated"),
@ApiResponse(responseCode = "400",
description = "Invalid ID or invalid access key",
content = { @Content(mediaType = MediaType.APPLICATION_JSON) }),
@ApiResponse(responseCode = "401",
description = "You do not have create permission and need to authenticate first",
content = { @Content(mediaType = MediaType.APPLICATION_JSON) }),
@ApiResponse(responseCode = "404",
description = "Object or access key does not exist",
content = { @Content(mediaType = MediaType.APPLICATION_JSON) }),
})
@RequestBody(required = true,
content = @Content(mediaType = MediaType.APPLICATION_JSON,
schema = @Schema(implementation = MCRAccessKey.class)))
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@MCRRestRequiredPermission(MCRRestAPIACLPermission.WRITE)
@MCRRequireTransaction
public Response updateAccessKeyFromObject(@PathParam(PARAM_MCRID) final MCRObjectID objectId,
@PathParam(PARAM_SECRET) final String secret, final String accessKeyJson,
@QueryParam(QUERY_PARAM_SECRET_ENCODING) final String secretEncoding) {
return MCRRestAccessKeyHelper.doUpdateAccessKey(objectId, secret, accessKeyJson, secretEncoding);
}
@DELETE
@Path("/{" + PARAM_SECRET + "}")
@Operation(
summary = "Deletes an access key from an object",
responses = {
@ApiResponse(responseCode = "204", description = "Access key was successfully deleted"),
@ApiResponse(responseCode = "" + MCRObjectIDParamConverterProvider.CODE_INVALID, // 400
description = MCRObjectIDParamConverterProvider.MSG_INVALID,
content = { @Content(mediaType = MediaType.APPLICATION_JSON) }),
@ApiResponse(responseCode = "401",
description = "You do not have create permission and need to authenticate first",
content = { @Content(mediaType = MediaType.APPLICATION_JSON) }),
@ApiResponse(responseCode = "404",
description = "Object or access key does not exist",
content = { @Content(mediaType = MediaType.APPLICATION_JSON) }),
})
@Produces(MediaType.APPLICATION_JSON)
@MCRRestRequiredPermission(MCRRestAPIACLPermission.WRITE)
@MCRRequireTransaction
public Response removeAccessKeyFromObject(@PathParam(PARAM_MCRID) final MCRObjectID objectId,
@PathParam(PARAM_SECRET) final String secret,
@QueryParam(QUERY_PARAM_SECRET_ENCODING) final String secretEncoding) {
return MCRRestAccessKeyHelper.doRemoveAccessKey(objectId, secret, secretEncoding);
}
}
| 10,289 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestAccessKeyExceptionMapper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/restapi/v2/MCRRestAccessKeyExceptionMapper.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.mcr.acl.accesskey.restapi.v2;
import java.util.Optional;
import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyException;
import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyNotFoundException;
import org.mycore.restapi.v2.MCRErrorResponse;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Request;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
@Provider
public class MCRRestAccessKeyExceptionMapper implements ExceptionMapper<MCRAccessKeyException> {
@Context
Request request;
@Override
public Response toResponse(MCRAccessKeyException exception) {
return fromException(exception);
}
public static Response fromException(MCRAccessKeyException e) {
if (e instanceof MCRAccessKeyNotFoundException) {
return getResponse(e, Response.Status.NOT_FOUND.getStatusCode(),
e.getErrorCode());
}
return getResponse(e, Response.Status.BAD_REQUEST.getStatusCode(),
e.getErrorCode());
}
private static Response getResponse(Exception e, int statusCode, String errorCode) {
MCRErrorResponse response = MCRErrorResponse.fromStatus(statusCode)
.withCause(e)
.withMessage(e.getMessage())
.withDetail(Optional.of(e)
.map(ex -> (ex instanceof WebApplicationException) ? ex.getCause() : ex)
.map(Object::getClass)
.map(Class::getName)
.orElse(null))
.withErrorCode(errorCode);
//LogManager.getLogger().error(response::getLogMessage, e);
return Response.status(response.getStatus())
.entity(response)
.build();
}
}
| 2,548 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessKeyFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/restapi/v2/filter/MCRAccessKeyFilter.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.mcr.acl.accesskey.restapi.v2.filter;
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.datamodel.metadata.MCRObjectID;
import org.mycore.mcr.acl.accesskey.MCRAccessKeyUtils;
import org.mycore.restapi.v2.MCRRestAuthorizationFilter;
import jakarta.annotation.Priority;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.ext.Provider;
@Provider
@Priority(Priorities.AUTHENTICATION + 1)
public class MCRAccessKeyFilter implements ContainerRequestFilter {
private static final Logger LOGGER = LogManager.getLogger();
@Override
public void filter(ContainerRequestContext requestContext) {
LOGGER.debug("Access key filter started.");
if (!MCRAccessKeyUtils.isAccessKeyForSessionAllowed()) {
LOGGER.debug("Access keys are not allowed for session. Skipping filter...");
return;
}
if (!MCRSessionMgr.hasCurrentSession()) {
LOGGER.debug("Session is not initialised. Skipping filter...");
return;
}
final String secret = requestContext.getHeaderString("X-Access-Key");
if (secret != null) {
LOGGER.debug("Found X-Access-Key with value {}.", secret);
final MultivaluedMap<String, String> pathParameters = requestContext.getUriInfo().getPathParameters();
final String objectIdString = pathParameters.getFirst(MCRRestAuthorizationFilter.PARAM_MCRID);
if (objectIdString != null) {
try {
final MCRObjectID objectId = MCRObjectID.getInstance(objectIdString);
if (objectId != null) {
MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(objectId, secret);
}
} catch (MCRException e) {
LOGGER.debug("The access key could not be added to the current session: ", e);
}
}
}
}
}
| 2,934 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessKeyInformation.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/restapi/v2/model/MCRAccessKeyInformation.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.mcr.acl.accesskey.restapi.v2.model;
import java.util.List;
import org.mycore.mcr.acl.accesskey.model.MCRAccessKey;
import com.fasterxml.jackson.annotation.JsonProperty;
public class MCRAccessKeyInformation {
private List<MCRAccessKey> accessKeys;
private int totalAccessKeyCount;
public MCRAccessKeyInformation(List<MCRAccessKey> accessKeys, int totalAccessKeyCount) {
setAccessKeys(accessKeys);
setTotalAccessKeyCount(totalAccessKeyCount);
}
public void setAccessKeys(List<MCRAccessKey> accessKeys) {
this.accessKeys = accessKeys;
}
@JsonProperty("items")
public List<MCRAccessKey> getAccessKeys() {
return this.accessKeys;
}
public void setTotalAccessKeyCount(int totalAccessKeyCount) {
this.totalAccessKeyCount = totalAccessKeyCount;
}
@JsonProperty("totalResults")
public int getTotalAccessKeyCount() {
return this.totalAccessKeyCount;
}
}
| 1,705 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessKeyFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/frontend/filter/MCRAccessKeyFilter.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.mcr.acl.accesskey.frontend.filter;
import java.io.IOException;
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.MCRTransactionHelper;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.frontend.servlets.MCRServlet;
import org.mycore.mcr.acl.accesskey.MCRAccessKeyUtils;
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;
/**
* Servlet filter that extracts access key value from query string and includes value if valid as
* an attribute into the session
*/
public class MCRAccessKeyFilter implements Filter {
private static final Logger LOGGER = LogManager.getLogger();
@Override
public void init(FilterConfig filterConfig) {
if (MCRAccessKeyUtils.isAccessKeyForSessionAllowed()) {
LOGGER.info("MCRAccessKeyFilter is enabled and the following permssions are allowed: {}",
String.join(",", MCRAccessKeyUtils.getAllowedSessionPermissionTypes()));
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (MCRAccessKeyUtils.isAccessKeyForSessionAllowed()) {
final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
final MCRObjectID objectId = extractObjectId(httpServletRequest);
if (objectId != null) {
String value = httpServletRequest.getParameter("accesskey");
if (value != null) {
try {
MCRServlet.initializeMCRSession(httpServletRequest, getFilterName());
MCRFrontendUtil.configureSession(MCRSessionMgr.getCurrentSession(), httpServletRequest,
(HttpServletResponse) response);
MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(objectId, value);
} catch (Exception e) {
LOGGER.debug("Cannot set access key to session", e);
MCRTransactionHelper.rollbackTransaction();
} finally {
MCRServlet.cleanupMCRSession(httpServletRequest, getFilterName());
httpServletRequest.removeAttribute(MCRServlet.CURRENT_THREAD_NAME_KEY);
httpServletRequest.removeAttribute(MCRServlet.INITIAL_SERVLET_NAME_KEY);
}
}
}
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
//not needed
}
private String getFilterName() {
return this.getClass().getSimpleName();
}
private static MCRObjectID extractObjectId(final HttpServletRequest request) {
final String pathInfo = request.getPathInfo();
final String id = pathInfo == null ? null : pathInfo.substring(1);
if (id != null) {
try {
return MCRObjectID.getInstance(id);
} catch (final MCRException e) {
LOGGER.debug("Cannot convert {} to MCRObjectID", id);
}
}
return null;
}
}
| 4,316 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessKeyStrategyHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/strategy/MCRAccessKeyStrategyHelper.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.mcr.acl.accesskey.strategy;
import static org.mycore.access.MCRAccessManager.PERMISSION_PREVIEW;
import static org.mycore.access.MCRAccessManager.PERMISSION_READ;
import static org.mycore.access.MCRAccessManager.PERMISSION_VIEW;
import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE;
import java.util.Date;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.mcr.acl.accesskey.model.MCRAccessKey;
public class MCRAccessKeyStrategyHelper {
private static final Logger LOGGER = LogManager.getLogger();
/**
* maps view and preview permission to read
*
* @param permission permission
* @return (sanitized) permission
*/
protected static String sanitizePermission(final String permission) {
if (PERMISSION_VIEW.equals(permission) || PERMISSION_PREVIEW.equals(permission)) {
LOGGER.debug("Mapped {} to read.", permission);
return PERMISSION_READ;
}
return permission;
}
/**
* verifies {@link MCRAccessKey} for permission.
*
* @param permission permission type
* @param accessKey the {@link MCRAccessKey}
* @return true if valid, otherwise false
*/
public static boolean verifyAccessKey(final String permission, final MCRAccessKey accessKey) {
final String sanitizedPermission = sanitizePermission(permission);
if (PERMISSION_READ.equals(sanitizedPermission) || PERMISSION_WRITE.equals(sanitizedPermission)) {
if (Boolean.FALSE.equals(accessKey.getIsActive())) {
return false;
}
final Date expiration = accessKey.getExpiration();
if (expiration != null && new Date().after(expiration)) {
return false;
}
if ((sanitizedPermission.equals(PERMISSION_READ)
&& accessKey.getType().equals(PERMISSION_READ))
|| accessKey.getType().equals(PERMISSION_WRITE)) {
LOGGER.debug("Access granted.");
return true;
}
}
return false;
}
}
| 2,871 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessKeyStrategy.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/strategy/MCRAccessKeyStrategy.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.mcr.acl.accesskey.strategy;
import static org.mycore.access.MCRAccessManager.PERMISSION_PREVIEW;
import static org.mycore.access.MCRAccessManager.PERMISSION_READ;
import static org.mycore.access.MCRAccessManager.PERMISSION_VIEW;
import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.access.strategies.MCRAccessCheckStrategy;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.mcr.acl.accesskey.MCRAccessKeyUtils;
import org.mycore.mcr.acl.accesskey.model.MCRAccessKey;
/**
* Strategy for {@link MCRAccessKey}.
*/
public class MCRAccessKeyStrategy implements MCRAccessCheckStrategy {
private static final Logger LOGGER = LogManager.getLogger();
@Override
public boolean checkPermission(final String objectIdString, final String permission) {
if ((PERMISSION_READ.equals(permission) || PERMISSION_WRITE.equals(permission)
|| PERMISSION_VIEW.equals(permission) || PERMISSION_PREVIEW.equals(permission))
&& MCRObjectID.isValid(objectIdString)) {
final MCRObjectID objectId = MCRObjectID.getInstance(objectIdString);
if ("derivate".equals(objectId.getTypeId())) {
return checkDerivatePermission(objectId, permission);
}
return checkObjectPermission(objectId, permission);
}
return false;
}
/**
* Fetches access key and checks object permission
*
* @param objectId the {@link MCRObjectID}
* @param permission permission type
* @return true if permitted, otherwise false
*/
public boolean checkObjectPermission(final MCRObjectID objectId, final String permission) {
LOGGER.debug("check object {} permission {}.", objectId.toString(), permission);
if ((PERMISSION_READ.equals(permission) || PERMISSION_WRITE.equals(permission)
|| PERMISSION_VIEW.equals(permission) || PERMISSION_PREVIEW.equals(permission))
&& MCRAccessKeyUtils.isAccessKeyForObjectTypeAllowed(objectId.getTypeId())) {
if (MCRAccessKeyUtils.isAccessKeyForSessionAllowed(permission)) {
final MCRAccessKey accessKey = MCRAccessKeyUtils.getLinkedAccessKeyFromCurrentSession(objectId);
if (accessKey != null && MCRAccessKeyStrategyHelper.verifyAccessKey(permission, accessKey)) {
return true;
}
}
final MCRAccessKey accessKey = MCRAccessKeyUtils.getLinkedAccessKeyFromCurrentUser(objectId);
return accessKey != null && MCRAccessKeyStrategyHelper.verifyAccessKey(permission, accessKey);
}
return false;
}
/**
* Fetches access key and checks derivate permission
*
* @param objectId the {@link MCRObjectID}
* @param permission permission type
* @return true if permitted, otherwise false
*/
public boolean checkDerivatePermission(final MCRObjectID objectId, final String permission) {
LOGGER.debug("check derivate {} permission {}.", objectId.toString(), permission);
if ((PERMISSION_READ.equals(permission) || PERMISSION_WRITE.equals(permission)
|| PERMISSION_VIEW.equals(permission) || PERMISSION_PREVIEW.equals(permission))
&& MCRAccessKeyUtils.isAccessKeyForObjectTypeAllowed(objectId.getTypeId())) {
if (checkObjectPermission(objectId, permission)) {
return true;
}
final MCRObjectID parentObjectId = MCRMetadataManager.getObjectId(objectId, 10, TimeUnit.MINUTES);
if (parentObjectId != null) {
return checkObjectPermission(parentObjectId, permission);
}
}
return false;
}
}
| 4,646 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessKeyCommands.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/cli/MCRAccessKeyCommands.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.mcr.acl.accesskey.cli;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.cli.annotation.MCRCommand;
import org.mycore.frontend.cli.annotation.MCRCommandGroup;
import org.mycore.mcr.acl.accesskey.MCRAccessKeyManager;
import org.mycore.mcr.acl.accesskey.MCRAccessKeyTransformer;
import org.mycore.mcr.acl.accesskey.MCRAccessKeyUtils;
import org.mycore.mcr.acl.accesskey.model.MCRAccessKey;
@MCRCommandGroup(
name = "Access keys")
public class MCRAccessKeyCommands {
private static final Logger LOGGER = LogManager.getLogger();
@MCRCommand(syntax = "clear all access keys",
help = "Clears all access keys")
public static void clearAccessKeys() {
MCRAccessKeyManager.clearAccessKeys();
LOGGER.info("Cleared all access keys.");
}
@MCRCommand(syntax = "clear all access keys for {0}",
help = "Clears all access keys for MCRObject/Derivate {0}")
public static void clearAccessKeys(final String objectIdString) throws MCRException {
final MCRObjectID objectId = MCRObjectID.getInstance(objectIdString);
if (!MCRMetadataManager.exists(objectId)) {
throw new MCRException("MCRObject/Derivate doesn't exists.");
}
MCRAccessKeyManager.clearAccessKeys(objectId);
LOGGER.info("Cleared all access keys of {}.", objectIdString);
}
@MCRCommand(syntax = "create access key for {0} from file {1}",
help = "Creates an access key {0} for MCRObject/Derivate from file {1} in json format")
public static void createAccessKey(final String objectIdString, final String pathString)
throws IOException, MCRException {
final MCRObjectID objectId = MCRObjectID.getInstance(objectIdString);
if (!MCRMetadataManager.exists(objectId)) {
throw new MCRException("MCRObject/Derivate doesn't exists.");
}
final MCRAccessKey accessKey = readAccessKeyFromFile(pathString);
MCRAccessKeyManager.createAccessKey(objectId, accessKey);
LOGGER.info("Created access key for {}.", objectIdString);
}
@MCRCommand(syntax = "update access key for {0} with secret {1} from file {2}",
help = "Updates an access key for MCRObject/Derivate {0}"
+ " with (hashed) secret {1} from file {2} in json format")
public static void updateAccessKey(final String objectIdString, final String secret, final String pathString)
throws IOException, MCRException {
final MCRObjectID objectId = MCRObjectID.getInstance(objectIdString);
if (!MCRMetadataManager.exists(objectId)) {
throw new MCRException("MCRObject/Derivate doesn't exists.");
}
final MCRAccessKey accessKey = readAccessKeyFromFile(pathString);
MCRAccessKeyManager.updateAccessKey(objectId, secret, accessKey);
LOGGER.info("Updated access key ({}) for {}.", secret, objectIdString);
}
@MCRCommand(syntax = "delete access key for {0} with secret {1}",
help = "Deletes an access key for MCRObject/Derivate {0} with (hashed) secret {1}")
public static void removeAccessKey(final String objectIdString, final String secret) throws MCRException {
final MCRObjectID objectId = MCRObjectID.getInstance(objectIdString);
if (!MCRMetadataManager.exists(objectId)) {
throw new MCRException("MCRObject/Derivate doesn't exists.");
}
MCRAccessKeyManager.removeAccessKey(objectId, secret);
LOGGER.info("Deleted access key ({}) for {}.", secret, objectIdString);
}
@MCRCommand(syntax = "import access keys for {0} from file {1}",
help = "Imports access keys for MCRObject/Derivate {0} from file {1} in json array format")
public static void importAccessKeysFromFile(final String objectIdString, final String pathString)
throws IOException, MCRException {
final MCRObjectID objectId = MCRObjectID.getInstance(objectIdString);
if (!MCRMetadataManager.exists(objectId)) {
throw new MCRException("MCRObject/Derivate doesn't exists.");
}
final Path path = Path.of(pathString);
final String accessKeysJson = Files.readString(path, UTF_8);
final List<MCRAccessKey> accessKeys = MCRAccessKeyTransformer.accessKeysFromJson(accessKeysJson);
MCRAccessKeyManager.addAccessKeys(objectId, accessKeys);
LOGGER.info("Imported access keys for {} from file {}.", objectIdString, pathString);
}
@MCRCommand(syntax = "export access keys for {0} to file {1}",
help = "Exports access keys for MCRObject/Derivate {0} to file {1} in json array format")
public static void exportAccessKeysToFile(final String objectIdString, final String pathString)
throws IOException, MCRException {
final MCRObjectID objectId = MCRObjectID.getInstance(objectIdString);
if (!MCRMetadataManager.exists(objectId)) {
throw new MCRException("MCRObject/Derivate doesn't exists.");
}
final Path path = Path.of(pathString);
final List<MCRAccessKey> accessKeys = MCRAccessKeyManager.listAccessKeys(objectId);
final String accessKeysJson = MCRAccessKeyTransformer.jsonFromAccessKeys(accessKeys);
Files.writeString(path, accessKeysJson, UTF_8);
LOGGER.info("Exported access keys for {} to file {}.", objectIdString, pathString);
}
@MCRCommand(syntax = "clean up access key user attributes",
help = "Cleans all access key secret attributes of users if the corresponding key does not exist.")
public static void cleanUp() {
MCRAccessKeyUtils.cleanUpUserAttributes();
LOGGER.info("Cleaned up access keys.");
}
@MCRCommand(syntax = "hash access key secret {0} for {1}",
help = "Hashes secret {0} for MCRObject/Derivate {1}")
public static void hashSecret(final String secret, final String objectIdString) throws MCRException {
final MCRObjectID objectId = MCRObjectID.getInstance(objectIdString);
final String result = MCRAccessKeyManager.hashSecret(secret, objectId);
LOGGER.info("Hashed secret for {}: '{}'.", objectIdString, result);
}
private static MCRAccessKey readAccessKeyFromFile(final String pathString) throws IOException, MCRException {
final Path path = Path.of(pathString);
final String accessKeyJson = Files.readString(path, UTF_8);
return MCRAccessKeyTransformer.accessKeyFromJson(accessKeyJson);
}
}
| 7,568 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessKeyCollisionException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/exception/MCRAccessKeyCollisionException.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.mcr.acl.accesskey.exception;
/**
* Exception that refers to a collision of access keys.
* This refers to value duplicates.
*/
public class MCRAccessKeyCollisionException extends MCRAccessKeyException {
private static final long serialVersionUID = 1L;
public MCRAccessKeyCollisionException(String errorMessage) {
super(errorMessage, "component.acl.accesskey.frontend.error.collision");
}
}
| 1,161 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessKeyExpiredException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/exception/MCRAccessKeyExpiredException.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.mcr.acl.accesskey.exception;
/**
* Exception that refers to an expired access key.
*/
public class MCRAccessKeyExpiredException extends MCRAccessKeyException {
private static final long serialVersionUID = 1L;
public MCRAccessKeyExpiredException(String errorMessage) {
super(errorMessage, "component.acl.accesskey.frontend.error.expired");
}
}
| 1,114 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessKeyTransformationException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/exception/MCRAccessKeyTransformationException.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.mcr.acl.accesskey.exception;
/**
* Exception that refers to an error during transformation of an access key.
*/
public class MCRAccessKeyTransformationException extends MCRAccessKeyException {
private static final long serialVersionUID = 1L;
public MCRAccessKeyTransformationException(String errorMessage) {
super(errorMessage, "component.acl.accesskey.frontend.error.transformation");
}
}
| 1,161 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessKeyNotFoundException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/exception/MCRAccessKeyNotFoundException.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.mcr.acl.accesskey.exception;
/**
* Exception that refers to an unknown access key.
*/
public class MCRAccessKeyNotFoundException extends MCRAccessKeyException {
private static final long serialVersionUID = 1L;
public MCRAccessKeyNotFoundException(String errorMessage) {
super(errorMessage, "component.acl.accesskey.frontend.error.unknownKey");
}
}
| 1,119 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessKeyInvalidTypeException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/exception/MCRAccessKeyInvalidTypeException.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.mcr.acl.accesskey.exception;
/**
* Exception that refers to an invalid permission type.
*/
public class MCRAccessKeyInvalidTypeException extends MCRAccessKeyException {
private static final long serialVersionUID = 1L;
public MCRAccessKeyInvalidTypeException(String errorMessage) {
super(errorMessage, "component.acl.accesskey.frontend.error.invalidType");
}
}
| 1,131 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessKeyDisabledException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/exception/MCRAccessKeyDisabledException.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.mcr.acl.accesskey.exception;
/**
* Exception that refers to a disabled access key.
*/
public class MCRAccessKeyDisabledException extends MCRAccessKeyException {
private static final long serialVersionUID = 1L;
public MCRAccessKeyDisabledException(String errorMessage) {
super(errorMessage, "component.acl.accesskey.frontend.error.disabled");
}
}
| 1,117 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessKeyInvalidSecretException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/exception/MCRAccessKeyInvalidSecretException.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.mcr.acl.accesskey.exception;
/**
* Exception that refers to an invalid value.
*/
public class MCRAccessKeyInvalidSecretException extends MCRAccessKeyException {
private static final long serialVersionUID = 1L;
public MCRAccessKeyInvalidSecretException(String errorMessage) {
super(errorMessage, "component.acl.accesskey.frontend.error.invalidSecret");
}
}
| 1,127 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessKeyException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/exception/MCRAccessKeyException.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.mcr.acl.accesskey.exception;
import org.mycore.common.MCRException;
/**
* Instances of this class represent a general exception related to access keys.
*/
public class MCRAccessKeyException extends MCRException {
private static final long serialVersionUID = 1L;
/**
* Reference for error messages for i18n.
*/
private String errorCode;
public MCRAccessKeyException(String errorMessage) {
super(errorMessage);
}
public MCRAccessKeyException(String errorMessage, String errorCode) {
super(errorMessage);
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
}
| 1,509 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessKey.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/model/MCRAccessKey.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.mcr.acl.accesskey.model;
import java.util.Date;
import jakarta.persistence.Basic;
import org.mycore.backend.jpa.MCRObjectIDConverter;
import org.mycore.datamodel.metadata.MCRObjectID;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import jakarta.persistence.Column;
import jakarta.persistence.Convert;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.Table;
@NamedQueries({
@NamedQuery(name = "MCRAccessKey.getWithObjectId",
query = "SELECT k"
+ " FROM MCRAccessKey k"
+ " WHERE k.objectId = :objectId"
+ " ORDER BY k.lastModified ASC"),
@NamedQuery(name = "MCRAccessKey.getWithSecret",
query = "SELECT k"
+ " FROM MCRAccessKey k"
+ " WHERE k.secret = :secret AND k.objectId = :objectId"),
@NamedQuery(name = "MCRAccessKey.getWithType",
query = "SELECT k"
+ " FROM MCRAccessKey k"
+ " WHERE k.type = :type AND k.objectId = :objectId"),
@NamedQuery(name = "MCRAccessKey.clearWithObjectId",
query = "DELETE"
+ " FROM MCRAccessKey k"
+ " WHERE k.objectId = :objectId"),
@NamedQuery(name = "MCRAccessKey.clear",
query = "DELETE"
+ " FROM MCRAccessKey k"),
})
/**
* Access keys for a {@link MCRObject}.
* An access keys contains a secret and a type.
* Value is the key secret of the key and type the permission.
*/
@Entity
@Table(name = "MCRAccessKey")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MCRAccessKey {
private static final long serialVersionUID = 1L;
/** The unique and internal information id */
private int id;
/** The access key information */
private MCRObjectID objectId;
/** The secret */
private String secret;
/** The permission type */
private String type;
/** The status */
private Boolean isActive;
/** The expiration date* */
private Date expiration;
/** The comment */
private String comment;
/** The date of creation */
private Date created;
/** The name of creator */
private String createdBy;
/** The date of last modification */
private Date lastModified;
/** The name of the last modifier */
private String lastModifiedBy;
protected MCRAccessKey() {
}
/**
* Creates a new access key with secret and type.
*
* @param secret the secret the user must know to acquire permission.
* @param type the type of permission.
*/
public MCRAccessKey(final String secret, final String type) {
this();
setSecret(secret);
setType(type);
}
/**
* @return the linked objectId
*/
@JsonIgnore
@Column(name = "object_id",
length = MCRObjectID.MAX_LENGTH,
nullable = false)
@Convert(converter = MCRObjectIDConverter.class)
@Basic
public MCRObjectID getObjectId() {
return objectId;
}
/**
* @param objectId the {@link MCRObjectID} to set
*/
public void setObjectId(final MCRObjectID objectId) {
this.objectId = objectId;
}
/**
* @return internal id
*/
@JsonIgnore
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "accesskey_id",
nullable = false)
public int getId() {
return id;
}
/**
* @param id internal id
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the key secret
*/
@Column(name = "secret",
nullable = false)
public String getSecret() {
return secret;
}
/**
* @param secret key secret
*/
public void setSecret(final String secret) {
this.secret = secret;
}
/**
* @return permission type
*/
@Column(name = "type",
nullable = false)
public String getType() {
return type;
}
/**
* @param type permission type
*/
public void setType(String type) {
this.type = type;
}
/**
* @return active or not
*/
@Column(name = "isActive",
nullable = false)
public Boolean getIsActive() {
return isActive;
}
/**
* @param isActive the state
*/
public void setIsActive(final Boolean isActive) {
this.isActive = isActive;
}
/**
* @return expiration date
*/
@Column(name = "expiration")
public Date getExpiration() {
return expiration;
}
/**
* @param expiration the expiration date
*/
public void setExpiration(final Date expiration) {
this.expiration = expiration;
}
/**
* @return comment
*/
@Column(name = "comment")
public String getComment() {
return comment;
}
/**
* @param comment the comment
*/
public void setComment(String comment) {
this.comment = comment;
}
/**
* @return date of creation
*/
@Column(name = "created")
public Date getCreated() {
return created;
}
/**
* @param created date of creation
*/
public void setCreated(final Date created) {
this.created = created;
}
/**
* @return name of creator
*/
@Column(name = "createdBy")
public String getCreatedBy() {
return createdBy;
}
/**
* @param createdBy name of creator
*/
public void setCreatedBy(final String createdBy) {
this.createdBy = createdBy;
}
/**
* @return date of last modification
*/
@Column(name = "lastModified")
public Date getLastModified() {
return lastModified;
}
/**
* @param lastModified date of last modification
*/
@Column(name = "lastModified")
public void setLastModified(final Date lastModified) {
this.lastModified = lastModified;
}
/**
* @return name of last modifier
*/
@Column(name = "lastModifiedBy")
public String getLastModifiedBy() {
return lastModifiedBy;
}
/**
* @param lastModifiedBy name of last modifier
*/
public void setLastModifiedBy(final String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof MCRAccessKey other)) {
return false;
}
return this.id == other.getId() && this.type.equals(other.getType())
&& this.secret.equals(other.getSecret());
}
}
| 7,578 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCronjobManagerTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-cronjob/src/test/java/org/mycore/mcr/cronjob/MCRCronjobManagerTest.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.mcr.cronjob;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.common.MCRException;
import org.mycore.common.MCRTestCase;
import org.mycore.common.processing.impl.MCRCentralProcessableRegistry;
public class MCRCronjobManagerTest extends MCRTestCase {
@Test
public void startUp() {
Assert.assertEquals("Count should be 0", MCRTestCronJob.count, 0);
MCRCronjobManager.getInstance().startUp(null);
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
throw new MCRException(e);
}
Assert.assertEquals("Count should be 2", MCRTestCronJob.count, 2);
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Processable.Registry.Class", MCRCentralProcessableRegistry.class.getName());
testProperties.put(MCRCronjobManager.JOBS_CONFIG_PREFIX + "Test2", MCRTestCronJob.class.getName());
testProperties.put(MCRCronjobManager.JOBS_CONFIG_PREFIX + "Test2.Contexts", "CLI");
testProperties.put(MCRCronjobManager.JOBS_CONFIG_PREFIX + "Test2.CronType", "QUARTZ");
testProperties.put(MCRCronjobManager.JOBS_CONFIG_PREFIX + "Test2.Cron", "* * * * * ? *");
testProperties.put(MCRCronjobManager.JOBS_CONFIG_PREFIX + "Test2.N", "1");
return testProperties;
}
}
| 2,195 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCommandCronJobTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-cronjob/src/test/java/org/mycore/mcr/cronjob/MCRCommandCronJobTest.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.mcr.cronjob;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.common.MCRJPATestCase;
import org.mycore.common.processing.impl.MCRCentralProcessableRegistry;
import org.mycore.frontend.cli.MCRCommand;
import org.mycore.frontend.cli.MCRCommandManager;
public class MCRCommandCronJobTest extends MCRJPATestCase {
public static boolean commandRun = false;
public static String message;
@Test
public void runJob() throws InterruptedException {
Assert.assertFalse("The command should not run yet!", commandRun);
MCRCommandManager.getKnownCommands().put("test",
Stream
.of(new MCRCommand("test command {0}",
"org.mycore.mcr.cronjob.MCRCommandCronJobTest.testCommand String", "just a test command."))
.collect(Collectors.toList()));
MCRCronjobManager.getInstance().startUp(null);
Thread.sleep(2000);
Assert.assertTrue("The command should have been executed!", commandRun);
Assert.assertNotNull("The message should be set", message);
Assert.assertEquals("Message should be the same", "Welt", message);
}
public static List<String> testCommand(String msg) {
System.out.println(msg);
commandRun = true;
message = msg;
if (message.equals("Welt")) {
return null;
} else {
return Stream.of("test command Welt").collect(Collectors.toList());
}
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> properties = super.getTestProperties();
properties.put("MCR.Processable.Registry.Class", MCRCentralProcessableRegistry.class.getName());
properties.put(MCRCronjobManager.JOBS_CONFIG_PREFIX + "Command", MCRCommandCronJob.class.getName());
properties.put(MCRCronjobManager.JOBS_CONFIG_PREFIX + "Command.Contexts", "CLI");
properties.put(MCRCronjobManager.JOBS_CONFIG_PREFIX + "Command.CronType", "QUARTZ");
properties.put(MCRCronjobManager.JOBS_CONFIG_PREFIX + "Command.Cron", "* * * * * ? *");
properties.put(MCRCronjobManager.JOBS_CONFIG_PREFIX + "Command.Command", "test command Hallo");
return properties;
}
}
| 3,108 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTestCronJob.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-cronjob/src/test/java/org/mycore/mcr/cronjob/MCRTestCronJob.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.mcr.cronjob;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.annotation.MCRProperty;
import org.mycore.common.processing.MCRProcessableStatus;
public class MCRTestCronJob extends MCRCronjob {
public static final Logger LOGGER = LogManager.getLogger();
public static int count = 0;
private Integer n;
@Override
public void runJob() {
getProcessable().setStatus(MCRProcessableStatus.processing);
getProcessable().setProgress(0);
for (int i = 0; i < getN(); i++) {
Double progress = ((double) i / getN()) * 100;
getProcessable().setProgress(progress.intValue());
count++;
LOGGER.info("Process: " + i);
}
}
public Integer getN() {
return n;
}
@MCRProperty(name = "N")
public void setN(String n) {
Integer n1 = Integer.valueOf(n);
if (n1 < 0) {
throw new IllegalArgumentException("N should be >0");
}
this.n = n1;
}
@Override
public String getDescription() {
return "Counts to " + getN();
}
}
| 1,907 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCronjob.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-cronjob/src/main/java/org/mycore/mcr/cronjob/MCRCronjob.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.mcr.cronjob;
import java.time.Duration;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.mycore.common.MCRException;
import org.mycore.common.config.annotation.MCRPostConstruction;
import org.mycore.common.config.annotation.MCRProperty;
import org.mycore.common.processing.MCRAbstractProcessable;
import org.mycore.common.processing.MCRProcessableStatus;
import com.cronutils.descriptor.CronDescriptor;
import com.cronutils.model.Cron;
import com.cronutils.model.CronType;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;
/**
* {@link MCRCronjobManager#JOBS_CONFIG_PREFIX} and automatic executed. If you want to create your own
* {@link MCRCronjob} you should maybe look if {@link MCRCommandCronJob} is good enough.
* <p>
* The Default properties for this Configurable are:
* {@link #cronType} and {@link #setCron(String)}
*/
public abstract class MCRCronjob implements Runnable {
private MCRAbstractProcessable processable;
private boolean enabled;
private Set<Context> contexts;
private CronType cronType;
private Cron cron;
private String id;
private String property;
public String getID() {
return id;
}
public void setID(String id) {
this.id = id;
}
@MCRPostConstruction
public void checkConfiguration(String property) {
setID(property.substring(MCRCronjobManager.JOBS_CONFIG_PREFIX.length()));
this.processable = new MCRAbstractProcessable();
this.processable.setStatus(MCRProcessableStatus.created);
this.processable.setName(getClass().getSimpleName() + " - " + getDescription());
this.processable.setProgressText("Wait for " + getCronDescription() + "..");
}
/**
* Whether this Cronjob is enabled as all. Possible values are: true, false.
*
* @param enabled Whether this Cronjob is enabled.
*/
@MCRProperty(name = "Enabled", defaultName = "MCR.Cronjob.Default.Enabled")
public void setEnabled(String enabled) {
this.enabled = Boolean.parseBoolean(enabled);
}
/**
* Comma separated list of contexts in which this Cronjob is executed. Possible values are: WEBAPP, CLI.
*
* @param contexts List of contexts in which this Cronjob is executed.
*/
@MCRProperty(name = "Contexts", defaultName = "MCR.Cronjob.Default.Contexts")
public void setContexts(String contexts) {
this.contexts = Arrays.stream(contexts.split(",")).map(Context::valueOf).collect(Collectors.toSet());
}
/**
* Whether this Cronjob is active, i.e. whether it is enabled at all and
* whether it is executed in the given context.
*
* @param context The context
* @return Whether this Cronjob is active.
*/
public boolean isActive(Context context) {
return enabled && contexts.contains(context);
}
/**
* The format type of the cron description property. Possible values are: CRON4J, QUARTZ, UNIX, SPRING
*
* @param cronType The format type of the {@link #setCron(String)} property.
*/
@MCRProperty(name = "CronType", defaultName = "MCR.Cronjob.Default.CronType", order = 1)
public void setCronType(String cronType) {
this.cronType = CronType.valueOf(cronType);
}
/**
* Set the cron description (i.e. a string like like "42 23 * * *") that describes
* when this Cronjob is executed. The interpretation of this string is dependent on the
* set cron type.
*
* @param cron The description of when this Cronjob is executed.
*/
@MCRProperty(name = "Cron", order = 2)
public void setCron(String cron) {
CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(cronType);
CronParser parser = new CronParser(cronDefinition);
this.cron = parser.parse(cron);
}
public Cron getCron() {
return cron;
}
@MCRPostConstruction
public void setProperty(String property) {
this.property = property;
}
public String getProperty() {
return property;
}
public Optional<Long> getNextExecution() {
Cron cron = getCron();
ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
Optional<Duration> duration = ExecutionTime.forCron(cron).timeToNextExecution(now);
return duration.map(Duration::toMillis);
}
public String getCronDescription() {
CronDescriptor descriptor = CronDescriptor.instance(Locale.ENGLISH);
return descriptor.describe(this.getCron());
}
public MCRAbstractProcessable getProcessable() {
return processable;
}
@Override
public final void run() {
getProcessable().setStatus(MCRProcessableStatus.processing);
getProcessable().setProgressText("running..");
try {
runJob();
getProcessable().setStatus(MCRProcessableStatus.successful);
} catch (Exception e) {
getProcessable().setStatus(MCRProcessableStatus.failed);
throw new MCRException("Error while running Cronjob " + getID() + " - " + getDescription(), e);
}
}
/**
* Will be executed according to the Cron schedule. Remember to call {@link #getProcessable()} and
* update its values to let the user know what you are doing.
*/
public abstract void runJob();
/**
* @return A Description what this Cronjob does.
*/
public abstract String getDescription();
public enum Context {
WEBAPP,
CLI
}
}
| 6,582 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCronStarter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-cronjob/src/main/java/org/mycore/mcr/cronjob/MCRCronStarter.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.mcr.cronjob;
import org.mycore.common.events.MCRStartupHandler;
import jakarta.servlet.ServletContext;
public class MCRCronStarter implements MCRStartupHandler.AutoExecutable {
@Override
public String getName() {
return MCRCronjobManager.class.getSimpleName();
}
@Override
public int getPriority() {
return 0;
}
@Override
public void startUp(ServletContext servletContext) {
if (servletContext != null) {
MCRCronjobManager.getInstance().startUp(servletContext);
}
}
}
| 1,301 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCronjobManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-cronjob/src/main/java/org/mycore/mcr/cronjob/MCRCronjobManager.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.mcr.cronjob;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.events.MCRShutdownHandler;
import org.mycore.common.log.MCRTableMessage;
import org.mycore.common.log.MCRTableMessage.Column;
import org.mycore.common.processing.MCRProcessableDefaultCollection;
import org.mycore.common.processing.MCRProcessableRegistry;
import org.mycore.mcr.cronjob.MCRCronjob.Context;
import jakarta.servlet.ServletContext;
/**
* Schedules all Cronjobs defined with the property prefix {@link #JOBS_CONFIG_PREFIX}. Couples the execution with the
* {@link MCRProcessableRegistry}.
*/
public class MCRCronjobManager implements MCRShutdownHandler.Closeable {
public static final String JOBS_CONFIG_PREFIX = "MCR.Cronjob.Jobs.";
public static final Logger LOGGER = LogManager.getLogger();
private final MCRProcessableDefaultCollection processableCollection;
private final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(
MCRConfiguration2.getOrThrow("MCR.Cronjob.CorePoolSize", Integer::valueOf));
private MCRCronjobManager() {
processableCollection = new MCRProcessableDefaultCollection(getClass().getSimpleName());
MCRProcessableRegistry.getSingleInstance().register(processableCollection);
executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
}
public static MCRCronjobManager getInstance() {
return MCRCronjobManagerInstanceHelper.INSTANCE;
}
@Override
public void prepareClose() {
LOGGER.info("Shutdown {}", this.getClass().getSimpleName());
executor.shutdown();
try {
executor.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOGGER.warn("Got interrupted while awaiting termination for MCRCronjobThreadPool");
}
}
@Override
public void close() {
if (!executor.isTerminated()) {
LOGGER.info("Force shutdown {}", this.getClass().getSimpleName());
executor.shutdownNow();
try {
executor.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOGGER.warn("Got interrupted while awaiting force termination for MCRCronjobThreadPool");
}
}
}
void startUp(ServletContext servletContext) {
MCRShutdownHandler.getInstance().addCloseable(this);
MCRTableMessage<Pair<MCRCronjob, Boolean>> schedule = new MCRTableMessage<>(
new Column<>("Property", p -> p.getLeft().getProperty()),
new Column<>("Description", p -> p.getLeft().getDescription()),
new Column<>("State", p -> p.getRight() ? "ACTIVE" : "INACTIVE"),
new Column<>("Cron", p -> p.getLeft().getCronDescription()));
Context context = getContext(servletContext);
MCRConfiguration2.getInstantiatablePropertyKeys(JOBS_CONFIG_PREFIX)
.sorted()
.map(MCRCronjobManager::toJob)
.forEach(job -> {
if (job.isActive(context)) {
schedule.add(Pair.of(job, true));
scheduleNextRun(job);
} else {
schedule.add(Pair.of(job, false));
}
});
LOGGER.info(schedule.logMessage("Cron schedule"));
}
private MCRCronjob.Context getContext(ServletContext servletContext) {
return servletContext != null ? MCRCronjob.Context.WEBAPP : MCRCronjob.Context.CLI;
}
private void scheduleNextRun(MCRCronjob job) {
this.processableCollection.add(job.getProcessable());
job.getNextExecution().ifPresent(next -> {
if (next > 0) {
executor.schedule(() -> {
try {
LOGGER.info("Execute job " + job.getID() + " - " + job.getDescription());
job.run();
this.processableCollection.remove(job.getProcessable());
// schedule next run with a fresh instance of the same job
scheduleNextRun(toJob(job.getProperty()));
} catch (Exception ex) {
LOGGER.error("Error while executing job " + job.getID() + " " + job.getDescription(), ex);
this.processableCollection.remove(job.getProcessable());
}
}, next, TimeUnit.MILLISECONDS);
}
});
}
public MCRCronjob getJob(String id) {
return toJob(JOBS_CONFIG_PREFIX + id);
}
private static MCRCronjob toJob(String property) {
return MCRConfiguration2.<MCRCronjob>getInstanceOf(property).orElseThrow();
}
private static class MCRCronjobManagerInstanceHelper {
public static MCRCronjobManager INSTANCE = new MCRCronjobManager();
}
}
| 5,929 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCommandCronJob.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-cronjob/src/main/java/org/mycore/mcr/cronjob/MCRCommandCronJob.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.mcr.cronjob;
import java.util.List;
import org.mycore.common.MCRException;
import org.mycore.common.config.annotation.MCRProperty;
import org.mycore.frontend.cli.MCRCommandManager;
import org.mycore.util.concurrent.MCRTransactionableRunnable;
public class MCRCommandCronJob extends MCRCronjob {
private String command;
public String getCommand() {
return command;
}
@MCRProperty(name = "Command")
public void setCommand(String command) {
this.command = command;
}
@Override
public void runJob() {
new MCRTransactionableRunnable(() -> {
String command = getCommand();
MCRCommandManager cmdMgr = new MCRCommandManager();
invokeCommand(command, cmdMgr);
}).run();
}
private void invokeCommand(String command, MCRCommandManager cmdMgr) {
try {
List<String> result = cmdMgr.invokeCommand(command);
if (result.size() > 0) {
for (String s : result) {
invokeCommand(s, cmdMgr);
}
}
} catch (Exception e) {
throw new MCRException("Error while invoking command " + command, e);
}
}
@Override
public String getDescription() {
return "Runs the command '" + getCommand() + "'";
}
}
| 2,080 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRClassificationBrowser2.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classbrowser/src/main/java/org/mycore/frontend/servlets/MCRClassificationBrowser2.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.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import javax.xml.transform.TransformerException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import org.mycore.common.MCRUtils;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
import org.xml.sax.SAXException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* This servlet provides a way to visually navigate through the tree of
* categories of a classification. The XML output is transformed to HTML
* using classificationBrowserData.xsl on the server side, then sent to
* the client browser, where AJAX does the rest.
*
* @author Frank Lützenkirchen
*/
public class MCRClassificationBrowser2 extends MCRServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LogManager.getLogger(MCRClassificationBrowser2.class);
protected MCRQueryAdapter getQueryAdapter(final String fieldName) {
MCRQueryAdapter adapter = MCRConfiguration2
.getOrThrow("MCR.Module-classbrowser.QueryAdapter", MCRConfiguration2::instantiateClass);
adapter.setFieldName(fieldName);
return adapter;
}
protected void configureQueryAdapter(MCRQueryAdapter queryAdapter, HttpServletRequest req) {
queryAdapter.configure(req);
}
@Override
public void doGetPost(MCRServletJob job) throws Exception {
LOGGER.info("ClassificationBrowser finished in {} ms.", MCRUtils.measure(() -> processRequest(job)).toMillis());
}
private void processRequest(MCRServletJob job) throws IOException, TransformerException, SAXException {
HttpServletRequest req = job.getRequest();
Settings settings = Settings.fromRequest(req);
LOGGER.info("ClassificationBrowser {}", settings);
MCRCategoryID id = settings.getCategID()
.map(categId -> new MCRCategoryID(settings.getClassifID(), categId))
.orElse(MCRCategoryID.rootID(settings.getClassifID()));
MCRCategory category = MCRCategoryDAOFactory.getInstance().getCategory(id, 1);
if (category == null) {
job.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, "Could not find category: " + id);
return;
}
Element xml = getClassificationBrowserData(req, settings, category);
renderToHTML(job, settings, xml);
}
private Element getClassificationBrowserData(HttpServletRequest req, Settings settings,
MCRCategory category) {
Element xml = new Element("classificationBrowserData");
xml.setAttribute("classification", settings.getClassifID());
xml.setAttribute("webpage", settings.getWebpage());
settings.getParameters().ifPresent(p -> xml.setAttribute("parameters", p));
Optional<MCRQueryAdapter> queryAdapter = configureQueryAdapter(req, settings, xml);
Function<MCRCategoryID, String> toIdSearchValue = settings.addClassId() ? MCRCategoryID::toString
: MCRCategoryID::getId;
List<Element> data = new ArrayList<>();
for (MCRCategory child : category.getChildren()) {
queryAdapter.ifPresent(qa -> qa.setCategory(toIdSearchValue.apply(child.getId())));
long numResults = queryAdapter
.filter(qa -> settings.countResults())
.map(MCRQueryAdapter::getResultCount)
.orElse(0L);
if ((settings.removeEmptyLeaves()) && (numResults < 1)) {
continue;
}
if (settings.excludeCategories().contains(child.getId().getId())) {
continue;
}
Element categoryE = getCategoryElement(child, numResults, settings);
queryAdapter.ifPresent(qa -> categoryE.setAttribute("query", qa.getQueryAsString()));
data.add(categoryE);
}
String objectType = queryAdapter.map(MCRQueryAdapter::getObjectType).orElse(null);
countLinks(settings, objectType, category, data);
sortCategories(settings.getSortBy(), data);
xml.addContent(data);
return xml;
}
private Element getCategoryElement(MCRCategory category, long numResults,
Settings settings) {
Element categoryE = new Element("category");
if (settings.countResults()) {
categoryE.setAttribute("numResults", String.valueOf(numResults));
}
categoryE.setAttribute("id", category.getId().getId());
categoryE.setAttribute("children", Boolean.toString(category.hasChildren()));
if (settings.addUri() && (category.getURI() != null)) {
categoryE.addContent(new Element("uri").setText(category.getURI().toString()));
}
addLabel(settings, category, categoryE);
return categoryE;
}
private Optional<MCRQueryAdapter> configureQueryAdapter(HttpServletRequest req, Settings settings, Element xml) {
if (settings.countResults() || settings.getField().isPresent()) {
MCRQueryAdapter queryAdapter = getQueryAdapter(settings.getField().orElse(null));
configureQueryAdapter(queryAdapter, req);
if (queryAdapter.getObjectType() != null) {
xml.setAttribute("objectType", queryAdapter.getObjectType());
}
return Optional.of(queryAdapter);
}
return Optional.empty();
}
/**
* Add label in current lang, otherwise default lang, optional with
* description
*/
private void addLabel(Settings settings, MCRCategory child, Element category) {
MCRLabel label = child.getCurrentLabel()
.orElseThrow(() -> new MCRException("Category " + child.getId() + " has no labels."));
category.addContent(new Element("label").setText(label.getText()));
// if true, add description
if (settings.addDescription() && (label.getDescription() != null)) {
category.addContent(new Element("description").setText(label.getDescription()));
}
}
/** Add link count to each category */
private void countLinks(Settings settings, String objectType, MCRCategory category,
List<Element> data) {
if (!settings.countLinks()) {
return;
}
String objType = objectType;
if (objType != null && objType.trim().length() == 0) {
objType = null;
}
String classifID = category.getId().getRootID();
Map<MCRCategoryID, Number> count = MCRCategLinkServiceFactory.getInstance().countLinksForType(category,
objType, true);
for (Iterator<Element> it = data.iterator(); it.hasNext();) {
Element child = it.next();
MCRCategoryID childID = new MCRCategoryID(classifID, child.getAttributeValue("id"));
int num = (count.containsKey(childID) ? count.get(childID).intValue() : 0);
child.setAttribute("numLinks", String.valueOf(num));
if ((settings.removeEmptyLeaves()) && (num < 1)) {
it.remove();
}
}
}
/** Sorts by id, by label in current language, or keeps natural order */
private void sortCategories(String sortBy, List<Element> data) {
switch (sortBy) {
case "id" -> data.sort(Comparator.comparing(e -> e.getAttributeValue("id")));
case "label" -> data.sort(Comparator.comparing(e -> e.getChildText("label"), String::compareToIgnoreCase));
default -> {
}
//no sort;
}
}
/** Sends output to client browser
*/
private void renderToHTML(MCRServletJob job, Settings settings, Element xml)
throws IOException, TransformerException,
SAXException {
settings.getStyle()
.ifPresent(style -> job.getRequest().setAttribute("XSL.Style", style)); // XSL.Style, optional
MCRServlet.getLayoutService().doLayout(job.getRequest(), job.getResponse(), new MCRJDOMContent(xml));
}
@Override
protected boolean allowCrossDomainRequests() {
return true;
}
public interface MCRQueryAdapter {
void setFieldName(String fieldname);
void setRestriction(String text);
void setCategory(String text);
String getObjectType();
void setObjectType(String text);
long getResultCount();
String getQueryAsString();
void configure(HttpServletRequest request);
}
private static class Settings {
private String classifID;
private String categID;
private boolean countResults;
private boolean addClassId;
private List<String> excludeCategories;
private boolean addUri;
private boolean removeEmptyLeaves;
private String webpage;
private String field;
private String parameters;
private boolean addDescription;
private boolean countLinks;
private String sortBy;
private String style;
static Settings fromRequest(HttpServletRequest req) {
Settings s = new Settings();
s.classifID = req.getParameter("classification");
s.categID = req.getParameter("category");
s.countResults = Boolean.parseBoolean(req.getParameter("countresults"));
s.addClassId = Boolean.parseBoolean(req.getParameter("addclassid"));
s.excludeCategories = Arrays.asList(
Optional.ofNullable(req.getParameter("excludeCategories")).orElse("").split(","));
s.addUri = Boolean.parseBoolean(req.getParameter("adduri"));
s.removeEmptyLeaves = !MCRUtils.filterTrimmedNotEmpty(req.getParameter("emptyleaves"))
.map(Boolean::valueOf)
.orElse(true);
s.webpage = req.getParameter("webpage");
s.field = req.getParameter("field");
s.parameters = req.getParameter("parameters");
s.addDescription = Boolean.parseBoolean(req.getParameter("adddescription"));
s.countLinks = Boolean.parseBoolean(req.getParameter("countlinks"));
s.sortBy = req.getParameter("sortby");
s.style = req.getParameter("style");
return s;
}
String getSortBy() {
return sortBy;
}
Optional<String> getStyle() {
return MCRUtils.filterTrimmedNotEmpty(style);
}
String getClassifID() {
return classifID;
}
Optional<String> getCategID() {
return MCRUtils.filterTrimmedNotEmpty(categID);
}
boolean countResults() {
return countResults;
}
boolean countLinks() {
return countLinks;
}
boolean addClassId() {
return addClassId;
}
List<String> excludeCategories() {
return excludeCategories;
}
boolean addUri() {
return addUri;
}
boolean removeEmptyLeaves() {
return removeEmptyLeaves;
}
boolean addDescription() {
return addDescription;
}
String getWebpage() {
return webpage;
}
Optional<String> getField() {
return MCRUtils.filterTrimmedNotEmpty(field);
}
Optional<String> getParameters() {
return MCRUtils.filterTrimmedNotEmpty(parameters);
}
@Override
public String toString() {
return "Settings{" +
"classifID='" + classifID + '\'' +
", categID='" + categID + '\'' +
", countResults=" + countResults +
", addClassId=" + addClassId +
", excludeCategories=" + excludeCategories +
", addUri=" + addUri +
", removeEmptyLeaves=" + removeEmptyLeaves +
", webpage='" + webpage + '\'' +
", field='" + field + '\'' +
", parameters='" + parameters + '\'' +
", addDescription=" + addDescription +
", countLinks=" + countLinks +
", sortBy='" + sortBy + '\'' +
", style='" + style + '\'' +
'}';
}
}
}
| 13,699 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSassCompilerManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sass/src/main/java/org/mycore/sass/MCRSassCompilerManager.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.sass;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.mycore.common.MCRException;
import org.mycore.common.MCRUtils;
import org.mycore.common.config.MCRConfiguration2;
import com.google.common.css.SourceCode;
import com.google.common.css.compiler.ast.GssParser;
import com.google.common.css.compiler.ast.GssParserException;
import com.google.common.css.compiler.passes.CompactPrinter;
import com.google.common.css.compiler.passes.NullGssSourceMapGenerator;
import de.larsgrefer.sass.embedded.SassCompilationFailedException;
import de.larsgrefer.sass.embedded.connection.ConnectionFactory;
import de.larsgrefer.sass.embedded.importer.Importer;
import jakarta.servlet.ServletContext;
/**
* Compiles .scss to .css or .min.css using different sources ({@link Importer}s)
*
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSassCompilerManager {
private static final String DEVELOPER_MODE_CONFIG_KEY = "MCR.SASS.DeveloperMode";
private Map<String, String> fileCompiledContentMap = new ConcurrentHashMap<>();
private Map<String, Date> fileLastCompileDateMap = new ConcurrentHashMap<>();
private Map<String, String> fileMD5Map = new ConcurrentHashMap<>();
/**
* @return the singleton instance of this class
*/
public static MCRSassCompilerManager getInstance() {
return MCRSASSCompilerManagerHolder.INSTANCE;
}
/**
* Gets the compiled(&compressed) CSS
*
* @param file the path to a .scss file. File should end with .css or .min.css (The compiler will look for the
* .scss file, then compiles and decides to minify or not).
* @param servletContext the servlet context to locate web resources
* @return Optional with the compiled css as string. Empty optional if the fileName is not valid.
* @throws SassCompilationFailedException if compiling sass input fails
* @throws IOException if communication with dart-sass or reading input fails
*/
public synchronized Optional<String> getCSSFile(String file, ServletContext servletContext)
throws IOException, SassCompilationFailedException {
if (!isDeveloperMode() && fileCompiledContentMap.containsKey(file)) {
return Optional.of(fileCompiledContentMap.get(file));
} else {
return Optional.ofNullable(compile(file, servletContext));
}
}
/**
* @param name the name of file
* @return the time when the specific file was compiled last time.
*/
public Optional<Date> getLastCompiled(String name) {
return Optional.ofNullable(fileLastCompileDateMap.get(name));
}
/**
* @param name the name of file
* @return the md5 hash of the last compiled specific file.
*/
public Optional<String> getLastMD5(String name) {
return Optional.ofNullable(fileMD5Map.get(name));
}
/**
* Just compiles a file and fills all maps.
*
* @param name the name of the file (with .min.css or .css ending)
* @return the compiled css
* @throws SassCompilationFailedException if compiling sass input fails
* @throws IOException if communication with dart-sass or reading input fails
*/
private String compile(String name, ServletContext servletContext)
throws IOException, SassCompilationFailedException {
String css;
try (MCRSassCompiler sassCompiler = new MCRSassCompiler(ConnectionFactory.bundled(), servletContext)) {
String realFileName = getRealFileName(name);
var compileSuccess = sassCompiler.compile(realFileName);
css = compileSuccess.getCss();
}
boolean compress = name.endsWith(".min.css");
if (compress) {
try {
GssParser parser = new GssParser(new SourceCode(null, css));
final CompactPrinter cp = new CompactPrinter(parser.parse(), new NullGssSourceMapGenerator());
cp.setPreserveMarkedComments(true);
cp.runPass();
css = cp.getCompactPrintedString();
} catch (GssParserException e) {
throw new MCRException("Error while parsing result css with compressor (" + name + ")", e);
}
}
this.fileCompiledContentMap.put(name, css);
this.fileLastCompileDateMap.put(name, new Date());
try {
this.fileMD5Map.put(name, MCRUtils.asMD5String(1, null, css));
} catch (NoSuchAlgorithmException e) {
throw new MCRException("Error while generating md5 of result css!", e);
}
return css;
}
/**
* Replaces {@code (.min).css} with {@code .scss}
* @param name filename a browser expects
* @return the filename available as a resource
*/
public static String getRealFileName(String name) {
return name.replace(".min.css", ".scss").replace(".css", ".scss");
}
/**
*
* @return true if the SASS compiler is run in developer mode
*/
public boolean isDeveloperMode() {
return MCRConfiguration2.getBoolean(DEVELOPER_MODE_CONFIG_KEY).orElse(false);
}
private static final class MCRSASSCompilerManagerHolder {
public static final MCRSassCompilerManager INSTANCE = new MCRSassCompilerManager();
}
}
| 6,239 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRResourceImporter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sass/src/main/java/org/mycore/sass/MCRResourceImporter.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.sass;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRDeveloperTools;
import org.mycore.common.config.MCRConfigurationDir;
import com.google.protobuf.ByteString;
import com.sass_lang.embedded_protocol.InboundMessage.ImportResponse.ImportSuccess;
import de.larsgrefer.sass.embedded.importer.CustomImporter;
import de.larsgrefer.sass.embedded.importer.CustomUrlImporter;
import de.larsgrefer.sass.embedded.util.SyntaxUtil;
import jakarta.servlet.ServletContext;
/**
* The MCRResourceImporter class is responsible for importing resources from URLs that start with the "sass:/" prefix.
*/
public class MCRResourceImporter extends CustomImporter {
private static final Logger LOGGER = LogManager.getLogger();
static final String SASS_URL_PREFIX = "sass:/";
private final ServletContext servletContext;
private static final UrlHelper URL_HELPER = new UrlHelper();
/**
* Initializes a new instance of the MCRResourceImporter class.
*
* @param servletContext The ServletContext used for importing resources.
*/
public MCRResourceImporter(ServletContext servletContext) {
this.servletContext = servletContext;
}
/**
* Canonicalizes the given URL of the import and determines if it is from an `@import` rule.
* <br>
* This method takes a URL as input and checks if it starts with the "sass:/" prefix. If it does,
* it removes the prefix and attempts to locate the resource URL using the getWebResourceUrl() method. If the
* resource URL is found and is a file, it returns the original URL; otherwise, it returns null
*
* @param url The URL of the import to be canonicalized. This may be either absolute or relative.
* @param fromImport Whether this request comes from an `@import` rule.
* @return The canonicalized URL if it starts with "sass:/" and the resource exists, otherwise null.
* @throws Exception If an error occurs during the canonicalization process.
*/
@Override
public String canonicalize(String url, boolean fromImport) throws Exception {
LOGGER.debug(() -> "handle canonicalize: " + url);
URL sassResourceURL = toURL(url);
if (sassResourceURL == null || sassResourceURL.getFile().endsWith("/") || !URL_HELPER.isFile(sassResourceURL)) {
//with jetty the directory does not end with /, so we need to REAL check
return null;
}
LOGGER.debug("Resolved {} to {}", url, sassResourceURL);
return sassResourceURL == null ? null : url;
}
/**
* Handles the import of a URL and returns the success of the import along with its content.
* <br>
* This method takes a URL as input and checks if it starts with the "sass:/" prefix. If it does,
* it attempts to locate the resource URL. If the resource URL is found,
* it reads its content returns the an ImportSuccess object.
*
* @param url The URL of the resource to import.
* @return An ImportSuccess object containing the content and syntax of the imported resource.
* @throws IOException If there is an error in handling the import.
*/
@Override
public ImportSuccess handleImport(String url) throws IOException {
LOGGER.debug(() -> "handle import: " + url);
URL sassResourceURL = toURL(url);
if (sassResourceURL == null) {
return null;
}
LOGGER.debug(() -> "resource url: " + sassResourceURL);
ImportSuccess.Builder result = ImportSuccess.newBuilder();
URLConnection urlConnection = sassResourceURL.openConnection();
try (InputStream in = urlConnection.getInputStream()) {
ByteString content = ByteString.readFrom(in);
result.setContentsBytes(content);
result.setSyntax(SyntaxUtil.guessSyntax(urlConnection));
}
return result.build();
}
private URL toURL(String url) {
if (!url.startsWith(SASS_URL_PREFIX)) {
return null;
}
String resourcePath = url.substring(SASS_URL_PREFIX.length());
URL configResource = getWebResourceUrl(resourcePath);
return configResource;
}
/**
* Retrieves the URL of a web resource given its path.
*
* @param resourcePath The path of the web resource to retrieve.
* @return The URL of the web resource.
*/
private URL getWebResourceUrl(String resourcePath) {
return MCRDeveloperTools.getOverriddenFilePath(resourcePath, true)
.map(p -> {
try {
return p.toUri().toURL();
} catch (MalformedURLException e) {
throw new UncheckedIOException(e);
}
})
.or(() -> Optional.ofNullable(MCRConfigurationDir.getConfigResource("META-INF/resources/" + resourcePath)))
.orElseGet(() -> {
try {
return servletContext.getResource("/" + resourcePath);
} catch (MalformedURLException e) {
throw new UncheckedIOException(e);
}
});
}
/**
* Helper class for working with URLs.
*
* Exposes {@link CustomUrlImporter#isFile(URL)} as a utility method for internal use.
*/
private static class UrlHelper extends CustomUrlImporter {
@Override
public URL canonicalizeUrl(String url) throws Exception {
return null;
}
@Override
public boolean isFile(URL url) throws IOException {
return super.isFile(url);
}
}
}
| 6,629 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSassCompiler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sass/src/main/java/org/mycore/sass/MCRSassCompiler.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.sass;
import java.io.Closeable;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.protobuf.ByteString;
import com.sass_lang.embedded_protocol.InboundMessage;
import com.sass_lang.embedded_protocol.InboundMessage.CanonicalizeResponse;
import com.sass_lang.embedded_protocol.InboundMessage.CompileRequest;
import com.sass_lang.embedded_protocol.InboundMessage.FunctionCallResponse;
import com.sass_lang.embedded_protocol.InboundMessage.ImportResponse;
import com.sass_lang.embedded_protocol.InboundMessage.ImportResponse.ImportSuccess;
import com.sass_lang.embedded_protocol.OutboundMessage;
import com.sass_lang.embedded_protocol.OutboundMessage.CanonicalizeRequest;
import com.sass_lang.embedded_protocol.OutboundMessage.FunctionCallRequest;
import com.sass_lang.embedded_protocol.OutboundMessage.ImportRequest;
import com.sass_lang.embedded_protocol.OutputStyle;
import com.sass_lang.embedded_protocol.Syntax;
import de.larsgrefer.sass.embedded.CompileSuccess;
import de.larsgrefer.sass.embedded.SassCompilationFailedException;
import de.larsgrefer.sass.embedded.SassProtocolErrorException;
import de.larsgrefer.sass.embedded.connection.CompilerConnection;
import de.larsgrefer.sass.embedded.connection.Packet;
import de.larsgrefer.sass.embedded.importer.CustomImporter;
import de.larsgrefer.sass.embedded.importer.Importer;
import de.larsgrefer.sass.embedded.logging.Log4jLoggingHandler;
import de.larsgrefer.sass.embedded.logging.LoggingHandler;
import de.larsgrefer.sass.embedded.util.ProtocolUtil;
import jakarta.servlet.ServletContext;
/**
* A forked version of {@link de.larsgrefer.sass.embedded.SassCompiler} to support inputs from different artifacts.
*/
class MCRSassCompiler implements Closeable {
private static final Logger LOGGER = LogManager.getLogger();
private final ServletContext servletContext;
private OutputStyle outputStyle;
private boolean generateSourceMaps;
private boolean alertColor;
private boolean alertAscii;
private boolean verbose;
private boolean quietDeps;
private boolean sourceMapIncludeSources;
private boolean emitCharset;
private final CompilerConnection connection;
private static final AtomicInteger COMPILE_REQUEST_IDS = new AtomicInteger();
private final Map<Integer, CustomImporter> customImporters;
private LoggingHandler loggingHandler;
MCRSassCompiler(CompilerConnection connection, ServletContext servletContext) {
this.outputStyle = OutputStyle.EXPANDED;
this.generateSourceMaps = false;
this.alertColor = false;
this.alertAscii = false;
this.verbose = false;
this.quietDeps = false;
this.sourceMapIncludeSources = false;
this.emitCharset = false;
this.customImporters = new HashMap<>();
this.loggingHandler = new Log4jLoggingHandler(LOGGER);
this.connection = connection;
this.servletContext = servletContext;
}
protected CompileRequest.Builder compileRequestBuilder() {
CompileRequest.Builder builder = CompileRequest.newBuilder();
builder.setStyle(outputStyle);
builder.setSourceMap(generateSourceMaps);
for (Importer value : customImporters.values()) {
CompileRequest.Importer importer = CompileRequest.Importer.newBuilder()
.setImporterId(value.getId())
.build();
builder.addImporters(importer);
}
builder.setAlertColor(alertColor);
builder.setAlertAscii(alertAscii);
builder.setVerbose(verbose);
builder.setQuietDeps(quietDeps);
builder.setSourceMapIncludeSources(sourceMapIncludeSources);
builder.setCharset(emitCharset);
return builder;
}
public CompileSuccess compile(String realFileName)
throws SassCompilationFailedException, IOException {
return this.compile(Objects.requireNonNull(realFileName), this.outputStyle);
}
public CompileSuccess compile(String realFileName, OutputStyle outputStyle)
throws SassCompilationFailedException, IOException {
String ourURL = MCRResourceImporter.SASS_URL_PREFIX + realFileName;
MCRResourceImporter importer = new MCRResourceImporter(servletContext);
ImportSuccess importSuccess = importer.handleImport(ourURL);
Syntax syntax = importSuccess.getSyntax();
ByteString content = importSuccess.getContentsBytes();
customImporters.put(importer.getId(), importer.autoCanonicalize());
CompileRequest.StringInput build = CompileRequest.StringInput.newBuilder()
.setUrl(ourURL)
.setSourceBytes(content)
.setImporter(CompileRequest.Importer.newBuilder()
.setImporterId(importer.getId())
.build())
.setSyntax(syntax)
.build();
try {
return compileString(build, outputStyle);
} finally {
customImporters.remove(importer.getId());
}
}
public CompileSuccess compileString(CompileRequest.StringInput string, OutputStyle outputStyle)
throws IOException, SassCompilationFailedException {
CompileRequest compileRequest = this.compileRequestBuilder()
.setString(string)
.setStyle(Objects.requireNonNull(outputStyle))
.build();
return this.execCompileRequest(compileRequest);
}
private CompileSuccess execCompileRequest(CompileRequest compileRequest)
throws IOException, SassCompilationFailedException {
OutboundMessage outboundMessage = exec(ProtocolUtil.inboundMessage(compileRequest));
if (!outboundMessage.hasCompileResponse()) {
throw new IllegalStateException("No compile response");
}
OutboundMessage.CompileResponse compileResponse = outboundMessage.getCompileResponse();
if (compileResponse.hasSuccess()) {
return new CompileSuccess(compileResponse);
} else if (compileResponse.hasFailure()) {
throw new SassCompilationFailedException(compileResponse);
} else {
throw new IllegalStateException("Neither success nor failure");
}
}
private OutboundMessage exec(InboundMessage inboundMessage) throws IOException {
int compilationId;
if (inboundMessage.hasVersionRequest()) {
compilationId = 0;
} else if (inboundMessage.hasCompileRequest()) {
compilationId = Math.abs(COMPILE_REQUEST_IDS.incrementAndGet());
} else {
throw new IllegalArgumentException("Invalid message type: " + inboundMessage.getMessageCase());
}
Packet<InboundMessage> request = new Packet<>(compilationId, inboundMessage);
synchronized (this.connection) {
this.connection.sendMessage(request);
while (true) {
Packet<OutboundMessage> response = connection.readResponse();
if (response.getCompilationId() != compilationId) {
//Should never happen
throw new IllegalStateException(
String.format(Locale.ENGLISH, "Compilation ID mismatch: expected %d, but got %d", compilationId,
response.getCompilationId()));
}
OutboundMessage outboundMessage = response.getMessage();
switch (outboundMessage.getMessageCase()) {
case ERROR -> throw new SassProtocolErrorException(outboundMessage.getError());
case COMPILE_RESPONSE, VERSION_RESPONSE -> {
return outboundMessage;
}
case LOG_EVENT -> this.loggingHandler.handle(outboundMessage.getLogEvent());
case CANONICALIZE_REQUEST -> this.handleCanonicalizeRequest(compilationId,
outboundMessage.getCanonicalizeRequest());
case IMPORT_REQUEST -> this.handleImportRequest(compilationId, outboundMessage.getImportRequest());
case FILE_IMPORT_REQUEST -> throw new IllegalStateException(
"No file import request supported: " + outboundMessage.getFileImportRequest().getUrl());
case FUNCTION_CALL_REQUEST -> this.handleFunctionCallRequest(compilationId,
outboundMessage.getFunctionCallRequest());
case MESSAGE_NOT_SET -> throw new IllegalStateException("No message set");
default -> throw new IllegalStateException(
"Unknown OutboundMessage: " + outboundMessage.getMessageCase());
}
}
}
}
private void handleImportRequest(int compilationId, ImportRequest importRequest) throws IOException {
ImportResponse.Builder importResponse = ImportResponse.newBuilder()
.setId(importRequest.getId());
CustomImporter customImporter = customImporters.get(importRequest.getImporterId());
try {
ImportSuccess success = customImporter.handleImport(importRequest.getUrl());
if (success != null) {
importResponse.setSuccess(success);
}
} catch (Exception t) {
LOGGER.debug("Failed to handle ImportRequest {}", importRequest, t);
importResponse.setError(getErrorMessage(t));
}
connection.sendMessage(compilationId, ProtocolUtil.inboundMessage(importResponse.build()));
}
private void handleCanonicalizeRequest(int compilationId, CanonicalizeRequest canonicalizeRequest)
throws IOException {
CanonicalizeResponse.Builder canonicalizeResponse = CanonicalizeResponse.newBuilder()
.setId(canonicalizeRequest.getId());
CustomImporter customImporter = customImporters.get(canonicalizeRequest.getImporterId());
try {
String canonicalize = customImporter.canonicalize(canonicalizeRequest.getUrl(),
canonicalizeRequest.getFromImport());
if (canonicalize != null) {
canonicalizeResponse.setUrl(canonicalize);
}
} catch (Exception e) {
LOGGER.debug("Failed to handle CanonicalizeRequest {}", canonicalizeRequest, e);
canonicalizeResponse.setError(getErrorMessage(e));
}
connection.sendMessage(compilationId, ProtocolUtil.inboundMessage(canonicalizeResponse.build()));
}
private void handleFunctionCallRequest(int compilationId, FunctionCallRequest functionCallRequest)
throws IOException {
FunctionCallResponse.Builder response = FunctionCallResponse.newBuilder()
.setId(functionCallRequest.getId());
try {
switch (functionCallRequest.getIdentifierCase()) {
case NAME -> throw new UnsupportedOperationException(
"Calling function " + functionCallRequest.getName() + " is not supported");
case FUNCTION_ID -> throw new UnsupportedOperationException("Calling functions by ID is not supported");
case IDENTIFIER_NOT_SET -> throw new IllegalArgumentException("FunctionCallRequest has no identifier");
default -> throw new UnsupportedOperationException(
"Unsupported external function identifier case: " + functionCallRequest.getIdentifierCase());
}
} catch (Exception e) {
LOGGER.debug("Failed to handle FunctionCallRequest", e);
response.setError(getErrorMessage(e));
}
connection.sendMessage(compilationId, ProtocolUtil.inboundMessage(response.build()));
}
private String getErrorMessage(Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
public void close() throws IOException {
this.connection.close();
}
}
| 12,996 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSassResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sass/src/main/java/org/mycore/sass/resources/MCRSassResource.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.sass.resources;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import org.mycore.frontend.jersey.MCRStaticContent;
import org.mycore.sass.MCRSassCompilerManager;
import de.larsgrefer.sass.embedded.SassCompilationFailedException;
import jakarta.servlet.ServletContext;
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.CacheControl;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.EntityTag;
import jakarta.ws.rs.core.Request;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.StreamingOutput;
/**
* Resource to deliver CSS files compiled by SASS
*/
@Path("/sass/")
@MCRStaticContent
public class MCRSassResource {
private static final int SECONDS_OF_ONE_DAY = 60 * 60 * 24;
@Context
ServletContext context;
/**
* return the compiled CSS
* @param name - the name of file
* @param request - the Http request
* @return the response object
*/
@GET
@Path("{fileName:.+}")
@Produces("text/css")
public Response getCSS(@PathParam("fileName") String name, @Context Request request) {
try {
final String fileName = MCRSassCompilerManager.getRealFileName(name);
Optional<String> cssFile = MCRSassCompilerManager.getInstance()
.getCSSFile(name, context);
if (cssFile.isPresent()) {
CacheControl cc = new CacheControl();
cc.setMaxAge(SECONDS_OF_ONE_DAY);
String etagString = MCRSassCompilerManager.getInstance().getLastMD5(name).get();
EntityTag etag = new EntityTag(etagString);
Response.ResponseBuilder builder = request.evaluatePreconditions(etag);
if (builder != null) {
return builder.cacheControl(cc).tag(etag).build();
}
return Response.ok().status(Response.Status.OK)
.cacheControl(cc)
.tag(etag)
.entity(cssFile.get())
.build();
} else {
return Response.status(Response.Status.NOT_FOUND)
.build();
}
} catch (IOException | SassCompilationFailedException e) {
StreamingOutput so = (OutputStream os) -> e.printStackTrace(new PrintStream(os, true,
StandardCharsets.UTF_8));
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(so).build();
}
}
}
| 3,405 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDeleteFileOnCloseFilterInputStream.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/MCRDeleteFileOnCloseFilterInputStream.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.sword;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class MCRDeleteFileOnCloseFilterInputStream extends FilterInputStream {
private static final Logger LOGGER = LogManager.getLogger();
private final Path fileToDelete;
public MCRDeleteFileOnCloseFilterInputStream(InputStream source, Path fileToDelete) {
super(source);
this.fileToDelete = fileToDelete;
}
@Override
public void close() throws IOException {
try {
in.close();
} catch (IOException e) {
throw e;
} finally {
LOGGER.info("Delete File : {}", fileToDelete);
Files.delete(fileToDelete);
}
}
}
| 1,620 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordContainerHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/MCRSwordContainerHandler.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.sword;
import java.util.Map;
import java.util.Optional;
import org.mycore.access.MCRAccessException;
import org.mycore.common.MCRException;
import org.mycore.datamodel.common.MCRActiveLinkException;
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.sword.application.MCRSwordCollectionProvider;
import org.mycore.sword.application.MCRSwordLifecycle;
import org.mycore.sword.application.MCRSwordLifecycleConfiguration;
import org.swordapp.server.Deposit;
import org.swordapp.server.DepositReceipt;
import org.swordapp.server.SwordError;
import org.swordapp.server.SwordServerException;
/**
* Handles request made to the Edit-IRI.
*
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSwordContainerHandler implements MCRSwordLifecycle {
private MCRSwordLifecycleConfiguration lifecycleConfiguration;
public DepositReceipt addObject(Deposit deposit) throws SwordError, SwordServerException {
final MCRSwordCollectionProvider collection = MCRSword
.getCollection(this.lifecycleConfiguration.getCollection());
final MCRObjectID idOfIngested = collection.getIngester().ingestMetadata(deposit);
final MCRObject createdObject = (MCRObject) MCRMetadataManager.retrieve(idOfIngested);
return collection.getMetadataProvider().provideMetadata(createdObject);
}
public DepositReceipt addObjectWithDerivate(String objectIdString, Deposit deposit)
throws SwordError, SwordServerException {
final MCRSwordCollectionProvider collection = MCRSword
.getCollection(this.lifecycleConfiguration.getCollection());
final MCRObjectID idOfIngested = collection.getIngester().ingestMetadataResources(deposit);
final MCRObject createdObject = (MCRObject) MCRMetadataManager.retrieve(idOfIngested);
return collection.getMetadataProvider().provideMetadata(createdObject);
}
public DepositReceipt addMetadata(MCRObject object, Deposit deposit) throws SwordError, SwordServerException {
final MCRSwordCollectionProvider collection = MCRSword
.getCollection(this.lifecycleConfiguration.getCollection());
collection.getIngester().updateMetadata(object, deposit, false);
return collection.getMetadataProvider().provideMetadata(object);
}
/**
* Replaces the metadata of an existing object.
* @param object The object with the metadata to replace
* @param deposit the deposit with the new metadata
* @return a new {@link DepositReceipt} with the new metadata
*/
public DepositReceipt replaceMetadata(MCRObject object, Deposit deposit) throws SwordError, SwordServerException {
final MCRSwordCollectionProvider collection = MCRSword
.getCollection(this.lifecycleConfiguration.getCollection());
collection.getIngester().updateMetadata(object, deposit, true);
return collection.getMetadataProvider().provideMetadata(object);
}
public DepositReceipt replaceMetadataAndResources(MCRObject object, Deposit deposit)
throws SwordError, SwordServerException {
final MCRSwordCollectionProvider collection = MCRSword
.getCollection(this.lifecycleConfiguration.getCollection());
collection.getIngester().updateMetadataResources(object, deposit);
return collection.getMetadataProvider().provideMetadata(object);
}
public DepositReceipt addResources(MCRObject object, Deposit deposit) throws SwordError, SwordServerException {
final MCRSwordCollectionProvider collection = MCRSword
.getCollection(this.lifecycleConfiguration.getCollection());
collection.getIngester().ingestResource(object, deposit);
return collection.getMetadataProvider().provideMetadata(object);
}
/**
* This method should add metadata to the receipt. The are the more important Metadata.
*
* @param object the MyCoReObject
* @param accept the accept header of the HTTP-Request
*/
public DepositReceipt getMetadata(String collectionString, MCRObject object, Optional<Map<String, String>> accept)
throws SwordError {
return MCRSword.getCollection(collectionString).getMetadataProvider().provideMetadata(object);
}
public void deleteObject(MCRObject object) throws SwordServerException {
try {
object
.getStructure()
.getDerivates()
.stream()
.map(MCRMetaLinkID::getXLinkHrefID)
.forEach(id -> {
try {
MCRMetadataManager.deleteMCRDerivate(id);
} catch (Exception e) {
throw new MCRException(e);
}
});
MCRMetadataManager.delete(object);
} catch (MCRActiveLinkException | MCRAccessException | MCRException e) {
Throwable ex = e;
if (e instanceof MCRException && Optional.ofNullable(e.getCause()).map(Object::getClass)
.filter(MCRAccessException.class::isAssignableFrom).isPresent()) {
//unwrapp
ex = e.getCause();
}
throw new SwordServerException("Error while deleting Object.", ex);
}
}
@Override
public void init(MCRSwordLifecycleConfiguration lifecycleConfiguration) {
this.lifecycleConfiguration = lifecycleConfiguration;
}
@Override
public void destroy() {
}
}
| 6,399 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordConstants.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/MCRSwordConstants.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.sword;
import org.mycore.common.config.MCRConfiguration2;
/**
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSwordConstants {
public static final String SWORD2_COL_IRI = "sword2/col/";
public static final String SWORD2_EDIT_MEDIA_IRI = "sword2/edit-media/";
public static final String SWORD2_EDIT_IRI = "sword2/edit/";
public static final String SWORD2_EDIT_MEDIA_REL = "edit-media";
public static final String SWORD2_EDIT_REL = "edit";
public static final Integer MAX_ENTRYS_PER_PAGE = MCRConfiguration2
.getOrThrow("MCR.SWORD.Page.Object.Count", Integer::parseInt);
public static final String MCR_SWORD_COLLECTION_PREFIX = "MCR.Sword.Collection.";
public static final String MIME_TYPE_APPLICATION_ZIP = "application/zip";
public static final String MIME_TYPE_TEXT_XML = "text/xml";
}
| 1,599 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordMultiPartServletDeployer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/MCRSwordMultiPartServletDeployer.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.sword;
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 java.util.List;
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 org.mycore.sword.servlets.MCRSwordCollectionServlet;
import jakarta.servlet.MultipartConfigElement;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletRegistration.Dynamic;
import jakarta.servlet.http.HttpServlet;
/**
* Uses <code>mycore.properties</code> to configure {@link org.mycore.sword.servlets.MCRSwordCollectionServlet},
* {@link org.mycore.sword.servlets.MCRSwordContainerServlet} and
* {@link org.mycore.sword.servlets.MCRSwordMediaResourceServlet}.
* @author Thomas Scheffler (yagee)
*
*/
public class MCRSwordMultiPartServletDeployer implements AutoExecutable {
private static final String UPLOAD_TEMP_STORAGE_PATH = "MCR.SWORD.FileUpload.TempStoragePath";
private static final List<ServletConfig> MULTIPART_SERVLETS = List.of(
new ServletConfig("MCRSword2CollectionServlet", "/sword2/col/*", MCRSwordCollectionServlet.class),
new ServletConfig("MCRSword2ContainerServlet", "/sword2/edit/*", MCRSwordCollectionServlet.class),
new ServletConfig("MCRSword2MediaResourceServlet", "/sword2/edit-media/*", MCRSwordCollectionServlet.class));
/* (non-Javadoc)
* @see org.mycore.common.events.MCRStartupHandler.AutoExecutable#getName()
*/
@Override
public String getName() {
return "mycore-sword Servlet 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) {
MultipartConfigElement multipartConfig = getMultipartConfig();
try {
checkTempStoragePath(multipartConfig.getLocation());
} catch (IOException e) {
throw new MCRConfigurationException("Could not setup mycore-sword servlets!", e);
}
MULTIPART_SERVLETS.forEach(config -> {
LogManager.getLogger()
.info(() -> "Mapping " + config.name + " (" + config.servletClass.getName() + ") to url "
+ config.urlMapping);
Dynamic uploadServlet = servletContext.addServlet(config.name, config.servletClass);
uploadServlet.addMapping(config.urlMapping);
uploadServlet.setMultipartConfig(multipartConfig);
});
}
}
private void checkTempStoragePath(String location) throws IOException {
Path targetDir = Paths.get(location);
if (!targetDir.isAbsolute()) {
throw new MCRConfigurationException(
"'" + 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(UPLOAD_TEMP_STORAGE_PATH);
long maxFileSize = MCRConfiguration2.getOrThrow("MCR.SWORD.FileUpload.MaxSize", Long::parseLong);
int fileSizeThreshold = MCRConfiguration2.getOrThrow("MCR.SWORD.FileUpload.MemoryThreshold",
Integer::parseInt);
LogManager.getLogger().info(
() -> "mycore-sword 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);
}
//TODO use Record with JDK17
private static class ServletConfig {
String name;
String urlMapping;
Class<? extends HttpServlet> servletClass;
ServletConfig(String name, String urlMapping, Class<? extends HttpServlet> servletClass) {
this.name = name;
this.urlMapping = urlMapping;
this.servletClass = servletClass;
}
}
}
| 5,497 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSword.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/MCRSword.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.sword;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
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.config.MCRConfiguration2;
import org.mycore.sword.application.MCRSwordCollectionProvider;
import org.mycore.sword.application.MCRSwordLifecycleConfiguration;
/**
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSword {
private static Logger LOGGER = LogManager.getLogger(MCRSword.class);
private static Hashtable<String, MCRSwordCollectionProvider> collections = null;
private static Hashtable<String, List<String>> workspaceCollectionTable = null;
private static void initConfig() {
if (collections == null) {
collections = new Hashtable<>();
workspaceCollectionTable = new Hashtable<>();
LOGGER.info("--- INITIALIZE SWORD SERVER ---");
final int lenghtOfPropertyPrefix = MCRSwordConstants.MCR_SWORD_COLLECTION_PREFIX.length();
MCRConfiguration2.getPropertiesMap()
.keySet()
.stream()
.filter(prop -> prop.startsWith(MCRSwordConstants.MCR_SWORD_COLLECTION_PREFIX))
.map(prop -> prop.substring(lenghtOfPropertyPrefix)) // remove MCR_SWORD_COLLECTION_PREFIX
.map(prop -> prop.split(Pattern.quote("."), 2)) // split to workspace name and collection name
.filter(
array -> array.length == 2) // remove all whith no workspace or collection name
.forEach(wsCol -> initWorkspaceCollection(wsCol[0], wsCol[1]));
addCollectionShutdownHook();
}
}
private static void initWorkspaceCollection(String workspace, String collection) {
LOGGER.info("Found collection: {} in workspace {}", collection, workspace);
String name = MCRSwordConstants.MCR_SWORD_COLLECTION_PREFIX + workspace + "." + collection;
LOGGER.info("Try to init : {}", name);
MCRSwordCollectionProvider collectionProvider = MCRConfiguration2
.getOrThrow(name, MCRConfiguration2::instantiateClass);
collections.put(collection, collectionProvider);
final MCRSwordLifecycleConfiguration lifecycleConfiguration = new MCRSwordLifecycleConfiguration(collection);
collectionProvider.init(lifecycleConfiguration);
List<String> collectionsOfWorkspace;
if (workspaceCollectionTable.containsKey(workspace)) {
collectionsOfWorkspace = workspaceCollectionTable.get(workspace);
} else {
collectionsOfWorkspace = new ArrayList<>();
workspaceCollectionTable.put(workspace, collectionsOfWorkspace);
}
collectionsOfWorkspace.add(collection);
}
private static void addCollectionShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
LOGGER.info("Shutdown Sword Collections");
collections.values().forEach(MCRSwordCollectionProvider::destroy);
}));
}
public static MCRSwordCollectionProvider getCollection(String collectionName) {
initConfig();
return collections.get(collectionName);
}
public static List<String> getCollectionNames() {
initConfig();
return new ArrayList<>(collections.keySet());
}
public static List<String> getWorkspaces() {
initConfig();
return workspaceCollectionTable.keySet().stream().collect(Collectors.toUnmodifiableList());
}
public static List<String> getCollectionsOfWorkspace(String workspace) {
initConfig();
return Collections.unmodifiableList(workspaceCollectionTable.get(workspace));
}
}
| 4,575 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordConfigurationDefault.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/MCRSwordConfigurationDefault.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.sword;
import org.mycore.common.config.MCRConfiguration2;
import org.swordapp.server.SwordConfiguration;
/**
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSwordConfigurationDefault implements SwordConfiguration {
@Override
public boolean returnDepositReceipt() {
return true;
}
@Override
public boolean returnStackTraceInError() {
return true;
}
@Override
public boolean returnErrorBody() {
return true;
}
@Override
public String generator() {
return MCRConfiguration2.getStringOrThrow("MCR.SWORD.Generator.Content");
}
@Override
public String generatorVersion() {
return MCRConfiguration2.getStringOrThrow("MCR.SWORD.Generator.Version");
}
@Override
public String administratorEmail() {
return MCRConfiguration2.getStringOrThrow("MCR.SWORD.Administrator.Mail");
}
@Override
public String getAuthType() {
return MCRConfiguration2.getString("MCR.SWORD.Auth.Method").orElse("Basic");
}
@Override
public boolean storeAndCheckBinary() {
return false; // MCR code stores files and checks files..
}
@Override
public String getTempDirectory() {
return MCRConfiguration2.getString("MCR.SWORD.TempDirectory").orElse(System.getProperty("java.io.tmpdir"));
}
@Override
public long getMaxUploadSize() {
return MCRConfiguration2.getOrThrow("MCR.SWORD.Max.Uploaded.File.Size", Long::parseLong);
}
@Override
public String getAlternateUrl() {
return null;
}
@Override
public String getAlternateUrlContentType() {
return null;
}
@Override
public boolean allowUnauthenticatedMediaAccess() {
return false;
}
}
| 2,525 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordUtil.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/MCRSwordUtil.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.sword;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.DirectoryStream;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
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.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import java.util.zip.Deflater;
import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.model.Link;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
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.common.MCRException;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTransactionHelper;
import org.mycore.common.MCRUtils;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.xml.MCRXMLFunctions;
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.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.metadata.MCRObjectService;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.sword.application.MCRSwordCollectionProvider;
import org.mycore.sword.application.MCRSwordObjectIDSupplier;
import org.swordapp.server.DepositReceipt;
import org.swordapp.server.MediaResource;
import org.swordapp.server.SwordServerException;
import org.swordapp.server.UriRegistry;
public class MCRSwordUtil {
private static final int COPY_BUFFER_SIZE = 32 * 1024;
private static Logger LOGGER = LogManager.getLogger(MCRSwordUtil.class);
public static MCRDerivate createDerivate(String documentID)
throws MCRPersistenceException, IOException, MCRAccessException {
final String projectId = MCRObjectID.getInstance(documentID).getProjectId();
MCRObjectID oid = MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(projectId, "derivate");
final String derivateID = oid.toString();
MCRDerivate derivate = new MCRDerivate();
derivate.setId(oid);
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 {}", derivateID);
MCRMetadataManager.create(derivate);
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");
}
}
final MCRPath rootDir = MCRPath.getPath(derivateID, "/");
if (Files.notExists(rootDir)) {
rootDir.getFileSystem().createRoot(derivateID);
}
return derivate;
}
public static MediaResource getZippedDerivateMediaResource(String object) {
final Path tempFile;
try {
tempFile = Files.createTempFile("swordv2_", ".temp.zip");
} catch (IOException e) {
throw new MCRException("Could not create temp file!", e);
}
try (OutputStream tempFileStream = Files.newOutputStream(tempFile);
ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(tempFileStream)) {
zipOutputStream.setLevel(Deflater.BEST_COMPRESSION);
final MCRPath root = MCRPath.getPath(object, "/");
addDirectoryToZip(zipOutputStream, root);
} catch (IOException e) {
throw new MCRException(e);
}
MediaResource resultRessource;
InputStream is;
try {
is = new MCRDeleteFileOnCloseFilterInputStream(Files.newInputStream(tempFile), tempFile);
resultRessource = new MediaResource(is, MCRSwordConstants.MIME_TYPE_APPLICATION_ZIP,
UriRegistry.PACKAGE_SIMPLE_ZIP);
} catch (IOException e) {
throw new MCRException("could not read from temp file!", e);
}
return resultRessource;
}
private static void addDirectoryToZip(ZipArchiveOutputStream zipOutputStream, Path directory) {
MCRSession currentSession = MCRSessionMgr.getCurrentSession();
try (DirectoryStream<Path> paths = Files.newDirectoryStream(directory)) {
paths.forEach(p -> {
final boolean isDir = Files.isDirectory(p);
final ZipArchiveEntry zipArchiveEntry;
try {
final String fileName = getFilename(p);
LOGGER.info("Addding {} to zip file!", fileName);
if (isDir) {
addDirectoryToZip(zipOutputStream, p);
} else {
zipArchiveEntry = new ZipArchiveEntry(fileName);
zipArchiveEntry.setSize(Files.size(p));
zipOutputStream.putArchiveEntry(zipArchiveEntry);
if (MCRTransactionHelper.isTransactionActive()) {
MCRTransactionHelper.commitTransaction();
}
Files.copy(p, zipOutputStream);
MCRTransactionHelper.beginTransaction();
zipOutputStream.closeArchiveEntry();
}
} catch (IOException e) {
LOGGER.error("Could not add path {}", p);
}
});
} catch (IOException e) {
throw new MCRException(e);
}
}
public static String getFilename(Path path) {
return '/' + path.getRoot().relativize(path).toString();
}
/**
* Stores stream to temp file and checks md5
*
* @param inputStream the stream which holds the File
* @param checkMd5 the md5 to compare with (or null if no md5 check is needed)
* @return the path to the temp file
* @throws IOException if md5 does mismatch or if stream could not be read
*/
public static Path createTempFileFromStream(String fileName, InputStream inputStream, String checkMd5)
throws IOException {
MCRSession currentSession = MCRSessionMgr.getCurrentSession();
if (MCRTransactionHelper.isTransactionActive()) {
MCRTransactionHelper.commitTransaction();
}
final Path zipTempFile = Files.createTempFile("swordv2_", fileName);
MessageDigest md5Digest = null;
if (checkMd5 != null) {
try {
md5Digest = MessageDigest.getInstance("MD5");
inputStream = new DigestInputStream(inputStream, md5Digest);
} catch (NoSuchAlgorithmException e) {
MCRTransactionHelper.beginTransaction();
throw new MCRConfigurationException("No MD5 available!", e);
}
}
Files.copy(inputStream, zipTempFile, StandardCopyOption.REPLACE_EXISTING);
if (checkMd5 != null) {
final String md5String = MCRUtils.toHexString(md5Digest.digest());
if (!md5String.equals(checkMd5)) {
MCRTransactionHelper.beginTransaction();
throw new IOException("MD5 mismatch, expected " + checkMd5 + " got " + md5String);
}
}
MCRTransactionHelper.beginTransaction();
return zipTempFile;
}
public static void extractZipToPath(Path zipFilePath, MCRPath target)
throws IOException, URISyntaxException {
LOGGER.info("Extracting zip: {}", zipFilePath);
try (FileSystem zipfs = FileSystems.newFileSystem(new URI("jar:" + zipFilePath.toUri()), new HashMap<>())) {
final Path sourcePath = zipfs.getPath("/");
Files.walkFileTree(sourcePath,
new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
final Path relativeSP = sourcePath.relativize(dir);
//WORKAROUND for bug
Path targetdir = relativeSP.getNameCount() == 0 ? target : target.resolve(relativeSP);
try {
Files.copy(dir, targetdir);
} catch (FileAlreadyExistsException e) {
if (!Files.isDirectory(targetdir)) {
throw e;
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
MCRSession currentSession = MCRSessionMgr.getCurrentSession();
LOGGER.info("Extracting: {}", file);
Path targetFilePath = target.resolve(sourcePath.relativize(file));
// WORKAROUND: copy is bad with IFS because fsnodes is locked until copy is completed
// so we end the transaction after we got a byte channel, then we write the data
// and before completion we start the transaction to let niofs write the md5 to the table
try (SeekableByteChannel destinationChannel = Files.newByteChannel(targetFilePath,
StandardOpenOption.WRITE, StandardOpenOption.SYNC, StandardOpenOption.CREATE);
SeekableByteChannel sourceChannel = Files.newByteChannel(file, StandardOpenOption.READ)) {
if (MCRTransactionHelper.isTransactionActive()) {
MCRTransactionHelper.commitTransaction();
}
ByteBuffer buffer = ByteBuffer.allocateDirect(COPY_BUFFER_SIZE);
while (sourceChannel.read(buffer) != -1 || buffer.position() > 0) {
buffer.flip();
destinationChannel.write(buffer);
buffer.compact();
}
} finally {
if (!MCRTransactionHelper.isTransactionActive()) {
MCRTransactionHelper.beginTransaction();
}
}
return FileVisitResult.CONTINUE;
}
});
}
}
public static List<MCRValidationResult> validateZipFile(final MCRFileValidator validator, Path zipFile)
throws IOException, URISyntaxException {
try (FileSystem zipfs = FileSystems.newFileSystem(new URI("jar:" + zipFile.toUri()), new HashMap<>())) {
final Path sourcePath = zipfs.getPath("/");
ArrayList<MCRValidationResult> validationResults = new ArrayList<>();
Files.walkFileTree(sourcePath, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
MCRValidationResult validationResult = validator.validate(file);
if (!validationResult.isValid()) {
validationResults.add(validationResult);
}
return FileVisitResult.CONTINUE;
}
});
return validationResults;
}
}
public static String encodeURLPart(String uri) {
try {
return URLEncoder.encode(uri, BuildLinkUtil.DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new MCRException(BuildLinkUtil.DEFAULT_URL_ENCODING + " is not supported!", e);
}
}
public static String decodeURLPart(String uri) {
try {
if (uri == null) {
return null;
}
return URLDecoder.decode(uri, BuildLinkUtil.DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new MCRException(BuildLinkUtil.DEFAULT_URL_ENCODING + " is not supported!", e);
}
}
public static DepositReceipt buildDepositReceipt(IRI iri) {
DepositReceipt depositReceipt = new DepositReceipt();
depositReceipt.setEditIRI(iri);
return depositReceipt;
}
public static void addDatesToEntry(Entry entry, MCRObject mcrObject) {
MCRObjectService serviceElement = mcrObject.getService();
ArrayList<String> flags = serviceElement.getFlags(MCRObjectService.FLAG_TYPE_CREATEDBY);
flags.addAll(serviceElement.getFlags(MCRObjectService.FLAG_TYPE_MODIFIEDBY));
Set<String> clearedFlags = new LinkedHashSet<>(flags);
clearedFlags.forEach(entry::addAuthor);
Date modifyDate = serviceElement.getDate(MCRObjectService.DATE_TYPE_MODIFYDATE);
Date createDate = serviceElement.getDate(MCRObjectService.DATE_TYPE_CREATEDATE);
entry.setEdited(modifyDate);
entry.setPublished(createDate);
}
public static MCRObject getMcrObjectForDerivateID(String requestDerivateID) {
final MCRObjectID objectID = MCRObjectID.getInstance(MCRXMLFunctions.getMCRObjectID(requestDerivateID));
return (MCRObject) MCRMetadataManager.retrieve(objectID);
}
public static class ParseLinkUtil {
public static final Pattern COLLECTION_IRI_PATTERN = Pattern.compile("([a-zA-Z0-9]+)/([0-9]*)");
public static final Pattern COLLECTION_MCRID_IRI_PATTERN = Pattern
.compile("([a-zA-Z0-9]+)/([a-zA-Z0-9]+_[a-zA-Z0-9]+_[0-9]+)");
public static final Pattern COLLECTION_DERIVATEID_IRI_PATTERN = Pattern
.compile("([a-zA-Z0-9]+)/([a-zA-Z0-9]+_[a-zA-Z0-9]+_[0-9]+)(/.+)?");
private static String getXFromXIRI(IRI editIRI, Integer x, String iri, Pattern iriPattern) {
return getXFromXIRI(editIRI, x, iri, iriPattern, true);
}
private static String getXFromXIRI(IRI editIRI, Integer x, String iri, Pattern iriPattern, boolean required) {
String[] urlParts = editIRI.toString().split(iri);
if (urlParts.length < 2) {
final String message = "Invalid " + iri + " : " + editIRI;
throw new IllegalArgumentException(message);
}
String uriPathAsString = urlParts[1];
Matcher matcher = iriPattern.matcher(uriPathAsString);
if (matcher.matches()) {
if (matcher.groupCount() >= x) {
return matcher.group(x);
} else {
return null;
}
} else {
if (required) {
throw new IllegalArgumentException(
new MessageFormat("{0} does not match the pattern {1}", Locale.ROOT)
.format(new Object[] { uriPathAsString, iriPattern }));
} else {
return null;
}
}
}
public static class CollectionIRI {
public static String getCollectionNameFromCollectionIRI(IRI collectionIRI) {
String uriPathAsString = collectionIRI.getPath().split(MCRSwordConstants.SWORD2_COL_IRI)[1];
Matcher matcher = COLLECTION_IRI_PATTERN.matcher(uriPathAsString);
if (matcher.matches()) {
return matcher.group(1);
} else {
throw new IllegalArgumentException(
new MessageFormat("{0} does not match the pattern {1}", Locale.ROOT)
.format(new Object[] { uriPathAsString, COLLECTION_IRI_PATTERN }));
}
}
public static Integer getPaginationFromCollectionIRI(IRI collectionIRI) {
String uriPathAsString = collectionIRI.getPath().split(MCRSwordConstants.SWORD2_COL_IRI)[1];
Matcher matcher = COLLECTION_IRI_PATTERN.matcher(uriPathAsString);
if (matcher.matches() && matcher.groupCount() > 1) {
String numberGroup = matcher.group(2);
if (numberGroup.length() > 0) {
return Integer.parseInt(numberGroup);
}
}
return 1;
}
}
public static class EditIRI {
public static String getCollectionFromEditIRI(IRI editIRI) {
return getXFromXIRI(editIRI, 1, MCRSwordConstants.SWORD2_EDIT_IRI, COLLECTION_MCRID_IRI_PATTERN);
}
public static String getObjectFromEditIRI(IRI editIRI) {
return getXFromXIRI(editIRI, 2, MCRSwordConstants.SWORD2_EDIT_IRI, COLLECTION_MCRID_IRI_PATTERN);
}
}
public static class MediaEditIRI {
public static String getCollectionFromMediaEditIRI(IRI mediaEditIRI) {
return getXFromXIRI(mediaEditIRI, 1, MCRSwordConstants.SWORD2_EDIT_MEDIA_IRI,
COLLECTION_DERIVATEID_IRI_PATTERN);
}
public static String getDerivateFromMediaEditIRI(IRI mediaEditIRI) {
return getXFromXIRI(mediaEditIRI, 2, MCRSwordConstants.SWORD2_EDIT_MEDIA_IRI,
COLLECTION_DERIVATEID_IRI_PATTERN);
}
public static String getFilePathFromMediaEditIRI(IRI mediaEditIRI) {
return decodeURLPart(getXFromXIRI(mediaEditIRI, 3, MCRSwordConstants.SWORD2_EDIT_MEDIA_IRI,
COLLECTION_DERIVATEID_IRI_PATTERN, false));
}
}
}
public static class BuildLinkUtil {
public static final String DEFAULT_URL_ENCODING = "UTF-8";
private static Logger LOGGER = LogManager.getLogger(BuildLinkUtil.class);
public static String getEditHref(String collection, String id) {
return new MessageFormat("{0}{1}{2}/{3}", Locale.ROOT).format(
new Object[] { MCRFrontendUtil.getBaseURL(), MCRSwordConstants.SWORD2_EDIT_IRI, collection, id });
}
public static String getEditMediaHrefOfDerivate(String collection, String id) {
return new MessageFormat("{0}{1}{2}/{3}", Locale.ROOT).format(
new Object[] { MCRFrontendUtil.getBaseURL(), MCRSwordConstants.SWORD2_EDIT_MEDIA_IRI, collection, id });
}
/**
* Creates a edit link for every derivate of a mcrobject.
*
* @param mcrObjId the mcrobject id as String
* @return returns a Stream which contains links to every derivate.
*/
public static Stream<Link> getEditMediaIRIStream(final String collection, final String mcrObjId) {
return MCRSword.getCollection(collection).getDerivateIDsofObject(mcrObjId).map(derivateId -> {
final Factory abderaFactory = Abdera.getNewFactory();
final Stream<IRI> editMediaFileIRIStream = getEditMediaFileIRIStream(collection, derivateId);
return Stream
.concat(Stream.of(getEditMediaHrefOfDerivate(collection, derivateId)), editMediaFileIRIStream)
.map(link -> {
final Link newLinkElement = abderaFactory.newLink();
newLinkElement.setHref(link.toString());
newLinkElement.setRel("edit-media");
return newLinkElement;
});
}).flatMap(s -> s);
}
/**
* Creates a Stream which contains edit-media-IRIs to all files in a specific derivate derivate.
*
* @param collection the collection in which the derivate is.
* @param derivateId the id of the derivate
* @return a Stream which contains edit-media-IRIs to all files.
*/
private static Stream<IRI> getEditMediaFileIRIStream(final String collection, final String derivateId) {
MCRPath derivateRootPath = MCRPath.getPath(derivateId, "/");
try {
List<IRI> iris = new ArrayList<>();
Files.walkFileTree(derivateRootPath, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
String relativePath = derivateRootPath.relativize(file).toString();
final String uri = new MessageFormat("{0}{1}{2}/{3}/{4}", Locale.ROOT).format(
new Object[] { MCRFrontendUtil.getBaseURL(), MCRSwordConstants.SWORD2_EDIT_MEDIA_IRI,
collection, derivateId, encodeURLPart(relativePath) });
iris.add(new IRI(uri));
return FileVisitResult.CONTINUE;
}
});
return iris.stream();
} catch (IOException e) {
LOGGER.error("Error while processing directory stream of {}", derivateId, e);
throw new MCRException(e);
}
}
public static String buildCollectionPaginationLinkHref(String collection, Integer page) {
return MCRFrontendUtil.getBaseURL() + MCRSwordConstants.SWORD2_COL_IRI + collection + "/" + page;
}
/**
* Creates Pagination links
*
* @param collectionIRI IRI of the collection
* @param collection name of the collection
* @param feed the feed where the link will be inserted
* @param collectionProvider
* {@link MCRSwordCollectionProvider} of the collection (needed to count how much objects)
* @throws SwordServerException when the {@link MCRSwordObjectIDSupplier} throws a exception.
*/
public static void addPaginationLinks(IRI collectionIRI, String collection, Feed feed,
MCRSwordCollectionProvider collectionProvider) throws SwordServerException {
final int lastPage = (int) Math.ceil((double) collectionProvider.getIDSupplier().getCount()
/ (double) MCRSwordConstants.MAX_ENTRYS_PER_PAGE);
int currentPage = ParseLinkUtil.CollectionIRI.getPaginationFromCollectionIRI(collectionIRI);
feed.addLink(buildCollectionPaginationLinkHref(collection, 1), "first");
if (lastPage != currentPage) {
feed.addLink(buildCollectionPaginationLinkHref(collection, currentPage + 1), "next");
}
feed.addLink(buildCollectionPaginationLinkHref(collection, lastPage), "last");
}
static void addEditMediaLinks(String collection, DepositReceipt depositReceipt, MCRObjectID derivateId) {
getEditMediaFileIRIStream(collection, derivateId.toString()).forEach(depositReceipt::addEditMediaIRI);
}
}
public interface MCRFileValidator {
MCRValidationResult validate(Path pathToFile);
}
public static class MCRValidationResult {
private boolean valid;
private Optional<String> message;
public MCRValidationResult(boolean valid, String message) {
this.valid = valid;
this.message = Optional.ofNullable(message);
}
public boolean isValid() {
return valid;
}
public void setValid(boolean valid) {
this.valid = valid;
}
public Optional<String> getMessage() {
return message;
}
public void setMessage(String message) {
this.message = Optional.ofNullable(message);
}
}
}
| 26,700 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordContainerServlet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/servlets/MCRSwordContainerServlet.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.sword.servlets;
import java.io.IOException;
import org.mycore.sword.MCRSwordConfigurationDefault;
import org.mycore.sword.manager.MCRSwordContainerManager;
import org.mycore.sword.manager.MCRSwordStatementManager;
import org.swordapp.server.ContainerAPI;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSwordContainerServlet extends MCRSwordServlet {
private static final long serialVersionUID = 1L;
private ContainerAPI api;
public void init() {
MCRSwordConfigurationDefault swordConfiguration = new MCRSwordConfigurationDefault();
MCRSwordContainerManager containerManager = new MCRSwordContainerManager();
MCRSwordStatementManager statementManager = new MCRSwordStatementManager();
api = new ContainerAPI(containerManager, statementManager, swordConfiguration);
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
prepareRequest(req, resp);
api.get(req, resp);
afterRequest(req, resp);
}
public void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
prepareRequest(req, resp);
api.head(req, resp);
afterRequest(req, resp);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
prepareRequest(req, resp);
api.post(req, resp);
afterRequest(req, resp);
}
public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
prepareRequest(req, resp);
api.put(req, resp);
afterRequest(req, resp);
}
public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
prepareRequest(req, resp);
api.delete(req, resp);
afterRequest(req, resp);
}
}
| 2,804 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordCollectionServlet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/servlets/MCRSwordCollectionServlet.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.sword.servlets;
import java.io.IOException;
import org.mycore.sword.MCRSwordConfigurationDefault;
import org.mycore.sword.manager.MCRSwordCollectionManager;
import org.swordapp.server.CollectionAPI;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSwordCollectionServlet extends MCRSwordServlet {
private static final long serialVersionUID = 1L;
private CollectionAPI api;
public void init() {
MCRSwordConfigurationDefault swordConfiguration = new MCRSwordConfigurationDefault();
MCRSwordCollectionManager colMgr = new MCRSwordCollectionManager();
api = new CollectionAPI(colMgr, colMgr, swordConfiguration);
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
prepareRequest(req, resp);
api.get(req, resp);
afterRequest(req, resp);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
prepareRequest(req, resp);
api.post(req, resp);
afterRequest(req, resp);
}
}
| 1,989 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordServlet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/servlets/MCRSwordServlet.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.sword.servlets;
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.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSwordServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger LOGGER = LogManager.getLogger(MCRSwordServlet.class);
protected void prepareRequest(HttpServletRequest req, HttpServletResponse resp) {
if (req.getAttribute(MCRFrontendUtil.BASE_URL_ATTRIBUTE) == null) {
String webappBase = MCRFrontendUtil.getBaseURL(req);
req.setAttribute(MCRFrontendUtil.BASE_URL_ATTRIBUTE, webappBase);
}
MCRSession session = MCRServlet.getSession(req);
MCRSessionMgr.setCurrentSession(session);
LOGGER.info("{} ip={} mcr={} user={}", req.getPathInfo(), MCRFrontendUtil.getRemoteAddr(req), session.getID(),
session.getUserInformation().getUserID());
MCRFrontendUtil.configureSession(session, req, resp);
MCRSessionMgr.getCurrentSession();
MCRTransactionHelper.beginTransaction();
}
protected void afterRequest(HttpServletRequest req, HttpServletResponse resp) {
MCRSessionMgr.getCurrentSession();
MCRTransactionHelper.commitTransaction();
MCRSessionMgr.releaseCurrentSession();
}
}
| 2,427 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordServiceDocumentServlet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/servlets/MCRSwordServiceDocumentServlet.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.sword.servlets;
import java.io.IOException;
import org.mycore.sword.MCRSwordConfigurationDefault;
import org.mycore.sword.manager.MCRSwordServiceDocumentManager;
import org.swordapp.server.ServiceDocumentAPI;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSwordServiceDocumentServlet extends MCRSwordServlet {
private static final long serialVersionUID = 1L;
private ServiceDocumentAPI api;
@Override
public void init() {
MCRSwordConfigurationDefault swordConfiguration = new MCRSwordConfigurationDefault();
MCRSwordServiceDocumentManager sdMgr = new MCRSwordServiceDocumentManager();
api = new ServiceDocumentAPI(sdMgr, swordConfiguration);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
prepareRequest(req, resp);
api.get(req, resp);
afterRequest(req, resp);
}
}
| 1,828 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordMediaResourceServlet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/servlets/MCRSwordMediaResourceServlet.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.sword.servlets;
import java.io.IOException;
import org.mycore.sword.MCRSwordConfigurationDefault;
import org.mycore.sword.manager.MCRSwordMediaManager;
import org.swordapp.server.MediaResourceAPI;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class MCRSwordMediaResourceServlet extends MCRSwordServlet {
private static final long serialVersionUID = 1L;
private MCRSwordMediaManager mrm;
private MediaResourceAPI api;
public void init() {
MCRSwordConfigurationDefault swordConfiguration = new MCRSwordConfigurationDefault();
mrm = new MCRSwordMediaManager();
api = new MediaResourceAPI(mrm, swordConfiguration);
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
prepareRequest(req, resp);
api.get(req, resp);
afterRequest(req, resp);
}
public void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
prepareRequest(req, resp);
api.head(req, resp);
afterRequest(req, resp);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
prepareRequest(req, resp);
api.post(req, resp);
afterRequest(req, resp);
}
public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
prepareRequest(req, resp);
api.put(req, resp);
afterRequest(req, resp);
}
public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
prepareRequest(req, resp);
api.delete(req, resp);
afterRequest(req, resp);
}
}
| 2,591 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordServiceDocumentManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/manager/MCRSwordServiceDocumentManager.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.sword.manager;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.sword.MCRSword;
import org.mycore.sword.MCRSwordConstants;
import org.mycore.sword.application.MCRSwordCollectionProvider;
import org.swordapp.server.AuthCredentials;
import org.swordapp.server.ServiceDocument;
import org.swordapp.server.ServiceDocumentManager;
import org.swordapp.server.SwordCollection;
import org.swordapp.server.SwordConfiguration;
import org.swordapp.server.SwordWorkspace;
/**
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSwordServiceDocumentManager implements ServiceDocumentManager {
@Override
public ServiceDocument getServiceDocument(String sdUri, AuthCredentials auth, SwordConfiguration config) {
ServiceDocument serviceDocument = new ServiceDocument();
MCRSword.getWorkspaces().forEach(workspaceName -> {
SwordWorkspace workspace = buildSwordWorkspace(workspaceName, auth);
serviceDocument.addWorkspace(workspace);
});
return serviceDocument;
}
private SwordWorkspace buildSwordWorkspace(String workspaceName, AuthCredentials auth) {
SwordWorkspace workspace = new SwordWorkspace();
workspace.setTitle(workspaceName);
buildSwordCollectionList(workspaceName, auth).forEach(workspace::addCollection);
return workspace;
}
private List<SwordCollection> buildSwordCollectionList(String workspaceName, AuthCredentials auth) {
String baseURL = MCRFrontendUtil.getBaseURL();
List<SwordCollection> swordCollections = new ArrayList<>();
MCRSword.getCollectionsOfWorkspace(workspaceName).stream()
.map(collection -> new AbstractMap.SimpleEntry<>(collection, MCRSword.getCollection(collection)))
.filter(collectionEntry -> collectionEntry.getValue().isVisible())
.forEach(collection -> {
SwordCollection swordCollection = new SwordCollection();
final String collectionTitle = collection.getKey();
swordCollection.setTitle(collectionTitle);
// add the supported packaging to the collection Provider
final MCRSwordCollectionProvider collectionProvider = collection.getValue();
collectionProvider.getSupportedPagacking().forEach(swordCollection::addAcceptPackaging);
swordCollection.setHref(baseURL + MCRSwordConstants.SWORD2_COL_IRI + collectionTitle + "/");
swordCollections.add(swordCollection);
});
return swordCollections;
}
}
| 3,404 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordMediaManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/manager/MCRSwordMediaManager.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.sword.manager;
import java.util.Map;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.sword.MCRSword;
import org.mycore.sword.MCRSwordUtil;
import org.mycore.sword.application.MCRSwordMediaHandler;
import org.swordapp.server.AuthCredentials;
import org.swordapp.server.Deposit;
import org.swordapp.server.DepositReceipt;
import org.swordapp.server.MediaResource;
import org.swordapp.server.MediaResourceManager;
import org.swordapp.server.SwordAuthException;
import org.swordapp.server.SwordConfiguration;
import org.swordapp.server.SwordError;
import org.swordapp.server.SwordServerException;
import org.swordapp.server.UriRegistry;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSwordMediaManager implements MediaResourceManager {
protected static Logger LOGGER = LogManager.getLogger(MCRSwordMediaManager.class);
public static MCRSwordMediaHandler getMediaProvider(String collection) {
return MCRSword.getCollection(collection).getMediaHandler();
}
protected static void checkObject(String objectID) throws SwordError {
if (objectID == null) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_BAD_REQUEST,
"Could not extract ObjectID from IRI.");
}
if (!MCRMetadataManager.exists(MCRObjectID.getInstance(objectID))) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_NOT_FOUND,
"The requested object " + objectID + " does not exist!");
}
}
public static void doAuthentication(AuthCredentials authCredentials, String collection)
throws SwordAuthException {
MCRSword.getCollection(collection).getAuthHandler().authentication(authCredentials);
}
public MediaResource getMediaResourceRepresentation(String editMediaIRI, Map<String, String> accept,
AuthCredentials authCredentials, SwordConfiguration swordConfiguration)
throws SwordError, SwordAuthException {
LOGGER.info("getMediaResourceRepresentation: {}", editMediaIRI);
final IRI mediaEditIRI = new IRI(editMediaIRI);
final String requestDerivateID = MCRSwordUtil.ParseLinkUtil.MediaEditIRI
.getDerivateFromMediaEditIRI(mediaEditIRI);
final String requestFilePath = MCRSwordUtil.ParseLinkUtil.MediaEditIRI
.getFilePathFromMediaEditIRI(mediaEditIRI);
final String collection = MCRSwordUtil.ParseLinkUtil.MediaEditIRI.getCollectionFromMediaEditIRI(mediaEditIRI);
doAuthentication(authCredentials, collection);
checkObject(requestDerivateID);
return getMediaProvider(collection).getMediaResourceRepresentation(requestDerivateID, requestFilePath, accept);
}
public DepositReceipt replaceMediaResource(String editMediaIRI, Deposit deposit, AuthCredentials authCredentials,
SwordConfiguration swordConfiguration) throws SwordError, SwordAuthException {
LOGGER.info("replaceMediaResource: {}", editMediaIRI);
final IRI mediaEditIRI = new IRI(editMediaIRI);
final String requestDerivateID = MCRSwordUtil.ParseLinkUtil.MediaEditIRI
.getDerivateFromMediaEditIRI(mediaEditIRI);
final String requestFilePath = MCRSwordUtil.ParseLinkUtil.MediaEditIRI
.getFilePathFromMediaEditIRI(mediaEditIRI);
final String collection = MCRSwordUtil.ParseLinkUtil.MediaEditIRI.getCollectionFromMediaEditIRI(mediaEditIRI);
doAuthentication(authCredentials, collection);
checkObject(requestDerivateID);
getMediaProvider(collection).replaceMediaResource(requestDerivateID, requestFilePath, deposit);
final MCRObject mcrObject = MCRSwordUtil.getMcrObjectForDerivateID(requestDerivateID);
return MCRSword.getCollection(collection).getMetadataProvider().provideMetadata(mcrObject);
}
public DepositReceipt addResource(String editMediaIRI, Deposit deposit, AuthCredentials authCredentials,
SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException {
LOGGER.info("addResource: {}", editMediaIRI);
final IRI mediaEditIRI = new IRI(editMediaIRI);
final String requestDerivateID = MCRSwordUtil.ParseLinkUtil.MediaEditIRI
.getDerivateFromMediaEditIRI(mediaEditIRI);
String requestFilePath = MCRSwordUtil.ParseLinkUtil.MediaEditIRI.getFilePathFromMediaEditIRI(mediaEditIRI);
final String collection = MCRSwordUtil.ParseLinkUtil.MediaEditIRI.getCollectionFromMediaEditIRI(mediaEditIRI);
doAuthentication(authCredentials, collection);
checkObject(requestDerivateID);
if (requestFilePath == null) {
requestFilePath = "/";
}
getMediaProvider(collection).addResource(requestDerivateID, requestFilePath, deposit);
final MCRObject mcrObject = MCRSwordUtil.getMcrObjectForDerivateID(requestDerivateID);
return MCRSword.getCollection(collection).getMetadataProvider().provideMetadata(mcrObject);
}
public void deleteMediaResource(String editMediaIRI, AuthCredentials authCredentials,
SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException {
LOGGER.info("deleteMediaResource: {}", editMediaIRI);
final IRI mediaEditIRI = new IRI(editMediaIRI);
final String requestObjectID = MCRSwordUtil.ParseLinkUtil.MediaEditIRI
.getDerivateFromMediaEditIRI(mediaEditIRI);
final String requestFilePath = MCRSwordUtil.ParseLinkUtil.MediaEditIRI
.getFilePathFromMediaEditIRI(mediaEditIRI);
final String collection = MCRSwordUtil.ParseLinkUtil.MediaEditIRI.getCollectionFromMediaEditIRI(mediaEditIRI);
doAuthentication(authCredentials, collection);
getMediaProvider(collection).deleteMediaResource(requestObjectID, requestFilePath);
}
}
| 6,945 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordContainerManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/manager/MCRSwordContainerManager.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.sword.manager;
import java.util.Map;
import java.util.Optional;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.datamodel.metadata.MCRBase;
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.sword.MCRSword;
import org.mycore.sword.MCRSwordUtil;
import org.mycore.sword.application.MCRSwordCollectionProvider;
import org.swordapp.server.AuthCredentials;
import org.swordapp.server.ContainerManager;
import org.swordapp.server.Deposit;
import org.swordapp.server.DepositReceipt;
import org.swordapp.server.SwordAuthException;
import org.swordapp.server.SwordConfiguration;
import org.swordapp.server.SwordError;
import org.swordapp.server.SwordServerException;
import org.swordapp.server.UriRegistry;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSwordContainerManager implements ContainerManager {
private static Logger LOGGER = LogManager.getLogger(MCRSwordContainerManager.class);
public static void throwObjectDoesNotExist(String objectIdString) throws SwordError {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_NOT_FOUND,
"The object '" + objectIdString + "' does not exist!");
}
public static void checkIsObject(MCRBase retrievedMCRBase) throws SwordError {
if (retrievedMCRBase instanceof MCRDerivate) {
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, HttpServletResponse.SC_BAD_REQUEST,
"You cannot directly change Metadata of a Derivate!");
}
}
@Override
public DepositReceipt getEntry(String editIRI, Map<String, String> map, AuthCredentials authCredentials,
SwordConfiguration swordConfiguration) throws SwordServerException, SwordError, SwordAuthException {
IRI iri = new IRI(editIRI);
String collection = MCRSwordUtil.ParseLinkUtil.EditIRI.getCollectionFromEditIRI(iri);
String objectIdString = MCRSwordUtil.ParseLinkUtil.EditIRI.getObjectFromEditIRI(iri);
final MCRSwordCollectionProvider collectionProvider = MCRSword.getCollection(collection);
LOGGER.info("REQUEST: Get entry {} from {}!", objectIdString, collection);
collectionProvider.getAuthHandler().authentication(authCredentials);
MCRObjectID objectId = MCRObjectID.getInstance(objectIdString);
if (!MCRMetadataManager.exists(objectId)) {
throwObjectDoesNotExist(objectIdString);
}
MCRBase retrievedMCRBase = MCRMetadataManager.retrieve(objectId);
checkIsObject(retrievedMCRBase);
final Optional<Map<String, String>> accept = Optional.of(map);
return collectionProvider.getContainerHandler().getMetadata(collection,
(MCRObject) retrievedMCRBase, accept);
}
@Override
public DepositReceipt addMetadata(String editIRI, Deposit deposit, AuthCredentials authCredentials,
SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException {
return this.replaceMetadata(editIRI, deposit, authCredentials, swordConfiguration);
}
@Override
public DepositReceipt addMetadataAndResources(String editIRI, Deposit deposit, AuthCredentials authCredentials,
SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException {
// this is not even supported by the JavaSwordServer
return null;
}
@Override
public DepositReceipt replaceMetadata(String editIRI, Deposit deposit, AuthCredentials authCredentials,
SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException {
IRI iri = new IRI(editIRI);
String collection = MCRSwordUtil.ParseLinkUtil.EditIRI.getCollectionFromEditIRI(iri);
String objectIdString = MCRSwordUtil.ParseLinkUtil.EditIRI.getObjectFromEditIRI(iri);
final MCRSwordCollectionProvider collectionProvider = MCRSword.getCollection(collection);
LOGGER.info("REQUEST: Replace metadata of {} from {}!", objectIdString, collection);
collectionProvider.getAuthHandler().authentication(authCredentials);
MCRObjectID objectId = MCRObjectID.getInstance(objectIdString);
if (!MCRMetadataManager.exists(objectId)) {
throwObjectDoesNotExist(objectIdString);
}
MCRBase retrievedMCRBase = MCRMetadataManager.retrieve(objectId);
checkIsObject(retrievedMCRBase);
return collectionProvider.getContainerHandler().replaceMetadata((MCRObject) retrievedMCRBase, deposit);
}
@Override
public DepositReceipt replaceMetadataAndMediaResource(String editIRI, Deposit deposit,
AuthCredentials authCredentials, SwordConfiguration swordConfiguration)
throws SwordError, SwordServerException, SwordAuthException {
IRI iri = new IRI(editIRI);
String collection = MCRSwordUtil.ParseLinkUtil.EditIRI.getCollectionFromEditIRI(iri);
String objectIdString = MCRSwordUtil.ParseLinkUtil.EditIRI.getObjectFromEditIRI(iri);
final MCRSwordCollectionProvider collectionProvider = MCRSword.getCollection(collection);
LOGGER.info("REQUEST: Replace metadata and resource of {} from {}!", objectIdString, collection);
collectionProvider.getAuthHandler().authentication(authCredentials);
MCRObjectID objectId = MCRObjectID.getInstance(objectIdString);
if (!MCRMetadataManager.exists(objectId)) {
throwObjectDoesNotExist(objectIdString);
}
MCRBase retrievedMCRBase = MCRMetadataManager.retrieve(objectId);
return collectionProvider.getContainerHandler().replaceMetadataAndResources((MCRObject) retrievedMCRBase,
deposit);
}
@Override
public DepositReceipt addResources(String editIRI, Deposit deposit, AuthCredentials authCredentials,
SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException {
IRI iri = new IRI(editIRI);
String collection = MCRSwordUtil.ParseLinkUtil.EditIRI.getCollectionFromEditIRI(iri);
String objectIdString = MCRSwordUtil.ParseLinkUtil.EditIRI.getObjectFromEditIRI(iri);
final MCRSwordCollectionProvider collectionProvider = MCRSword.getCollection(collection);
LOGGER.info("REQUEST: add resources {} from {}!", objectIdString, collection);
collectionProvider.getAuthHandler().authentication(authCredentials);
MCRObjectID objectId = MCRObjectID.getInstance(objectIdString);
if (!MCRMetadataManager.exists(objectId)) {
throwObjectDoesNotExist(objectIdString);
}
MCRBase retrievedMCRBase = MCRMetadataManager.retrieve(objectId);
return collectionProvider.getContainerHandler().addResources((MCRObject) retrievedMCRBase, deposit);
}
@Override
public void deleteContainer(String editIRI, AuthCredentials authCredentials, SwordConfiguration swordConfiguration)
throws SwordError, SwordServerException, SwordAuthException {
IRI iri = new IRI(editIRI);
String collection = MCRSwordUtil.ParseLinkUtil.EditIRI.getCollectionFromEditIRI(iri);
String objectIdString = MCRSwordUtil.ParseLinkUtil.EditIRI.getObjectFromEditIRI(iri);
final MCRSwordCollectionProvider collectionProvider = MCRSword.getCollection(collection);
LOGGER.info("REQUEST: Delete {} from {}", objectIdString, collection);
collectionProvider.getAuthHandler().authentication(authCredentials);
MCRObjectID objectId = MCRObjectID.getInstance(objectIdString);
if (!MCRMetadataManager.exists(objectId)) {
throwObjectDoesNotExist(objectIdString);
}
final MCRBase object = MCRMetadataManager.retrieve(objectId);
checkIsObject(object);
collectionProvider.getContainerHandler().deleteObject((MCRObject) object);
}
@Override
public DepositReceipt useHeaders(String editIRI, Deposit deposit, AuthCredentials authCredentials,
SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException {
throw new UnsupportedOperationException();
}
@Override
public boolean isStatementRequest(String editIRI, Map<String, String> map, AuthCredentials authCredentials,
SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException {
return false;
}
}
| 9,470 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordCollectionManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/manager/MCRSwordCollectionManager.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.sword.manager;
import java.util.Objects;
import org.apache.abdera.Abdera;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.model.Feed;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.sword.MCRSword;
import org.mycore.sword.MCRSwordConstants;
import org.mycore.sword.MCRSwordUtil;
import org.mycore.sword.application.MCRSwordCollectionProvider;
import org.swordapp.server.AuthCredentials;
import org.swordapp.server.CollectionDepositManager;
import org.swordapp.server.CollectionListManager;
import org.swordapp.server.Deposit;
import org.swordapp.server.DepositReceipt;
import org.swordapp.server.SwordAuthException;
import org.swordapp.server.SwordConfiguration;
import org.swordapp.server.SwordError;
import org.swordapp.server.SwordServerException;
import org.swordapp.server.UriRegistry;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSwordCollectionManager implements CollectionListManager, CollectionDepositManager {
private static Logger LOGGER = LogManager.getLogger(MCRSwordCollectionManager.class);
@Override
public Feed listCollectionContents(IRI collectionIRI, AuthCredentials authCredentials, SwordConfiguration config)
throws SwordServerException, SwordAuthException, SwordError {
String collection = MCRSwordUtil.ParseLinkUtil.CollectionIRI.getCollectionNameFromCollectionIRI(collectionIRI);
collectionIRI.getPath();
LOGGER.info("List Collection: {}", collection);
Feed feed = new Abdera().newFeed();
if (MCRSword.getCollectionNames().contains(collection)) {
MCRSwordCollectionProvider collectionProvider = MCRSword.getCollection(collection);
collectionProvider.getAuthHandler().authentication(authCredentials);
if (collectionProvider.isVisible()) {
Integer paginationFromIRI = MCRSwordUtil.ParseLinkUtil.CollectionIRI
.getPaginationFromCollectionIRI(collectionIRI);
final int start = (paginationFromIRI - 1) * MCRSwordConstants.MAX_ENTRYS_PER_PAGE;
collectionProvider.getIDSupplier().get(start, MCRSwordConstants.MAX_ENTRYS_PER_PAGE).stream()
.map(id -> {
try {
return collectionProvider.getMetadataProvider().provideListMetadata(id);
} catch (SwordError swordError) {
LOGGER.warn("Error while creating feed for [{}]! (Will be removed from List)", id);
return null;
}
}).filter(Objects::nonNull)
.forEach(feed::addEntry);
MCRSwordUtil.BuildLinkUtil.addPaginationLinks(collectionIRI, collection, feed, collectionProvider);
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_NOT_FOUND,
"The collection '" + collection + "' does not exist!");
}
return feed;
}
@Override
public DepositReceipt createNew(String editIRI, Deposit deposit, AuthCredentials authCredentials,
SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException {
LOGGER.info("createNew:{}", editIRI);
String collection = MCRSwordUtil.ParseLinkUtil.CollectionIRI
.getCollectionNameFromCollectionIRI(new IRI(editIRI));
MCRSwordCollectionProvider collectionProvider = MCRSword.getCollection(collection);
collectionProvider.getAuthHandler().authentication(authCredentials);
return collectionProvider.getContainerHandler().addObject(deposit);
}
}
| 4,527 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordStatementManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/manager/MCRSwordStatementManager.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.sword.manager;
import java.util.Map;
import org.swordapp.server.AuthCredentials;
import org.swordapp.server.Statement;
import org.swordapp.server.StatementManager;
import org.swordapp.server.SwordConfiguration;
/**
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSwordStatementManager implements StatementManager {
@Override
public Statement getStatement(String iri, Map<String, String> accept, AuthCredentials auth,
SwordConfiguration config) {
return null;
}
}
| 1,252 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordMetadataProvider.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/application/MCRSwordMetadataProvider.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.sword.application;
import org.apache.abdera.Abdera;
import org.apache.abdera.model.Entry;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.sword.MCRSwordConstants;
import org.mycore.sword.MCRSwordUtil;
import org.swordapp.server.DepositReceipt;
import org.swordapp.server.SwordError;
public abstract class MCRSwordMetadataProvider implements MCRSwordLifecycle {
private MCRSwordLifecycleConfiguration lifecycleConfiguration;
public abstract DepositReceipt provideMetadata(MCRObject object) throws SwordError;
/**
* @param id the id of the MyCoReObject as String
*/
public Entry provideListMetadata(MCRObjectID id) throws SwordError {
Entry feedEntry = Abdera.getInstance().newEntry();
feedEntry.setId(id.toString());
MCRSwordUtil.BuildLinkUtil.getEditMediaIRIStream(lifecycleConfiguration.getCollection(), id.toString())
.forEach(feedEntry::addLink);
feedEntry.addLink(MCRFrontendUtil.getBaseURL() + MCRSwordConstants.SWORD2_EDIT_IRI
+ lifecycleConfiguration.getCollection() + "/" + id, "edit");
return feedEntry;
}
@Override
public void init(MCRSwordLifecycleConfiguration lifecycleConfiguration) {
this.lifecycleConfiguration = lifecycleConfiguration;
}
}
| 2,138 | 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-sword/src/main/java/org/mycore/sword/application/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/>.
*/
/**
* Contains Classes/Interfaces to configure/extend the behavior of the MyCoRe-Sword2-Implementation.
* @author Sebastian Hofmann (mcrshofm)
*/
package org.mycore.sword.application;
| 914 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordIngester.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/application/MCRSwordIngester.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.sword.application;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.sword.MCRSwordUtil;
import org.swordapp.server.Deposit;
import org.swordapp.server.SwordError;
import org.swordapp.server.SwordServerException;
/**
* Let the application decide how to add metadata and resources.
* Useful functions e.g. extract ZIP files can be found in {@link MCRSwordUtil}.
*/
public interface MCRSwordIngester extends MCRSwordLifecycle {
/**
* Will be called when the client tries to deposit an object with metadata.
* @param entry the entry with metadata which should be added
* @return object id for the new created object
* @throws SwordError
* @throws SwordServerException
*/
MCRObjectID ingestMetadata(Deposit entry) throws SwordError, SwordServerException;
/**
* Will be called when the client tries to deposit an object with metadata and resources.
* @param entry the entry with metadata and resources which should be added
* @return object id for the new created object
* @throws SwordError
* @throws SwordServerException
*/
MCRObjectID ingestMetadataResources(Deposit entry) throws SwordError, SwordServerException;
/**
* Will be called when the client tries to add resources to an existing object.
* @param object where the resources should be added
* @param entry which contains the resources
* @throws SwordError
*/
void ingestResource(MCRObject object, Deposit entry) throws SwordError, SwordServerException;
/**
* Will be called when the client tries to update the metadata or replace existing metadata
* @param object where metadata should be added or replaced
* @param entry which contains metadata
* @param replace indicates whether metadata should be added or replaced
* @throws SwordError
*/
void updateMetadata(MCRObject object, Deposit entry, boolean replace) throws SwordError, SwordServerException;
/**
* Will be called when the client tries to update the metadata and resources.
* @param object where metadata and resources should be replaced
* @param entry which contains metadata and reources
* @throws SwordError
*/
void updateMetadataResources(MCRObject object, Deposit entry) throws SwordError, SwordServerException;
}
| 3,138 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordSolrObjectIDSupplier.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/application/MCRSwordSolrObjectIDSupplier.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.sword.application;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.solr.MCRSolrClientFactory;
import org.swordapp.server.SwordServerException;
/**
* Supplies the Sword with results from solr. This is the Suggested method to use.
*/
public class MCRSwordSolrObjectIDSupplier extends MCRSwordObjectIDSupplier {
private SolrQuery solrQuery;
/**
* @param solrQuery
* the query which will be used to ask solr. (start and rows will be overwritten for pagination purposes)
*/
public MCRSwordSolrObjectIDSupplier(SolrQuery solrQuery) {
this.solrQuery = solrQuery;
}
@Override
public long getCount() throws SwordServerException {
try {
// make a copy to prevent multi threading issues
final SolrQuery queryCopy = this.solrQuery.getCopy();
// only need the numFound
queryCopy.setStart(0);
queryCopy.setRows(0);
final QueryResponse queryResponse = MCRSolrClientFactory.getMainSolrClient().query(queryCopy);
return queryResponse.getResults().getNumFound();
} catch (SolrServerException | IOException e) {
throw new SwordServerException(
"Error while getting count with MCRSword2SolrObjectIDSupplier and Query: " + this.solrQuery,
e);
}
}
@Override
public List<MCRObjectID> get(int from, int count) throws SwordServerException {
final SolrQuery queryCopy = this.solrQuery.getCopy();
queryCopy.setStart(from);
queryCopy.setRows(count);
try {
final QueryResponse queryResponse = MCRSolrClientFactory.getMainSolrClient().query(queryCopy);
return queryResponse.getResults().stream()
.map(r -> (String) r.getFieldValue("id"))
.map(MCRObjectID::getInstance)
.collect(Collectors.toList());
} catch (SolrServerException | IOException e) {
throw new SwordServerException("Error while getting id list with MCRSword2SolrObjectIDSupplier and Query: "
+ this.solrQuery, e);
}
}
}
| 3,146 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordAuthHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/application/MCRSwordAuthHandler.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.sword.application;
import org.swordapp.server.AuthCredentials;
import org.swordapp.server.SwordAuthException;
/**
* Authenticates a User with AuthCredentials.
* @author Sebastian Hofmann (mcrshofm)
*/
public abstract class MCRSwordAuthHandler {
public abstract void authentication(AuthCredentials credentials) throws SwordAuthException;
}
| 1,094 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordDefaultAuthHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/application/MCRSwordDefaultAuthHandler.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.sword.application;
import static org.mycore.user2.MCRUserManager.exists;
import static org.mycore.user2.MCRUserManager.login;
import org.mycore.user2.MCRUser;
import org.swordapp.server.AuthCredentials;
import org.swordapp.server.SwordAuthException;
/**
* This implementation ignores the on-behalf-of header in request and just authenticate with MyCoRe user and password.
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSwordDefaultAuthHandler extends MCRSwordAuthHandler {
public void authentication(AuthCredentials credentials) throws SwordAuthException {
if (!exists(credentials.getUsername())) {
throw new SwordAuthException("Wrong login data!");
}
MCRUser mcrUser = login(credentials.getUsername(), credentials.getPassword());
if (mcrUser == null) {
throw new SwordAuthException("Wrong login data!");
}
}
}
| 1,646 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordMediaHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/application/MCRSwordMediaHandler.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.sword.application;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
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.List;
import java.util.Map;
import java.util.Optional;
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.access.MCRAccessManager;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTransactionHelper;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.mets.validator.METSValidator;
import org.mycore.mets.validator.validators.ValidationException;
import org.mycore.sword.MCRSwordConstants;
import org.mycore.sword.MCRSwordUtil;
import org.swordapp.server.Deposit;
import org.swordapp.server.MediaResource;
import org.swordapp.server.SwordError;
import org.swordapp.server.SwordServerException;
import org.swordapp.server.UriRegistry;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRSwordMediaHandler implements MCRSwordLifecycle, MCRSwordUtil.MCRFileValidator {
protected static final Logger LOGGER = LogManager.getLogger(MCRSwordMediaHandler.class);
protected static boolean isValidFilePath(String filePath) {
return filePath != null && filePath.length() > 1;
}
protected static void checkFile(MCRPath path) throws SwordError {
if (!Files.exists(path)) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_NOT_FOUND,
"The requested file '" + path + "' does not exists.");
}
}
public MediaResource getMediaResourceRepresentation(String derivateID, String requestFilePath,
Map<String, String> accept) throws SwordError {
MediaResource resultRessource;
if (!MCRAccessManager.checkPermission(derivateID, MCRAccessManager.PERMISSION_READ)) {
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"You dont have the right to read from the derivate!");
}
if (isValidFilePath(requestFilePath)) {
final MCRPath path = MCRPath.getPath(derivateID, requestFilePath);
checkFile(path);
InputStream is = null;
try {
// MediaResource/Sword2 api should close the stream.
is = Files.newInputStream(path);
resultRessource = new MediaResource(is, Files.probeContentType(path), UriRegistry.PACKAGE_BINARY);
} catch (IOException e) {
LOGGER.error("Error while opening File: {}", path, e);
if (is != null) {
try {
is.close();
} catch (IOException e1) {
LOGGER.error("Could not close Stream after error. ", e);
}
}
throw new SwordError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} else {
// if there is no file path or file is just "/" or "" then send the zipped Derivate
resultRessource = MCRSwordUtil.getZippedDerivateMediaResource(derivateID);
}
MCRSessionMgr.getCurrentSession();
MCRTransactionHelper.commitTransaction();
return resultRessource;
}
public void replaceMediaResource(String derivateId, String requestFilePath, Deposit deposit)
throws SwordError {
if (!MCRAccessManager.checkPermission(derivateId, MCRAccessManager.PERMISSION_WRITE)) {
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"You dont have the right to write to the derivate!");
}
MCRPath path = MCRPath.getPath(derivateId, requestFilePath);
if (!Files.exists(path)) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_NOT_FOUND,
"Cannot replace a not existing file.");
}
final boolean pathIsDirectory = Files.isDirectory(path);
if (pathIsDirectory) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_METHOD_NOT_ALLOWED,
"replaceMediaResource is not supported with directories");
}
// TODO: replace file
}
public void addResource(String derivateId, String requestFilePath, Deposit deposit)
throws SwordError, SwordServerException {
MCRPath ifsRootPath = MCRPath.getPath(derivateId, requestFilePath);
final boolean pathIsDirectory = Files.isDirectory(ifsRootPath);
final String depositFilename = deposit.getFilename();
final String packaging = deposit.getPackaging();
if (!MCRAccessManager.checkPermission(derivateId, MCRAccessManager.PERMISSION_WRITE)) {
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"You dont have the right to write to the derivate!");
}
Path tempFile = null;
try {
try {
tempFile = MCRSwordUtil.createTempFileFromStream(deposit.getFilename(), deposit.getInputStream(),
deposit.getMd5());
} catch (IOException e) {
throw new SwordServerException("Could not store deposit to temp files", e);
}
if (packaging != null && packaging.equals(UriRegistry.PACKAGE_SIMPLE_ZIP)) {
if (pathIsDirectory && deposit.getMimeType().equals(MCRSwordConstants.MIME_TYPE_APPLICATION_ZIP)) {
ifsRootPath = MCRPath.getPath(derivateId, requestFilePath);
try {
List<MCRSwordUtil.MCRValidationResult> invalidResults = MCRSwordUtil
.validateZipFile(this, tempFile)
.stream()
.filter(validationResult -> !validationResult.isValid())
.collect(Collectors.toList());
if (invalidResults.size() > 0) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_BAD_REQUEST,
invalidResults.stream()
.map(MCRSwordUtil.MCRValidationResult::getMessage)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.joining(System.lineSeparator())));
}
MCRSwordUtil.extractZipToPath(tempFile, ifsRootPath);
} catch (IOException | URISyntaxException e) {
throw new SwordServerException("Error while extracting ZIP.", e);
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_BAD_REQUEST,
"The Request makes no sense. (mime type must be " + MCRSwordConstants.MIME_TYPE_APPLICATION_ZIP
+ " and path must be a directory)");
}
} else if (packaging != null && packaging.equals(UriRegistry.PACKAGE_BINARY)) {
try {
MCRSwordUtil.MCRValidationResult validationResult = validate(tempFile);
if (!validationResult.isValid()) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_BAD_REQUEST,
validationResult.getMessage().get());
}
ifsRootPath = MCRPath.getPath(derivateId, requestFilePath + depositFilename);
try (InputStream is = Files.newInputStream(tempFile)) {
Files.copy(is, ifsRootPath, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
throw new SwordServerException("Error while adding file " + ifsRootPath, e);
}
}
} finally {
if (tempFile != null) {
try {
LOGGER.info("Delete temp file: {}", tempFile);
Files.delete(tempFile);
} catch (IOException e) {
LOGGER.error("Could not delete temp file: {}", tempFile, e);
}
}
}
}
public void deleteMediaResource(String derivateId, String requestFilePath) throws SwordError, SwordServerException {
if (!MCRAccessManager.checkPermission(derivateId, MCRAccessManager.PERMISSION_DELETE)) {
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"You dont have the right to delete (from) the derivate!");
}
if (requestFilePath == null || requestFilePath.equals("/")) {
final MCRObjectID derivateID = MCRObjectID.getInstance(derivateId);
if (MCRMetadataManager.exists(derivateID)) {
final MCRDerivate mcrDerivate = MCRMetadataManager.retrieveMCRDerivate(derivateID);
try {
MCRMetadataManager.delete(mcrDerivate);
} catch (MCRAccessException e) {
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, e);
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_NOT_FOUND,
"The requested Object '" + requestFilePath + "' does not exists.");
}
} else {
final MCRPath path = MCRPath.getPath(derivateId, requestFilePath);
checkFile(path);
try {
if (Files.isDirectory(path)) {
Files.walkFileTree(path, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
} else {
Files.delete(path);
}
} catch (IOException e) {
throw new SwordServerException("Error while deleting media resource!", e);
}
}
}
@Override
public void init(MCRSwordLifecycleConfiguration lifecycleConfiguration) {
//lifecycleConfiguration is not used here;
}
@Override
public void destroy() {
}
@Override
public MCRSwordUtil.MCRValidationResult validate(Path pathToFile) {
// single added file name are remapped to mets.xml -> swordv2_*mets.xml
if (pathToFile.getFileName().toString().endsWith("mets.xml")) {
try (InputStream is = Files.newInputStream(pathToFile)) {
METSValidator validator = new METSValidator(is);
List<ValidationException> validateResult = validator.validate();
if (validateResult.size() > 0) {
String result = validateResult.stream().map(Throwable::getMessage)
.collect(Collectors.joining(System.lineSeparator()));
return new MCRSwordUtil.MCRValidationResult(false, result);
} else {
return new MCRSwordUtil.MCRValidationResult(true, null);
}
} catch (IOException | JDOMException e) {
return new MCRSwordUtil.MCRValidationResult(false, "Could not read mets.xml: " + e.getMessage());
}
} else {
return new MCRSwordUtil.MCRValidationResult(true, null);
}
}
}
| 13,146 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordLifecycle.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/application/MCRSwordLifecycle.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.sword.application;
public interface MCRSwordLifecycle {
void init(MCRSwordLifecycleConfiguration lifecycleConfiguration);
void destroy();
}
| 896 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordLifecycleConfiguration.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/application/MCRSwordLifecycleConfiguration.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.sword.application;
public class MCRSwordLifecycleConfiguration {
private String collection;
public MCRSwordLifecycleConfiguration(String collection) {
this.collection = collection;
}
public String getCollection() {
return collection;
}
}
| 1,024 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordObjectIDSupplier.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/application/MCRSwordObjectIDSupplier.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.sword.application;
import java.util.List;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.swordapp.server.SwordServerException;
/**
* Should supply the mycore sword implementation with the right MyCoReIds. It also handles pagination.
* The Standard impl. is {@link MCRSwordSolrObjectIDSupplier} and it should handle 99% of all use cases.
*/
public abstract class MCRSwordObjectIDSupplier {
/**
* @return how many objects a collection has
* @throws SwordServerException if an error occurs while determining the result
*/
public abstract long getCount() throws SwordServerException;
/**
* @param from first object id which should appear in the list
* @param count count how many ids should appear in the list
* @return a list of MyCoReObjectIDs
* @throws SwordServerException if an error occurs while determining the result
*/
public abstract List<MCRObjectID> get(int from, int count) throws SwordServerException;
}
| 1,737 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSwordCollectionProvider.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-sword/src/main/java/org/mycore/sword/application/MCRSwordCollectionProvider.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.sword.application;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.sword.MCRSwordContainerHandler;
/**
* Interface to tell the MyCoRe SwordV2 which MyCoRe Objects will be visible to sword and in which collections they are.
*
* @author Sebastian Hofmann (mcrshofm)
*/
public abstract class MCRSwordCollectionProvider implements MCRSwordLifecycle {
protected static Logger LOGGER = LogManager.getLogger(MCRSwordCollectionProvider.class);
private MCRSwordContainerHandler mcrSwordContainerHandler;
private MCRSwordMediaHandler mcrSwordMediaHandler;
protected MCRSwordCollectionProvider() {
mcrSwordContainerHandler = new MCRSwordContainerHandler();
mcrSwordMediaHandler = new MCRSwordMediaHandler();
}
/**
* tells the SwordV2 impl if the Collection is visible for the current User.
*
* @return true if the collection should be provided.
*/
public abstract boolean isVisible();
/**
* tells which packaging is supported by the collection.
*
* @return a list of supported packacking
*/
public abstract List<String> getSupportedPagacking();
/**
* @return a supplier which tells the MyCoRe Sword implementation which objects can be exposed to a collection
*/
public abstract MCRSwordObjectIDSupplier getIDSupplier();
public MCRSwordContainerHandler getContainerHandler() {
return mcrSwordContainerHandler;
}
public abstract MCRSwordIngester getIngester();
public abstract MCRSwordMetadataProvider getMetadataProvider();
/**
* @return the {@link MCRSwordMediaHandler} which will be used for this collection
*/
public MCRSwordMediaHandler getMediaHandler() {
return mcrSwordMediaHandler;
}
public abstract MCRSwordAuthHandler getAuthHandler();
public Stream<String> getDerivateIDsofObject(final String mcrObjectId) {
final List<MCRObjectID> derivateIds = MCRMetadataManager.getDerivateIds(MCRObjectID.getInstance(mcrObjectId),
10, TimeUnit.SECONDS);
return derivateIds.stream().map(MCRObjectID::toString);
}
@Override
public void init(MCRSwordLifecycleConfiguration lifecycleConfiguration) {
getIngester().init(lifecycleConfiguration);
getMetadataProvider().init(lifecycleConfiguration);
getMediaHandler().init(lifecycleConfiguration);
getContainerHandler().init(lifecycleConfiguration);
}
@Override
public void destroy() {
getIngester().destroy();
getMetadataProvider().destroy();
getMediaHandler().destroy();
getContainerHandler().destroy();
}
}
| 3,652 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFoFormatterHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-fo/src/main/java/org/mycore/component/fo/common/fo/MCRFoFormatterHelper.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.component.fo.common.fo;
import org.mycore.common.config.MCRConfiguration2;
/**
* Returns the XSL-FO formatter instance configured via PROPERTY, for example
*
* MCR.LayoutService.FoFormatter.class=org.mycore.common.fo.MCRFoFormatterFOP
*
* (which is the default using Apache FOP)
*
* @see MCRFoFormatterInterface
*
* @author Frank Lützenkirchen
*/
public class MCRFoFormatterHelper {
/** The configuration PROPERTY */
private static final String PROPERTY = "MCR.LayoutService.FoFormatter.class";
/** The singleton */
private static MCRFoFormatterInterface formatter;
/** @return the XSL-FO formatter instance configured */
public static synchronized MCRFoFormatterInterface getFoFormatter() {
if (formatter == null) {
formatter = MCRConfiguration2.<MCRFoFormatterInterface>getInstanceOf(PROPERTY)
.orElseGet(MCRFoFormatterFOP::new);
}
return formatter;
}
}
| 1,702 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFoFormatterInterface.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-fo/src/main/java/org/mycore/component/fo/common/fo/MCRFoFormatterInterface.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.component.fo.common.fo;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.transform.TransformerException;
import org.mycore.common.content.MCRContent;
/**
* This is an interface to use configured XSL-FO formatters for the layout service.
*
* @author Jens Kupferschmidt
*/
public interface MCRFoFormatterInterface {
/**
* transform the given MCRContent to the given OutputStream
*
* @param input the MCRContent
* @param out the target output stream
* @throws TransformerException if the transformation goes wrong
* @throws IOException if an I/O error occurs
*/
void transform(MCRContent input, OutputStream out) throws TransformerException, IOException;
}
| 1,479 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFoFormatterFOP.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-fo/src/main/java/org/mycore/component/fo/common/fo/MCRFoFormatterFOP.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.component.fo.common.fo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.sax.SAXResult;
import org.apache.fop.apps.EnvironmentalProfileFactory;
import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.FopFactoryBuilder;
import org.apache.fop.apps.MimeConstants;
import org.apache.fop.configuration.Configuration;
import org.apache.fop.configuration.ConfigurationException;
import org.apache.fop.configuration.DefaultConfigurationBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.xmlgraphics.io.Resource;
import org.apache.xmlgraphics.io.ResourceResolver;
import org.mycore.common.MCRClassTools;
import org.mycore.common.MCRCoreVersion;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationDir;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRSourceContent;
import org.mycore.common.xml.MCRURIResolver;
import org.mycore.common.xsl.MCRErrorListener;
/**
* This class implements the interface to use configured XSL-FO formatters for the layout service.
*
* @author Jens Kupferschmidt
* @author René Adler (eagle)
*/
public class MCRFoFormatterFOP implements MCRFoFormatterInterface {
private static final Logger LOGGER = LogManager.getLogger();
private FopFactory fopFactory;
final ResourceResolver resolver = new ResourceResolver() {
public OutputStream getOutputStream(URI uri) throws IOException {
URL url = MCRURIResolver.getServletContext().getResource(uri.toString());
return url.openConnection().getOutputStream();
}
public Resource getResource(URI uri) throws IOException {
MCRContent content;
try {
content = MCRSourceContent.getInstance(uri.toString());
return new Resource(uri.getScheme(), content.getInputStream());
} catch (TransformerException e) {
LOGGER.error("Error while resolving uri: {}", uri);
}
return null;
}
};
/**
* instantiate MCRFoFormatterFOP
*/
public MCRFoFormatterFOP() {
FopFactoryBuilder fopFactoryBuilder;
// use restricted io to prevent issues with font caching on some systems
fopFactoryBuilder = new FopFactoryBuilder(
EnvironmentalProfileFactory.createRestrictedIO(URI.create("resource:/"), resolver));
final String foCfg = MCRConfiguration2.getString("MCR.LayoutService.FoFormatter.FOP.config").orElse("");
if (!foCfg.isEmpty()) {
try {
URL configResource = MCRConfigurationDir.getConfigResource(foCfg);
URLConnection con = configResource.openConnection();
final DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
final Configuration cfg;
try (InputStream is = con.getInputStream()) {
cfg = cfgBuilder.build(is);
}
fopFactoryBuilder.setConfiguration(cfg);
// FIXME Workaround to get hyphenation work in FOP.
// FOP should use "hyphenation-base" to get base URI for patterns
Optional<Configuration[]> hyphPat = Optional.ofNullable(cfg.getChildren("hyphenation-pattern"));
hyphPat.ifPresent(configurations -> {
Map<String, String> hyphPatMap = new HashMap<>();
Arrays.stream(configurations).forEach(c -> {
try {
String lang = c.getAttribute("lang");
String file = c.getValue();
if ((lang != null && !lang.isEmpty()) && (file != null && !file.isEmpty())) {
hyphPatMap.put(lang, file);
}
} catch (Exception e) {
}
});
fopFactoryBuilder.setHyphPatNames(hyphPatMap);
});
} catch (ConfigurationException | IOException e) {
LOGGER.error("Exception while loading FOP configuration from {}.", foCfg, e);
}
}
fopFactory = fopFactoryBuilder.build();
getTransformerFactory();
}
private static TransformerFactory getTransformerFactory() throws TransformerFactoryConfigurationError {
TransformerFactory transformerFactory = MCRConfiguration2
.getString("MCR.LayoutService.FoFormatter.transformerFactoryImpl")
.map(impl -> TransformerFactory.newInstance(impl, MCRClassTools.getClassLoader()))
.orElseGet(TransformerFactory::newInstance);
transformerFactory.setURIResolver(MCRURIResolver.instance());
transformerFactory.setErrorListener(MCRErrorListener.getInstance());
return transformerFactory;
}
@Override
public void transform(MCRContent input, OutputStream out) throws TransformerException, IOException {
try {
final FOUserAgent userAgent = fopFactory.newFOUserAgent();
userAgent.setProducer(new MessageFormat("MyCoRe {0} ({1})", Locale.ROOT)
.format(new Object[] { MCRCoreVersion.getCompleteVersion(), userAgent.getProducer() }));
final Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, out);
final Source src = input.getSource();
final Result res = new SAXResult(fop.getDefaultHandler());
Transformer transformer = getTransformerFactory().newTransformer();
transformer.transform(src, res);
} catch (FOPException e) {
throw new TransformerException(e);
}
}
}
| 7,180 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFopper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-fo/src/main/java/org/mycore/component/fo/common/content/transformer/MCRFopper.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.component.fo.common.content.transformer;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.transform.TransformerException;
import org.mycore.common.content.MCRByteContent;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.streams.MCRByteArrayOutputStream;
import org.mycore.common.content.transformer.MCRContentTransformer;
import org.mycore.component.fo.common.fo.MCRFoFormatterHelper;
/**
* Transforms XSL-FO xml content to PDF.
*
* @see org.mycore.component.fo.common.fo.MCRFoFormatterInterface
*
* @author Frank Lützenkirchen
*/
public class MCRFopper extends MCRContentTransformer {
private static final String PDF_MIME_TYPE = "application/pdf";
@Override
public MCRContent transform(MCRContent source) throws IOException {
MCRByteArrayOutputStream pdf = new MCRByteArrayOutputStream(32 * 1024);
try {
MCRFoFormatterHelper.getFoFormatter().transform(source, pdf);
} catch (TransformerException e) {
throw new IOException(e);
}
MCRContent result = new MCRByteContent(pdf.getBuffer(), 0, pdf.size(), source.lastModified());
result.setMimeType(PDF_MIME_TYPE);
return result;
}
@Override
public void transform(MCRContent source, OutputStream out) throws IOException {
try {
MCRFoFormatterHelper.getFoFormatter().transform(source, out);
} catch (TransformerException e) {
throw new IOException(e);
}
}
@Override
public String getMimeType() {
return PDF_MIME_TYPE;
}
@Override
public String getFileExtension() {
return "pdf";
}
}
| 2,442 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLayoutTransformerFoFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-fo/src/main/java/org/mycore/component/fo/common/content/xml/MCRLayoutTransformerFoFactory.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.component.fo.common.content.xml;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.mycore.common.MCRException;
import org.mycore.common.content.transformer.MCRContentTransformer;
import org.mycore.common.content.transformer.MCRTransformerPipe;
import org.mycore.common.content.transformer.MCRXSLTransformer;
import org.mycore.common.xml.MCRLayoutTransformerFactory;
import org.mycore.component.fo.common.content.transformer.MCRFopper;
import org.xml.sax.SAXException;
/**
* This class acts as a {@link org.mycore.common.content.transformer.MCRContentTransformer} factory for
* {@link org.mycore.common.xml.MCRLayoutService}.
* @author Thomas Scheffler (yagee)
* @author Sebastian Hofmann
*
*/
public class MCRLayoutTransformerFoFactory extends MCRLayoutTransformerFactory {
private static final String APPLICATION_PDF = "application/pdf";
/** Map of transformer instances by ID */
private static Map<String, MCRContentTransformer> transformers = new ConcurrentHashMap<>();
private static MCRFopper fopper = new MCRFopper();
@Override
public MCRContentTransformer getTransformer(String id) {
return transformers.computeIfAbsent(id, (transformerId) -> {
try {
MCRContentTransformer transformer = super.getTransformer(transformerId);
if (MCRLayoutTransformerFactory.NOOP_TRANSFORMER.equals(transformer) ||
getConfiguredTransformer(id).isPresent()) {
return transformer;
}
if (APPLICATION_PDF.equals(transformer.getMimeType())) {
return new MCRTransformerPipe(transformer, fopper);
}
return transformer;
} catch (Exception e) {
throw new MCRException("Error while transforming!", e);
}
});
}
@Override
protected boolean isXMLOutput(String outputMethod, MCRXSLTransformer transformerTest)
throws ParserConfigurationException, TransformerException, SAXException {
return super.isXMLOutput(outputMethod, transformerTest) &&
!APPLICATION_PDF.equals(transformerTest.getMimeType());
}
}
| 3,068 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLCombineIgnoreXPathPrunerTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/test/java/org/mycore/ocfl/metadata/migration/MCROCFLCombineIgnoreXPathPrunerTest.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.ocfl.metadata.migration;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
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.junit.Assert;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.xml.MCRXMLHelper;
import org.mycore.datamodel.common.MCRMetadataVersionType;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.ocfl.metadata.migration.MCROCFLMigration.ContentSupplier;
public class MCROCFLCombineIgnoreXPathPrunerTest extends MCRTestCase {
public static final String JUNIT_TEST_00000001 = "junit_test_00000001";
public static final String AUTOR_1 = "Sebastian";
public static final String AUTOR_2 = "Hans";
public static final String AUTOR_3 = "Peter";
public static final ContentSupplier CONTENT_1 = () -> {
Element test = new Element("test");
Document testDoc = new Document(test);
test.addContent(new Element("a").setText("1"));
test.addContent(new Element("b").setText("2"));
test.addContent(new Element("c").setText("3"));
return new MCRJDOMContent(testDoc);
};
public static final ContentSupplier CONTENT_2 = () -> {
Element test = new Element("test");
Document testDoc = new Document(test);
test.addContent(new Element("a").setText("4"));
test.addContent(new Element("b").setText("5"));
test.addContent(new Element("c").setText("3"));
return new MCRJDOMContent(testDoc);
};
public static final ContentSupplier CONTENT_3 = () -> {
Element test = new Element("test");
Document testDoc = new Document(test);
test.addContent(new Element("a").setText("6"));
test.addContent(new Element("b").setText("7"));
test.addContent(new Element("c").setText("4"));
return new MCRJDOMContent(testDoc);
};
private static final Logger LOGGER = LogManager.getLogger();
@Test
public void testPrune() throws IOException, JDOMException {
MCROCFLCombineIgnoreXPathPruner xPathPruner = new MCROCFLCombineIgnoreXPathPruner();
xPathPruner.setXpath("/test/a|/test/b");
xPathPruner.setFirstAuthorWins(true);
xPathPruner.setFirstDateWins(true);
MCRObjectID objectID = MCRObjectID.getInstance(JUNIT_TEST_00000001);
Date baseDate = new Date();
MCROCFLRevision r1
= new MCROCFLRevision(MCRMetadataVersionType.CREATED, CONTENT_1, AUTOR_1, baseDate, objectID);
MCROCFLRevision r2
= new MCROCFLRevision(MCRMetadataVersionType.MODIFIED, CONTENT_2, AUTOR_2,
new Date(baseDate.getTime() + 1000), objectID);
MCROCFLRevision r3
= new MCROCFLRevision(MCRMetadataVersionType.MODIFIED, CONTENT_3, AUTOR_3,
new Date(baseDate.getTime() + 2000), objectID);
MCROCFLRevision r4
= new MCROCFLRevision(MCRMetadataVersionType.DELETED, null, AUTOR_3, new Date(baseDate.getTime() + 3000),
objectID);
MCROCFLRevision r5
= new MCROCFLRevision(MCRMetadataVersionType.CREATED, CONTENT_1, AUTOR_1,
new Date(baseDate.getTime() + 4000), objectID);
MCROCFLRevision r6
= new MCROCFLRevision(MCRMetadataVersionType.MODIFIED, CONTENT_2, AUTOR_2,
new Date(baseDate.getTime() + 5000), objectID);
MCROCFLRevision r7
= new MCROCFLRevision(MCRMetadataVersionType.MODIFIED, CONTENT_1, AUTOR_3,
new Date(baseDate.getTime() + 6000), objectID);
List<MCROCFLRevision> prune = xPathPruner.prune(List.of(r1, r2, r3, r4, r5, r6, r7));
Assert.assertEquals("r2, r6 and r7 should be pruned away", 4, prune.size());
Assert.assertEquals("r1 autor should be original r1 autor", AUTOR_1, prune.get(0).user());
Assert.assertEquals("r2 autor should be original r3 autor", AUTOR_3, prune.get(1).user());
Assert.assertEquals("r1 date should be original r1 date", baseDate, prune.get(0).date());
Assert.assertEquals("r2 date should be original r3 date", new Date(baseDate.getTime() + 2000),
prune.get(1).date());
Assert.assertTrue("r1 content should be original r2 content",
MCRXMLHelper.deepEqual(prune.get(0).contentSupplier().get().asXML(), CONTENT_2.get().asXML()));
Assert.assertTrue("r2 content should be original r3 content",
MCRXMLHelper.deepEqual(prune.get(1).contentSupplier().get().asXML(), CONTENT_3.get().asXML()));
LOGGER.info("First Result: " + prune.stream().map(MCROCFLRevision::toString).collect(Collectors.joining("\n")));
xPathPruner.setFirstDateWins(false);
xPathPruner.setFirstAuthorWins(false);
prune = xPathPruner.prune(List.of(r1, r2, r3, r4, r5, r6, r7));
Assert.assertEquals("r2, r6 and r7 should be pruned away", 4, prune.size());
Assert.assertEquals("r1 autor should be original r2 autor", AUTOR_2, prune.get(0).user());
Assert.assertEquals("r2 autor should be original r3 autor", AUTOR_3, prune.get(1).user());
Assert.assertEquals("r1 date should be original r2 date", new Date(baseDate.getTime() + 1000),
prune.get(0).date());
Assert.assertEquals("r2 date should be original r3 date", new Date(baseDate.getTime() + 2000),
prune.get(1).date());
Assert.assertTrue("r1 content should be original r2 content",
MCRXMLHelper.deepEqual(prune.get(0).contentSupplier().get().asXML(), CONTENT_2.get().asXML()));
Assert.assertTrue("r2 content should be original r3 content",
MCRXMLHelper.deepEqual(prune.get(1).contentSupplier().get().asXML(), CONTENT_3.get().asXML()));
LOGGER
.info("Second Result: " + prune.stream().map(MCROCFLRevision::toString).collect(Collectors.joining("\n")));
}
}
| 6,832 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLPersistenceTransaction.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/MCROCFLPersistenceTransaction.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.ocfl;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.mycore.common.MCRPersistenceTransaction;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.utils.MCRCategoryTransformer;
import org.mycore.datamodel.common.MCRAbstractMetadataVersion;
import org.mycore.ocfl.classification.MCROCFLXMLClassificationManager;
/**
* @author Tobias Lenhardt [Hammer1279]
* @author Thomas Scheffler (yagee)
*/
public class MCROCFLPersistenceTransaction implements MCRPersistenceTransaction {
private static final Logger LOGGER = LogManager.getLogger();
private static final MCROCFLXMLClassificationManager MANAGER = MCRConfiguration2
.<MCROCFLXMLClassificationManager>getSingleInstanceOf("MCR.Classification.Manager")
.orElse(null);
private static final ThreadLocal<Map<MCRCategoryID, Character>> CATEGORY_WORKSPACE = new ThreadLocal<>();
private final String threadId = Thread.currentThread().toString();
private boolean rollbackOnly;
private boolean active;
public MCROCFLPersistenceTransaction() {
rollbackOnly = false;
active = false;
}
@Override
public boolean isReady() {
LOGGER.debug("TRANSACTION {} READY CHECK - {}", threadId, MANAGER != null);
return MANAGER != null && !isActive();
}
@Override
public void begin() {
LOGGER.debug("TRANSACTION {} BEGIN", threadId);
if (isActive()) {
throw new IllegalStateException("TRANSACTION ALREADY ACTIVE");
}
CATEGORY_WORKSPACE.set(new HashMap<>());
active = true;
}
@Override
public void commit() {
LOGGER.debug("TRANSACTION {} COMMIT", threadId);
if (!isActive() || getRollbackOnly()) {
throw new IllegalStateException("TRANSACTION NOT ACTIVE OR MARKED FOR ROLLBACK");
}
final Map<MCRCategoryID, Character> mapOfChanges = CATEGORY_WORKSPACE.get();
// save new OCFL version of classifications
// value is category if classification should not be deleted
mapOfChanges.forEach((categoryID, eventType) -> MCRSessionMgr.getCurrentSession()
.onCommit(() -> {
LOGGER.debug("[{}] UPDATING CLASS <{}>", threadId, categoryID);
try {
switch (eventType) {
case MCRAbstractMetadataVersion.CREATED,
MCRAbstractMetadataVersion.UPDATED -> createOrUpdateOCFLClassification(
categoryID, eventType);
case MCRAbstractMetadataVersion.DELETED -> MANAGER.delete(categoryID);
default -> throw new IllegalStateException(
"Unsupported type in classification found: " + eventType + ", " + categoryID);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}));
CATEGORY_WORKSPACE.remove();
active = false;
}
private static void createOrUpdateOCFLClassification(MCRCategoryID categoryID, Character eventType)
throws IOException {
// read classification from just here
final MCRCategoryDAO categoryDAO = MCRCategoryDAOFactory.getInstance();
final MCRCategory categoryRoot = categoryDAO
.getCategory(categoryID, -1);
if (categoryID == null) {
throw new IOException(
"Could not get classification " + categoryID + " from " + categoryDAO.getClass().getName());
}
final Document categoryXML = MCRCategoryTransformer.getMetaDataDocument(categoryRoot, false);
final MCRJDOMContent classContent = new MCRJDOMContent(categoryXML);
try {
if (eventType == MCRAbstractMetadataVersion.CREATED) {
MANAGER.create(categoryID, classContent);
} else {
MANAGER.update(categoryID, classContent);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public void rollback() {
LOGGER.debug("TRANSACTION {} ROLLBACK", threadId);
if (!isActive()) {
throw new IllegalStateException("TRANSACTION NOT ACTIVE");
}
CATEGORY_WORKSPACE.remove();
rollbackOnly = false;
active = false;
}
@Override
public boolean getRollbackOnly() {
LOGGER.debug("TRANSACTION {} ROLLBACK CHECK - {}", threadId, rollbackOnly);
if (!isActive()) {
throw new IllegalStateException("TRANSACTION NOT ACTIVE");
}
return rollbackOnly;
}
@Override
public void setRollbackOnly() throws IllegalStateException {
LOGGER.debug("TRANSACTION {} SET ROLLBACK - {}", threadId, rollbackOnly);
if (!isActive()) {
throw new IllegalStateException("TRANSACTION NOT ACTIVE");
}
rollbackOnly = true;
}
@Override
public boolean isActive() {
LOGGER.debug("TRANSACTION {} ACTIVE CHECK - {}", threadId, active);
return active;
}
/**
* Add Classifications to get Updated/Deleted once the Transaction gets Committed
* @param id The ID of the Classification
* @param type 'A' for created, 'M' for modified, 'D' deleted
*/
public static void addClassficationEvent(MCRCategoryID id, char type) {
if (!Objects.requireNonNull(id).isRootID()) {
throw new IllegalArgumentException("Only root category ids are allowed: " + id);
}
switch (type) {
case MCRAbstractMetadataVersion.CREATED, MCRAbstractMetadataVersion.DELETED -> CATEGORY_WORKSPACE.get()
.put(id, type);
case MCRAbstractMetadataVersion.UPDATED -> {
final char oldType = CATEGORY_WORKSPACE.get().getOrDefault(id, '0');
switch (oldType) {
case MCRAbstractMetadataVersion.CREATED:
case MCRAbstractMetadataVersion.UPDATED:
break;
case '0':
CATEGORY_WORKSPACE.get().put(id, type);
break;
case MCRAbstractMetadataVersion.DELETED:
throw new IllegalArgumentException("Cannot update a deleted classification: " + id);
default:
throw new IllegalStateException(
"Unsupported type in classification found: " + oldType + ", " + id);
}
}
default -> throw new IllegalStateException(
"Unsupported event type for classification found: " + type + ", " + id);
}
}
}
| 8,061 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLMCRRepositoryProvider.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/repository/MCROCFLMCRRepositoryProvider.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.ocfl.repository;
import java.io.IOException;
import org.mycore.common.config.annotation.MCRPostConstruction;
import org.mycore.ocfl.layout.MCRStorageLayoutConfig;
import org.mycore.ocfl.layout.MCRStorageLayoutExtension;
import io.ocfl.core.extension.OcflExtensionConfig;
import io.ocfl.core.extension.OcflExtensionRegistry;
import jakarta.inject.Singleton;
/**
* Repository Provider for the MyCoRe-Storage-Layout
* @author Tobias Lenhardt [Hammer1279]
*/
@Singleton
public class MCROCFLMCRRepositoryProvider extends MCROCFLHashRepositoryProvider {
@Override
@MCRPostConstruction
public void init(String prop) throws IOException {
OcflExtensionRegistry.register(MCRStorageLayoutExtension.EXTENSION_NAME, MCRStorageLayoutExtension.class);
super.init(prop);
}
@Override
public OcflExtensionConfig getExtensionConfig() {
return new MCRStorageLayoutConfig();
}
}
| 1,665 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLHashRepositoryProvider.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/repository/MCROCFLHashRepositoryProvider.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.ocfl.repository;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.mycore.common.config.annotation.MCRPostConstruction;
import org.mycore.common.config.annotation.MCRProperty;
import io.ocfl.api.OcflRepository;
import io.ocfl.core.OcflRepositoryBuilder;
import io.ocfl.core.extension.OcflExtensionConfig;
import io.ocfl.core.extension.storage.layout.config.HashedNTupleIdEncapsulationLayoutConfig;
import jakarta.inject.Singleton;
/**
* Simple way to provide a {@link OcflRepository}
*/
@Singleton
public class MCROCFLHashRepositoryProvider extends MCROCFLRepositoryProvider {
protected Path repositoryRoot;
protected Path workDir;
protected OcflRepository repository;
@Override
public OcflRepository getRepository() {
return repository;
}
@MCRPostConstruction
public void init(String prop) throws IOException {
if (Files.notExists(workDir)) {
Files.createDirectories(workDir);
}
if (Files.notExists(repositoryRoot)) {
Files.createDirectories(repositoryRoot);
}
this.repository = new OcflRepositoryBuilder()
.defaultLayoutConfig(getExtensionConfig())
.storage(storage -> storage.fileSystem(repositoryRoot))
.workDir(workDir)
.build();
}
public OcflExtensionConfig getExtensionConfig() {
return new HashedNTupleIdEncapsulationLayoutConfig();
}
public Path getRepositoryRoot() {
return repositoryRoot;
}
public Path getWorkDir() {
return workDir;
}
@MCRProperty(name = "RepositoryRoot")
public MCROCFLHashRepositoryProvider setRepositoryRoot(String repositoryRoot) {
this.repositoryRoot = Paths.get(repositoryRoot);
return this;
}
@MCRProperty(name = "WorkDir")
public MCROCFLHashRepositoryProvider setWorkDir(String workDir) {
this.workDir = Paths.get(workDir);
return this;
}
}
| 2,773 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLRepositoryProvider.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/repository/MCROCFLRepositoryProvider.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.ocfl.repository;
import org.mycore.common.config.MCRConfiguration2;
import io.ocfl.api.OcflRepository;
import io.ocfl.core.extension.OcflExtensionConfig;
/**
* Base Class to provide a {@link OcflRepository}. A {@link MCROCFLRepositoryProvider} will be loaded from the property
* <code>MCR.OCFL.Repository.%id%</code> and the Method getRepository will be executed.
*/
public abstract class MCROCFLRepositoryProvider {
public static final String REPOSITORY_PROPERTY_PREFIX = "MCR.OCFL.Repository.";
public static OcflRepository getRepository(String id) {
return MCRConfiguration2.getSingleInstanceOf(REPOSITORY_PROPERTY_PREFIX + id)
.map(MCROCFLRepositoryProvider.class::cast)
.get()
.getRepository();
}
public abstract OcflRepository getRepository();
public abstract OcflExtensionConfig getExtensionConfig();
}
| 1,630 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRGZIPOCFLXMLMetadataManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/MCRGZIPOCFLXMLMetadataManager.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.ocfl.metadata;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.mycore.common.content.MCRContent;
import org.mycore.datamodel.metadata.MCRObjectID;
import io.ocfl.api.model.OcflObjectVersion;
import io.ocfl.api.model.VersionNum;
public class MCRGZIPOCFLXMLMetadataManager extends MCROCFLXMLMetadataManager {
@Override
protected InputStream getContentStream(MCRContent xml) throws IOException {
InputStream contentStream = super.getContentStream(xml);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try(GZIPOutputStream out = new GZIPOutputStream(baos)){
contentStream.transferTo(out);
}
byte[] byteArray = baos.toByteArray();
return new ByteArrayInputStream(byteArray);
}
@Override
protected InputStream getStoredContentStream(MCRObjectID mcrid, OcflObjectVersion storeObject) throws IOException {
InputStream storedContentStream = super.getStoredContentStream(mcrid, storeObject);
return new GZIPInputStream(storedContentStream);
}
@Override
protected MCROCFLContent getContent(MCRObjectID id, String ocflObjectID, VersionNum key) {
return new MCRGZIPOCFLContent(getRepository(), ocflObjectID, buildFilePath(id),
key.toString());
}
@Override
protected String buildFilePath(MCRObjectID mcrid) {
return super.buildFilePath(mcrid) + ".gz";
}
}
| 2,334 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/MCROCFLContent.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.ocfl.metadata;
import java.io.IOException;
import java.io.InputStream;
import org.mycore.common.content.MCRContent;
import io.ocfl.api.OcflRepository;
import io.ocfl.api.model.ObjectVersionId;
public class MCROCFLContent extends MCRContent {
private OcflRepository repository;
private String objectid;
private String fileName;
private String version = null;
public MCROCFLContent(OcflRepository repository, String objectid, String fileName, String version) {
this.repository = repository;
this.objectid = objectid;
this.fileName = fileName;
this.version = version;
}
public MCROCFLContent(OcflRepository repository, String objectid, String fileName) {
this.repository = repository;
this.objectid = objectid;
this.fileName = fileName;
}
@Override
public InputStream getInputStream() throws IOException {
return repository
.getObject(version == null ? ObjectVersionId.head(objectid) : ObjectVersionId.version(objectid, version))
.getFile(fileName).getStream();
}
}
| 1,852 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRGZIPOCFLContent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/MCRGZIPOCFLContent.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.ocfl.metadata;
import io.ocfl.api.OcflRepository;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
public class MCRGZIPOCFLContent extends MCROCFLContent {
public MCRGZIPOCFLContent(OcflRepository repository, String objectid, String fileName, String version) {
super(repository, objectid, fileName, version);
}
public MCRGZIPOCFLContent(OcflRepository repository, String objectid, String fileName) {
super(repository, objectid, fileName);
}
@Override
public InputStream getInputStream() throws IOException {
InputStream inputStream = super.getInputStream();
return new GZIPInputStream(inputStream);
}
}
| 1,461 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLXMLMetadataManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/MCROCFLXMLMetadataManager.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.ocfl.metadata;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.mycore.common.MCRCache;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRUsageException;
import org.mycore.common.MCRUserInformation;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.annotation.MCRProperty;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.content.MCRStreamContent;
import org.mycore.datamodel.common.MCRObjectIDDate;
import org.mycore.datamodel.common.MCRXMLMetadataManagerAdapter;
import org.mycore.datamodel.ifs2.MCRObjectIDDateImpl;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.metadata.history.MCRMetadataHistoryManager;
import org.mycore.ocfl.layout.MCRStorageLayoutConfig;
import org.mycore.ocfl.layout.MCRStorageLayoutExtension;
import org.mycore.ocfl.repository.MCROCFLHashRepositoryProvider;
import org.mycore.ocfl.repository.MCROCFLMCRRepositoryProvider;
import org.mycore.ocfl.repository.MCROCFLRepositoryProvider;
import org.mycore.ocfl.util.MCROCFLDeleteUtils;
import org.mycore.ocfl.util.MCROCFLMetadataVersion;
import org.mycore.ocfl.util.MCROCFLObjectIDPrefixHelper;
import io.ocfl.api.OcflOption;
import io.ocfl.api.OcflRepository;
import io.ocfl.api.exception.NotFoundException;
import io.ocfl.api.exception.OverwriteException;
import io.ocfl.api.model.ObjectVersionId;
import io.ocfl.api.model.OcflObjectVersion;
import io.ocfl.api.model.VersionDetails;
import io.ocfl.api.model.VersionInfo;
import io.ocfl.api.model.VersionNum;
import io.ocfl.core.extension.OcflExtensionConfig;
import io.ocfl.core.extension.storage.layout.HashedNTupleIdEncapsulationLayoutExtension;
import io.ocfl.core.extension.storage.layout.config.HashedNTupleIdEncapsulationLayoutConfig;
/**
* Manages persistence of MCRObject and MCRDerivate xml metadata. Provides
* methods to create, retrieve, update and delete object metadata using OCFL
*/
public class MCROCFLXMLMetadataManager implements MCRXMLMetadataManagerAdapter {
private static final String MESSAGE_CREATED = "Created";
private static final String MESSAGE_UPDATED = "Updated";
private static final String MESSAGE_DELETED = "Deleted";
private static final Map<String, Character> MESSAGE_TYPE_MAPPING = Collections.unmodifiableMap(Map.ofEntries(
Map.entry(MESSAGE_CREATED, MCROCFLMetadataVersion.CREATED),
Map.entry(MESSAGE_UPDATED, MCROCFLMetadataVersion.UPDATED),
Map.entry(MESSAGE_DELETED, MCROCFLMetadataVersion.DELETED)));
private String repositoryKey = "Default";
private static char convertMessageToType(String message) throws MCRPersistenceException {
if (!MESSAGE_TYPE_MAPPING.containsKey(message)) {
throw new MCRPersistenceException("Cannot identify version type from message '" + message + "'");
}
return MESSAGE_TYPE_MAPPING.get(message);
}
public OcflRepository getRepository() {
return MCROCFLRepositoryProvider.getRepository(getRepositoryKey());
}
public String getRepositoryKey() {
return repositoryKey;
}
@MCRProperty(name = "Repository", required = false)
public void setRepositoryKey(String repositoryKey) {
this.repositoryKey = repositoryKey;
}
@Override
public void reload() {
// nothing to reload here
}
@Override
public void verifyStore(String base) {
// not supported yet
}
@Override
public void create(MCRObjectID mcrid, MCRContent xml, Date lastModified) throws MCRPersistenceException {
create(mcrid, xml, lastModified, null);
}
public void create(MCRObjectID mcrid, MCRContent xml, Date lastModified, String user)
throws MCRPersistenceException {
String ocflObjectID = getOCFLObjectID(mcrid);
VersionInfo info = buildVersionInfo(MESSAGE_CREATED, lastModified, user);
try (InputStream objectAsStream = getContentStream(xml)) {
getRepository().updateObject(ObjectVersionId.head(ocflObjectID), info,
init -> init.writeFile(objectAsStream, buildFilePath(mcrid)));
} catch (IOException | OverwriteException e) {
throw new MCRPersistenceException("Failed to create object '" + ocflObjectID + "'", e);
}
}
protected InputStream getContentStream(MCRContent xml) throws IOException {
return xml.getInputStream();
}
@Override
public void delete(MCRObjectID mcrid) throws MCRPersistenceException {
delete(mcrid, null, null);
}
public void delete(MCRObjectID mcrid, Date date, String user) throws MCRPersistenceException {
String prefix = Objects.equals(mcrid.getTypeId(), "derivate") ? MCROCFLObjectIDPrefixHelper.MCRDERIVATE
: MCROCFLObjectIDPrefixHelper.MCROBJECT;
if (MCROCFLDeleteUtils.checkPurgeObject(mcrid, prefix)) {
purge(mcrid, date, user);
return;
}
String ocflObjectID = getOCFLObjectID(mcrid);
if (!exists(mcrid)) {
throw new MCRUsageException("Cannot delete nonexistent object '" + ocflObjectID + "'");
}
OcflRepository repo = getRepository();
VersionInfo headVersion = repo.describeObject(ocflObjectID).getHeadVersion().getVersionInfo();
char versionType = convertMessageToType(headVersion.getMessage());
if (versionType == MCROCFLMetadataVersion.DELETED) {
throw new MCRUsageException("Cannot delete already deleted object '" + ocflObjectID + "'");
}
repo.updateObject(ObjectVersionId.head(ocflObjectID), buildVersionInfo(MESSAGE_DELETED, date, null),
init -> init.removeFile(buildFilePath(mcrid)));
}
public void purge(MCRObjectID mcrid, Date date, String user) {
String ocflObjectID = getOCFLObjectID(mcrid);
if (!getRepository().containsObject(ocflObjectID)) {
throw new MCRUsageException("Cannot delete nonexistent object '" + ocflObjectID + "'");
}
OcflRepository repo = getRepository();
repo.purgeObject(ocflObjectID);
}
@Override
public void update(MCRObjectID mcrid, MCRContent xml, Date lastModified) throws MCRPersistenceException {
update(mcrid, xml, lastModified, null);
}
public void update(MCRObjectID mcrid, MCRContent xml, Date lastModified, String user)
throws MCRPersistenceException {
String ocflObjectID = getOCFLObjectID(mcrid);
if (!exists(mcrid)) {
throw new MCRUsageException("Cannot update nonexistent object '" + ocflObjectID + "'");
}
try (InputStream objectAsStream = getContentStream(xml)) {
VersionInfo versionInfo = buildVersionInfo(MESSAGE_UPDATED, lastModified, user);
getRepository().updateObject(ObjectVersionId.head(ocflObjectID), versionInfo,
init -> init.writeFile(objectAsStream, buildFilePath(mcrid), OcflOption.OVERWRITE));
} catch (IOException e) {
throw new MCRPersistenceException("Failed to update object '" + ocflObjectID + "'", e);
}
}
private String getOCFLObjectID(MCRObjectID mcrid) {
return getOCFLObjectID(mcrid.toString());
}
private String getOCFLObjectID(String mcrid) {
String objectType = MCRObjectID.getInstance(mcrid).getTypeId();
return Objects.equals(objectType, "derivate") ? MCROCFLObjectIDPrefixHelper.MCRDERIVATE + mcrid
: MCROCFLObjectIDPrefixHelper.MCROBJECT + mcrid;
}
protected String buildFilePath(MCRObjectID mcrid) {
return "metadata/" + mcrid + ".xml";
}
@Override
public MCRContent retrieveContent(MCRObjectID mcrid) throws IOException {
String ocflObjectID = getOCFLObjectID(mcrid);
OcflObjectVersion storeObject;
try {
storeObject = getRepository().getObject(ObjectVersionId.head(ocflObjectID));
} catch (NotFoundException e) {
throw new IOException("Object '" + ocflObjectID + "' could not be found", e);
}
if (convertMessageToType(
storeObject.getVersionInfo().getMessage()) == MCROCFLMetadataVersion.DELETED) {
throw new IOException("Cannot read already deleted object '" + ocflObjectID + "'");
}
// "metadata/" +
try (InputStream storedContentStream = getStoredContentStream(mcrid, storeObject)) {
return new MCRJDOMContent(new MCRStreamContent(storedContentStream).asXML());
} catch (JDOMException e) {
throw new IOException("Can not parse XML from OCFL-Store", e);
}
}
protected InputStream getStoredContentStream(MCRObjectID mcrid, OcflObjectVersion storeObject) throws IOException {
return storeObject.getFile(buildFilePath(mcrid)).getStream();
}
@Override
public MCRContent retrieveContent(MCRObjectID mcrid, String revision) throws IOException {
if (revision == null) {
return retrieveContent(mcrid);
}
String ocflObjectID = getOCFLObjectID(mcrid);
OcflObjectVersion storeObject;
OcflRepository repo = getRepository();
try {
storeObject = repo.getObject(ObjectVersionId.version(ocflObjectID, revision));
} catch (NotFoundException e) {
throw new IOException("Object '" + ocflObjectID + "' could not be found", e);
}
// maybe use .head(ocflObjectID) instead to prevent requests of old versions of deleted objects
if (convertMessageToType(repo.getObject(ObjectVersionId.version(ocflObjectID, revision)).getVersionInfo()
.getMessage()) == MCROCFLMetadataVersion.DELETED) {
throw new IOException("Cannot read already deleted object '" + ocflObjectID + "'");
}
try (InputStream storedContentStream = getStoredContentStream(mcrid, storeObject)) {
Document xml = new MCRStreamContent(storedContentStream).asXML();
xml.getRootElement().setAttribute("rev", revision); // bugfix: MCR-2510, PR #1373
return new MCRJDOMContent(xml);
} catch (JDOMException e) {
throw new IOException("Can not parse XML from OCFL-Store", e);
}
}
private VersionInfo buildVersionInfo(String message, Date versionDate, String user) {
VersionInfo versionInfo = new VersionInfo();
versionInfo.setMessage(message);
versionInfo.setCreated((versionDate == null ? new Date() : versionDate).toInstant().atOffset(ZoneOffset.UTC));
String userID = user != null ? user
: Optional.ofNullable(MCRSessionMgr.getCurrentSession())
.map(MCRSession::getUserInformation)
.map(MCRUserInformation::getUserID)
.orElse(null);
versionInfo.setUser(userID, null);
return versionInfo;
}
@Override
public List<MCROCFLMetadataVersion> listRevisions(MCRObjectID id) {
String ocflObjectID = getOCFLObjectID(id);
Map<VersionNum, VersionDetails> versionMap;
try {
versionMap = getRepository().describeObject(ocflObjectID).getVersionMap();
} catch (NotFoundException e) {
throw new MCRUsageException("Object '" + ocflObjectID + "' could not be found", e);
}
return versionMap.entrySet().stream().map(v -> {
VersionNum key = v.getKey();
VersionDetails details = v.getValue();
VersionInfo versionInfo = details.getVersionInfo();
MCROCFLContent content = getContent(id, ocflObjectID, key);
return new MCROCFLMetadataVersion(content,
key.toString(),
versionInfo.getUser().getName(),
Date.from(details.getCreated().toInstant()), convertMessageToType(versionInfo.getMessage()));
}).collect(Collectors.toList());
}
protected MCROCFLContent getContent(MCRObjectID id, String ocflObjectID, VersionNum key) {
return new MCROCFLContent(getRepository(), ocflObjectID, buildFilePath(id),
key.toString());
}
private boolean isMetadata(String id) {
return id.startsWith(MCROCFLObjectIDPrefixHelper.MCROBJECT)
|| id.startsWith(MCROCFLObjectIDPrefixHelper.MCRDERIVATE);
}
private String removePrefix(String id) {
return id.startsWith(MCROCFLObjectIDPrefixHelper.MCRDERIVATE)
? id.substring(MCROCFLObjectIDPrefixHelper.MCRDERIVATE.length())
: id.substring(MCROCFLObjectIDPrefixHelper.MCROBJECT.length());
}
public IntStream getStoredIDs(String project, String type) throws MCRPersistenceException {
return getRepository().listObjectIds()
.filter(this::isMetadata)
.map(this::removePrefix)
.filter(id -> id.startsWith(project + "_" + type))
.mapToInt((fullId) -> Integer.parseInt(fullId.substring(project.length() + type.length() + 2))).sorted();
}
@Override
public int getHighestStoredID(String project, String type) {
int highestStoredID = 0;
int maxDepth = Integer.MAX_VALUE;
MCROCFLRepositoryProvider oclfRepoProvider = MCRConfiguration2
.getSingleInstanceOf("MCR.OCFL.Repository." + repositoryKey)
.map(MCROCFLRepositoryProvider.class::cast).orElseThrow();
OcflExtensionConfig config = oclfRepoProvider.getExtensionConfig();
Path basePath = null;
// optimization for known layouts
if (Objects.equals(config.getExtensionName(), MCRStorageLayoutExtension.EXTENSION_NAME)) {
maxDepth = ((MCRStorageLayoutConfig) config).getSlotLayout().split("-").length;
basePath = ((MCROCFLMCRRepositoryProvider) oclfRepoProvider).getRepositoryRoot()
.resolve(MCROCFLObjectIDPrefixHelper.MCROBJECT.replace(":", ""))
.resolve(project).resolve(type);
highestStoredID = traverseMCRStorageDirectory(basePath, maxDepth);
} else if (Objects.equals(config.getExtensionName(),
HashedNTupleIdEncapsulationLayoutExtension.EXTENSION_NAME)) {
maxDepth = ((HashedNTupleIdEncapsulationLayoutConfig) config).getNumberOfTuples() + 1;
basePath = ((MCROCFLHashRepositoryProvider) oclfRepoProvider).getRepositoryRoot();
} else {
//for other repository provider implementation start with root directory
basePath = MCRConfiguration2.getString("MCR.OCFL.Repository." + repositoryKey + ".RepositoryRoot")
.map(Path::of).orElse(null);
}
if (basePath != null && highestStoredID == 0) {
Pattern pattern = Pattern.compile("^.*" + project + "_{1}" + type + "_{1}\\d+$");
try (Stream<Path> stream = Files.find(basePath, maxDepth,
(filePath, fileAttr) -> pattern.matcher(filePath.getFileName().toString()).matches())) {
highestStoredID = stream.map(entry -> entry.getFileName().toString())
.map(fileName -> Integer.parseInt(fileName.substring(fileName.lastIndexOf('_') + 1)))
.max(Integer::compareTo).orElse(0);
} catch (Exception e) {
// nothing found, let the HistoryManager take over
}
}
return Math.max(highestStoredID, MCRMetadataHistoryManager.getHighestStoredID(project, type)
.map(MCRObjectID::getNumberAsInteger)
.orElse(0));
}
/**
* This method recursively parses a directory structure in MCRStorageLayout,
* like this:
* <pre>
* ocfl-root
* +-- mcrobject
* +-- mir
* +-- mods
* +-- 0000
* +-- 00
* +-- mir_mods_0000000018
* ...
* +-- mir_mods_0000004567
* ...
* +-- mir_mods_0000009997
* +-- 01
* +-- mir_mods_0000010001
* ...
* +-- mir_mods_0000014567
* ...
* +-- mir_mods_0000017654
* </pre>
*
* and searches on each level for the directory with the highest number at the end of it's name
* finally it returns the highest available number part of a MyCoRe object id.
*
* @param path - the root path
* @param depth - the level of subdirectories to look into
* @return the highest number, or 0 if such cannot be found
*/
private int traverseMCRStorageDirectory(Path path, int depth) {
int max = -1;
Path newPath = path;
try (DirectoryStream<Path> ds = Files.newDirectoryStream(path,
p -> p.getFileName().toString().matches("^.*\\d+$"))) {
for (Path entry : ds) {
int current = Integer.parseInt(entry.getFileName().toString().replaceAll("^.*_", ""));
if (max < current) {
max = current;
newPath = entry;
}
}
} catch (IOException | NumberFormatException e) {
// fallback to slower full tree search
return 0;
}
if (depth <= 1) {
return Math.max(0, max);
} else {
return traverseMCRStorageDirectory(newPath, depth - 1);
}
}
@Override
public boolean exists(MCRObjectID mcrid) throws MCRPersistenceException {
String ocflObjectID = getOCFLObjectID(mcrid);
return getRepository().containsObject(ocflObjectID) && isNotDeleted(ocflObjectID);
}
@Override
public List<String> listIDsForBase(String base) {
return getRepository().listObjectIds()
.filter(this::isMetadata)
.filter(this::isNotDeleted)
.map(this::removePrefix)
.filter(s -> s.startsWith(base))
.collect(Collectors.toList());
}
@Override
public List<String> listIDsOfType(String type) {
return getRepository().listObjectIds()
.filter(this::isMetadata)
.filter(this::isNotDeleted)
.map(this::removePrefix)
.filter(s -> type.equals(s.split("_")[1]))
.collect(Collectors.toList());
}
@Override
public List<String> listIDs() {
OcflRepository repo = getRepository();
return repo
.listObjectIds()
.filter(this::isMetadata)
.filter(this::isNotDeleted)
.map(this::removePrefix)
.collect(Collectors.toList());
}
private boolean isNotDeleted(String ocflID) {
return convertMessageToType(getRepository().describeVersion(ObjectVersionId.head(ocflID)).getVersionInfo()
.getMessage()) != MCROCFLMetadataVersion.DELETED;
}
@Override
public Collection<String> getObjectTypes() {
return getRepository()
.listObjectIds()
.filter(this::isMetadata)
.map(this::removePrefix)
.map(s -> s.split("_")[1])
.distinct()
.collect(Collectors.toList());
}
@Override
public Collection<String> getObjectBaseIds() {
return getRepository()
.listObjectIds()
.filter(this::isMetadata)
.map(this::removePrefix)
.map(s -> s.substring(0, s.lastIndexOf("_")))
.distinct()
.collect(Collectors.toList());
}
@Override
public List<MCRObjectIDDate> retrieveObjectDates(List<String> ids) throws IOException {
try {
return ids.stream()
.filter(this::isMetadata)
.filter(this::isNotDeleted)
.map(this::removePrefix)
.map(id -> {
try {
return new MCRObjectIDDateImpl(new Date(getLastModified(getOCFLObjectID(id))), id);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
})
.collect(Collectors.toList());
} catch (UncheckedIOException e) {
throw e.getCause();
}
}
@Override
public long getLastModified(MCRObjectID id) throws IOException {
return getLastModified(getOCFLObjectID(id));
}
public long getLastModified(String ocflObjectId) throws IOException {
try {
return Date.from(getRepository()
.getObject(ObjectVersionId.head(ocflObjectId))
.getVersionInfo()
.getCreated()
.toInstant())
.getTime();
} catch (NotFoundException e) {
throw new IOException(e);
}
}
@Override
public MCRCache.ModifiedHandle getLastModifiedHandle(MCRObjectID id, long expire, TimeUnit unit) {
return new MCROCFLXMLMetadataManager.StoreModifiedHandle(id, expire, unit);
}
private final class StoreModifiedHandle implements MCRCache.ModifiedHandle {
private final long expire;
private final MCRObjectID id;
private StoreModifiedHandle(MCRObjectID id, long time, TimeUnit unit) {
this.expire = unit.toMillis(time);
this.id = id;
}
@Override
public long getCheckPeriod() {
return expire;
}
@Override
public long getLastModified() throws IOException {
return MCROCFLXMLMetadataManager.this.getLastModified(id);
}
}
}
| 23,056 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLRevisionPruner.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/migration/MCROCFLRevisionPruner.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.ocfl.metadata.migration;
import org.jdom2.JDOMException;
import java.io.IOException;
import java.util.List;
/**
* Prunes a list of revisions to remove any that are not needed.
*/
public interface MCROCFLRevisionPruner {
List<MCROCFLRevision> prune(List<MCROCFLRevision> revisions) throws IOException, JDOMException;
}
| 1,074 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLCombineComparePruner.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/migration/MCROCFLCombineComparePruner.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.ocfl.metadata.migration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.mycore.common.content.MCRContent;
import org.mycore.datamodel.common.MCRMetadataVersionType;
/**
* A pruner that combines and compares revisions to decide which to keep and which to discard.
* The method {@link #getMergeDecider()} should return a {@link RevisionMergeDecider} that decides if two
* revisions should be merged.
*
* The method {@link #buildMergedRevision(MCROCFLRevision, MCROCFLRevision, Document, Document)} should return a new
* revision that is the result of merging the two given revisions.
*/
public abstract class MCROCFLCombineComparePruner implements MCROCFLRevisionPruner {
private static final Logger LOGGER = LogManager.getLogger();
@Override
public List<MCROCFLRevision> prune(List<MCROCFLRevision> revisions) throws IOException, JDOMException {
ArrayList<MCROCFLRevision> newRevisions = new ArrayList<>();
Iterator<MCROCFLRevision> iterator = revisions.listIterator();
if (!iterator.hasNext()) {
return newRevisions;
}
MCROCFLRevision last = iterator.next();
RevisionMergeDecider comparator = getMergeDecider();
while (iterator.hasNext()) {
MCROCFLRevision next = iterator.next();
if (last.type() != MCRMetadataVersionType.DELETED && next.type() != MCRMetadataVersionType.DELETED) {
MCRContent currentContent = last.contentSupplier().get();
Document currentDocument = currentContent.asXML();
MCRContent nextContent = next.contentSupplier().get();
Document nextDocument = nextContent.asXML();
if (comparator.shouldMerge(last, currentDocument, next,nextDocument)) {
LOGGER.info("Merging revisions {} and {}", last, next);
last = buildMergedRevision(last, next, currentDocument, nextDocument);
continue;
}
}
LOGGER.info("Keeping revision {}", last);
newRevisions.add(last);
last = next;
}
LOGGER.info("Keeping revision {}", last);
newRevisions.add(last);
return newRevisions;
}
/**
* Returns a {@link RevisionMergeDecider} that decides if two revisions should be merged.
* @return a {@link RevisionMergeDecider}
*/
public abstract RevisionMergeDecider getMergeDecider();
/**
* Builds a new revision that is the result of merging the two given revisions.
* @param current the current revision
* @param next the next revision to merge
* @param currentDocument the current document
* @param nextDocument the document of the next revision
* @return a new revision that is the result of merging the two given revisions
*/
public abstract MCROCFLRevision buildMergedRevision(MCROCFLRevision current, MCROCFLRevision next,
Document currentDocument, Document nextDocument);
/**
* A decider that decides if two revisions should be merged.
*/
public interface RevisionMergeDecider {
boolean shouldMerge(MCROCFLRevision revision1, Document document1,
MCROCFLRevision revision2, Document document2);
}
}
| 4,234 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLMigration.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/migration/MCROCFLMigration.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.ocfl.metadata.migration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.IntStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.datamodel.common.MCRAbstractMetadataVersion;
import org.mycore.datamodel.common.MCRMetadataVersionType;
import org.mycore.datamodel.common.MCRObjectIDGenerator;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.ocfl.metadata.MCROCFLXMLMetadataManager;
public class MCROCFLMigration {
private static final Logger LOGGER = LogManager.getLogger();
private final MCROCFLXMLMetadataManager target;
private final ArrayList<String> invalidState;
private final ArrayList<String> withoutHistory;
private final ArrayList<String> success;
private final ArrayList<String> failed;
private final List<MCROCFLRevisionPruner> pruners;
public MCROCFLMigration(String newRepoKey) {
this(newRepoKey, new ArrayList<>());
}
public MCROCFLMigration(String newRepoKey, List<MCROCFLRevisionPruner> pruners) {
this(newRepoKey, pruners, new MCROCFLXMLMetadataManager());
}
public MCROCFLMigration(String newRepoKey, List<MCROCFLRevisionPruner> pruners, MCROCFLXMLMetadataManager target) {
this.target = target;
if (newRepoKey != null) {
target.setRepositoryKey(newRepoKey);
}
invalidState = new ArrayList<>();
withoutHistory = new ArrayList<>();
success = new ArrayList<>();
failed = new ArrayList<>();
this.pruners = pruners;
}
public ArrayList<String> getInvalidState() {
return invalidState;
}
public ArrayList<String> getWithoutHistory() {
return withoutHistory;
}
public ArrayList<String> getSuccess() {
return success;
}
public ArrayList<String> getFailed() {
return failed;
}
public void start() {
MCRObjectIDGenerator mcrObjectIDGenerator = MCRMetadataManager.getMCRObjectIDGenerator();
for (String baseId : mcrObjectIDGenerator.getBaseIDs()) {
int maxId = mcrObjectIDGenerator.getLastID(baseId).getNumberAsInteger();
List<String> possibleIds = IntStream.rangeClosed(1, maxId)
.mapToObj(i -> MCRObjectID.formatID(baseId, i))
.toList();
for (String id : possibleIds) {
LOGGER.info("Try migrate {}", id);
migrateID(id);
}
}
}
private void migrateID(String id) {
List<? extends MCRAbstractMetadataVersion<?>> revisions;
MCRObjectID objectID = MCRObjectID.getInstance(id);
revisions = readRevisions(objectID);
List<MCROCFLRevision> steps = new ArrayList<>();
if (revisions != null) {
try {
for (MCRAbstractMetadataVersion<?> rev : revisions) {
MCROCFLRevision step = migrateRevision(rev, objectID);
// read one time now, to avoid errors later, but do not store it
retriveActualContent(rev);
steps.add(step);
}
} catch (Exception e) {
// an error happened, so all steps are useless
LOGGER.warn("Error while receiving all information which are needed to migrate the object " + id, e);
steps.clear();
}
}
int originalStepsSize = steps.size();
for (MCROCFLRevisionPruner pruner : pruners) {
try {
int size = steps.size();
steps = pruner.prune(steps);
LOGGER.info("Pruned {} revisions to {} with {}", size, steps.size(), pruner);
} catch (IOException | JDOMException e) {
LOGGER.warn("Error while pruning " + id, e);
failed.add(id);
return;
}
}
if (originalStepsSize > 0) {
// try version migration
try {
for (MCROCFLRevision step : steps) {
writeRevision(step, objectID);
}
success.add(id);
return;
} catch (Exception e) {
// invalid state now
LOGGER.warn("Error while migrating " + id, e);
invalidState.add(id);
return;
}
}
MCRXMLMetadataManager instance = MCRXMLMetadataManager.instance();
// does it even exist?
if (instance.exists(objectID)) {
// try without versions
MCRJDOMContent jdomContent;
long lastModified;
try {
MCRContent mcrContent = instance.retrieveContent(objectID);
jdomContent = new MCRJDOMContent(mcrContent.asXML());
lastModified = instance.getLastModified(objectID);
} catch (IOException | JDOMException e) {
// can not even read the object
LOGGER.warn("Error while migrating " + id, e);
failed.add(id);
return;
}
target.create(objectID, jdomContent, new Date(lastModified));
withoutHistory.add(id);
}
}
private void writeRevision(MCROCFLRevision step, MCRObjectID objectID) throws IOException {
switch (step.type()) {
case CREATED -> target.create(objectID, step.contentSupplier().get(), step.date());
case MODIFIED -> target.update(objectID, step.contentSupplier().get(), step.date());
case DELETED -> target.delete(objectID, step.date(), step.user());
}
}
private MCROCFLRevision migrateRevision(MCRAbstractMetadataVersion<?> rev, MCRObjectID objectID)
throws IOException {
String user = rev.getUser();
Date date = rev.getDate();
LOGGER.info("Migrate revision {} of {}", rev.getRevision(), objectID);
MCRMetadataVersionType type = MCRMetadataVersionType.fromValue(rev.getType());
ContentSupplier supplier = type == MCRMetadataVersionType.DELETED ? null : () -> retriveActualContent(rev);
return new MCROCFLRevision(type, supplier, user, date, objectID);
}
private MCRContent retriveActualContent(MCRAbstractMetadataVersion<?> rev) throws IOException {
if (rev.getType() == MCRAbstractMetadataVersion.DELETED) {
return null;
}
MCRContent content = rev.retrieve();
Document document;
try {
document = content.asXML();
} catch (JDOMException e) {
throw new IOException("Error while reading as as XML", e);
}
return new MCRJDOMContent(document);
}
private List<? extends MCRAbstractMetadataVersion<?>> readRevisions(MCRObjectID objectID) {
List<? extends MCRAbstractMetadataVersion<?>> revisions = null;
MCRXMLMetadataManager instance = MCRXMLMetadataManager.instance();
try {
revisions = instance.listRevisions(objectID);
} catch (Exception e) {
LOGGER.error("Could not read revisions of {}", objectID, e);
}
return revisions;
}
public interface ContentSupplier {
MCRContent get() throws IOException;
}
}
| 8,371 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLCombineIgnoreXPathPruner.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/migration/MCROCFLCombineIgnoreXPathPruner.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.ocfl.metadata.migration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import org.jdom2.Content;
import org.jdom2.Document;
import org.jdom2.Parent;
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.mycore.common.MCRConstants;
import org.mycore.common.config.annotation.MCRProperty;
import org.mycore.common.xml.MCRXMLHelper;
import org.mycore.datamodel.common.MCRMetadataVersionType;
/**
* A pruner that combines and compares revisions, based on an XPath expression, to decide which to keep and which to
* discard.
* The XPath expression marks content that should be ignored when comparing two revisions and when the content is equal,
* the revisions are merged. There is a property NeedSameAuthor that can be set to true to require that the revisions
* have the same author. The properties FirstAuthorWins and FirstDateWins can be set to true to decide which revision
* metadata should be used in the merged revision.
*/
public class MCROCFLCombineIgnoreXPathPruner extends MCROCFLCombineComparePruner
implements MCROCFLCombineComparePruner.RevisionMergeDecider {
private XPathExpression<Content> xpath;
private boolean firstAuthorWins;
private boolean firstDateWins;
private boolean needSameAuthor;
public XPathExpression<Content> getXpath() {
return xpath;
}
@MCRProperty(name = "XPath", required = true)
public void setXpath(String xpath) {
this.xpath = MCRConstants.XPATH_FACTORY.compile(xpath, Filters.content(), null,
MCRConstants.getStandardNamespaces());
}
public void setXpath(XPathExpression<Content> xpath) {
this.xpath = xpath;
}
public boolean isFirstAuthorWins() {
return firstAuthorWins;
}
@MCRProperty(name = "FirstAuthorWins", required = true)
public void setFirstAuthorWins(String firstAuthorWins) {
this.firstAuthorWins = Boolean.parseBoolean(firstAuthorWins);
}
public void setFirstAuthorWins(boolean firstAuthorWins) {
this.firstAuthorWins = firstAuthorWins;
}
public boolean isFirstDateWins() {
return firstDateWins;
}
@MCRProperty(name = "FirstDateWins", required = true)
public void setFirstDateWins(String firstDateWins) {
this.firstDateWins = Boolean.parseBoolean(firstDateWins);
}
public void setFirstDateWins(boolean firstDateWins) {
this.firstDateWins = firstDateWins;
}
@Override
public RevisionMergeDecider getMergeDecider() {
return this;
}
@MCRProperty(name = "NeedSameAuthor", required = true)
public void setNeedSameAuthor(String needSameAuthor) {
this.needSameAuthor = Boolean.parseBoolean(needSameAuthor);
}
public void setNeedSameAuthor(boolean needSameAuthor) {
this.needSameAuthor = needSameAuthor;
}
public boolean needSameAuthor() {
return needSameAuthor;
}
@Override
public MCROCFLRevision buildMergedRevision(MCROCFLRevision current, MCROCFLRevision next, Document currentDocument,
Document nextDocument) {
MCRMetadataVersionType type = current.type();
String user = chooseUser(current, next);
Date date = chooseDate(current, next);
if (type == MCRMetadataVersionType.DELETED) {
throw new IllegalArgumentException("Unsupported type: " + type);
}
return new MCROCFLRevision(type, next.contentSupplier(), user, date, next.objectID());
}
public String chooseUser(MCROCFLRevision current, MCROCFLRevision next) {
if (isFirstAuthorWins()) {
return current.user();
} else {
return next.user();
}
}
public Date chooseDate(MCROCFLRevision current, MCROCFLRevision next) {
if (isFirstDateWins()) {
return current.date();
} else {
return next.date();
}
}
private void pruneXPathMatches(Document o1Clone) {
List<Content> evaluate = getXpath().evaluate(o1Clone);
for (Content content : new ArrayList<>(evaluate)) {
Parent parent = content.getParent();
if (parent != null) {
parent.removeContent(content);
}
}
}
@Override
public boolean shouldMerge(MCROCFLRevision revision1, Document document1, MCROCFLRevision revision2,
Document document2) {
if (needSameAuthor() && !Objects.equals(revision1.user(), revision2.user())) {
return false;
}
Document document1Clone = document1.clone();
Document document2Clone = document2.clone();
pruneXPathMatches(document1Clone);
pruneXPathMatches(document2Clone);
return MCRXMLHelper.deepEqual(document1Clone, document2Clone);
}
@Override
public String toString() {
return "MCROCFLCombineIgnoreXPathPruner{" +
"xpath=" + xpath.getExpression() +
", firstAuthorWins=" + firstAuthorWins +
", firstDateWins=" + firstDateWins +
", needSameAuthor=" + needSameAuthor +
'}';
}
}
| 5,932 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLRevision.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/metadata/migration/MCROCFLRevision.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.ocfl.metadata.migration;
import java.util.Date;
import org.mycore.datamodel.common.MCRMetadataVersionType;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.ocfl.metadata.migration.MCROCFLMigration.ContentSupplier;
public record MCROCFLRevision(MCRMetadataVersionType type,
ContentSupplier contentSupplier,
String user,
Date date,
MCRObjectID objectID) {
}
| 1,140 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStorageLayoutExtension.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/layout/MCRStorageLayoutExtension.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.ocfl.layout;
import org.mycore.ocfl.util.MCROCFLObjectIDPrefixHelper;
import io.ocfl.api.exception.OcflExtensionException;
import io.ocfl.core.extension.OcflExtensionConfig;
import io.ocfl.core.extension.storage.layout.OcflStorageLayoutExtension;
public class MCRStorageLayoutExtension implements OcflStorageLayoutExtension {
public static final String EXTENSION_NAME = "mycore-storage-layout";
private MCRStorageLayoutConfig config;
/**
* {@inheritDoc}
*/
@Override
public String getExtensionName() {
return EXTENSION_NAME;
}
/**
* {@inheritDoc}
*/
@Override
public String getDescription() {
return "OCFL object identifiers are separated by their parts, " +
"the namespace gets used for defining the type, the ID Parts calculated from the " +
"MCR SlotLayout get used in nesting the paths under the OCFL Storage root.";
}
/**
* {@inheritDoc}
*/
@Override
public synchronized void init(OcflExtensionConfig config) {
this.config = (MCRStorageLayoutConfig) config;
}
@Override
public Class<? extends OcflExtensionConfig> getExtensionConfigClass() {
return MCRStorageLayoutConfig.class;
}
/**
* {@inheritDoc}
*/
@Override
public String mapObjectId(String objectId) {
if (config == null) {
throw new OcflExtensionException("Extension must be initialized before usage!");
}
StringBuilder builder = new StringBuilder();
String type = objectId.substring(0, objectId.indexOf(':') + 1);
builder.append(type.substring(0, type.length() - 1)).append('/');
switch (type) {
case MCROCFLObjectIDPrefixHelper.MCROBJECT, MCROCFLObjectIDPrefixHelper.MCRDERIVATE -> {
String mcrid = objectId.replaceAll(".*:", "");
String[] idParts = mcrid.split("_");
builder.append(idParts[0]).append('/').append(idParts[1]).append('/');
String id = idParts[2];
String[] layers = config.getSlotLayout().split("-");
int position = 0;
for (int i = 0; i < layers.length; i++) {
if (i == layers.length - 1) {
break;
}
int layerNum = Integer.parseInt(layers[i]);
if (layerNum <= 0) {
continue;
}
String layerId = id.substring(position, position + layerNum);
builder.append(layerId).append('/');
position += layerNum;
}
builder.append(mcrid);
return builder.toString();
}
// add more switch cases for own type behaviour
default -> {
return type.substring(0, type.length() - 1) + "/" + objectId.replaceAll(".*:", "");
}
}
}
}
| 3,734 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStorageLayoutConfig.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/layout/MCRStorageLayoutConfig.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.ocfl.layout;
import org.mycore.common.config.MCRConfiguration2;
import io.ocfl.api.util.Enforce;
import io.ocfl.core.extension.OcflExtensionConfig;
public class MCRStorageLayoutConfig implements OcflExtensionConfig {
public String extensionName;
private String slotLayout;
public MCRStorageLayoutConfig() {
slotLayout = MCRConfiguration2.getString("MCR.OCFL.MyCoReStorageLayout.SlotLayout").orElseGet(() -> {
String pattern = MCRConfiguration2.getString("MCR.Metadata.ObjectID.NumberPattern").orElse("0000000000");
return pattern.length() - 4 + "-2-2";
});
}
@Override
public String getExtensionName() {
return MCRStorageLayoutExtension.EXTENSION_NAME;
}
@Override
public boolean hasParameters() {
return true;
}
/**
* Overwrites the Class SlotLayout for the OCFL Repository
*
* @param slotLayout MyCoRe SlotLayout, see MCRStore for more info
* @return MCRLayoutConfig
*/
public MCRStorageLayoutConfig setSlotLayout(String slotLayout) {
this.slotLayout = Enforce.notNull(slotLayout, "Class SlotLayout cannot be null!");
return this;
}
/**
* @return Current SlotLayout
*/
public String getSlotLayout() {
return this.slotLayout;
}
}
| 2,068 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLRegexCommands.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/commands/MCROCFLRegexCommands.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.ocfl.commands;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.cli.annotation.MCRCommand;
import org.mycore.frontend.cli.annotation.MCRCommandGroup;
import org.mycore.ocfl.classification.MCROCFLXMLClassificationManager;
import org.mycore.ocfl.metadata.MCROCFLXMLMetadataManager;
import org.mycore.ocfl.repository.MCROCFLRepositoryProvider;
import org.mycore.ocfl.user.MCROCFLXMLUserManager;
import org.mycore.ocfl.util.MCROCFLObjectIDPrefixHelper;
import io.ocfl.api.OcflRepository;
/**
* All OCFL commands utilizing RegEx for bulk operations
* @author Tobias Lenhardt [Hammer1279]
*/
@MCRCommandGroup(name = "OCFL Regular Expression Commands")
public class MCROCFLRegexCommands {
private static final Logger LOGGER = LogManager.getLogger();
private static boolean confirmPurge = false;
private static String metadataRepositoryKey = MCRConfiguration2.getString("MCR.Metadata.Manager.Repository")
.orElse(null);
private static String classificationRepositoryKey = MCRConfiguration2
.getString("MCR.Classification.Manager.Repository").orElse(null);
private static String userRepositoryKey = MCRConfiguration2.getString("MCR.Users.Manager.Repository").orElse(null);
/*
* add other regex as well in the future:
* delete,update,sync
* list -> dry run
*/
// Purge
@SuppressWarnings("MixedMutabilityReturnType")
@MCRCommand(syntax = "purge all ocfl entries matching {0}",
help = "Purge all ocfl entries that match the given regex, use .* for all")
public static List<String> purgeMatchAll(String regex) {
if (!confirmPurge) {
LOGGER.info("\n"
+ "\u001B[93m" + "Enter the command again to confirm \u001B[4mPERMANENTLY\u001B[24m deleting ALL"
+ " matching OCFL entries." + "\u001B[0m" + "\n"
+ "\u001B[41m" + "THIS ACTION CANNOT BE UNDONE!" + "\u001B[0m");
confirmPurge = true;
return Collections.emptyList();
}
List<String> commands = new ArrayList<>();
String[] parts = regex.split(":", 2);
if (parts.length < 2) {
parts = Arrays.copyOf(parts, parts.length + 1);
parts[1] = parts[0];
parts[0] = ".*";
}
parts[0] += ":";
if (MCROCFLObjectIDPrefixHelper.MCROBJECT.matches(parts[0])
|| MCROCFLObjectIDPrefixHelper.MCRDERIVATE.matches(parts[0])) {
confirmPurge = true;
commands.addAll(purgeMatchObj(parts[1]));
}
if (MCROCFLObjectIDPrefixHelper.CLASSIFICATION.matches(parts[0])) {
confirmPurge = true;
commands.addAll(purgeMatchClass(parts[1]));
}
if (MCROCFLObjectIDPrefixHelper.USER.matches(parts[0])) {
confirmPurge = true;
commands.addAll(purgeMatchUsr(parts[1]));
}
confirmPurge = false;
return commands;
}
@MCRCommand(syntax = "purge ocfl objects matching {0}",
help = "Purge ocfl objects that are matching the RegEx {0}")
public static List<String> purgeMatchObj(String regex) {
MCROCFLXMLMetadataManager manager = new MCROCFLXMLMetadataManager();
manager.setRepositoryKey(metadataRepositoryKey);
if (!confirmPurge) {
LOGGER.info("\n"
+ "\u001B[93m" + "Enter the command again to confirm \u001B[4mPERMANENTLY\u001B[24m deleting ALL"
+ " matching OCFL objects." + "\u001B[0m" + "\n"
+ "\u001B[41m" + "THIS ACTION CANNOT BE UNDONE!" + "\u001B[0m");
confirmPurge = true;
return Collections.emptyList();
}
confirmPurge = false;
return manager.getRepository().listObjectIds()
.filter(obj -> obj.startsWith(MCROCFLObjectIDPrefixHelper.MCROBJECT)
|| obj.startsWith(MCROCFLObjectIDPrefixHelper.MCRDERIVATE))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.MCROBJECT, ""))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.MCRDERIVATE, ""))
.filter(obj -> obj.matches(regex))
.map(id -> "purge object " + id + " from ocfl")
.collect(Collectors.toList());
}
@MCRCommand(syntax = "purge ocfl classifications matching {0}",
help = "Purge ocfl classifications that are matching the RegEx {0}")
public static List<String> purgeMatchClass(String regex) {
if (!confirmPurge) {
LOGGER.info("\n"
+ "\u001B[93m" + "Enter the command again to confirm \u001B[4mPERMANENTLY\u001B[24m deleting ALL"
+ " matching OCFL classes." + "\u001B[0m" + "\n"
+ "\u001B[41m" + "THIS ACTION CANNOT BE UNDONE!" + "\u001B[0m");
confirmPurge = true;
return Collections.emptyList();
}
confirmPurge = false;
OcflRepository repository = MCROCFLRepositoryProvider.getRepository(classificationRepositoryKey);
return repository.listObjectIds()
.filter(obj -> obj.startsWith(MCROCFLObjectIDPrefixHelper.CLASSIFICATION))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.CLASSIFICATION, ""))
.filter(obj -> obj.matches(regex))
.map(id -> "purge classification " + id + " from ocfl")
.collect(Collectors.toList());
}
@MCRCommand(syntax = "purge ocfl users matching {0}",
help = "Purge ocfl users that are matching the RegEx {0}")
public static List<String> purgeMatchUsr(String regex) {
if (!confirmPurge) {
LOGGER.info("\n"
+ "\u001B[93m" + "Enter the command again to confirm \u001B[4mPERMANENTLY\u001B[24m deleting ALL"
+ " matching OCFL users." + "\u001B[0m" + "\n"
+ "\u001B[41m" + "THIS ACTION CANNOT BE UNDONE!" + "\u001B[0m");
confirmPurge = true;
return Collections.emptyList();
}
confirmPurge = false;
OcflRepository repository = MCROCFLRepositoryProvider.getRepository(userRepositoryKey);
return repository.listObjectIds()
.filter(obj -> obj.startsWith(MCROCFLObjectIDPrefixHelper.USER))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.USER, ""))
.filter(obj -> obj.matches(regex))
.map(id -> "purge user " + id + " from ocfl")
.collect(Collectors.toList());
}
// Purge Marked
@MCRCommand(syntax = "purge all marked ocfl entries matching {0}",
help = "Purge all marked ocfl entries that match the given regex, use .* for all")
public static List<String> purgeMarkedMatchAll(String regex) {
List<String> commands = new ArrayList<>();
String[] parts = regex.split(":", 2);
if (parts.length < 2) {
parts = Arrays.copyOf(parts, parts.length + 1);
parts[1] = parts[0];
parts[0] = ".*";
}
parts[0] += ":";
if (MCROCFLObjectIDPrefixHelper.MCROBJECT.matches(parts[0])
|| MCROCFLObjectIDPrefixHelper.MCRDERIVATE.matches(parts[0])) {
commands.add("purge marked ocfl objects matching " + parts[1]);
}
if (MCROCFLObjectIDPrefixHelper.CLASSIFICATION.matches(parts[0])) {
commands.add("purge marked ocfl classifications matching " + parts[1]);
}
if (MCROCFLObjectIDPrefixHelper.USER.matches(parts[0])) {
commands.add("purge marked ocfl users matching " + parts[1]);
}
return commands;
}
@MCRCommand(syntax = "purge marked ocfl objects matching {0}",
help = "Purge marked ocfl objects that are matching the RegEx {0}")
public static List<String> purgeMarkedMatchObj(String regex) {
MCROCFLXMLMetadataManager manager = new MCROCFLXMLMetadataManager();
manager.setRepositoryKey(metadataRepositoryKey);
return manager.getRepository().listObjectIds()
.filter(obj -> obj.startsWith(MCROCFLObjectIDPrefixHelper.MCROBJECT)
|| obj.startsWith(MCROCFLObjectIDPrefixHelper.MCRDERIVATE))
.filter(obj -> Objects.equals(
manager.getRepository().describeObject(obj).getHeadVersion().getVersionInfo().getMessage(), "Deleted"))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.MCROBJECT, ""))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.MCRDERIVATE, ""))
.filter(obj -> obj.matches(regex))
.map(id -> "purge object " + id + " from ocfl")
.collect(Collectors.toList());
}
@MCRCommand(syntax = "purge marked ocfl classifications matching {0}",
help = "Purge marked ocfl classifications that are matching the RegEx {0}")
public static List<String> purgeMarkedMatchClass(String regex) {
OcflRepository repository = MCROCFLRepositoryProvider.getRepository(classificationRepositoryKey);
return repository.listObjectIds()
.filter(obj -> obj.startsWith(MCROCFLObjectIDPrefixHelper.CLASSIFICATION))
.filter(obj -> Objects.equals(repository.describeObject(obj).getHeadVersion().getVersionInfo().getMessage(),
MCROCFLXMLClassificationManager.MESSAGE_DELETED))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.CLASSIFICATION, ""))
.filter(obj -> obj.matches(regex))
.map(id -> "purge classification " + id + " from ocfl")
.collect(Collectors.toList());
}
@MCRCommand(syntax = "purge marked ocfl users matching {0}",
help = "Purge marked ocfl users that are matching the RegEx {0}")
public static List<String> purgeMarkedMatchUsr(String regex) {
OcflRepository repository = MCROCFLRepositoryProvider.getRepository(userRepositoryKey);
return repository.listObjectIds()
.filter(obj -> obj.startsWith(MCROCFLObjectIDPrefixHelper.USER))
.filter(obj -> Objects.equals(repository.describeObject(obj).getHeadVersion().getVersionInfo().getMessage(),
MCROCFLXMLUserManager.MESSAGE_DELETED))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.USER, ""))
.filter(obj -> obj.matches(regex))
.map(id -> "purge user " + id + " from ocfl")
.collect(Collectors.toList());
}
// Restore
@MCRCommand(syntax = "restore all ocfl entries matching {0}",
help = "Restores all ocfl entries that match the given regex, use .* for all")
public static List<String> restoreMatchAll(String regex) {
List<String> commands = new ArrayList<>();
String[] parts = regex.split(":", 2);
if (parts.length < 2) {
parts = Arrays.copyOf(parts, parts.length + 1);
parts[1] = parts[0];
parts[0] = ".*";
}
parts[0] += ":";
if (MCROCFLObjectIDPrefixHelper.MCROBJECT.matches(parts[0])
|| MCROCFLObjectIDPrefixHelper.MCRDERIVATE.matches(parts[0])) {
commands.add("restore ocfl objects matching " + parts[1]);
}
if (MCROCFLObjectIDPrefixHelper.CLASSIFICATION.matches(parts[0])) {
commands.add("restore ocfl classifications matching " + parts[1]);
}
if (MCROCFLObjectIDPrefixHelper.USER.matches(parts[0])) {
commands.add("restore ocfl users matching " + parts[1]);
}
return commands;
}
@MCRCommand(syntax = "restore ocfl objects matching {0}",
help = "Restore ocfl objects that are matching the RegEx {0}")
public static List<String> restoreMatchObj(String regex) {
MCROCFLXMLMetadataManager manager = new MCROCFLXMLMetadataManager();
manager.setRepositoryKey(metadataRepositoryKey);
return manager.getRepository().listObjectIds()
.filter(obj -> obj.startsWith(MCROCFLObjectIDPrefixHelper.MCROBJECT)
|| obj.startsWith(MCROCFLObjectIDPrefixHelper.MCRDERIVATE))
.filter(obj -> Objects.equals(
manager.getRepository().describeObject(obj).getHeadVersion().getVersionInfo().getMessage(), "Deleted"))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.MCROBJECT, ""))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.MCRDERIVATE, ""))
.filter(obj -> obj.matches(regex))
.map(id -> "restore object " + id + " from ocfl with version v"
+ (manager.listRevisions(MCRObjectID.getInstance(id)).size() - 1))
.collect(Collectors.toList());
}
@MCRCommand(syntax = "restore ocfl classifications matching {0}",
help = "Restore ocfl classifications that are matching the RegEx {0}")
public static List<String> restoreMatchClass(String regex) {
OcflRepository repository = MCROCFLRepositoryProvider.getRepository(classificationRepositoryKey);
return repository.listObjectIds()
.filter(obj -> obj.startsWith(MCROCFLObjectIDPrefixHelper.CLASSIFICATION))
.filter(obj -> Objects.equals(repository.describeObject(obj).getHeadVersion().getVersionInfo().getMessage(),
MCROCFLXMLClassificationManager.MESSAGE_DELETED))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.CLASSIFICATION, ""))
.filter(obj -> obj.matches(regex))
.map(id -> "restore classification " + id + " from ocfl with version v"
+ (repository.describeObject(MCROCFLObjectIDPrefixHelper.CLASSIFICATION + id).getVersionMap().size()
- 1))
.collect(Collectors.toList());
}
@MCRCommand(syntax = "restore ocfl users matching {0}",
help = "Restore ocfl users that are matching the RegEx {0}")
public static List<String> restoreMatchUsr(String regex) {
OcflRepository repository = MCROCFLRepositoryProvider.getRepository(userRepositoryKey);
return repository.listObjectIds()
.filter(obj -> obj.startsWith(MCROCFLObjectIDPrefixHelper.USER))
.filter(obj -> Objects.equals(repository.describeObject(obj).getHeadVersion().getVersionInfo().getMessage(),
MCROCFLXMLUserManager.MESSAGE_DELETED))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.USER, ""))
.filter(obj -> obj.matches(regex))
.map(id -> "restore user " + id + " from ocfl with version v"
+ (repository.describeObject(MCROCFLObjectIDPrefixHelper.USER + id).getVersionMap().size() - 1))
.collect(Collectors.toList());
}
}
| 15,570 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLCommands.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/commands/MCROCFLCommands.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.ocfl.commands;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.JDOMException;
import org.mycore.common.MCRUsageException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRContent;
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.impl.MCRCategoryDAOImpl;
import org.mycore.datamodel.classifications2.utils.MCRXMLTransformer;
import org.mycore.datamodel.common.MCRAbstractMetadataVersion;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.cli.annotation.MCRCommand;
import org.mycore.frontend.cli.annotation.MCRCommandGroup;
import org.mycore.ocfl.MCROCFLPersistenceTransaction;
import org.mycore.ocfl.classification.MCROCFLXMLClassificationManager;
import org.mycore.ocfl.metadata.MCROCFLXMLMetadataManager;
import org.mycore.ocfl.metadata.migration.MCROCFLMigration;
import org.mycore.ocfl.metadata.migration.MCROCFLRevisionPruner;
import org.mycore.ocfl.repository.MCROCFLRepositoryProvider;
import org.mycore.ocfl.user.MCROCFLXMLUserManager;
import org.mycore.ocfl.util.MCROCFLObjectIDPrefixHelper;
import org.mycore.user2.MCRUser;
import org.mycore.user2.MCRUserManager;
import org.xml.sax.SAXException;
import io.ocfl.api.OcflRepository;
@SuppressWarnings("JavaUtilDate")
@MCRCommandGroup(name = "OCFL Commands")
public class MCROCFLCommands {
private static final Logger LOGGER = LogManager.getLogger();
public static final String SUCCESS = "success";
public static final String SUCCESS_BUT_WITHOUT_HISTORY = SUCCESS + " but without history";
public static final String FAILED = "failed";
public static final String FAILED_AND_NOW_INVALID_STATE = FAILED + " and now invalid state";
public static final String PRUNERS_CONFIG_PREFIX = "MCR.OCFL.Metadata.Migration.Pruners.";
private static boolean confirmPurgeMarked = false;
protected static void migrateWithPrunersAndRepositoryKeyOrMetadataManager(String repository,
String metadataManagerConfigKey,
String prunersStringList) throws Exception {
List<MCROCFLRevisionPruner> prunerList = new ArrayList<>();
if (!prunersStringList.isBlank()) {
String[] prunerIds = prunersStringList.split(",");
Map<String, Callable<Object>> pruners = MCRConfiguration2.getInstances(PRUNERS_CONFIG_PREFIX);
for (String prunerId : prunerIds) {
prunerList.add((MCROCFLRevisionPruner) pruners.get(PRUNERS_CONFIG_PREFIX + prunerId).call());
}
}
MCROCFLMigration migration = null;
if (metadataManagerConfigKey != null && !metadataManagerConfigKey.isEmpty()) {
MCROCFLXMLMetadataManager metadataManager
= MCRConfiguration2.<MCROCFLXMLMetadataManager>getInstanceOf(metadataManagerConfigKey)
.orElseThrow(() -> MCRConfiguration2.createConfigurationException(metadataManagerConfigKey));
migration = new MCROCFLMigration(null, prunerList, metadataManager);
} else if(repository != null && !repository.isEmpty()) {
migration = new MCROCFLMigration(repository, prunerList);
} else {
throw new MCRUsageException("Either a repository or a metadata manager must be specified");
}
migration.start();
ArrayList<String> success = migration.getSuccess();
ArrayList<String> failed = migration.getFailed();
ArrayList<String> invalidState = migration.getInvalidState();
ArrayList<String> withoutHistory = migration.getWithoutHistory();
LOGGER.info("The migration resulted in \n" +
SUCCESS + ": {} \n" +
FAILED + ": {} \n" +
FAILED_AND_NOW_INVALID_STATE + ": {} \n" +
SUCCESS_BUT_WITHOUT_HISTORY + ": {} \n",
String.join(", ", success),
String.join(", ", failed),
String.join(", ", invalidState),
String.join(", ", withoutHistory));
LOGGER.info("The migration resulted in \n" +
SUCCESS + ": {} \n" +
FAILED + ": {} \n" +
FAILED_AND_NOW_INVALID_STATE + ": {} \n" +
SUCCESS_BUT_WITHOUT_HISTORY + ": {} \n",
success.size(),
failed.size(),
invalidState.size(),
withoutHistory.size());
}
@MCRCommand(syntax = "migrate metadata to metadatamanager {1} and pruners {2} ",
help = "migrates all the metadata to the ocfl " +
"repository with the id {0} and prunes the revisions with the given pruners",
order = 0)
public static void migrateToMetadataMangerWithPruners(String metadataManagerConfigKey, String prunersStringList)
throws Exception {
migrateWithPrunersAndRepositoryKeyOrMetadataManager(null, metadataManagerConfigKey, prunersStringList);
}
@MCRCommand(syntax = "migrate metadata to repository {0} with pruners {1}",
help = "migrates all the metadata to the ocfl " +
"repository with the id {0} and prunes the revisions with the given pruners",
order = 1)
public static void migrateToRepositoryKeyWithPruners(String repository, String prunersStringList) throws Exception {
migrateWithPrunersAndRepositoryKeyOrMetadataManager(repository, null, prunersStringList);
}
@MCRCommand(syntax = "migrate metadata to repository {0}",
help = "migrates all the metadata to the ocfl " +
"repository with the id {0}",
order = 2)
public static void migrateToRepositoryKey(String repository) throws Exception {
migrateToRepositoryKeyWithPruners(repository, "");
}
@MCRCommand(syntax = "update ocfl classifications",
help = "Update all classifications in the OCFL store from database")
public static List<String> updateOCFLClassifications() {
List<MCRCategoryID> list = new MCRCategoryDAOImpl().getRootCategoryIDs();
return list.stream()
.map(id -> "update ocfl classification " + id)
.collect(Collectors.toList());
}
@MCRCommand(syntax = "update ocfl classification {0}",
help = "Update classification {0} in the OCFL Store from database")
public static void updateOCFLClassification(String classId) {
final MCRCategoryID rootID = MCRCategoryID.rootID(classId);
MCROCFLPersistenceTransaction.addClassficationEvent(rootID, MCRAbstractMetadataVersion.UPDATED);
}
@MCRCommand(syntax = "delete ocfl classification {0}",
help = "Delete classification {0} in the OCFL Store")
public static void deleteOCFLClassification(String classId) {
final MCRCategoryID rootID = MCRCategoryID.rootID(classId);
MCROCFLPersistenceTransaction.addClassficationEvent(rootID, MCRAbstractMetadataVersion.DELETED);
}
@MCRCommand(syntax = "sync ocfl classifications",
help = "Update all classifications and remove deleted Classifications to resync OCFL Store to the Database")
public static List<String> syncClassificationRepository() {
List<String> commands = new ArrayList<>();
commands.add("update ocfl classifications");
List<String> outOfSync = getStaleOCFLClassificationIDs();
commands.addAll(
outOfSync.stream()
.map(id -> "delete ocfl classification " + id).collect(Collectors.toList()));
return commands;
}
@MCRCommand(syntax = "update ocfl users",
help = "Update all users in the OCFL store from database")
public static List<String> updateOCFLUsers() {
List<MCRUser> list = MCRUserManager.listUsers("*", null, null, null);
return list.stream()
.map(usr -> "update ocfl user " + usr.getUserID())
.collect(Collectors.toList());
}
@MCRCommand(syntax = "update ocfl user {0}",
help = "Update user {0} in the OCFL Store from database")
public static void updateOCFLUser(String userId) {
if (MCRUserManager.getUser(userId) == null) {
throw new MCRUsageException("The User '" + userId + "' does not exist!");
}
new MCROCFLXMLUserManager().updateUser(MCRUserManager.getUser(userId));
}
@MCRCommand(syntax = "delete ocfl user {0}",
help = "Delete user {0} in the OCFL Store")
public static void deleteOCFLUser(String userId) {
new MCROCFLXMLUserManager().deleteUser(userId);
}
@MCRCommand(syntax = "sync ocfl users",
help = "Update all users and remove deleted users to resync OCFL Store to the Database")
public static List<String> syncUserRepository() {
List<String> commands = new ArrayList<>();
commands.add("update ocfl users");
List<String> outOfSync = getStaleOCFLUserIDs();
commands.addAll(
outOfSync.stream()
.map(id -> "delete ocfl user " + id).collect(Collectors.toList()));
return commands;
}
@MCRCommand(syntax = "restore user {0} from ocfl with version {1}",
help = "restore a specified revision of a ocfl user backup to the primary user store")
public static void writeUserToDbVersioned(String userId, String revision) throws IOException {
MCRUser user = new MCROCFLXMLUserManager().retrieveContent(userId, revision);
MCRUserManager.updateUser(user);
}
@MCRCommand(syntax = "restore user {0} from ocfl",
help = "restore the latest revision of a ocfl user backup to the primary user store")
public static void writeUserToDb(String userId) throws IOException {
MCRUser user = new MCROCFLXMLUserManager().retrieveContent(userId, null);
MCRUserManager.updateUser(user);
}
@MCRCommand(syntax = "restore classification {0} from ocfl with version {1}",
help = "restore a specified revision of a ocfl classification backup to the primary classification store")
public static void writeClassToDbVersioned(String classId, String revision)
throws URISyntaxException, JDOMException, IOException, SAXException {
MCROCFLXMLClassificationManager manager = MCRConfiguration2
.<MCROCFLXMLClassificationManager>getSingleInstanceOf("MCR.Classification.Manager").orElseThrow();
MCRCategoryID cId = MCRCategoryID.fromString(classId);
MCRContent content = manager.retrieveContent(cId, revision);
MCRCategory category = MCRXMLTransformer.getCategory(content.asXML());
MCRCategoryDAO dao = MCRCategoryDAOFactory.getInstance();
if (dao.exist(category.getId())) {
dao.replaceCategory(category);
} else {
// add if classification does not exist
dao.addCategory(null, category);
}
}
@MCRCommand(syntax = "restore classification {0} from ocfl",
help = "restore the latest revision of a ocfl classification backup to the primary classification store")
public static void writeClassToDb(String classId)
throws URISyntaxException, JDOMException, IOException, SAXException {
writeClassToDbVersioned(classId, null);
}
@MCRCommand(syntax = "restore object {0} from ocfl with version {1}",
help = "restore mcrobject {0} with version {1} to current store from ocfl history")
public static void restoreObjFromOCFLVersioned(String mcridString, String revision) throws IOException {
MCRObjectID mcrid = MCRObjectID.getInstance(mcridString);
MCROCFLXMLMetadataManager manager = new MCROCFLXMLMetadataManager();
manager.setRepositoryKey(MCRConfiguration2.getStringOrThrow("MCR.Metadata.Manager.Repository"));
MCRContent content = manager.retrieveContent(mcrid, revision);
try {
MCRXMLMetadataManager.instance().update(mcrid, content, new Date(content.lastModified()));
} catch (MCRUsageException e) {
MCRXMLMetadataManager.instance().create(mcrid, content, new Date(content.lastModified()));
}
}
@MCRCommand(syntax = "restore object {0} from ocfl",
help = "restore latest mcrobject {0} to current store from ocfl history")
public static void restoreObjFromOCFL(String mcridString) throws IOException {
restoreObjFromOCFLVersioned(mcridString, null);
}
@MCRCommand(syntax = "purge object {0} from ocfl",
help = "Permanently delete object {0} and its history from ocfl")
public static void purgeObject(String mcridString) throws IOException {
MCRObjectID mcrid = MCRObjectID.getInstance(mcridString);
MCROCFLXMLMetadataManager manager = new MCROCFLXMLMetadataManager();
manager.setRepositoryKey(MCRConfiguration2.getStringOrThrow("MCR.Metadata.Manager.Repository"));
manager.purge(mcrid, new Date(), MCRUserManager.getCurrentUser().getUserName());
}
@MCRCommand(syntax = "purge classification {0} from ocfl",
help = "Permanently delete classification {0} and its history from ocfl")
public static void purgeClass(String mcrCgIdString) throws IOException {
MCRCategoryID mcrCgId = MCRCategoryID.fromString(mcrCgIdString);
if (!mcrCgId.isRootID()) {
throw new MCRUsageException("You can only purge root classifications!");
}
MCRConfiguration2.<MCROCFLXMLClassificationManager>getSingleInstanceOf("MCR.Classification.Manager")
.orElseThrow().purge(mcrCgId);
}
@MCRCommand(syntax = "purge user {0} from ocfl",
help = "Permanently delete user {0} and its history from ocfl")
public static void purgeUser(String userId) throws IOException {
new MCROCFLXMLUserManager().purgeUser(userId);
}
@MCRCommand(syntax = "purge all marked from ocfl",
help = "Permanently delete all hidden/archived ocfl entries")
public static void purgeMarked() throws IOException {
if (!confirmPurgeMarked) {
LOGGER.info("\n"
+ "\u001B[93m" + "Enter the command again to confirm \u001B[4mPERMANENTLY\u001B[24m deleting ALL"
+ " hidden/archived OCFL entries." + "\u001B[0m" + "\n"
+ "\u001B[41m" + "THIS ACTION CANNOT BE UNDONE!" + "\u001B[0m");
confirmPurgeMarked = true;
return;
}
purgeMarkedObjects();
confirmPurgeMarked = true;
purgeMarkedClasses();
confirmPurgeMarked = true;
purgeMarkedUsers();
confirmPurgeMarked = false;
}
@MCRCommand(syntax = "purge marked metadata from ocfl",
help = "Permanently delete all hidden/archived ocfl objects")
public static void purgeMarkedObjects() throws IOException {
if (!confirmPurgeMarked) {
LOGGER.info("\n"
+ "\u001B[93m" + "Enter the command again to confirm \u001B[4mPERMANENTLY\u001B[24m deleting ALL"
+ " hidden/archived OCFL objects." + "\u001B[0m" + "\n"
+ "\u001B[41m" + "THIS ACTION CANNOT BE UNDONE!" + "\u001B[0m");
confirmPurgeMarked = true;
return;
}
String repositoryKey = MCRConfiguration2.getStringOrThrow("MCR.Metadata.Manager.Repository");
MCROCFLXMLMetadataManager manager = new MCROCFLXMLMetadataManager();
manager.setRepositoryKey(repositoryKey);
OcflRepository repository = manager.getRepository();
repository.listObjectIds()
.filter(obj -> obj.startsWith(MCROCFLObjectIDPrefixHelper.MCROBJECT)
|| obj.startsWith(MCROCFLObjectIDPrefixHelper.MCRDERIVATE))
.filter(obj -> Objects.equals(repository.describeObject(obj).getHeadVersion().getVersionInfo().getMessage(),
"Deleted"))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.MCROBJECT, ""))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.MCRDERIVATE, ""))
.forEach(oId -> manager.purge(MCRObjectID.getInstance(oId), new Date(),
MCRUserManager.getCurrentUser().getUserName()));
confirmPurgeMarked = false;
}
@MCRCommand(syntax = "purge marked classifications from ocfl",
help = "Permanently delete all hidden/archived ocfl classes")
public static void purgeMarkedClasses() throws IOException {
if (!confirmPurgeMarked) {
LOGGER.info("\n"
+ "\u001B[93m" + "Enter the command again to confirm \u001B[4mPERMANENTLY\u001B[24m deleting ALL"
+ " hidden/archived OCFL classes." + "\u001B[0m" + "\n"
+ "\u001B[41m" + "THIS ACTION CANNOT BE UNDONE!" + "\u001B[0m");
confirmPurgeMarked = true;
return;
}
String repositoryKey = MCRConfiguration2.getStringOrThrow("MCR.Classification.Manager.Repository");
OcflRepository repository = MCROCFLRepositoryProvider.getRepository(repositoryKey);
MCROCFLXMLClassificationManager manager = MCRConfiguration2
.<MCROCFLXMLClassificationManager>getSingleInstanceOf("MCR.Classification.Manager").orElseThrow();
repository.listObjectIds()
.filter(obj -> obj.startsWith(MCROCFLObjectIDPrefixHelper.CLASSIFICATION))
.filter(obj -> Objects.equals(repository.describeObject(obj).getHeadVersion().getVersionInfo().getMessage(),
MCROCFLXMLClassificationManager.MESSAGE_DELETED))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.CLASSIFICATION, ""))
.forEach(cId -> manager.purge(MCRCategoryID.fromString(cId)));
confirmPurgeMarked = false;
}
@MCRCommand(syntax = "purge marked users from ocfl",
help = "Permanently delete all hidden/archived ocfl users")
public static void purgeMarkedUsers() throws IOException {
if (!confirmPurgeMarked) {
LOGGER.info("\n"
+ "\u001B[93m" + "Enter the command again to confirm \u001B[4mPERMANENTLY\u001B[24m deleting ALL"
+ " hidden/archived OCFL users." + "\u001B[0m" + "\n"
+ "\u001B[41m" + "THIS ACTION CANNOT BE UNDONE!" + "\u001B[0m");
confirmPurgeMarked = true;
return;
}
String repositoryKey = MCRConfiguration2.getStringOrThrow("MCR.Users.Manager.Repository");
OcflRepository repository = MCROCFLRepositoryProvider.getRepository(repositoryKey);
repository.listObjectIds()
.filter(obj -> obj.startsWith(MCROCFLObjectIDPrefixHelper.USER))
.filter(obj -> Objects.equals(repository.describeObject(obj).getHeadVersion().getVersionInfo().getMessage(),
MCROCFLXMLUserManager.MESSAGE_DELETED))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.USER, ""))
.forEach(u -> new MCROCFLXMLUserManager().purgeUser(u));
confirmPurgeMarked = false;
}
private static List<String> getStaleOCFLClassificationIDs() {
String repositoryKey = MCRConfiguration2.getStringOrThrow("MCR.Classification.Manager.Repository");
List<String> classDAOList = new MCRCategoryDAOImpl().getRootCategoryIDs().stream()
.map(MCRCategoryID::toString)
.collect(Collectors.toList());
OcflRepository repository = MCROCFLRepositoryProvider.getRepository(repositoryKey);
return repository.listObjectIds()
.filter(obj -> obj.startsWith(MCROCFLObjectIDPrefixHelper.CLASSIFICATION))
.filter(
obj -> !Objects.equals(repository.describeObject(obj).getHeadVersion().getVersionInfo().getMessage(),
MCROCFLXMLClassificationManager.MESSAGE_DELETED))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.CLASSIFICATION, ""))
.filter(Predicate.not(classDAOList::contains))
.collect(Collectors.toList());
}
private static List<String> getStaleOCFLUserIDs() {
String repositoryKey = MCRConfiguration2.getStringOrThrow("MCR.Users.Manager.Repository");
List<String> userEMList = MCRUserManager.listUsers("*", null, null, null).stream()
.map(MCRUser::getUserID)
.collect(Collectors.toList());
OcflRepository repository = MCROCFLRepositoryProvider.getRepository(repositoryKey);
return repository.listObjectIds()
.filter(obj -> obj.startsWith(MCROCFLObjectIDPrefixHelper.USER))
.filter(
obj -> !Objects.equals(repository.describeObject(obj).getHeadVersion().getVersionInfo().getMessage(),
MCROCFLXMLUserManager.MESSAGE_DELETED))
.map(obj -> obj.replace(MCROCFLObjectIDPrefixHelper.USER, ""))
.filter(Predicate.not(userEMList::contains))
.collect(Collectors.toList());
}
}
| 21,982 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLXMLUserManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/user/MCROCFLXMLUserManager.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.ocfl.user;
import java.io.IOException;
import java.io.InputStream;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.MCRUsageException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.content.MCRStreamContent;
import org.mycore.ocfl.repository.MCROCFLRepositoryProvider;
import org.mycore.ocfl.util.MCROCFLDeleteUtils;
import org.mycore.ocfl.util.MCROCFLObjectIDPrefixHelper;
import org.mycore.user2.MCRTransientUser;
import org.mycore.user2.MCRUser;
import org.mycore.user2.MCRUserManager;
import org.mycore.user2.utils.MCRUserTransformer;
import io.ocfl.api.OcflOption;
import io.ocfl.api.OcflRepository;
import io.ocfl.api.exception.OverwriteException;
import io.ocfl.api.model.ObjectVersionId;
import io.ocfl.api.model.VersionInfo;
/**
* XML Manager to handle MCRUsers in a MyCoRe OCFL Repository
* @author Tobias Lenhardt [Hammer1279]
*/
public class MCROCFLXMLUserManager {
private static final Logger LOGGER = LogManager.getLogger();
public static final String MESSAGE_CREATED = "Created";
public static final String MESSAGE_UPDATED = "Updated";
public static final String MESSAGE_DELETED = "Deleted";
private static final String IGNORING_TRANSIENT_USER = "Got TransientUser, ignoring...";
private final OcflRepository repository;
/**
* Initializes the UserManager with the in the config defined repository.
*/
public MCROCFLXMLUserManager() {
this.repository = MCROCFLRepositoryProvider.getRepository(
MCRConfiguration2.getStringOrThrow("MCR.Users.Manager.Repository"));
}
/**
* Initializes the UserManager with the given repositoryKey.
* @param repositoryKey the ID for the repository to be used
*/
public MCROCFLXMLUserManager(String repositoryKey) {
this.repository = MCROCFLRepositoryProvider.getRepository(repositoryKey);
}
public void updateUser(MCRUser user) {
MCRUser currentUser = MCRUserManager.getCurrentUser();
String ocflUserID = MCROCFLObjectIDPrefixHelper.USER + user.getUserID();
/*
* On every Login, a update event gets called to update the "lastLogin" of a user.
* This would create many unnecessary versions/copies every time someone logs in.
* To prevent this, the update event gets ignored if the current user is a guest.
* Usually guests do not have rights to modify users, so the only time they trigger this event
* is during the update of "lastLogin", since the user switch has not happened yet.
*/
if (MCRSystemUserInformation.getGuestInstance().getUserID().equals(currentUser.getUserID())) {
LOGGER.debug("Login Detected, ignoring...");
return;
}
// Transient users are not MyCoRe managed users, but rather from external sources
if (user instanceof MCRTransientUser) {
LOGGER.debug(IGNORING_TRANSIENT_USER);
return;
}
if (!exists(ocflUserID)) {
createUser(user);
return;
}
VersionInfo info = new VersionInfo()
.setMessage(MESSAGE_UPDATED)
.setCreated(OffsetDateTime.now(ZoneOffset.UTC))
.setUser(currentUser.getUserName(), buildEmail(currentUser));
MCRJDOMContent content = new MCRJDOMContent(MCRUserTransformer.buildExportableXML(user));
try (InputStream userAsStream = content.getInputStream()) {
repository.updateObject(ObjectVersionId.head(ocflUserID), info,
updater -> updater.writeFile(userAsStream, user.getUserID() + ".xml", OcflOption.OVERWRITE));
} catch (IOException | OverwriteException e) {
throw new MCRPersistenceException("Failed to update user '" + ocflUserID + "'", e);
}
}
public void createUser(MCRUser user) {
if (user instanceof MCRTransientUser) {
LOGGER.debug(IGNORING_TRANSIENT_USER);
return;
}
MCRUser currentUser = MCRUserManager.getCurrentUser();
String ocflUserID = MCROCFLObjectIDPrefixHelper.USER + user.getUserID();
if (exists(ocflUserID)) {
updateUser(user);
return;
}
VersionInfo info = new VersionInfo()
.setMessage(MESSAGE_CREATED)
.setCreated(OffsetDateTime.now(ZoneOffset.UTC))
.setUser(currentUser.getUserName(), buildEmail(currentUser));
MCRJDOMContent content = new MCRJDOMContent(MCRUserTransformer.buildExportableXML(user));
try (InputStream userAsStream = content.getInputStream()) {
repository.updateObject(ObjectVersionId.head(ocflUserID), info,
updater -> updater.writeFile(userAsStream, user.getUserID() + ".xml"));
} catch (IOException | OverwriteException e) {
throw new MCRPersistenceException("Failed to update user '" + ocflUserID + "'", e);
}
}
public void deleteUser(MCRUser user) {
if (user instanceof MCRTransientUser) {
LOGGER.debug(IGNORING_TRANSIENT_USER);
return;
}
deleteUser(user.getUserID());
}
public void deleteUser(String userId) {
MCRUser currentUser = MCRUserManager.getCurrentUser();
String ocflUserID = MCROCFLObjectIDPrefixHelper.USER + userId;
if (MCROCFLDeleteUtils.checkPurgeUser(userId)) {
purgeUser(ocflUserID);
return;
}
if (!exists(ocflUserID)) {
throw new MCRUsageException(
"The User '" + userId + "' does not exist or has already been deleted!");
}
VersionInfo info = new VersionInfo()
.setMessage(MESSAGE_DELETED)
.setCreated(OffsetDateTime.now(ZoneOffset.UTC))
.setUser(currentUser.getUserName(), buildEmail(currentUser));
repository.updateObject(ObjectVersionId.head(ocflUserID), info,
updater -> updater.removeFile(userId + ".xml"));
}
public void purgeUser(String userId) {
String ocflUserID = MCROCFLObjectIDPrefixHelper.USER + userId;
if (!repository.containsObject(ocflUserID)) {
throw new MCRUsageException(
"The User '" + userId + "' does not exist!");
}
repository.purgeObject(ocflUserID);
}
private String buildEmail(MCRUser currentUser) {
return Optional.ofNullable(currentUser.getEMailAddress()).map(email -> "mailto:" + email).orElse(null);
}
/**
* Retrieve a MCRUser from the ocfl store.
* @param userId the userId of the requested user
* @param revision the version in ocfl store or <code>null</code> for latest
* @return the requested MCRUser
* @throws IOException if a error occurs during retrieval
*/
public MCRUser retrieveContent(String userId, String revision) throws IOException {
String ocflUserID = MCROCFLObjectIDPrefixHelper.USER + userId;
if (!repository.containsObject(ocflUserID)) {
throw new MCRUsageException("The User '" + ocflUserID + "' does not exist!");
}
ObjectVersionId version = revision == null ? ObjectVersionId.head(ocflUserID)
: ObjectVersionId.version(ocflUserID, revision);
if (isDeleted(version)) {
throw new MCRUsageException("The User '" + ocflUserID + "' with version '" + revision
+ "' has been deleted!");
}
try (InputStream storedContentStream = repository.getObject(version).getFile(userId + ".xml").getStream()) {
Document xml = new MCRStreamContent(storedContentStream).asXML();
return MCRUserTransformer.buildMCRUser(xml.getRootElement());
} catch (JDOMException e) {
throw new IOException("Can not parse XML from OCFL-Store", e);
}
}
private boolean isDeleted(ObjectVersionId version) {
return MESSAGE_DELETED.equals(repository.describeVersion(version).getVersionInfo().getMessage());
}
boolean exists(String ocflUserID) {
return repository.containsObject(ocflUserID)
&& !isDeleted(ObjectVersionId.head(ocflUserID));
}
boolean exists(String ocflUserID, String revision) {
return repository.containsObject(ocflUserID)
&& !isDeleted(ObjectVersionId.version(ocflUserID, revision));
}
}
| 9,467 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLUserEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/user/MCROCFLUserEventHandler.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.ocfl.user;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandler;
import org.mycore.user2.MCRUser;
/**
* Event Handler to Handle MCRUser Events for OCFL
* @author Tobias Lenhardt [Hammer1279]
*/
public class MCROCFLUserEventHandler implements MCREventHandler {
private static final Logger LOGGER = LogManager.getLogger();
private static final MCROCFLXMLUserManager MANAGER = new MCROCFLXMLUserManager();
@Override
public void doHandleEvent(MCREvent evt) throws MCRException {
if (MCREvent.ObjectType.USER == evt.getObjectType()) {
MCRUser user = (MCRUser) evt.get(MCREvent.USER_KEY);
LOGGER.debug("{} handling {} {}", getClass().getName(), user.getUserID(),
evt.getEventType());
switch (evt.getEventType()) {
case UPDATE -> MANAGER.updateUser(user);
case CREATE -> MANAGER.createUser(user);
case DELETE -> MANAGER.deleteUser(user);
default -> LOGGER.info("Event Type '{}' is not valid for {}", evt.getEventType(), getClass().getName());
}
}
}
@Override
public void undoHandleEvent(MCREvent evt) throws MCRException {
// undo not supported
LOGGER.warn("A Error has occurred while saving User, please run 'sync ocfl users' in cli.");
}
}
| 2,243 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLDeleteUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/util/MCROCFLDeleteUtils.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.ocfl.util;
// actually increases readability
import static org.mycore.common.config.MCRConfiguration2.getBoolean;
import static org.mycore.common.config.MCRConfiguration2.getString;
import java.util.Optional;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* Utility Class to decide when to keep or drop the history of elements
* @author Tobias Lenhardt [Hammer1279]
*/
public final class MCROCFLDeleteUtils {
public static final String PROPERTY_PREFIX = "MCR.OCFL.dropHistory.";
private static final String PP = PROPERTY_PREFIX;
private MCROCFLDeleteUtils() {
throw new IllegalStateException("Utility class");
}
public static boolean checkPurgeObject(MCRObjectID mcrid) {
return checkPurgeObject(mcrid, MCROCFLObjectIDPrefixHelper.MCROBJECT);
}
public static boolean checkPurgeDerivate(MCRObjectID mcrid) {
return checkPurgeObject(mcrid, MCROCFLObjectIDPrefixHelper.MCRDERIVATE);
}
public static boolean checkPurgeObject(MCRObjectID mcrid, String prefix) {
String ocflType = prefix.replace(":", "");
boolean doPurge = false;
doPurge = getBoolean(PP.substring(0, PP.length() - 1)).orElse(doPurge);
doPurge = regexMatcher(mcrid.toString(), getString(PP + "preMatch")).orElse(doPurge);
doPurge = getBoolean(PP + ocflType).orElse(doPurge);
doPurge = getBoolean(PP + mcrid.getProjectId()).orElse(doPurge);
doPurge = getBoolean(PP + mcrid.getTypeId()).orElse(doPurge);
doPurge = getBoolean(PP + mcrid.getBase()).orElse(doPurge);
doPurge = regexMatcher(mcrid.toString(), getString(PP + ocflType + ".preMatch")).orElse(doPurge);
doPurge = getBoolean(PP + ocflType + "." + mcrid.getProjectId()).orElse(doPurge);
doPurge = getBoolean(PP + ocflType + "." + mcrid.getTypeId()).orElse(doPurge);
doPurge = getBoolean(PP + ocflType + "." + mcrid.getBase()).orElse(doPurge);
doPurge = getBoolean(PP + mcrid).orElse(doPurge);
doPurge = getBoolean(PP + ocflType + "." + mcrid).orElse(doPurge);
doPurge = regexMatcher(mcrid.toString(), getString(PP + "postMatch")).orElse(doPurge);
doPurge = regexMatcher(mcrid.toString(), getString(PP + ocflType + ".postMatch")).orElse(doPurge);
return doPurge;
}
public static boolean checkPurgeClass(MCRCategoryID mcrid) {
return checkPurgeClass(mcrid, MCROCFLObjectIDPrefixHelper.CLASSIFICATION);
}
public static boolean checkPurgeClass(MCRCategoryID mcrid, String prefix) {
String ocflType = prefix.replace(":", "");
boolean doPurge = false;
doPurge = getBoolean(PP.substring(0, PP.length() - 1)).orElse(doPurge);
doPurge = regexMatcher(mcrid.toString(), getString(PP + "preMatch")).orElse(doPurge);
doPurge = regexMatcher(mcrid.toString(), getString(PP + ocflType + ".preMatch")).orElse(doPurge);
doPurge = getBoolean(PP + ocflType).orElse(doPurge);
doPurge = getBoolean(PP + mcrid.getRootID()).orElse(doPurge);
doPurge = getBoolean(PP + ocflType + "." + mcrid.getRootID()).orElse(doPurge);
doPurge = regexMatcher(mcrid.toString(), getString(PP + "postMatch")).orElse(doPurge);
doPurge = regexMatcher(mcrid.toString(), getString(PP + ocflType + ".postMatch")).orElse(doPurge);
return doPurge;
}
public static boolean checkPurgeUser(String userID) {
return checkPurgeUser(userID, MCROCFLObjectIDPrefixHelper.USER);
}
public static boolean checkPurgeUser(String userID, String prefix) {
String ocflType = prefix.replace(":", "");
boolean doPurge = false;
doPurge = getBoolean(PP.substring(0, PP.length() - 1)).orElse(doPurge);
doPurge = regexMatcher(userID, getString(PP + "preMatch")).orElse(doPurge);
doPurge = regexMatcher(userID, getString(PP + ocflType + ".preMatch")).orElse(doPurge);
doPurge = getBoolean(PP + ocflType).orElse(doPurge);
doPurge = getBoolean(PP + userID).orElse(doPurge);
doPurge = getBoolean(PP + ocflType + "." + userID).orElse(doPurge);
doPurge = regexMatcher(userID, getString(PP + "postMatch")).orElse(doPurge);
doPurge = regexMatcher(userID, getString(PP + ocflType + ".postMatch")).orElse(doPurge);
return doPurge;
}
/**
* Provides a Optional boolean if pattern is defined, otherwise returns empty Optional
* @param toTest String to run pattern against
* @param pattern pattern to test with or null
* @return empty Optional if pattern is null, otherwise Optional Boolean of match result
*/
public static Optional<Boolean> regexMatcher(String toTest, Optional<String> pattern) {
if (pattern.isEmpty()) {
return Optional.empty();
}
return Optional.of(toTest.matches(pattern.get()));
}
}
| 5,665 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLObjectIDPrefixHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/util/MCROCFLObjectIDPrefixHelper.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.ocfl.util;
/**
* Prefixes to map MyCoRe IDs to OCFL object IDs.
*/
public class MCROCFLObjectIDPrefixHelper {
public static final String MCROBJECT = "mcrobject:";
public static final String MCRDERIVATE = "mcrderivate:";
public static final String CLASSIFICATION = "mcrclass:";
public static final String USER = "mcruser:";
public static final String ACL = "mcracl:";
public static final String WEB = "mcrweb:";
}
| 1,191 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLMetadataVersion.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/util/MCROCFLMetadataVersion.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.ocfl.util;
import java.io.IOException;
import java.util.Date;
import org.mycore.common.content.MCRContent;
import org.mycore.datamodel.common.MCRAbstractMetadataVersion;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlRootElement;
/**
* Provides information about a stored version of metadata and allows to
* retrieve that version from SVN
*
* @author Frank Lützenkirchen
*/
@XmlRootElement(name = "revision")
@XmlAccessorType(XmlAccessType.FIELD)
public class MCROCFLMetadataVersion extends MCRAbstractMetadataVersion<MCRContent> {
public MCROCFLMetadataVersion(MCRContent vm, String revision, String user, Date date, char type) {
super(vm, revision, user, date, type);
}
/**
* Retrieves this version of the metadata
*
* @return the metadata document as it was in this version
*/
@Override
public MCRContent retrieve() {
return vm;
}
/**
* Replaces the current version of the metadata object with this version,
* which means that a new version is created that is identical to this old
* version. The stored metadata document is updated to this old version of
* the metadata.
*/
@Override
public void restore() throws IOException { // TODO see where this is used
throw new IOException("Can not restore a version!");
}
}
| 2,182 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLXMLClassificationManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/classification/MCROCFLXMLClassificationManager.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.ocfl.classification;
import java.io.IOException;
import java.io.InputStream;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.MCRUsageException;
import org.mycore.common.config.annotation.MCRProperty;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.content.MCRStreamContent;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.common.MCRXMLClassificationManager;
import org.mycore.ocfl.repository.MCROCFLRepositoryProvider;
import org.mycore.ocfl.util.MCROCFLDeleteUtils;
import org.mycore.ocfl.util.MCROCFLMetadataVersion;
import org.mycore.ocfl.util.MCROCFLObjectIDPrefixHelper;
import io.ocfl.api.OcflOption;
import io.ocfl.api.OcflRepository;
import io.ocfl.api.exception.NotFoundException;
import io.ocfl.api.exception.ObjectOutOfSyncException;
import io.ocfl.api.model.ObjectVersionId;
import io.ocfl.api.model.VersionInfo;
/**
* OCFL File Manager for MyCoRe Classifications
* @author Tobias Lenhardt [Hammer1279]
*/
public class MCROCFLXMLClassificationManager implements MCRXMLClassificationManager {
public static final String MESSAGE_CREATED = "Created";
public static final String MESSAGE_UPDATED = "Updated";
public static final String MESSAGE_DELETED = "Deleted";
private static final String ROOT_FOLDER = "classification/";
@MCRProperty(name = "Repository")
public String repositoryKey;
// FIXME make seperate versionhelper
protected static final Map<String, Character> MESSAGE_TYPE_MAPPING = Map.ofEntries(
Map.entry(MESSAGE_CREATED, MCROCFLMetadataVersion.CREATED),
Map.entry(MESSAGE_UPDATED, MCROCFLMetadataVersion.UPDATED),
Map.entry(MESSAGE_DELETED, MCROCFLMetadataVersion.DELETED));
protected static char convertMessageToType(String message) throws MCRPersistenceException {
if (!MESSAGE_TYPE_MAPPING.containsKey(message)) {
throw new MCRPersistenceException("Cannot identify version type from message '" + message + "'");
}
return MESSAGE_TYPE_MAPPING.get(message);
}
protected OcflRepository getRepository() throws ClassCastException {
return MCROCFLRepositoryProvider.getRepository(repositoryKey);
}
public void create(MCRCategoryID mcrCg, MCRContent xml) throws IOException {
fileUpdate(mcrCg, xml, MESSAGE_CREATED);
}
public void update(MCRCategoryID mcrCg, MCRContent xml) throws IOException {
fileUpdate(mcrCg, xml, MESSAGE_UPDATED);
}
void fileUpdate(MCRCategoryID mcrCg, MCRContent xml, String messageOpt) throws IOException {
String ocflObjectID = getOCFLObjectID(mcrCg);
String message = messageOpt; // PMD Fix - AvoidReassigningParameters
if (Objects.isNull(message)) {
message = MESSAGE_UPDATED;
}
try (InputStream objectAsStream = xml.getInputStream()) {
VersionInfo versionInfo = buildVersionInfo(message, new Date());
getRepository().updateObject(ObjectVersionId.head(ocflObjectID), versionInfo,
updater -> updater.writeFile(objectAsStream, buildFilePath(mcrCg), OcflOption.OVERWRITE));
}
}
@SuppressWarnings("JavaUtilDate")
public void delete(MCRCategoryID mcrid) throws IOException {
if (MCROCFLDeleteUtils.checkPurgeClass(mcrid)) {
purge(mcrid);
return;
}
String ocflObjectID = getOCFLObjectID(mcrid);
VersionInfo versionInfo = buildVersionInfo(MESSAGE_DELETED, new Date());
try {
getRepository().updateObject(ObjectVersionId.head(ocflObjectID), versionInfo,
updater -> updater.removeFile(buildFilePath(mcrid)));
} catch (NotFoundException | ObjectOutOfSyncException e) {
throw new IOException(e);
}
}
public void purge(MCRCategoryID mcrid) {
getRepository().purgeObject(getOCFLObjectID(mcrid));
}
/**
* Load a Classification from the OCFL Store.
* @param mcrid ID of the Category
* @param revision Revision of the Category or <code>null</code> for HEAD
* @return Content of the Classification
*/
@Override
public MCRContent retrieveContent(MCRCategoryID mcrid, String revision) throws IOException {
String ocflObjectID = getOCFLObjectID(mcrid);
OcflRepository repo = getRepository();
ObjectVersionId vId = revision != null ? ObjectVersionId.version(ocflObjectID, revision)
: ObjectVersionId.head(ocflObjectID);
try {
repo.getObject(vId);
} catch (NotFoundException e) {
throw new IOException("Object '" + ocflObjectID + "' could not be found", e);
}
if (convertMessageToType(repo.getObject(vId).getVersionInfo().getMessage()) == MCROCFLMetadataVersion.DELETED) {
throw new IOException("Cannot read already deleted object '" + ocflObjectID + "'");
}
try (InputStream storedContentStream = repo.getObject(vId).getFile(buildFilePath(mcrid)).getStream()) {
Document xml = new MCRStreamContent(storedContentStream).asXML();
if (revision != null) {
xml.getRootElement().setAttribute("rev", revision);
}
return new MCRJDOMContent(xml);
} catch (JDOMException e) {
throw new IOException("Can not parse XML from OCFL-Store", e);
}
}
protected String getOCFLObjectID(MCRCategoryID mcrid) {
return MCROCFLObjectIDPrefixHelper.CLASSIFICATION + mcrid.getRootID();
}
/**
* Build file path from ID, <em>use for root classifications only!</em>
* @param mcrid The ID to the Classification
* @return The Path to the File.
* @throws MCRUsageException if the Category is not a root classification
*/
protected String buildFilePath(MCRCategoryID mcrid) {
if (!mcrid.isRootID()) {
throw new IllegalArgumentException("Only root categories are allowed: " + mcrid);
}
return ROOT_FOLDER + mcrid + ".xml";
}
protected VersionInfo buildVersionInfo(String message, Date versionDate) {
VersionInfo versionInfo = new VersionInfo();
versionInfo.setMessage(message);
versionInfo.setCreated((versionDate == null ? new Date() : versionDate).toInstant().atOffset(ZoneOffset.UTC));
return versionInfo;
}
}
| 7,363 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROCFLClassificationEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ocfl/src/main/java/org/mycore/ocfl/classification/MCROCFLClassificationEventHandler.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.ocfl.classification;
import static org.mycore.ocfl.MCROCFLPersistenceTransaction.addClassficationEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandler;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.common.MCRAbstractMetadataVersion;
/**
* @author Tobias Lenhardt [Hammer1279]
*/
public class MCROCFLClassificationEventHandler implements MCREventHandler {
private static final Logger LOGGER = LogManager.getLogger();
@Override
public void doHandleEvent(MCREvent evt) throws MCRException {
if (evt.getObjectType() == MCREvent.ObjectType.CLASS) {
MCRCategory mcrCg = (MCRCategory) evt.get(MCREvent.CLASS_KEY);
LOGGER.debug("{} handling {} {}", getClass().getName(), mcrCg.getId(), evt.getEventType());
switch (evt.getEventType()) {
case CREATE -> addClassficationEvent(mcrCg.getRoot().getId(), MCRAbstractMetadataVersion.CREATED);
case UPDATE -> addClassficationEvent(mcrCg.getRoot().getId(), MCRAbstractMetadataVersion.UPDATED);
case DELETE -> {
if (mcrCg.getId().isRootID()) {
// delete complete classification
addClassficationEvent(mcrCg.getRoot().getId(), MCRAbstractMetadataVersion.DELETED);
} else {
// update classification to new version
addClassficationEvent(mcrCg.getRoot().getId(), MCRAbstractMetadataVersion.UPDATED);
}
}
default -> LOGGER.error("No Method available for {}", evt.getEventType());
}
}
}
@Override
public void undoHandleEvent(MCREvent evt) throws MCRException {
if (evt.getObjectType() == MCREvent.ObjectType.CLASS) {
LOGGER.debug("{} handling undo of {} {}", getClass().getName(),
((MCRCategory) evt.get(MCREvent.CLASS_KEY)).getId(),
evt.getEventType());
LOGGER.info("Doing nothing for undo of {} {}", ((MCRCategory) evt.get(MCREvent.CLASS_KEY)).getId(),
evt.getEventType());
}
}
}
| 3,083 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLodFeature.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-lod/src/main/java/org/mycore/lod/MCRLodFeature.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.lod;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.jersey.feature.MCRJerseyDefaultFeature;
import org.mycore.restapi.MCREnableTransactionFilter;
import org.mycore.restapi.annotations.MCRRequireTransaction;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.FeatureContext;
import jakarta.ws.rs.ext.Provider;
/**
* Jersey configuration for Linked Open Data Endpoint
*
* @author Robert Stephan
*
* @see MCRJerseyDefaultFeature
*
*/
@Provider
public class MCRLodFeature extends MCRJerseyDefaultFeature {
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
Class<?> resourceClass = resourceInfo.getResourceClass();
Method resourceMethod = resourceInfo.getResourceMethod();
if (requiresTransaction(resourceClass, resourceMethod)) {
context.register(MCREnableTransactionFilter.class);
}
super.configure(resourceInfo, context);
}
/**
* Checks if the class/method is annotated by {@link MCRRequireTransaction}.
*
* @param resourceClass the class to check
* @param resourceMethod the method to check
* @return true if one ore both is annotated and requires transaction
*/
protected boolean requiresTransaction(Class<?> resourceClass, Method resourceMethod) {
return resourceClass.getAnnotation(MCRRequireTransaction.class) != null
|| resourceMethod.getAnnotation(MCRRequireTransaction.class) != null;
}
@Override
protected List<String> getPackages() {
return MCRConfiguration2.getString("MCR.LOD.Resource.Packages").map(MCRConfiguration2::splitValue)
.orElse(Stream.empty())
.collect(Collectors.toList());
}
@Override
protected void registerSessionHookFilter(FeatureContext context) {
// don't register transaction filter, is already implemented by MCRSessionFilter
}
@Override
protected void registerTransactionFilter(FeatureContext context) {
// don't register transaction filter, is already implemented by MCRSessionFilter
}
@Override
protected void registerAccessFilter(FeatureContext context, Class<?> resourceClass, Method resourceMethod) {
//don't have to register access filter yet
// example: context.register(org.mycore.restapi.v1.MCRRestAuthorizationFilter.class);
super.registerAccessFilter(context, resourceClass, resourceMethod);
}
}
| 3,360 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJerseyLodApp.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-lod/src/main/java/org/mycore/lod/MCRJerseyLodApp.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.lod;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFHandlerException;
import org.eclipse.rdf4j.rio.RDFParseException;
import org.eclipse.rdf4j.rio.RDFParser;
import org.eclipse.rdf4j.rio.RDFWriter;
import org.eclipse.rdf4j.rio.Rio;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.ServerProperties;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.jersey.access.MCRRequestScopeACLFilter;
import org.mycore.restapi.MCRCORSResponseFilter;
import org.mycore.restapi.MCRIgnoreClientAbortInterceptor;
import org.mycore.restapi.MCRSessionFilter;
import org.mycore.restapi.MCRTransactionFilter;
import org.mycore.restapi.converter.MCRWrappedXMLWriter;
import io.swagger.v3.jaxrs2.integration.resources.OpenApiResource;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Response;
/**
* Basic configuration for the MyCoRe Linked Open Data Endpoint
*
* @author Robert Stephan
*/
@ApplicationPath("/open-data")
public class MCRJerseyLodApp extends ResourceConfig {
//RDFXML is the default/fallback format an does not have to be on this list
private static List<RDFFormat> RDF_OUTPUT_FORMATS = List.of(RDFFormat.TURTLE, RDFFormat.JSONLD);
/**
* Constructor
*/
public MCRJerseyLodApp() {
super();
initAppName();
property(ServerProperties.APPLICATION_NAME, getApplicationName());
packages(getRestPackages());
property(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, true);
register(MCRSessionFilter.class);
register(MCRTransactionFilter.class);
register(MCRLodFeature.class);
register(MCRCORSResponseFilter.class);
register(MCRRequestScopeACLFilter.class);
register(MCRIgnoreClientAbortInterceptor.class);
}
/**
* read name for the Jersey App from properties or generate a default one
*/
protected void initAppName() {
setApplicationName(MCRConfiguration2.getString("MCR.NameOfProject").orElse("MyCoRe") + " LOD-Endpoint");
LogManager.getLogger().info("Initiialize {}", getApplicationName());
}
/**
* read packages with Rest controllers and configuration
* @return an array of package names
*/
protected String[] getRestPackages() {
return Stream
.concat(
Stream.of(MCRWrappedXMLWriter.class.getPackage().getName(),
OpenApiResource.class.getPackage().getName()),
MCRConfiguration2.getOrThrow("MCR.LOD.Resource.Packages", MCRConfiguration2::splitValue))
.toArray(String[]::new);
}
/**
* create a Response object that contains the linked data in the given format
*
* @param rdfxmlString - the linked data as String in RDFXML format
* @param uri - the base URI of the document
* @param mimeTypes - the mime types, sent with the request
* @return the Jersey Response with the requested Linked Data format
*/
public static Response returnLinkedData(String rdfxmlString, URI uri, List<String> mimeTypes) {
try {
for (RDFFormat rdfOutFormat : RDF_OUTPUT_FORMATS) {
if (!Collections.disjoint(mimeTypes, rdfOutFormat.getMIMETypes())) {
RDFParser rdfParser = Rio.createParser(RDFFormat.RDFXML);
StringWriter sw = new StringWriter();
RDFWriter rdfWriter = Rio.createWriter(rdfOutFormat, sw);
rdfParser.setRDFHandler(rdfWriter);
rdfParser.parse(new StringReader(rdfxmlString), uri.toString());
return Response.ok(sw.toString()).type(rdfOutFormat.getDefaultMIMEType() + ";charset=UTF-8")
.build();
}
}
} catch (IOException | RDFParseException | RDFHandlerException e) {
// do nothing
}
//fallback, default: RDFFormat.RDFXML
return Response.ok(rdfxmlString, RDFFormat.RDFXML.getDefaultMIMEType() + ";charset=UTF-8")
.build();
}
}
| 5,089 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLodClassification.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-lod/src/main/java/org/mycore/lod/controller/MCRLodClassification.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.lod.controller;
import java.io.IOException;
import java.net.URI;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.jdom2.Document;
import org.jdom2.Element;
import org.mycore.common.MCRConstants;
import org.mycore.common.content.MCRJDOMContent;
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.model.MCRClass;
import org.mycore.datamodel.classifications2.model.MCRClassCategory;
import org.mycore.datamodel.classifications2.utils.MCRSkosTransformer;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.frontend.jersey.MCRCacheControl;
import org.mycore.lod.MCRJerseyLodApp;
import org.mycore.restapi.converter.MCRDetailLevel;
import org.mycore.restapi.v2.MCRErrorResponse;
import org.mycore.restapi.v2.MCRRestUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
/**
* Linked Open Data: Classification End point
*
* @author Robert Stephan
*/
@Path("/classification")
public class MCRLodClassification {
/** error code for error response */
public static final String ERROR_MCRCLASS_NOT_FOUND = "MCRCLASS_NOT_FOUND";
/** error code for error response */
public static final String ERROR_MCRCLASS_ID_MISMATCH = "MCRCLASS_ID_MISMATCH";
/** error code for error response */
public static final String ERROR_MCRCLASS_TRANSFORMATION = "MCRCLASS_TRANSFORMATION";
/** parameter key in request url paths */
private static final String PARAM_CLASSID = "classid";
/** parameter key in request url paths */
private static final String PARAM_CATEGID = "categid";
@Context
ContainerRequestContext request;
/**
* return the list of available classifications as Linked Open Data
*
* TODO Is there a reasonable response on the base path of an LOD URI,
* or remove this endpoint completely?
*
* @return a jersey response with the list of classifications
*/
@GET
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.HOURS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.HOURS))
public Response outputLODClassificationRoot() {
MCRCategoryDAO categoryDAO = MCRCategoryDAOFactory.getInstance();
Date lastModified = new Date(categoryDAO.getLastModified());
Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request.getRequest(), lastModified);
if (cachedResponse.isPresent()) {
return cachedResponse.get();
}
try {
Document classRdfxml = createClassList();
String rdfxmlString = new MCRJDOMContent(classRdfxml).asString();
List<String> mimeTypes = request.getAcceptableMediaTypes().parallelStream().map(MediaType::toString)
.toList();
URI uri = request.getUriInfo().getBaseUri();
return MCRJerseyLodApp.returnLinkedData(rdfxmlString, uri, mimeTypes);
} catch (IOException e) {
throw MCRErrorResponse.fromStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
.withErrorCode(ERROR_MCRCLASS_TRANSFORMATION)
.withMessage("Could create classification list.")
.toException();
}
}
/**
* return a classification (with its categories on the first hierarchy level as linked open data)
* @param classId - the classification ID
* @return the Response with the classification as linked open data
*/
@GET
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS))
@Path("/{" + PARAM_CLASSID + "}")
public Response getClassification(@PathParam(PARAM_CLASSID) String classId) {
List<MediaType> mediaTypes = request.getAcceptableMediaTypes();
return getClassification(MCRCategoryID.rootID(classId),
dao -> dao.getCategory(MCRCategoryID.rootID(classId), 1), mediaTypes,
request.getUriInfo().getBaseUri());
}
/**
* return a category and its children on the first hierarchy level as linked open data
*
* @param classId - the class ID
* @param categId - the category ID
* @return the Response with the category as linked open data
*/
@GET
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS))
@Path("/{" + PARAM_CLASSID + "}/{" + PARAM_CATEGID + "}")
@Operation(summary = "Returns Classification with the given " + PARAM_CLASSID + " and " + PARAM_CATEGID + ".",
responses = @ApiResponse(content = {
@Content(schema = @Schema(implementation = MCRClass.class)),
@Content(schema = @Schema(implementation = MCRClassCategory.class))
},
description = "If media type parameter " + MCRDetailLevel.MEDIA_TYPE_PARAMETER
+ " is 'summary' an MCRClassCategory is returned. "
+ "In other cases MCRClass with different detail level."),
tags = MCRRestUtils.TAG_MYCORE_CLASSIFICATION)
public Response getClassification(@PathParam(PARAM_CLASSID) String classId,
@PathParam(PARAM_CATEGID) String categId) {
MCRCategoryID categoryId = new MCRCategoryID(classId, categId);
return getClassification(categoryId, dao -> dao.getRootCategory(categoryId, 0),
request.getAcceptableMediaTypes(),
request.getUriInfo().getBaseUri());
}
private Response getClassification(MCRCategoryID categId, Function<MCRCategoryDAO, MCRCategory> categorySupplier,
List<MediaType> acceptMediaTypes, URI uri) {
MCRCategoryDAO categoryDAO = MCRCategoryDAOFactory.getInstance();
String classId = categId.getRootID();
Date lastModified = getLastModifiedDate(classId, categoryDAO);
Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request.getRequest(), lastModified);
if (cachedResponse.isPresent()) {
return cachedResponse.get();
}
MCRCategory classification = categorySupplier.apply(categoryDAO);
if (classification == null) {
throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode())
.withErrorCode(ERROR_MCRCLASS_NOT_FOUND)
.withMessage("Could not find classification or category in " + classId + ".")
.toException();
}
try {
Document classRdfXml = MCRSkosTransformer.getSkosInRDFXML(classification, categId);
String rdfxmlString = new MCRJDOMContent(classRdfXml).asString();
List<String> mimeTypes = acceptMediaTypes.parallelStream().map(MediaType::toString).toList();
return MCRJerseyLodApp.returnLinkedData(rdfxmlString, uri, mimeTypes);
} catch (IOException e) {
throw MCRErrorResponse.fromStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
.withErrorCode(ERROR_MCRCLASS_TRANSFORMATION)
.withMessage("Could not find classification or category in " + classId + ".")
.toException();
}
}
private Document createClassList() {
Element eBag = new Element("Bag", MCRConstants.RDF_NAMESPACE);
MCRCategoryDAO categoryDAO = MCRCategoryDAOFactory.getInstance();
for (MCRCategory categ : categoryDAO.getRootCategories()) {
eBag.addContent(new Element("li", MCRConstants.RDF_NAMESPACE)
.setAttribute("resource",
MCRFrontendUtil.getBaseURL() + "open-data/classification/" + categ.getId().toString(),
MCRConstants.RDF_NAMESPACE));
}
return new Document(eBag);
}
private static Date getLastModifiedDate(@PathParam(PARAM_CLASSID) String classId, MCRCategoryDAO categoryDAO) {
long categoryLastModified = categoryDAO.getLastModified(classId);
return new Date(categoryLastModified > 0 ? categoryLastModified : categoryDAO.getLastModified());
}
}
| 9,522 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLodRoot.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-lod/src/main/java/org/mycore/lod/controller/MCRLodRoot.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.lod.controller;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.mycore.common.MCRConstants;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.frontend.jersey.MCRCacheControl;
import org.mycore.lod.MCRJerseyLodApp;
import org.mycore.restapi.v2.MCRErrorResponse;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
/**
* Linked Open Data: Root End point
*
* (Work in Progress - find some reasonable schema to for repository metadata)
*
* @author Robert Stephan
*/
@Path("/")
public class MCRLodRoot {
private static Namespace NS_FOAF = Namespace.getNamespace("foaf", "http://xmlns.com/foaf/0.1/");
@Context
ContainerRequestContext request;
/**
* provide some basic information about the linked open data endpoint
*
* @return a short description using FOAF vocabulary
*/
@GET
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.HOURS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.HOURS))
public Response outputLODRoot() {
try {
Document docRepository = createRepositoryInfo();
String rdfxmlString = new MCRJDOMContent(docRepository).asString();
URI uri = request.getUriInfo().getBaseUri();
List<String> mimeTypes = request.getAcceptableMediaTypes().parallelStream().map(MediaType::toString)
.toList();
return MCRJerseyLodApp.returnLinkedData(rdfxmlString, uri, mimeTypes);
} catch (IOException e) {
throw MCRErrorResponse.fromStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
.withErrorCode("INFO_ERROR")
.withMessage("Could not create Repository information")
.toException();
}
}
private Document createRepositoryInfo() {
Element eAgent = new Element("Agent", NS_FOAF);
eAgent.addContent(
new Element("name", NS_FOAF)
.setText(MCRConfiguration2.getString("MCR.NameOfProject").orElse("MyCoRe Repository")));
eAgent.addContent(
new Element("homepage", NS_FOAF)
.setAttribute("resource", MCRFrontendUtil.getBaseURL(), MCRConstants.RDF_NAMESPACE));
return new Document(eAgent);
}
}
| 3,433 | 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-wfc/src/main/java/org/mycore/wfc/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/>.
*/
/** MyCoRe workflow components */
package org.mycore.wfc;
| 785 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConstants.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wfc/src/main/java/org/mycore/wfc/MCRConstants.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.wfc;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.wfc.actionmapping.MCRAction;
import org.mycore.wfc.actionmapping.MCRActionMappings;
import org.mycore.wfc.actionmapping.MCRCollection;
import org.mycore.wfc.actionmapping.MCRDecision;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
/**
* @author Thomas Scheffler (yagee)
*
*/
public abstract class MCRConstants {
private MCRConstants() {
}
public static final String CONFIG_PREFIX = "MCR.Module-wfc.";
public static final JAXBContext JAXB_CONTEXT = initContext();
public static final MCRCategoryID STATUS_CLASS_ID = getStatusClassID();
public static final MCRCategoryID COLLECTION_CLASS_ID = getCollectionClassID();
private static JAXBContext initContext() {
try {
return JAXBContext.newInstance(MCRActionMappings.class, MCRCollection.class, MCRAction.class,
MCRDecision.class);
} catch (JAXBException e) {
throw new MCRException("Could not initialize JAXBContext.", e);
}
}
private static MCRCategoryID getStatusClassID() {
final String classID = MCRConfiguration2.getString(CONFIG_PREFIX + "StatusClassID").orElse("objectStatus");
return MCRCategoryID.rootID(classID);
}
private static MCRCategoryID getCollectionClassID() {
final String classID = MCRConfiguration2.getString(CONFIG_PREFIX + "CollectionClassID")
.orElse("objectCollection");
return MCRCategoryID.rootID(classID);
}
}
| 2,402 | 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-wfc/src/main/java/org/mycore/wfc/mail/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/>.
*/
/** Mail events */
package org.mycore.wfc.mail;
| 775 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMailEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wfc/src/main/java/org/mycore/wfc/mail/MCRMailEventHandler.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.wfc.mail;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRMailer;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandlerBase;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.utils.MCRCategoryTransformer;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.datamodel.niofs.MCRPathXML;
/**
* Uses "e-mail-events.xsl" to transform derivate, object and files to emails.
*
* See {@link MCRMailer} for email xml format.
*
* @author Thomas Scheffler (yagee)
*
*/
public class MCRMailEventHandler extends MCREventHandlerBase {
private static final Logger LOGGER = LogManager.getLogger(MCRMailEventHandler.class);
private void sendNotificationMail(MCREvent evt, MCRContent doc, String description) throws Exception {
LOGGER.info("Preparing mail for: {}", description);
HashMap<String, String> parameters = new HashMap<>();
for (Map.Entry<String, Object> entry : evt.entrySet()) {
parameters.put(entry.getKey(), entry.getValue().toString());
}
parameters.put("action", evt.getEventType().toString());
parameters.put("type", evt.getObjectType().toString());
MCRMailer.sendMail(doc.asXML(), "e-mail-events", parameters);
}
private void handleCategoryEvent(MCREvent evt, MCRCategory obj) {
MCRContent xml = new MCRJDOMContent(MCRCategoryTransformer.getMetaDataDocument(obj, false));
handleEvent(evt, xml, obj.toString());
}
private void handleObjectEvent(MCREvent evt, MCRObject obj) {
MCRContent xml = new MCRJDOMContent(obj.createXML());
handleEvent(evt, xml, obj.getId().toString());
}
private void handleDerivateEvent(MCREvent evt, MCRDerivate der) {
MCRContent xml = new MCRJDOMContent(der.createXML());
handleEvent(evt, xml, der.getId().toString());
}
private void handlePathEvent(MCREvent evt, Path file, BasicFileAttributes attrs) {
if (!(file instanceof MCRPath)) {
return;
}
MCRPath path = MCRPath.toMCRPath(file);
MCRContent xml;
try {
xml = new MCRJDOMContent(MCRPathXML.getFileXML(path, attrs));
handleEvent(evt, xml, path.toString());
} catch (IOException e) {
LOGGER.error("Error while generating mail for {}", file, e);
}
}
private void handleEvent(MCREvent evt, MCRContent xml, String description) {
try {
sendNotificationMail(evt, xml, description);
} catch (Exception e) {
LOGGER.error("Error while handling event: {}", evt, e);
}
}
@Override
protected void handleClassificationCreated(MCREvent evt, MCRCategory obj) {
handleCategoryEvent(evt, obj);
}
@Override
protected void handleClassificationUpdated(MCREvent evt, MCRCategory obj) {
handleCategoryEvent(evt, obj);
}
@Override
protected void handleClassificationDeleted(MCREvent evt, MCRCategory obj) {
handleCategoryEvent(evt, obj);
}
@Override
protected void handleObjectCreated(MCREvent evt, MCRObject obj) {
handleObjectEvent(evt, obj);
}
@Override
protected void handleObjectUpdated(MCREvent evt, MCRObject obj) {
handleObjectEvent(evt, obj);
}
@Override
protected void handleObjectDeleted(MCREvent evt, MCRObject obj) {
handleObjectEvent(evt, obj);
}
@Override
protected void handleDerivateCreated(MCREvent evt, MCRDerivate der) {
handleDerivateEvent(evt, der);
}
@Override
protected void handleDerivateUpdated(MCREvent evt, MCRDerivate der) {
handleDerivateEvent(evt, der);
}
@Override
protected void handleDerivateDeleted(MCREvent evt, MCRDerivate der) {
handleDerivateEvent(evt, der);
}
@Override
protected void handlePathCreated(MCREvent evt, Path file, BasicFileAttributes attrs) {
handlePathEvent(evt, file, attrs);
}
@Override
protected void handlePathUpdated(MCREvent evt, Path file, BasicFileAttributes attrs) {
handlePathEvent(evt, file, attrs);
}
@Override
protected void handlePathDeleted(MCREvent evt, Path file, BasicFileAttributes attrs) {
handlePathEvent(evt, file, attrs);
}
}
| 5,509 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCollection.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wfc/src/main/java/org/mycore/wfc/actionmapping/MCRCollection.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.wfc.actionmapping;
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;
/**
* @author Thomas Scheffler (yagee)
*
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "collection")
public class MCRCollection {
@XmlElement(name = "action")
MCRAction[] actions;
@XmlAttribute
String name;
public MCRAction[] getActions() {
return actions;
}
public void setActions(MCRAction... actions) {
this.actions = actions;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 1,551 | 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-wfc/src/main/java/org/mycore/wfc/actionmapping/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/>.
*/
/** Context sensitive mapping of actions */
package org.mycore.wfc.actionmapping;
| 809 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWorkflowRuleParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wfc/src/main/java/org/mycore/wfc/actionmapping/MCRWorkflowRuleParser.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.wfc.actionmapping;
import org.jdom2.Element;
import org.mycore.access.mcrimpl.MCRRuleParser;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.parsers.bool.MCRCondition;
import org.mycore.parsers.bool.MCRParseException;
import org.mycore.wfc.MCRConstants;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRWorkflowRuleParser extends MCRRuleParser {
private static final String EQUALS = "=";
private static final String EQUALS_NOT = "!=";
private static final String STATUS = "status";
private MCRCategoryID statusClassId;
protected MCRWorkflowRuleParser() {
super();
this.statusClassId = MCRConstants.STATUS_CLASS_ID;
}
/* (non-Javadoc)
* @see org.mycore.access.mcrimpl.MCRRuleParser#parseElement(org.jdom2.Element)
*/
@Override
protected MCRCondition<?> parseElement(Element e) {
String field = e.getAttributeValue("field");
String operator = e.getAttributeValue("operator");
String value = e.getAttributeValue("value");
boolean not = EQUALS_NOT.equals(operator);
if (STATUS.equals(field)) {
return new MCRCategoryCondition(STATUS, new MCRCategoryID(statusClassId.getRootID(), value), not);
}
return super.parseElement(e);
}
/* (non-Javadoc)
* @see org.mycore.access.mcrimpl.MCRRuleParser#parseString(java.lang.String)
*/
@Override
protected MCRCondition<?> parseString(String s) {
if (s.startsWith(STATUS)) {
s = s.substring(STATUS.length()).trim();
boolean not;
String value;
if (s.startsWith(EQUALS_NOT)) {
not = true;
value = s.substring(EQUALS_NOT.length()).trim();
} else if (s.startsWith(EQUALS)) {
not = false;
value = s.substring(EQUALS.length()).trim();
} else {
throw new MCRParseException("syntax error: " + s);
}
return new MCRCategoryCondition(STATUS, new MCRCategoryID(statusClassId.getRootID(), value), not);
}
return super.parseString(s);
}
}
| 2,918 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWorkflowData.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wfc/src/main/java/org/mycore/wfc/actionmapping/MCRWorkflowData.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.wfc.actionmapping;
import org.mycore.access.mcrimpl.MCRAccessData;
import org.mycore.datamodel.classifications2.MCRCategLinkReference;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRWorkflowData extends MCRAccessData {
MCRCategLinkReference categoryReference;
public MCRWorkflowData(MCRCategLinkReference categoryReference) {
this.categoryReference = categoryReference;
}
public MCRCategLinkReference getCategoryReference() {
return categoryReference;
}
}
| 1,260 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDecision.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wfc/src/main/java/org/mycore/wfc/actionmapping/MCRDecision.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.wfc.actionmapping;
import org.mycore.parsers.bool.MCRCondition;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* @author Thomas Scheffler (yagee)
*
*/
@XmlRootElement(name = "when")
@XmlAccessorType(XmlAccessType.NONE)
public class MCRDecision {
@XmlAttribute
private String url;
@XmlAttribute
@XmlJavaTypeAdapter(MCRWorkflowRuleAdapter.class)
private MCRCondition<?> condition;
/**
* @return the url
*/
public String getUrl() {
return url;
}
/**
* @param url the url to set
*/
public void setUrl(String url) {
this.url = url;
}
/**
* @return the condition
*/
public MCRCondition<?> getCondition() {
return condition;
}
/**
* @param condition the condition to set
*/
public void setCondition(MCRCondition<?> condition) {
this.condition = condition;
}
}
| 1,875 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.