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
MCRRestAuthorizationFilter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/MCRRestAuthorizationFilter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.v2; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.mycore.access.MCRAccessManager; import org.mycore.access.mcrimpl.MCRAccessControlSystem; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.frontend.jersey.access.MCRRequestScopeACL; import org.mycore.restapi.converter.MCRDetailLevel; import org.mycore.restapi.converter.MCRObjectIDParamConverterProvider; import org.mycore.restapi.v2.access.MCRRestAPIACLPermission; import org.mycore.restapi.v2.access.MCRRestAccessManager; import org.mycore.restapi.v2.annotation.MCRRestRequiredPermission; import jakarta.annotation.Priority; import jakarta.ws.rs.ForbiddenException; import jakarta.ws.rs.HttpMethod; import jakarta.ws.rs.Path; import jakarta.ws.rs.Priorities; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerRequestFilter; import jakarta.ws.rs.container.ResourceInfo; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.ext.ParamConverter; @Priority(Priorities.AUTHORIZATION) public class MCRRestAuthorizationFilter implements ContainerRequestFilter { public static final String PARAM_CLASSID = "classid"; public static final String PARAM_MCRID = "mcrid"; public static final String PARAM_DERID = "derid"; public static final String PARAM_DER_PATH = "path"; public static final ParamConverter<MCRObjectID> OBJECT_ID_PARAM_CONVERTER = new MCRObjectIDParamConverterProvider() .getConverter(MCRObjectID.class, null, null); @Context ResourceInfo resourceInfo; /** * checks if the given REST API operation is allowed * @param permission "read" or "write" * @param path - the REST API path, e.g. /v1/messages * * @throws jakarta.ws.rs.ForbiddenException if access is restricted */ private void checkRestAPIAccess(final ContainerRequestContext requestContext, final MCRRestAPIACLPermission permission, final String path) throws ForbiddenException { LogManager.getLogger().warn(path + ": Checking API access: " + permission); final MCRRequestScopeACL aclProvider = MCRRequestScopeACL.getInstance(requestContext); if (MCRRestAccessManager.checkRestAPIAccess(aclProvider, permission, path)) { return; } throw MCRErrorResponse.fromStatus(Response.Status.FORBIDDEN.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.API_NO_PERMISSION) .withMessage("REST-API action is not allowed.") .withDetail("Check access right '" + permission + "' on ACLs 'restapi:/' and 'restapi:" + path + "'!") .toException(); } private void checkBaseAccess(ContainerRequestContext requestContext, MCRRestAPIACLPermission permission, String objectId, String derId, String path) throws ForbiddenException { LogManager.getLogger().debug("Permission: {}, Object: {}, Derivate: {}, Path: {}", permission, objectId, derId, path); Optional<String> checkable = Optional.ofNullable(derId) .filter(d -> path != null) //only check for derId if path is given .map(Optional::of) .orElseGet(() -> Optional.ofNullable(objectId)) .map(OBJECT_ID_PARAM_CONVERTER::fromString) //MCR-3041 check for Bad Request .map(MCRObjectID::toString); checkable.ifPresent(id -> LogManager.getLogger().info("Checking " + permission + " access on " + id)); MCRRequestScopeACL aclProvider = MCRRequestScopeACL.getInstance(requestContext); boolean allowed = checkable .map(id -> aclProvider.checkPermission(id, permission.toString())) .orElse(true); if (allowed) { return; } if (checkable.get().equals(objectId)) { throw MCRErrorResponse.fromStatus(Response.Status.FORBIDDEN.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_NO_PERMISSION) .withMessage("You do not have " + permission + " permission on MCRObject " + objectId + ".") .toException(); } throw MCRErrorResponse.fromStatus(Response.Status.FORBIDDEN.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_NO_PERMISSION) .withMessage("You do not have " + permission + " permission on MCRDerivate " + derId + ".") .toException(); } private void checkDetailLevel(ContainerRequestContext requestContext, String... detail) throws ForbiddenException { MCRRequestScopeACL aclProvider = MCRRequestScopeACL.getInstance(requestContext); List<String> missedPermissions = Stream.of(detail) .map(d -> "rest-detail-" + d) .filter(d -> MCRAccessManager.hasRule(MCRAccessControlSystem.POOL_PRIVILEGE_ID, d)) .filter(d -> !aclProvider.checkPermission(d)) .collect(Collectors.toList()); if (!missedPermissions.isEmpty()) { throw MCRErrorResponse.fromStatus(Response.Status.FORBIDDEN.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.API_NO_PERMISSION) .withMessage("REST-API action is not allowed.") .withDetail("Check access right(s) '" + missedPermissions + "' on " + MCRAccessControlSystem.POOL_PRIVILEGE_ID + "'!") .toException(); } } @Override public void filter(ContainerRequestContext requestContext) { final String method = requestContext.getMethod(); if (HttpMethod.OPTIONS.equals(method)) { return; } final MCRRestRequiredPermission annotation = resourceInfo.getResourceMethod() .getAnnotation(MCRRestRequiredPermission.class); final MCRRestAPIACLPermission permission = Optional.ofNullable(annotation) .map(MCRRestRequiredPermission::value) .orElseGet(() -> MCRRestAPIACLPermission.fromMethod(method)); Optional.ofNullable(resourceInfo.getResourceClass().getAnnotation(Path.class)) .map(Path::value) .ifPresent(path -> { checkRestAPIAccess(requestContext, permission, path); MultivaluedMap<String, String> pathParameters = requestContext.getUriInfo().getPathParameters(); checkBaseAccess(requestContext, permission, pathParameters.getFirst(PARAM_MCRID), pathParameters.getFirst(PARAM_DERID), pathParameters.getFirst(PARAM_DER_PATH)); }); checkDetailLevel(requestContext, requestContext.getAcceptableMediaTypes() .stream() .map(m -> m.getParameters().get(MCRDetailLevel.MEDIA_TYPE_PARAMETER)) .filter(Objects::nonNull) .toArray(String[]::new)); } }
7,756
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRestDerivates.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/MCRRestDerivates.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.v2; import static org.mycore.restapi.v2.MCRRestAuthorizationFilter.PARAM_DERID; import static org.mycore.restapi.v2.MCRRestAuthorizationFilter.PARAM_MCRID; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.nio.file.FileSystemException; import java.nio.file.Files; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.JDOMException; import org.mycore.access.MCRAccessException; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRStreamContent; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetaClassification; import org.mycore.datamodel.metadata.MCRMetaEnrichedLinkID; import org.mycore.datamodel.metadata.MCRMetaIFS; import org.mycore.datamodel.metadata.MCRMetaLangText; import org.mycore.datamodel.metadata.MCRMetaLinkID; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.frontend.jersey.MCRCacheControl; import org.mycore.restapi.annotations.MCRAccessControlExposeHeaders; import org.mycore.restapi.annotations.MCRApiDraft; import org.mycore.restapi.annotations.MCRParam; import org.mycore.restapi.annotations.MCRParams; import org.mycore.restapi.annotations.MCRRequireTransaction; import org.mycore.restapi.converter.MCRContentAbstractWriter; import org.mycore.restapi.converter.MCRObjectIDParamConverterProvider; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; 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.ExampleObject; 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 jakarta.ws.rs.BeanParam; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.DefaultValue; import jakarta.ws.rs.FormParam; import jakarta.ws.rs.GET; import jakarta.ws.rs.PATCH; 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.core.Context; import jakarta.ws.rs.core.GenericEntity; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Request; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriInfo; import jakarta.xml.bind.annotation.XmlElementWrapper; @Path("/objects/{" + PARAM_MCRID + "}/derivates") public class MCRRestDerivates { public static final Logger LOGGER = LogManager.getLogger(); @Context Request request; @Context UriInfo uriInfo; @Parameter(example = "mir_mods_00004711") @PathParam(PARAM_MCRID) MCRObjectID mcrId; public static void validateDerivateRelation(MCRObjectID mcrId, MCRObjectID derId) { MCRObjectID objectId = MCRMetadataManager.getObjectId(derId, 1, TimeUnit.DAYS); if (objectId != null && !mcrId.equals(objectId)) { objectId = MCRMetadataManager.getObjectId(derId, 0, TimeUnit.SECONDS); } if (mcrId.equals(objectId)) { return; } if (objectId == null) { throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_NOT_FOUND) .withMessage("MCRDerivate " + derId + " not found") .toException(); } throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_NOT_FOUND_IN_OBJECT) .withMessage("MCRDerivate " + derId + " not found in object " + mcrId + ".") .toException(); } @GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON + ";charset=UTF-8" }) @MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS), sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS)) @Operation( summary = "Lists all derivates in the given object", responses = { @ApiResponse( description = "List of derivates (file collections) attached to the given metadata object", content = @Content(array = @ArraySchema(schema = @Schema(implementation = MCRMetaLinkID.class)))), @ApiResponse(responseCode = "" + MCRObjectIDParamConverterProvider.CODE_INVALID, description = MCRObjectIDParamConverterProvider.MSG_INVALID), }, tags = MCRRestUtils.TAG_MYCORE_DERIVATE) @XmlElementWrapper(name = "derobjects") public Response listDerivates() throws IOException { long modified = MCRXMLMetadataManager.instance().getLastModified(mcrId); if (modified < 0) { throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_NOT_FOUND) .withMessage("MCRObject " + mcrId + " not found") .toException(); } Date lastModified = new Date(modified); Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request, lastModified); if (cachedResponse.isPresent()) { return cachedResponse.get(); } MCRObject obj = MCRMetadataManager.retrieveMCRObject(mcrId); List<MCRMetaEnrichedLinkID> derivates = obj.getStructure().getDerivates(); return Response.ok() .entity(new GenericEntity<>(derivates) { }) .lastModified(lastModified) .build(); } @GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON + ";charset=UTF-8" }) @MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS), sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS)) @Operation( summary = "Returns given derivate in the given object", tags = MCRRestUtils.TAG_MYCORE_DERIVATE) @Path("/{" + PARAM_DERID + "}") public Response getDerivate(@Parameter(example = "mir_derivate_00004711") @PathParam(PARAM_DERID) MCRObjectID derid) throws IOException { validateDerivateRelation(mcrId, derid); long modified = MCRXMLMetadataManager.instance().getLastModified(derid); Date lastModified = new Date(modified); Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request, lastModified); if (cachedResponse.isPresent()) { return cachedResponse.get(); } MCRContent mcrContent = MCRXMLMetadataManager.instance().retrieveContent(derid); return Response.ok() .entity(mcrContent, new Annotation[] { MCRParams.Factory .get(MCRParam.Factory.get(MCRContentAbstractWriter.PARAM_OBJECTTYPE, derid.getTypeId())) }) .lastModified(lastModified) .build(); } @PUT @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON + ";charset=UTF-8" }) @Operation(summary = "Creates or updates MCRDerivate with the body of this request", tags = MCRRestUtils.TAG_MYCORE_DERIVATE, responses = { @ApiResponse(responseCode = "400", content = { @Content(mediaType = MediaType.TEXT_PLAIN) }, description = "'Invalid body content' or 'MCRObjectID mismatch'"), @ApiResponse(responseCode = "201", description = "MCRDerivate successfully created"), @ApiResponse(responseCode = "204", description = "MCRDerivate successfully updated"), }) @MCRRequireTransaction @Path("/{" + PARAM_DERID + "}") public Response updateDerivate( @Parameter(example = "mir_derivate_00004711") @PathParam(PARAM_DERID) MCRObjectID derid, @Parameter(required = true, description = "MCRObject XML", examples = @ExampleObject("<mycoreobject ID=\"{mcrid}\" ..>\n...\n</mycorobject>")) InputStream xmlSource) throws IOException { //check preconditions try { long lastModified = MCRXMLMetadataManager.instance().getLastModified(derid); if (lastModified >= 0) { Date lmDate = new Date(lastModified); Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request, lmDate); if (cachedResponse.isPresent()) { return cachedResponse.get(); } } } catch (Exception e) { //ignore errors as PUT is idempotent } boolean create = true; if (MCRMetadataManager.exists(derid)) { validateDerivateRelation(mcrId, derid); create = false; } MCRStreamContent inputContent = new MCRStreamContent(xmlSource, null, MCRDerivate.ROOT_NAME); MCRDerivate derivate; try { derivate = new MCRDerivate(inputContent.asXML()); derivate.validate(); } catch (JDOMException | MCRException e) { throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_INVALID) .withMessage("MCRDerivate " + derid + " is not valid") .withDetail(e.getMessage()) .withCause(e) .toException(); } if (!derid.equals(derivate.getId())) { throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_ID_MISMATCH) .withMessage("MCRDerivate " + derid + " cannot be overwritten by " + derivate.getId() + ".") .toException(); } try { if (create) { MCRMetadataManager.create(derivate); MCRPath rootDir = MCRPath.getPath(derid.toString(), "/"); if (Files.notExists(rootDir)) { rootDir.getFileSystem().createRoot(derid.toString()); } return Response.status(Response.Status.CREATED).build(); } else { MCRMetadataManager.update(derivate); return Response.status(Response.Status.NO_CONTENT).build(); } } catch (MCRAccessException e) { throw MCRErrorResponse.fromStatus(Response.Status.FORBIDDEN.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_NO_PERMISSION) .withMessage("You may not modify or create MCRDerivate " + derid + ".") .withDetail(e.getMessage()) .withCause(e) .toException(); } } @DELETE @Operation(summary = "Deletes MCRDerivate {" + PARAM_DERID + "}", tags = MCRRestUtils.TAG_MYCORE_DERIVATE, responses = { @ApiResponse(responseCode = "204", description = "MCRDerivate successfully deleted"), }) @MCRRequireTransaction @Path("/{" + PARAM_DERID + "}") public Response deleteDerivate( @Parameter(example = "mir_derivate_00004711") @PathParam(PARAM_DERID) MCRObjectID derid) { if (!MCRMetadataManager.exists(derid)) { throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_NOT_FOUND) .withMessage("MCRDerivate " + derid + " not found") .toException(); } try { MCRMetadataManager.deleteMCRDerivate(derid); return Response.noContent().build(); } catch (MCRAccessException e) { throw MCRErrorResponse.fromStatus(Response.Status.FORBIDDEN.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_NO_PERMISSION) .withMessage("You may not delete MCRDerivate " + derid + ".") .withDetail(e.getMessage()) .withCause(e) .toException(); } } @POST @Operation( summary = "Adds a new derivate (with defaults for 'display-enabled', 'main-doc', 'label') in the given object", responses = @ApiResponse(responseCode = "201", headers = @Header(name = HttpHeaders.LOCATION, schema = @Schema( type = "string", format = "uri"), description = "URL of the new derivate")), tags = MCRRestUtils.TAG_MYCORE_DERIVATE) @MCRRequireTransaction @MCRAccessControlExposeHeaders(HttpHeaders.LOCATION) public Response createDefaultDerivate() { return doCreateDerivate(new DerivateMetadata()); } @POST @Operation( summary = "Adds a new derivate in the given object", responses = @ApiResponse(responseCode = "201", description = "Derivate successfully created", headers = @Header(name = HttpHeaders.LOCATION, schema = @Schema(type = "string", format = "uri"), description = "URL of the new derivate")), tags = MCRRestUtils.TAG_MYCORE_DERIVATE) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @RequestBody(required = true, content = @Content(mediaType = MediaType.APPLICATION_FORM_URLENCODED, schema = @Schema(implementation = DerivateMetadata.class))) @MCRRequireTransaction @MCRAccessControlExposeHeaders(HttpHeaders.LOCATION) public Response createDerivate(@BeanParam DerivateMetadata der) { return doCreateDerivate(der); } private Response doCreateDerivate(@BeanParam DerivateMetadata der) { LOGGER.debug(der); String projectID = mcrId.getProjectId(); MCRObjectID zeroId = MCRObjectID.getInstance(MCRObjectID.formatID(projectID + "_derivate", 0)); MCRDerivate derivate = new MCRDerivate(); derivate.setId(zeroId); derivate.setOrder(der.getOrder()); derivate.getDerivate().getClassifications() .addAll(der.getClassifications().stream() .map(categId -> new MCRMetaClassification("classification", 0, null, categId)) .collect(Collectors.toList())); derivate.getDerivate().getTitles() .addAll(der.getTitles().stream() .map(DerivateTitle::toMetaLangText) .collect(Collectors.toList())); 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(mcrId, null, null); derivate.getDerivate().setLinkMeta(linkId); MCRMetaIFS ifs = new MCRMetaIFS(); ifs.setSubTag("internal"); ifs.setSourcePath(null); ifs.setMainDoc(der.getMainDoc()); derivate.getDerivate().setInternals(ifs); try { MCRMetadataManager.create(derivate); } catch (MCRAccessException e) { throw MCRErrorResponse.fromStatus(Response.Status.FORBIDDEN.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_NO_PERMISSION) .withMessage("You may not create MCRDerivate for project " + zeroId.getProjectId() + ".") .withDetail(e.getMessage()) .withCause(e) .toException(); } MCRObjectID derId = derivate.getId(); LOGGER.debug("Created new derivate with ID {}", derId); MCRPath rootDir = MCRPath.getPath(derId.toString(), "/"); if (Files.notExists(rootDir)) { try { rootDir.getFileSystem().createRoot(derId.toString()); } catch (FileSystemException e) { throw MCRErrorResponse.fromStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_CREATE_DIRECTORY) .withMessage("Could not create root directory for MCRDerivate " + derId + ".") .withDetail(e.getMessage()) .withCause(e) .toException(); } } return Response.created(uriInfo.getAbsolutePathBuilder().path(derId.toString()).build()).build(); } @PATCH @Operation( summary = "Updates the metadata (or partial metadata) of the given derivate", responses = @ApiResponse(responseCode = "204"), tags = MCRRestUtils.TAG_MYCORE_DERIVATE) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @RequestBody(required = true, content = @Content(mediaType = MediaType.APPLICATION_FORM_URLENCODED, schema = @Schema(implementation = DerivateMetadata.class))) @MCRRequireTransaction @MCRAccessControlExposeHeaders(HttpHeaders.LOCATION) @Path("/{" + PARAM_DERID + "}") @MCRApiDraft("MCRPatchDerivate") public Response patchDerivate(@BeanParam DerivateMetadata der, @Parameter(example = "mir_derivate_00004711") @PathParam(PARAM_DERID) MCRObjectID derid) { LOGGER.debug(der); MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derid); boolean modified = false; if (der.getOrder() != -1 && derivate.getOrder() != der.getOrder()) { modified = true; derivate.setOrder(der.getOrder()); } if (der.getMainDoc() != null && !der.getMainDoc().equals(derivate.getDerivate().getInternals().getMainDoc())) { modified = true; derivate.getDerivate().getInternals().setMainDoc(der.getMainDoc()); } List<MCRCategoryID> oldClassifications = derivate.getDerivate().getClassifications().stream() .map(x -> MCRCategoryID.fromString(x.getClassId() + ":" + x.getCategId())) .collect(Collectors.toList()); if (!der.getClassifications().isEmpty() && (oldClassifications.size() != der.getClassifications().size() || !oldClassifications.containsAll(der.getClassifications()))) { modified = true; derivate.getDerivate().getClassifications().clear(); derivate.getDerivate().getClassifications() .addAll(der.getClassifications().stream() .map(categId -> new MCRMetaClassification("classification", 0, null, categId)) .collect(Collectors.toList())); } List<MCRMetaLangText> newTitles = der.getTitles().stream() .map(DerivateTitle::toMetaLangText) .collect(Collectors.toList()); if (!newTitles.isEmpty() && (derivate.getDerivate().getTitleSize() != newTitles.size() || !derivate.getDerivate().getTitles().containsAll(newTitles))) { modified = true; derivate.getDerivate().getTitles().clear(); derivate.getDerivate().getTitles().addAll(newTitles); } if (modified) { try { MCRMetadataManager.update(derivate); } catch (MCRAccessException e) { throw MCRErrorResponse.fromStatus(Response.Status.FORBIDDEN.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_NO_PERMISSION) .withMessage("You may not update MCRDerivate " + derivate.getId() + ".") .withDetail(e.getMessage()) .withCause(e) .toException(); } } return Response.noContent().build(); } @PUT @Path("/{" + PARAM_DERID + "}/try") @Operation(summary = "pre-flight target to test write operation on {" + PARAM_DERID + "}", tags = MCRRestUtils.TAG_MYCORE_DERIVATE, responses = { @ApiResponse(responseCode = "202", description = "You have write permission"), @ApiResponse(responseCode = "401", description = "You do not have write permission and need to authenticate first"), @ApiResponse(responseCode = "403", description = "You do not have write permission"), }) public Response testUpdateDerivate(@PathParam(PARAM_DERID) MCRObjectID id) { return Response.status(Response.Status.ACCEPTED).build(); } @DELETE @Path("/{" + PARAM_DERID + "}/try") @Operation(summary = "pre-flight target to test delete operation on {" + PARAM_DERID + "}", tags = MCRRestUtils.TAG_MYCORE_DERIVATE, responses = { @ApiResponse(responseCode = "202", description = "You have delete permission"), @ApiResponse(responseCode = "401", description = "You do not have delete permission and need to authenticate first"), @ApiResponse(responseCode = "403", description = "You do not have delete permission"), }) public Response testDeleteDerivate(@PathParam(PARAM_DERID) MCRObjectID id) { return Response.status(Response.Status.ACCEPTED).build(); } public static class DerivateTitle { private String lang; private String text; //Jersey can use this method without further configuration public static DerivateTitle fromString(String value) { final DerivateTitle derivateTitle = new DerivateTitle(); if (value.length() >= 4 && value.charAt(0) == '(') { int pos = value.indexOf(')'); if (pos > 1) { derivateTitle.setLang(value.substring(1, pos)); derivateTitle.setText(value.substring(pos + 1)); return derivateTitle; } } derivateTitle.setText(value); return derivateTitle; } public String getLang() { return lang; } public void setLang(String lang) { this.lang = lang; } public String getText() { return text; } public void setText(String text) { this.text = text; } public MCRMetaLangText toMetaLangText() { return new MCRMetaLangText("title", getLang(), null, 0, null, getText()); } } public static class DerivateMetadata { private String mainDoc; private int order = 1; private List<MCRCategoryID> classifications = List.of(); private List<DerivateTitle> titles = List.of(); String getMainDoc() { return mainDoc; } @FormParam("maindoc") @JsonProperty("maindoc") public void setMainDoc(String mainDoc) { this.mainDoc = mainDoc; } public int getOrder() { return order; } @JsonProperty @FormParam("order") @DefaultValue("1") public void setOrder(int order) { this.order = order; } public List<MCRCategoryID> getClassifications() { return classifications; } @JsonProperty @FormParam("classification") public void setClassifications(List<MCRCategoryID> classifications) { this.classifications = classifications; } public List<DerivateTitle> getTitles() { return titles; } @FormParam("title") public void setTitles(List<DerivateTitle> titles) { this.titles = titles; } } }
24,990
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCREventHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/MCREventHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.v2; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.time.Instant; import java.util.Base64; import java.util.Date; import java.util.Locale; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Function; import org.apache.logging.log4j.LogManager; import org.mycore.common.MCRException; import org.mycore.common.MCRSessionMgr; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandlerBase; 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.datamodel.niofs.MCRFileAttributes; import org.mycore.datamodel.niofs.MCRPath; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import jakarta.servlet.ServletContext; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.sse.OutboundSseEvent; import jakarta.ws.rs.sse.Sse; import jakarta.ws.rs.sse.SseBroadcaster; class MCREventHandler { private static String getName(MCREvent evt) { return evt.getObjectType() + "." + evt.getEventType(); } private static URI getPathURI(String path) { try { return new URI(null, null, path, null); } catch (URISyntaxException e) { throw new MCRException(e); } } private static String getId(MCREvent evt) { ByteBuffer byteBuffer = ByteBuffer.allocate(Long.BYTES + Integer.BYTES); byte[] bytes = byteBuffer.putLong(System.currentTimeMillis()) .putInt(evt.hashCode()) .array(); Base64.Encoder b64 = Base64.getEncoder(); return b64.encodeToString(bytes); } private static void addUserInfo(JsonObject jEvent) { if (!MCRSessionMgr.hasCurrentSession()) { return; } String userID = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID(); jEvent.addProperty("user", userID); } private static void copyServiceDateToProperty(MCRBase obj, JsonObject jsonObj, String dateType, String propertyName) { Optional.ofNullable(obj.getService().getDate(dateType)) .map(Date::toInstant) .map(Instant::toString) .ifPresent(d -> jsonObj.addProperty(propertyName, d)); } private static void copyFlagToProperty(MCRBase obj, JsonObject json, String flagName, String propertyName) { obj.getService() .getFlags(flagName) .stream() .findFirst() .ifPresent(c -> json.addProperty(propertyName, c)); } public static class MCRObjectHandler implements org.mycore.common.events.MCREventHandler { private final SseBroadcaster sseBroadcaster; private final Sse sse; private final Function<URI, URI> uriResolver; MCRObjectHandler(SseBroadcaster sseBroadcaster, Sse sse, Function<URI, URI> uriResolver) { this.sseBroadcaster = sseBroadcaster; this.sse = sse; this.uriResolver = uriResolver; } @Override public void doHandleEvent(MCREvent evt) throws MCRException { if (evt.getObjectType() != MCREvent.ObjectType.OBJECT) { return; } MCRObject obj = (MCRObject) evt.get(MCREvent.OBJECT_KEY); JsonObject jEvent = new JsonObject(); JsonObject newData = getData(obj); addUserInfo(jEvent); jEvent.add("current", newData); MCRObject oldObj = (MCRObject) evt.get(MCREvent.OBJECT_OLD_KEY); if (oldObj != null) { JsonObject oldData = getData(oldObj); jEvent.add("old", oldData); } OutboundSseEvent event = sse.newEventBuilder() .mediaType(MediaType.APPLICATION_JSON_TYPE) .id(getId(evt)) .name(getName(evt)) .data(jEvent.toString()) .build(); sseBroadcaster.broadcast(event); } private JsonObject getData(MCRObject obj) { JsonObject event = new JsonObject(); event.addProperty("id", obj.getId().toString()); event.addProperty("uri", uriResolver.apply(getPathURI("objects/" + obj.getId())).toString()); Optional.ofNullable(obj.getService().getState()) .ifPresent(s -> event.addProperty("state", s.getId())); copyFlagToProperty(obj, event, "createdby", "createdBy"); copyServiceDateToProperty(obj, event, "createdate", "created"); copyFlagToProperty(obj, event, "modifiedby", "modifiedBy"); copyServiceDateToProperty(obj, event, "modifydate", "modified"); JsonArray pi = new JsonArray(); obj.getService().getFlags("MyCoRe-PI").stream() .map(JsonParser::parseString) .forEach(pi::add); event.add("pi", pi); return event; } @Override public void undoHandleEvent(MCREvent evt) throws MCRException { //do nothing } } public static class MCRDerivateHandler implements org.mycore.common.events.MCREventHandler { private final SseBroadcaster sseBroadcaster; private final Sse sse; private final Function<URI, URI> uriResolver; MCRDerivateHandler(SseBroadcaster sseBroadcaster, Sse sse, Function<URI, URI> uriResolver) { this.sseBroadcaster = sseBroadcaster; this.sse = sse; this.uriResolver = uriResolver; } @Override public void doHandleEvent(MCREvent evt) throws MCRException { if (evt.getObjectType() != MCREvent.ObjectType.DERIVATE) { return; } MCRDerivate der = (MCRDerivate) evt.get(MCREvent.DERIVATE_KEY); JsonObject jEvent = new JsonObject(); addUserInfo(jEvent); JsonObject newData = getData(der); jEvent.add("current", newData); MCRDerivate oldDer = (MCRDerivate) evt.get(MCREvent.DERIVATE_OLD_KEY); if (oldDer != null) { JsonObject oldData = getData(oldDer); jEvent.add("old", oldData); } OutboundSseEvent event = sse.newEventBuilder() .mediaType(MediaType.APPLICATION_JSON_TYPE) .id(getId(evt)) .name(getName(evt)) .data(jEvent.toString()) .build(); sseBroadcaster.broadcast(event); } private JsonObject getData(MCRDerivate der) { JsonObject event = new JsonObject(); event.addProperty("id", der.getId().toString()); event.addProperty("uri", uriResolver.apply(getPathURI("objects/" + der.getOwnerID())) + "/derivates/" + der.getId()); event.addProperty("object", der.getOwnerID().toString()); event.addProperty("objectUri", uriResolver.apply(getPathURI("objects/" + der.getOwnerID())).toString()); copyFlagToProperty(der, event, "createdby", "createdBy"); copyServiceDateToProperty(der, event, "createdate", "created"); copyFlagToProperty(der, event, "modifiedby", "modifiedBy"); copyServiceDateToProperty(der, event, "modifydate", "modified"); return event; } @Override public void undoHandleEvent(MCREvent evt) throws MCRException { //do nothing } } public static class MCRPathHandler extends MCREventHandlerBase { private final SseBroadcaster sseBroadcaster; private final Sse sse; private final ServletContext context; private final Function<URI, URI> uriResolver; MCRPathHandler(SseBroadcaster sseBroadcaster, Sse sse, Function<URI, URI> uriResolver, ServletContext context) { this.sseBroadcaster = sseBroadcaster; this.sse = sse; this.context = context; this.uriResolver = uriResolver; } @Override public void doHandleEvent(MCREvent evt) throws MCRException { if (evt.getObjectType() != MCREvent.ObjectType.PATH) { return; } super.doHandleEvent(evt); } @Override protected void handlePathUpdated(MCREvent evt, Path path, BasicFileAttributes attrs) { sendEvent(evt, path, attrs); } @Override protected void handlePathDeleted(MCREvent evt, Path path, BasicFileAttributes attrs) { sendEvent(evt, path, attrs); } @Override protected void handlePathRepaired(MCREvent evt, Path path, BasicFileAttributes attrs) { sendEvent(evt, path, attrs); } @Override protected void updatePathIndex(MCREvent evt, Path path, BasicFileAttributes attrs) { sendEvent(evt, path, attrs); } @Override protected void handlePathCreated(MCREvent evt, Path path, BasicFileAttributes attrs) { sendEvent(evt, path, attrs); } public void sendEvent(MCREvent evt, Path path, BasicFileAttributes attrs) { if (!(path instanceof MCRPath) || !(attrs instanceof MCRFileAttributes)) { LogManager.getLogger().warn("Cannot handle {} {}", path.getClass(), attrs.getClass()); return; } JsonObject file = new JsonObject(); addUserInfo(file); String derId = ((MCRPath) path).getOwner(); String fPath = ((MCRPath) path).getOwnerRelativePath(); String objId = MCRMetadataManager.getObjectId(MCRObjectID.getInstance(derId), 1, TimeUnit.MINUTES) .toString(); String relPath = String.format(Locale.ROOT, "objects/%s/derivates/%s/contents/%s", objId, derId, fPath); String uri = uriResolver.apply(getPathURI(relPath)).toString(); file.addProperty("uri", uri); file.addProperty("derivate", derId); file.addProperty("object", objId); file.addProperty("size", attrs.size()); file.addProperty("modified", attrs.lastModifiedTime().toInstant().toString()); file.addProperty("md5", ((MCRFileAttributes) attrs).md5sum()); file.addProperty("mimeType", context.getMimeType(path.getFileName().toString())); OutboundSseEvent event = sse.newEventBuilder() .mediaType(MediaType.APPLICATION_JSON_TYPE) .id(getId(evt)) .name(getName(evt)) .data(file.toString()) .build(); sseBroadcaster.broadcast(event); } @Override public void undoHandleEvent(MCREvent evt) throws MCRException { //do nothing } } }
11,913
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRestCheckAPIAccessResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/MCRRestCheckAPIAccessResolver.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.v2; import javax.xml.transform.Source; import javax.xml.transform.URIResolver; import org.jdom2.Element; import org.jdom2.transform.JDOMSource; import org.mycore.access.MCRAccessInterface; import org.mycore.access.MCRAccessManager; import org.mycore.restapi.v2.access.MCRRestAPIACLPermission; import org.mycore.restapi.v2.access.MCRRestAccessManager; public class MCRRestCheckAPIAccessResolver implements URIResolver { /** * Checks permission for a given rest api path. * * Syntax: <code>checkRestAPIAccess:{path}:{permission}</code> * * @param href * URI in the syntax above * @param base * not used * * @return the root element "boolean" of the XML document with content string "true" or "false" * @see javax.xml.transform.URIResolver */ @Override public Source resolve(final String href, final String base) throws IllegalArgumentException { final String[] hrefParts = href.split(":"); if (hrefParts.length == 3) { final String permission = hrefParts[2]; final MCRRestAPIACLPermission apiPermission = MCRRestAPIACLPermission.resolve(permission); if (apiPermission == null) { throw new IllegalArgumentException("Unknown permission: " + permission); } final MCRAccessInterface acl = MCRAccessManager.getAccessImpl(); final boolean isPermitted = MCRRestAccessManager.checkRestAPIAccess(acl, apiPermission, hrefParts[1]); final Element resultElement = new Element("boolean"); resultElement.setText(Boolean.toString(isPermitted)); return new JDOMSource(resultElement); } throw new IllegalArgumentException("Invalid format of uri for retrieval of checkRestAPIAccess: " + href); } }
2,592
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRestUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/MCRRestUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.v2; import java.util.Date; import java.util.Optional; import jakarta.ws.rs.core.EntityTag; import jakarta.ws.rs.core.Request; import jakarta.ws.rs.core.Response; public final class MCRRestUtils { public static final String JSON_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; public static final String TAG_MYCORE_CLASSIFICATION = "mcr_class"; public static final String TAG_MYCORE_OBJECT = "mcr_object"; public static final String TAG_MYCORE_DERIVATE = "mcr_derivate"; public static final String TAG_MYCORE_FILE = "mcr_file"; public static final String TAG_MYCORE_ABOUT = "mcr_about"; public static final String TAG_MYCORE_EVENTS = "mcr_events"; private MCRRestUtils() { } public static Optional<Response> getCachedResponse(Request request, Date lastModified) { return Optional.ofNullable(request) .map(r -> r.evaluatePreconditions(lastModified)) .map(Response.ResponseBuilder::build); } public static Optional<Response> getCachedResponse(Request request, Date lastModified, EntityTag eTag) { return Optional.ofNullable(request) .map(r -> r.evaluatePreconditions(lastModified, eTag)) .map(Response.ResponseBuilder::build); } }
2,005
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRestV2App.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/MCRRestV2App.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.v2; import java.net.URI; import java.util.stream.Collectors; import java.util.stream.Stream; import org.mycore.common.MCRCoreVersion; import org.mycore.common.config.MCRConfiguration2; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.restapi.MCRApiDraftFilter; import org.mycore.restapi.MCRContentNegotiationViaExtensionFilter; import org.mycore.restapi.MCRDropSessionFilter; import org.mycore.restapi.MCRJerseyRestApp; import org.mycore.restapi.MCRNoFormDataPutFilter; import org.mycore.restapi.MCRNormalizeMCRObjectIDsFilter; import org.mycore.restapi.MCRRemoveMsgBodyFilter; import org.mycore.restapi.converter.MCRWrappedXMLWriter; import org.mycore.restapi.v1.MCRRestAPIAuthentication; import com.fasterxml.jackson.jakarta.rs.json.JacksonXmlBindJsonProvider; import io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder; import io.swagger.v3.jaxrs2.integration.resources.OpenApiResource; import io.swagger.v3.oas.integration.OpenApiConfigurationException; import io.swagger.v3.oas.integration.SwaggerConfiguration; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; import io.swagger.v3.oas.models.servers.Server; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.InternalServerErrorException; @ApplicationPath("/api/v2") public class MCRRestV2App extends MCRJerseyRestApp { public MCRRestV2App() { super(); register(MCRContentNegotiationViaExtensionFilter.class); register(MCRNormalizeMCRObjectIDsFilter.class); register(MCRRestAPIAuthentication.class); // keep 'unchanged' in v2 register(MCRRemoveMsgBodyFilter.class); register(MCRNoFormDataPutFilter.class); register(MCRDropSessionFilter.class); register(MCRExceptionMapper.class); register(MCRApiDraftFilter.class); //after removing the following line, test if json output from MCRRestClassification is still OK register(JacksonXmlBindJsonProvider.class); //jetty >= 2.31, do not use DefaultJacksonJaxbJsonProvider setupOAS(); } @Override protected String getVersion() { return "v2"; } @Override protected String[] getRestPackages() { return Stream .concat( Stream.of(MCRWrappedXMLWriter.class.getPackage().getName(), OpenApiResource.class.getPackage().getName()), MCRConfiguration2.getOrThrow("MCR.RestAPI.V2.Resource.Packages", MCRConfiguration2::splitValue)) .toArray(String[]::new); } private void setupOAS() { OpenAPI oas = new OpenAPI(); Info oasInfo = new Info(); oas.setInfo(oasInfo); oasInfo.setVersion(MCRCoreVersion.getVersion()); oasInfo.setTitle(getApplicationName()); License oasLicense = new License(); oasLicense.setName("GNU General Public License, version 3"); oasLicense.setUrl("http://www.gnu.org/licenses/gpl-3.0.txt"); oasInfo.setLicense(oasLicense); URI baseURI = URI.create(MCRFrontendUtil.getBaseURL()); Server oasServer = new Server(); oasServer.setUrl(baseURI.resolve("api").toString()); oas.addServersItem(oasServer); SwaggerConfiguration oasConfig = new SwaggerConfiguration() .openAPI(oas) .resourcePackages(Stream.of(getRestPackages()).collect(Collectors.toSet())) .ignoredRoutes( MCRConfiguration2.getString("MCR.RestAPI.V2.OpenAPI.IgnoredRoutes") .map(MCRConfiguration2::splitValue) .orElseGet(Stream::empty) .collect(Collectors.toSet())) .prettyPrint(true); try { new JaxrsOpenApiContextBuilder() .application(getApplication()) .openApiConfiguration(oasConfig) .buildContext(true); } catch (OpenApiConfigurationException e) { throw new InternalServerErrorException(e); } } }
4,797
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRInfo.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/MCRInfo.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.v2; import java.time.Instant; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.mycore.common.MCRCoreVersion; import org.mycore.restapi.converter.MCRInstantXMLAdapter; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.OpenAPIDefinition; 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 io.swagger.v3.oas.annotations.tags.Tag; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Request; import jakarta.ws.rs.core.Response; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElementWrapper; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlValue; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; @Path("/mycore") @OpenAPIDefinition( tags = @Tag(name = MCRRestUtils.TAG_MYCORE_ABOUT, description = "informations about this repository")) public class MCRInfo { private static final Date INIT_TIME = new Date(); @Context Request request; @GET @Path("version") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Operation(description = "get MyCoRe version information", responses = { @ApiResponse( description = "Information about the MyCoRe version", content = @Content(schema = @Schema(implementation = GitInfo.class))) }, tags = MCRRestUtils.TAG_MYCORE_ABOUT) public Response getVersion() { Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request, INIT_TIME); return cachedResponse.orElseGet( () -> Response.ok(new GitInfo(MCRCoreVersion.getVersionProperties())).lastModified(INIT_TIME).build()); } @XmlRootElement @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY) static class GitInfo { private String branch; private BuildInfo build; private GitClosestTag closestTag; private GitCommitInfo commit; private boolean dirty; private Map<String, String> remoteURL; private Set<String> tags; private GitInfo() { //JAXB; } GitInfo(Map<String, String> props) { branch = props.get("git.branch"); build = new BuildInfo(props); closestTag = new GitClosestTag(props); commit = new GitCommitInfo(props); dirty = Boolean.parseBoolean(props.get("git.dirty")); remoteURL = new LinkedHashMap<>(); props.entrySet() .stream() .filter(e -> e.getKey().startsWith("git.remote.")) .filter(e -> e.getKey().endsWith(".url")) .forEach(e -> { String name = e.getKey().split("\\.")[2]; remoteURL.put(name, e.getValue()); }); tags = Stream.of(props.get("git.tags").split(",")).collect(Collectors.toSet()); } @XmlElement public BuildInfo getBuild() { return build; } @JsonProperty(required = true) @XmlElement public GitClosestTag getClosestTag() { return closestTag; } @XmlElement public GitCommitInfo getCommit() { return commit; } @JsonProperty(required = true) @XmlAttribute public boolean isDirty() { return dirty; } @JsonProperty(required = true) @XmlElement public Map<String, String> getRemoteURL() { return remoteURL; } @XmlElementWrapper(name = "tags") @XmlElement(name = "tag") public Set<String> getTags() { return tags; } @JsonProperty(required = true) @XmlAttribute public String getBranch() { return branch; } } @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY) public static class BuildInfo { private Instant time; private User user; private String host; private String version; private BuildInfo() { //JAXB } BuildInfo(Map<String, String> props) { time = Instant.parse(props.get("git.build.time")); user = new User(props.get("git.build.user.name"), props.get("git.build.user.email")); host = props.get("git.build.host"); version = props.get("git.build.version"); } @XmlAttribute @XmlJavaTypeAdapter(MCRInstantXMLAdapter.class) public Instant getTime() { return time; } @XmlElement public User getUser() { return user; } @XmlAttribute public String getHost() { return host; } @XmlAttribute public String getVersion() { return version; } } @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY) public static class GitCommitInfo { private GitId id; private GitCommitMessage message; private Instant time; private User user; private GitCommitInfo() { //JAXB } GitCommitInfo(Map<String, String> props) { id = new GitId(props); message = new GitCommitMessage(props.get("git.commit.message.full"), props.get("git.commit.message.short")); time = Instant.parse(props.get("git.commit.time")); user = new User(props.get("git.commit.user.name"), props.get("git.commit.user.email")); } @JsonProperty(required = true) @XmlElement public GitId getId() { return id; } @JsonProperty(required = true) @XmlElement public GitCommitMessage getMessage() { return message; } @JsonProperty(required = true) @XmlAttribute @XmlJavaTypeAdapter(MCRInstantXMLAdapter.class) public Instant getTime() { return time; } @XmlElement public User getUser() { return user; } } @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY) public static class GitClosestTag { private int commitCount; private String name; private GitClosestTag() { //JAXB } GitClosestTag(Map<String, String> props) { name = props.get("git.closest.tag.name"); commitCount = Integer.parseInt(props.get("git.closest.tag.commit.count")); } @JsonProperty(required = true) @XmlAttribute public int getCommitCount() { return commitCount; } @JsonProperty(required = true) @XmlAttribute public String getName() { return name; } } @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY) public static class GitId { String abbrev; String describeShort; String describe; String full; private GitId() { //JAXB } private GitId(Map<String, String> props) { abbrev = props.get("git.commit.id.abbrev"); describeShort = props.get("git.commit.id.describe-short"); describe = props.get("git.commit.id.describe"); full = props.get("git.commit.id.full"); } @JsonProperty(required = true) @XmlAttribute public String getAbbrev() { return abbrev; } @JsonProperty(value = "describe-short", required = true) @XmlAttribute public String getDescribeShort() { return describeShort; } @JsonProperty(required = true) @XmlAttribute public String getDescribe() { return describe; } @JsonProperty(required = true) @XmlAttribute public String getFull() { return full; } } @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY) public static class GitCommitMessage { private String full; private String shortMsg; private GitCommitMessage() { //JAXB } GitCommitMessage(String full, String shortMsg) { this.full = full; this.shortMsg = shortMsg; } @XmlValue public String getFull() { return full; } @XmlAttribute public String getShort() { return shortMsg; } } @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY) public static class User { private String name; private String email; private User() { //JAXB } User(String name, String email) { this.name = name; this.email = email; } @JsonProperty(required = true) @XmlAttribute public String getName() { return name; } @XmlAttribute public String getEmail() { return email; } } }
10,517
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRErrorCodeConstants.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/MCRErrorCodeConstants.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.v2; final class MCRErrorCodeConstants { public static final String API_NO_PERMISSION = "API_NO_PERMISSION"; //Classification public static final String MCRCLASS_NOT_FOUND = "MCRCLASS_NOT_FOUND"; public static final String MCRCLASS_ID_MISMATCH = "MCRCLASS_ID_MISMATCH"; public static final String MCRCLASS_SERIALIZATION_ERROR = "MCRCLASS_SERIALIZATION_ERROR"; //MCRObject public static final String MCROBJECT_NO_PERMISSION = "MCROBJECT_NO_PERMISSION"; public static final String MCROBJECT_NOT_FOUND = "MCROBJECT_NOT_FOUND"; public static final String MCROBJECT_REVISION_NOT_FOUND = "MCROBJECT_REVISION_NOT_FOUND"; public static final String MCROBJECT_INVALID = "MCROBJECT_INVALID"; public static final String MCROBJECT_ID_MISMATCH = "MCROBJECT_ID_MISMATCH"; public static final String MCROBJECT_STILL_LINKED = "MCROBJECT_STILL_LINKED"; public static final String MCROBJECT_INVALID_STATE = "MCROBJECT_INVALID_STATE"; //MCRDerivate public static final String MCRDERIVATE_NO_PERMISSION = "MCRDERIVATE_NO_PERMISSION"; public static final String MCRDERIVATE_NOT_FOUND = "MCRDERIVATE_NOT_FOUND"; public static final String MCRDERIVATE_NOT_FOUND_IN_OBJECT = "MCRDERIVATE_NOT_FOUND_IN_OBJECT"; public static final String MCRDERIVATE_INVALID = "MCRDERIVATE_INVALID"; public static final String MCRDERIVATE_ID_MISMATCH = "MCRDERIVATE_ID_MISMATCH"; //Derivate Content public static final String MCRDERIVATE_CREATE_DIRECTORY_ON_FILE = "MCRDERIVATE_CREATE_DIRECTORY_ON_FILE"; public static final String MCRDERIVATE_CREATE_DIRECTORY = "MCRDERIVATE_CREATE_DIRECTORY"; public static final String MCRDERIVATE_UPDATE_FILE = "MCRDERIVATE_UPDATE_FILE"; public static final String MCRDERIVATE_FILE_NOT_FOUND = "MCRDERIVATE_FILE_NOT_FOUND"; public static final String MCRDERIVATE_FILE_IO_ERROR = "MCRDERIVATE_FILE_IO_ERROR"; public static final String MCRDERIVATE_NOT_DIRECTORY = "MCRDERIVATE_NOT_DIRECTORY"; public static final String MCRDERIVATE_FILE_SIZE = "MCRDERIVATE_FILE_SIZE"; public static final String MCRDERIVATE_DIRECTORY_NOT_EMPTY = "MCRDERIVATE_DIRECTORY_NOT_EMPTY"; public static final String MCRDERIVATE_FILE_DELETE = "MCRDERIVATE_FILE_DELETE"; public static final String MCRDERIVATE_NOT_FILE = "MCRDERIVATE_NOT_FILE"; private MCRErrorCodeConstants() { } }
3,160
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRestObjects.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/MCRRestObjects.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.v2; import static org.mycore.common.MCRConstants.XSI_NAMESPACE; import static org.mycore.restapi.v2.MCRRestAuthorizationFilter.PARAM_MCRID; import java.awt.image.BufferedImage; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.lang.annotation.Annotation; import java.net.URI; import java.nio.file.Files; import java.nio.file.attribute.FileTime; 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.function.Predicate; import java.util.stream.Collectors; import org.apache.commons.lang3.reflect.TypeUtils; 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.mycore.access.MCRAccessException; import org.mycore.access.MCRAccessManager; import org.mycore.common.MCRCoreVersion; import org.mycore.common.MCRException; import org.mycore.common.MCRPersistenceException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.content.MCRStreamContent; import org.mycore.common.content.MCRStringContent; import org.mycore.common.xml.MCRXMLParserFactory; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.common.MCRAbstractMetadataVersion; import org.mycore.datamodel.common.MCRActiveLinkException; import org.mycore.datamodel.common.MCRObjectIDDate; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.datamodel.objectinfo.MCRObjectQuery; import org.mycore.datamodel.objectinfo.MCRObjectQueryResolver; import org.mycore.frontend.jersey.MCRCacheControl; import org.mycore.media.services.MCRThumbnailGenerator; import org.mycore.restapi.annotations.MCRAccessControlExposeHeaders; import org.mycore.restapi.annotations.MCRApiDraft; import org.mycore.restapi.annotations.MCRParam; import org.mycore.restapi.annotations.MCRParams; import org.mycore.restapi.annotations.MCRRequireTransaction; import org.mycore.restapi.converter.MCRContentAbstractWriter; import org.mycore.restapi.v2.access.MCRRestAPIACLPermission; import org.mycore.restapi.v2.annotation.MCRRestRequiredPermission; import org.mycore.restapi.v2.model.MCRRestObjectIDDate; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.jakarta.rs.annotation.JacksonFeatures; import io.swagger.v3.oas.annotations.OpenAPIDefinition; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; 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.ExampleObject; 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.servlet.ServletContext; import jakarta.ws.rs.BadRequestException; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.DefaultValue; import jakarta.ws.rs.ForbiddenException; import jakarta.ws.rs.GET; import jakarta.ws.rs.InternalServerErrorException; import jakarta.ws.rs.NotFoundException; 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.GenericEntity; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Request; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriBuilder; import jakarta.ws.rs.core.UriInfo; import jakarta.xml.bind.annotation.XmlElementWrapper; @Path("/objects") @OpenAPIDefinition(tags = { @Tag(name = MCRRestUtils.TAG_MYCORE_OBJECT, description = "Operations on metadata objects"), @Tag(name = MCRRestUtils.TAG_MYCORE_DERIVATE, description = "Operations on derivates belonging to metadata objects"), @Tag(name = MCRRestUtils.TAG_MYCORE_FILE, description = "Operations on files in derivates"), }) public class MCRRestObjects { public static final String PARAM_AFTER_ID = "after_id"; public static final String PARAM_OFFSET = "offset"; public static final String PARAM_LIMIT = "limit"; public static final String PARAM_TYPE = "type"; public static final String PARAM_PROJECT = "project"; public static final String PARAM_NUMBER_GREATER = "number_greater"; public static final String PARAM_NUMBER_LESS = "number_less"; public static final String PARAM_CREATED_AFTER = "created_after"; public static final String PARAM_CREATED_BEFORE = "created_before"; public static final String PARAM_MODIFIED_AFTER = "modified_after"; public static final String PARAM_MODIFIED_BEFORE = "modified_before"; public static final String PARAM_DELETED_AFTER = "deleted_after"; public static final String PARAM_DELETED_BEFORE = "deleted_before"; public static final String PARAM_CREATED_BY = "created_by"; public static final String PARAM_MODIFIED_BY = "modified_by"; public static final String PARAM_DELETED_BY = "deleted_by"; public static final String PARAM_SORT_ORDER = "sort_order"; public static final String PARAM_SORT_BY = "sort_by"; public static final String HEADER_X_TOTAL_COUNT = "X-Total-Count"; public static final List<MCRThumbnailGenerator> THUMBNAIL_GENERATORS = Collections .unmodifiableList(MCRConfiguration2 .getOrThrow("MCR.Media.Thumbnail.Generators", MCRConfiguration2::splitValue) .map(MCRConfiguration2::instantiateClass) .map(MCRThumbnailGenerator.class::cast) .collect(Collectors.toList())); private static final String PARAM_CATEGORIES = "category"; private static final Logger LOGGER = LogManager.getLogger(); private static final int PAGE_SIZE_MAX = MCRConfiguration2.getInt("MCR.RestAPI.V2.ListObjects.PageSize.Max") .orElseThrow(); private static final int PAGE_SIZE_DEFAULT = MCRConfiguration2 .getInt("MCR.RestAPI.V2.ListObjects.PageSize.Default") .orElse(1000); @Context Request request; @Context ServletContext context; @Context UriInfo uriInfo; @GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON + ";charset=UTF-8" }) @MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.HOURS), sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.HOURS)) @Operation( summary = "Lists all objects in this repository", parameters = { @Parameter( name = PARAM_AFTER_ID, description = "the id after which the results should be listed. Do not use after_id and offset " + "together."), @Parameter( name = PARAM_OFFSET, description = "dictates the number of rows to skip from the beginning of the returned data before " + "presenting the results. Do not use after_id and offset together."), @Parameter( name = PARAM_LIMIT, description = "limits the number of result returned"), @Parameter( name = PARAM_TYPE, description = "objects with have the type in the id"), @Parameter( name = PARAM_PROJECT, description = "only objects that have the project in the id"), @Parameter( name = PARAM_NUMBER_GREATER, description = "only objects which id have a number greater than this"), @Parameter( name = PARAM_NUMBER_LESS, description = "only objects which id have a number less than this"), @Parameter( name = PARAM_CREATED_AFTER, description = "objects created after this date"), @Parameter( name = PARAM_CREATED_BEFORE, description = "objects created before this date"), @Parameter( name = PARAM_MODIFIED_AFTER, description = "objects last modified after this date"), @Parameter( name = PARAM_MODIFIED_BEFORE, description = "objects last modified before this date"), @Parameter( name = PARAM_MODIFIED_AFTER, description = "objects last modified after this date"), @Parameter( name = PARAM_MODIFIED_BEFORE, description = "objects last modified before this date"), @Parameter( name = PARAM_SORT_ORDER, description = "sort results 'asc' or 'desc'"), @Parameter( name = PARAM_SORT_BY, description = "sort objects by 'id', 'created' (default) or 'modified'") }, responses = @ApiResponse( description = "List of all or matched metadata object IDs with time of last modification", content = @Content(array = @ArraySchema(schema = @Schema(implementation = MCRObjectIDDate.class)))), tags = MCRRestUtils.TAG_MYCORE_OBJECT) @XmlElementWrapper(name = "mycoreobjects") @JacksonFeatures(serializationDisable = { SerializationFeature.WRITE_DATES_AS_TIMESTAMPS }) @MCRAccessControlExposeHeaders({ HEADER_X_TOTAL_COUNT, HttpHeaders.LINK }) public Response listObjects( @QueryParam(PARAM_AFTER_ID) MCRObjectID afterID, @QueryParam(PARAM_OFFSET) Integer offset, @QueryParam(PARAM_LIMIT) Integer limit, @QueryParam(PARAM_TYPE) String type, @QueryParam(PARAM_PROJECT) String project, @QueryParam(PARAM_NUMBER_GREATER) Integer numberGreater, @QueryParam(PARAM_NUMBER_LESS) Integer numberLess, @QueryParam(PARAM_CREATED_AFTER) Date createdAfter, @QueryParam(PARAM_CREATED_BEFORE) Date createdBefore, @QueryParam(PARAM_MODIFIED_AFTER) Date modifiedAfter, @QueryParam(PARAM_MODIFIED_BEFORE) Date modifiedBefore, @QueryParam(PARAM_DELETED_AFTER) Date deletedAfter, @QueryParam(PARAM_DELETED_BEFORE) Date deletedBefore, @QueryParam(PARAM_CREATED_BY) String createdBy, @QueryParam(PARAM_MODIFIED_BY) String modifiedBy, @QueryParam(PARAM_DELETED_BY) String deletedBy, @QueryParam(PARAM_SORT_BY) @DefaultValue("id") MCRObjectQuery.SortBy sortBy, @QueryParam(PARAM_SORT_ORDER) @DefaultValue("asc") MCRObjectQuery.SortOrder sortOrder, @QueryParam(PARAM_CATEGORIES) List<String> categories) { MCRObjectQuery query = new MCRObjectQuery(); int limitInt = Optional.ofNullable(limit) .map(l -> Integer.min(l, PAGE_SIZE_MAX)) .orElse(PAGE_SIZE_DEFAULT); query.limit(limitInt); Optional.ofNullable(offset).ifPresent(query::offset); Optional.ofNullable(afterID).ifPresent(query::afterId); Optional.ofNullable(type).ifPresent(query::type); Optional.ofNullable(project).ifPresent(query::project); Optional.ofNullable(modifiedAfter).map(Date::toInstant).ifPresent(query::modifiedAfter); Optional.ofNullable(modifiedBefore).map(Date::toInstant).ifPresent(query::modifiedBefore); Optional.ofNullable(createdAfter).map(Date::toInstant).ifPresent(query::createdAfter); Optional.ofNullable(createdBefore).map(Date::toInstant).ifPresent(query::createdBefore); Optional.ofNullable(deletedAfter).map(Date::toInstant).ifPresent(query::deletedAfter); Optional.ofNullable(deletedBefore).map(Date::toInstant).ifPresent(query::deletedBefore); Optional.ofNullable(createdBy).ifPresent(query::createdBy); Optional.ofNullable(modifiedBy).ifPresent(query::modifiedBy); Optional.ofNullable(deletedBy).ifPresent(query::deletedBy); Optional.ofNullable(numberGreater).ifPresent(query::numberGreater); Optional.ofNullable(numberLess).ifPresent(query::numberLess); List<String> includeCategories = query.getIncludeCategories(); categories.stream() .filter(Predicate.not(String::isBlank)) .forEach(includeCategories::add); query.sort(sortBy, sortOrder); MCRObjectQueryResolver queryResolver = MCRObjectQueryResolver.getInstance(); List<MCRObjectIDDate> idDates = limitInt == 0 ? Collections.emptyList() : queryResolver.getIdDates(query); List<MCRRestObjectIDDate> restIdDate = idDates.stream().map(MCRRestObjectIDDate::new) .collect(Collectors.toList()); int count = queryResolver.count(query); UriBuilder nextBuilder = null; if (query.afterId() != null && idDates.size() == limitInt) { nextBuilder = uriInfo.getRequestUriBuilder(); nextBuilder.replaceQueryParam(PARAM_AFTER_ID, idDates.get(idDates.size() - 1).getId()); } else { if (query.offset() + query.limit() < count) { nextBuilder = uriInfo.getRequestUriBuilder(); nextBuilder.replaceQueryParam(PARAM_OFFSET, String.valueOf(query.offset() + limitInt)); } } Response.ResponseBuilder responseBuilder = Response.ok(new GenericEntity<>(restIdDate) { }) .header(HEADER_X_TOTAL_COUNT, count); if (nextBuilder != null) { responseBuilder.link("next", nextBuilder.toString()); } return responseBuilder.build(); } @POST @Operation( summary = "Create a new MyCoRe Object", responses = @ApiResponse(responseCode = "201", description = "Metadata object successfully created", headers = @Header(name = HttpHeaders.LOCATION, schema = @Schema(type = "string", format = "uri"), description = "URL of the new MyCoRe Object")), tags = MCRRestUtils.TAG_MYCORE_OBJECT) @Consumes(MediaType.APPLICATION_XML) @RequestBody(required = true, content = @Content(mediaType = MediaType.APPLICATION_XML)) @MCRRequireTransaction @MCRAccessControlExposeHeaders(HttpHeaders.LOCATION) public Response createObject(String xml) { try { Document doc = MCRXMLParserFactory.getNonValidatingParser().parseXML(new MCRStringContent(xml)); Element eMCRObj = doc.getRootElement(); if (eMCRObj.getAttributeValue("ID") != null) { MCRObjectID id = MCRObjectID.getInstance(eMCRObj.getAttributeValue("ID")); MCRObjectID zeroId = MCRObjectID.getInstance(MCRObjectID.formatID(id.getBase(), 0)); eMCRObj.setAttribute("ID", zeroId.toString()); if (eMCRObj.getAttribute("label") == null) { eMCRObj.setAttribute("label", zeroId.toString()); } if (eMCRObj.getAttribute("version") == null) { eMCRObj.setAttribute("version", MCRCoreVersion.getVersion()); } eMCRObj.setAttribute("noNamespaceSchemaLocation", "datamodel-" + zeroId.getTypeId() + ".xsd", XSI_NAMESPACE); } else { //TODO error handling throw new BadRequestException("Please provide an object with ID"); } MCRObject mcrObj = new MCRObject(new MCRJDOMContent(doc).asByteArray(), true); LOGGER.debug("Create new MyCoRe Object"); MCRMetadataManager.create(mcrObj); return Response.created(uriInfo.getAbsolutePathBuilder().path(mcrObj.getId().toString()).build()).build(); } catch (MCRPersistenceException | JDOMException | IOException e) { throw new InternalServerErrorException(e); } catch (MCRAccessException e) { throw new ForbiddenException(e); } } @GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON + ";charset=UTF-8" }) @MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS), sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS)) @Path("/{" + PARAM_MCRID + "}") @Operation( summary = "Returns MCRObject with the given " + PARAM_MCRID + ".", tags = MCRRestUtils.TAG_MYCORE_OBJECT) public Response getObject(@Parameter(example = "mir_mods_00004711") @PathParam(PARAM_MCRID) MCRObjectID id) throws IOException { long modified; try { modified = MCRXMLMetadataManager.instance().getLastModified(id); } catch (IOException io) { throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_NOT_FOUND) .withMessage("MCRObject " + id + " not found") .toException(); } Date lastModified = new Date(modified); Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request, lastModified); if (cachedResponse.isPresent()) { return cachedResponse.get(); } MCRContent mcrContent = MCRXMLMetadataManager.instance().retrieveContent(id); return Response.ok() .entity(mcrContent, new Annotation[] { MCRParams.Factory .get(MCRParam.Factory.get(MCRContentAbstractWriter.PARAM_OBJECTTYPE, id.getTypeId())) }) .lastModified(lastModified) .build(); } @GET @Produces({ MediaType.APPLICATION_XML }) @MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS), sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS)) @Path("/{" + PARAM_MCRID + "}/metadata") @Operation( summary = "Returns metadata section MCRObject with the given " + PARAM_MCRID + ".", tags = MCRRestUtils.TAG_MYCORE_OBJECT) public Response getObjectMetadata(@Parameter(example = "mir_mods_00004711") @PathParam(PARAM_MCRID) MCRObjectID id) throws IOException { long modified = MCRXMLMetadataManager.instance().getLastModified(id); if (modified < 0) { throw new NotFoundException("MCRObject " + id + " not found"); } Date lastModified = new Date(modified); Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request, lastModified); if (cachedResponse.isPresent()) { return cachedResponse.get(); } MCRObject mcrObj = MCRMetadataManager.retrieveMCRObject(id); MCRContent mcrContent = new MCRJDOMContent(mcrObj.getMetadata().createXML()); return Response.ok() .entity(mcrContent, new Annotation[] { MCRParams.Factory .get(MCRParam.Factory.get(MCRContentAbstractWriter.PARAM_OBJECTTYPE, id.getTypeId())) }) .lastModified(lastModified) .build(); } @GET @Path("{" + PARAM_MCRID + "}/thumb-{size}.{ext : (jpg|jpeg|png)}") @Produces({ "image/png", "image/jpeg" }) @Operation( summary = "Returns thumbnail of MCRObject with the given " + PARAM_MCRID + ".", tags = MCRRestUtils.TAG_MYCORE_OBJECT) @MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS), sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS)) public Response getThumbnailWithSize(@PathParam(PARAM_MCRID) String id, @PathParam("size") int size, @PathParam("ext") String ext) { return getThumbnail(id, size, ext); } @GET @Path("{" + PARAM_MCRID + "}/thumb.{ext : (jpg|jpeg|png)}") @Produces({ "image/png", "image/jpeg" }) @Operation( summary = "Returns thumbnail of MCRObject with the given " + PARAM_MCRID + ".", tags = MCRRestUtils.TAG_MYCORE_OBJECT) @MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS), sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS)) public Response getThumbnail(@PathParam(PARAM_MCRID) String id, @PathParam("ext") String ext) { int defaultSize = MCRConfiguration2.getOrThrow("MCR.Media.Thumbnail.DefaultSize", Integer::parseInt); return getThumbnail(id, defaultSize, ext); } private Response getThumbnail(String id, int size, String ext) { List<MCRPath> mainDocs = MCRMetadataManager.getDerivateIds(MCRObjectID.getInstance(id), 1, TimeUnit.MINUTES) .stream() .filter(d -> MCRAccessManager.checkDerivateContentPermission(d, MCRAccessManager.PERMISSION_READ)) .map(d -> { String nameOfMainFile = MCRMetadataManager.retrieveMCRDerivate(d).getDerivate().getInternals() .getMainDoc(); return nameOfMainFile.isEmpty() ? null : MCRPath.getPath(d.toString(), '/' + nameOfMainFile); }) .filter(Objects::nonNull) .collect(Collectors.toList()); if (mainDocs.isEmpty()) { throw new NotFoundException(); } for (MCRPath mainDoc : mainDocs) { Optional<MCRThumbnailGenerator> thumbnailGenerator = THUMBNAIL_GENERATORS.stream() .filter(g -> g.matchesFileType(context.getMimeType(mainDoc.getFileName().toString()), mainDoc)) .findFirst(); if (thumbnailGenerator.isPresent()) { try { FileTime lastModified = Files.getLastModifiedTime(mainDoc); Date lastModifiedDate = new Date(lastModified.toMillis()); Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request, lastModifiedDate); return cachedResponse.orElseGet(() -> { Optional<BufferedImage> thumbnail; try { thumbnail = thumbnailGenerator.get().getThumbnail(mainDoc, size); } catch (IOException e) { throw new UncheckedIOException(e); } return thumbnail.map(b -> { String type = "image/png"; if (Objects.equals(ext, "jpg") || Objects.equals(ext, "jpeg")) { type = "image/jpeg"; } return Response.ok(b) .lastModified(lastModifiedDate) .type(type) .build(); }).orElseGet(() -> Response.status(Response.Status.NOT_FOUND).build()); }); } catch (FileNotFoundException e) { continue; //try another mainDoc if present } catch (IOException e) { throw new InternalServerErrorException(e); } catch (UncheckedIOException e) { throw new InternalServerErrorException(e.getCause()); } } } throw new NotFoundException(); } @GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON + ";charset=UTF-8" }) @MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS), sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS)) @Path("/{" + PARAM_MCRID + "}/versions") @Operation( summary = "Returns MCRObject with the given " + PARAM_MCRID + ".", responses = @ApiResponse( description = "List of available versions for this metadata object", content = @Content( array = @ArraySchema(uniqueItems = true, schema = @Schema(implementation = MCRAbstractMetadataVersion.class)))), tags = MCRRestUtils.TAG_MYCORE_OBJECT) @JacksonFeatures(serializationDisable = { SerializationFeature.WRITE_DATES_AS_TIMESTAMPS }) @XmlElementWrapper(name = "versions") @MCRRestRequiredPermission(MCRRestAPIACLPermission.HISTORY_VIEW) public Response getObjectVersions(@Parameter(example = "mir_mods_00004711") @PathParam(PARAM_MCRID) MCRObjectID id) throws IOException { long modified = MCRXMLMetadataManager.instance().getLastModified(id); if (modified < 0) { throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_NOT_FOUND) .withMessage("MCRObject " + id + " not found") .toException(); } Date lastModified = new Date(modified); Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request, lastModified); if (cachedResponse.isPresent()) { return cachedResponse.get(); } List<? extends MCRAbstractMetadataVersion<?>> versions = MCRXMLMetadataManager.instance().listRevisions(id); return Response.ok() .entity(new GenericEntity<>(versions, TypeUtils.parameterize(List.class, MCRAbstractMetadataVersion.class))) .lastModified(lastModified) .build(); } @GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON + ";charset=UTF-8" }) @MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1000, unit = TimeUnit.DAYS), sMaxAge = @MCRCacheControl.Age(time = 1000, unit = TimeUnit.DAYS)) //will never expire actually @Path("/{" + PARAM_MCRID + "}/versions/{revision}") @Operation( summary = "Returns MCRObject with the given " + PARAM_MCRID + " and revision.", tags = MCRRestUtils.TAG_MYCORE_OBJECT) @MCRRestRequiredPermission(MCRRestAPIACLPermission.HISTORY_READ) public Response getObjectVersion(@Parameter(example = "mir_mods_00004711") @PathParam(PARAM_MCRID) MCRObjectID id, @PathParam("revision") String revision) throws IOException { MCRContent mcrContent = MCRXMLMetadataManager.instance().retrieveContent(id, revision); if (mcrContent == null) { throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_REVISION_NOT_FOUND) .withMessage("MCRObject " + id + " has no revision " + revision + ".") .toException(); } long modified = mcrContent.lastModified(); Date lastModified = new Date(modified); Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request, lastModified); if (cachedResponse.isPresent()) { return cachedResponse.get(); } LogManager.getLogger().info("OK: {}", mcrContent.getETag()); return Response.ok() .entity(mcrContent, new Annotation[] { MCRParams.Factory .get(MCRParam.Factory.get(MCRContentAbstractWriter.PARAM_OBJECTTYPE, id.getTypeId())) }) .lastModified(lastModified) .build(); } @PUT @Consumes(MediaType.APPLICATION_XML) @Path("/{" + PARAM_MCRID + "}") @Operation(summary = "Creates or updates MCRObject with the body of this request", tags = MCRRestUtils.TAG_MYCORE_OBJECT, responses = { @ApiResponse(responseCode = "400", content = { @Content(mediaType = MediaType.TEXT_PLAIN) }, description = "'Invalid body content' or 'MCRObjectID mismatch'"), @ApiResponse(responseCode = "201", description = "MCRObject successfully created"), @ApiResponse(responseCode = "204", description = "MCRObject successfully updated"), }) @MCRRequireTransaction public Response updateObject(@PathParam(PARAM_MCRID) MCRObjectID id, @Parameter(required = true, description = "MCRObject XML", examples = @ExampleObject("<mycoreobject ID=\"{mcrid}\" ..>\n...\n</mycorobject>")) InputStream xmlSource) throws IOException { //check preconditions try { long lastModified = MCRXMLMetadataManager.instance().getLastModified(id); if (lastModified >= 0) { Date lmDate = new Date(lastModified); Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request, lmDate); if (cachedResponse.isPresent()) { return cachedResponse.get(); } } } catch (Exception e) { //ignore errors as PUT is idempotent } MCRStreamContent inputContent = new MCRStreamContent(xmlSource, null, MCRObject.ROOT_NAME); MCRObject updatedObject; try { updatedObject = new MCRObject(inputContent.asXML()); updatedObject.validate(); } catch (JDOMException | MCRException e) { throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_INVALID) .withMessage("MCRObject " + id + " is not valid") .withDetail(e.getMessage()) .withCause(e) .toException(); } if (!id.equals(updatedObject.getId())) { throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_ID_MISMATCH) .withMessage("MCRObject " + id + " cannot be overwritten by " + updatedObject.getId() + ".") .toException(); } try { if (MCRMetadataManager.exists(id)) { MCRMetadataManager.update(updatedObject); return Response.status(Response.Status.NO_CONTENT).build(); } else { MCRMetadataManager.create(updatedObject); return Response.status(Response.Status.CREATED).build(); } } catch (MCRAccessException e) { throw MCRErrorResponse.fromStatus(Response.Status.FORBIDDEN.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_NO_PERMISSION) .withMessage("You may not modify or create MCRObject " + id + ".") .withDetail(e.getMessage()) .withCause(e) .toException(); } } @PUT @Consumes(MediaType.APPLICATION_XML) @Path("/{" + PARAM_MCRID + "}/metadata") @Operation(summary = "Updates the metadata section of a MCRObject with the body of this request", tags = MCRRestUtils.TAG_MYCORE_OBJECT, responses = { @ApiResponse(responseCode = "400", content = { @Content(mediaType = MediaType.TEXT_PLAIN) }, description = "'Invalid body content' or 'MCRObjectID mismatch'"), @ApiResponse(responseCode = "204", description = "MCRObject metadata successfully updated"), }) @MCRRequireTransaction public Response updateObjectMetadata(@PathParam(PARAM_MCRID) MCRObjectID id, @Parameter(required = true, description = "MCRObject XML", examples = @ExampleObject("<metadata>\n...\n</metadata>")) InputStream xmlSource) throws IOException { //check preconditions try { long lastModified = MCRXMLMetadataManager.instance().getLastModified(id); if (lastModified >= 0) { Date lmDate = new Date(lastModified); Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request, lmDate); if (cachedResponse.isPresent()) { return cachedResponse.get(); } } } catch (Exception e) { //ignore errors as PUT is idempotent } MCRStreamContent inputContent = new MCRStreamContent(xmlSource, null); MCRObject updatedObject; try { updatedObject = MCRMetadataManager.retrieveMCRObject(id); updatedObject.getMetadata().setFromDOM(inputContent.asXML().getRootElement().detach()); updatedObject.validate(); } catch (JDOMException | MCRException e) { throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_INVALID) .withMessage("MCRObject " + id + " is not valid") .withDetail(e.getMessage()) .withCause(e) .toException(); } try { MCRMetadataManager.update(updatedObject); return Response.status(Response.Status.NO_CONTENT).build(); } catch (MCRAccessException e) { throw MCRErrorResponse.fromStatus(Response.Status.FORBIDDEN.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_NO_PERMISSION) .withMessage("You may not modify or create metadata of MCRObject " + id + ".") .withDetail(e.getMessage()) .withCause(e) .toException(); } } @DELETE @Path("/{" + PARAM_MCRID + "}") @Operation(summary = "Deletes MCRObject {" + PARAM_MCRID + "}", tags = MCRRestUtils.TAG_MYCORE_OBJECT, responses = { @ApiResponse(responseCode = "204", description = "MCRObject successfully deleted"), @ApiResponse(responseCode = "409", description = "MCRObject could not be deleted as it is referenced.", content = @Content(schema = @Schema( description = "Map<String, <Collection<String>> of source (key) to targets (value)", implementation = Map.class))), }) @MCRRequireTransaction public Response deleteObject(@PathParam(PARAM_MCRID) MCRObjectID id) { //check preconditions if (!MCRMetadataManager.exists(id)) { throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_NOT_FOUND) .withMessage("MCRObject " + id + " not found") .toException(); } try { MCRMetadataManager.deleteMCRObject(id); } catch (MCRActiveLinkException e) { Map<String, Collection<String>> activeLinks = e.getActiveLinks(); throw MCRErrorResponse.fromStatus(Response.Status.CONFLICT.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_STILL_LINKED) .withMessage("MCRObject " + id + " is still linked by other objects.") .withDetail(activeLinks.toString()) .withCause(e) .toException(); } catch (MCRAccessException e) { //usually handled before throw MCRErrorResponse.fromStatus(Response.Status.FORBIDDEN.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_NO_PERMISSION) .withMessage("You may not delete MCRObject " + id + ".") .withDetail(e.getMessage()) .withCause(e) .toException(); } return Response.noContent().build(); } @PUT @Path("/{" + PARAM_MCRID + "}/try") @Operation(summary = "pre-flight target to test write operation on {" + PARAM_MCRID + "}", tags = MCRRestUtils.TAG_MYCORE_OBJECT, responses = { @ApiResponse(responseCode = "202", description = "You have write permission"), @ApiResponse(responseCode = "401", description = "You do not have write permission and need to authenticate first"), @ApiResponse(responseCode = "403", description = "You do not have write permission"), }) public Response testUpdateObject(@PathParam(PARAM_MCRID) MCRObjectID id) { return Response.status(Response.Status.ACCEPTED).build(); } @DELETE @Path("/{" + PARAM_MCRID + "}/try") @Operation(summary = "pre-flight target to test delete operation on {" + PARAM_MCRID + "}", tags = MCRRestUtils.TAG_MYCORE_OBJECT, responses = { @ApiResponse(responseCode = "202", description = "You have delete permission"), @ApiResponse(responseCode = "401", description = "You do not have delete permission and need to authenticate first"), @ApiResponse(responseCode = "403", description = "You do not have delete permission"), }) public Response testDeleteObject(@PathParam(PARAM_MCRID) MCRObjectID id) { return Response.status(Response.Status.ACCEPTED).build(); } @PUT @Consumes(MediaType.TEXT_PLAIN) @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Path("/{" + PARAM_MCRID + "}/service/state") @Operation(summary = "change state of object {" + PARAM_MCRID + "}", tags = MCRRestUtils.TAG_MYCORE_OBJECT, responses = { @ApiResponse(responseCode = "204", description = "operation was successful"), @ApiResponse(responseCode = "400", description = "Invalid state"), @ApiResponse(responseCode = "404", description = "object is not found"), }) @MCRRequireTransaction @MCRApiDraft("MCRObjectState") public Response setState(@PathParam(PARAM_MCRID) MCRObjectID id, String state) { //check preconditions if (!MCRMetadataManager.exists(id)) { throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_NOT_FOUND) .withMessage("MCRObject " + id + " not found") .toException(); } if (!state.isEmpty()) { MCRCategoryID categState = new MCRCategoryID( MCRConfiguration2.getString("MCR.Metadata.Service.State.Classification.ID").orElse("state"), state); if (!MCRCategoryDAOFactory.getInstance().exist(categState)) { throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_INVALID_STATE) .withMessage("Category " + categState + " not found") .toException(); } } final MCRObject mcrObject = MCRMetadataManager.retrieveMCRObject(id); if (state.isEmpty()) { mcrObject.getService().removeState(); } else { mcrObject.getService().setState(state); } try { MCRMetadataManager.update(mcrObject); return Response.status(Response.Status.NO_CONTENT).build(); } catch (MCRAccessException e) { throw MCRErrorResponse.fromStatus(Response.Status.FORBIDDEN.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_NO_PERMISSION) .withMessage("You may not modify or create metadata of MCRObject " + id + ".") .withDetail(e.getMessage()) .withCause(e) .toException(); } } @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Path("/{" + PARAM_MCRID + "}/service/state") @Operation(summary = "get state of object {" + PARAM_MCRID + "}", tags = MCRRestUtils.TAG_MYCORE_OBJECT, responses = { @ApiResponse(responseCode = "307", description = "redirect to state category"), @ApiResponse(responseCode = "204", description = "no state is set"), @ApiResponse(responseCode = "404", description = "object is not found"), }) @MCRApiDraft("MCRObjectState") public Response getState(@PathParam(PARAM_MCRID) MCRObjectID id) { //check preconditions if (!MCRMetadataManager.exists(id)) { throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.MCROBJECT_NOT_FOUND) .withMessage("MCRObject " + id + " not found") .toException(); } final MCRCategoryID state = MCRMetadataManager.retrieveMCRObject(id).getService().getState(); if (state == null) { return Response.noContent().build(); } return Response.temporaryRedirect( uriInfo.resolve(URI.create("classifications/" + state.getRootID() + "/" + state.getId()))) .build(); } }
41,796
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRestRequiredPermission.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/annotation/MCRRestRequiredPermission.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.v2.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.mycore.restapi.v2.access.MCRRestAPIACLPermission; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MCRRestRequiredPermission { MCRRestAPIACLPermission value(); }
1,143
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRestAccessManager.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/access/MCRRestAccessManager.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.v2.access; import org.mycore.access.MCRAccessInterface; import org.mycore.access.MCRAccessManager; import org.mycore.access.MCRRuleAccessInterface; public class MCRRestAccessManager { private static final String REST_API_OBJECT_ID = "restapi:/"; public static boolean checkRestAPIAccess(final MCRAccessInterface aclProvider, final MCRRestAPIACLPermission permission, final String path) { final MCRAccessInterface acl = MCRAccessManager.getAccessImpl(); final String permStr = permission.toString(); if (aclProvider.checkPermission(REST_API_OBJECT_ID, permStr)) { final String objectId = path.startsWith("/") ? REST_API_OBJECT_ID + path.substring(1) : REST_API_OBJECT_ID + path; if (!(acl instanceof MCRRuleAccessInterface ruleAccess) || ruleAccess.hasRule(objectId, permStr)) { return aclProvider.checkPermission(objectId, permStr); } else { return true; } } return false; } }
1,791
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRestAPIACLPermission.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/access/MCRRestAPIACLPermission.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.v2.access; import java.util.Arrays; import org.mycore.access.MCRAccessManager; import jakarta.ws.rs.HttpMethod; /** * The REST API access permissions (read, write, delete) */ public enum MCRRestAPIACLPermission { READ(MCRAccessManager.PERMISSION_READ), WRITE(MCRAccessManager.PERMISSION_WRITE), DELETE(MCRAccessManager.PERMISSION_DELETE), HISTORY_READ(MCRAccessManager.PERMISSION_HISTORY_READ), HISTORY_VIEW(MCRAccessManager.PERMISSION_HISTORY_VIEW); private final String value; MCRRestAPIACLPermission(final String value) { this.value = value; } public static MCRRestAPIACLPermission resolve(final String permission) { return Arrays.stream(values()) .filter(object -> object.value.equalsIgnoreCase(permission)) .findFirst() .orElse(null); } @Override public String toString() { return this.value; } public static MCRRestAPIACLPermission fromMethod(final String method) { return switch (method) { case HttpMethod.GET, HttpMethod.HEAD -> READ; case HttpMethod.DELETE -> DELETE; case HttpMethod.POST, HttpMethod.PUT, HttpMethod.PATCH -> WRITE; default -> null; }; } }
2,007
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRestObjectIDDate.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/model/MCRRestObjectIDDate.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.v2.model; import java.time.Instant; import org.mycore.datamodel.common.MCRObjectIDDate; import org.mycore.restapi.converter.MCRInstantXMLAdapter; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * wraps an MCRObjectIDDate to return it via REST API * and uses Instant instead of Date * * @author Robert Stephan * */ @XmlRootElement(name = "mycoreobject") @XmlType(propOrder = { "id", "lastModified" }) public class MCRRestObjectIDDate { protected Instant lastModified; protected String id; protected MCRRestObjectIDDate() { //required for JAXB serialization super(); } public MCRRestObjectIDDate(MCRObjectIDDate idDate) { super(); id = idDate.getId(); lastModified = idDate.getLastModified().toInstant(); } @XmlAttribute(required = true) @XmlJavaTypeAdapter(value = MCRInstantXMLAdapter.class) public Instant getLastModified() { return lastModified; } @XmlAttribute(required = true) public String getId() { return id; } protected void setLastModified(Instant lastModified) { this.lastModified = lastModified; } protected void setId(String id) { this.id = id; } }
2,137
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetaDefaultListXMLWriter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/converter/MCRMetaDefaultListXMLWriter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.converter; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.mycore.datamodel.metadata.MCRMetaDefault; import jakarta.ws.rs.InternalServerErrorException; import jakarta.ws.rs.Produces; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.ext.MessageBodyWriter; import jakarta.ws.rs.ext.Provider; import jakarta.xml.bind.annotation.XmlElementWrapper; @Provider @Produces({ MediaType.APPLICATION_XML, MediaType.TEXT_XML + ";charset=UTF-8" }) public class MCRMetaDefaultListXMLWriter implements MessageBodyWriter<List<? extends MCRMetaDefault>> { public static final String PARAM_XMLWRAPPER = "xmlWrapper"; @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return Stream.of(MediaType.APPLICATION_XML_TYPE, MediaType.TEXT_XML_TYPE) .anyMatch(t -> t.isCompatible(mediaType)) && List.class.isAssignableFrom(type) && MCRConverterUtils.isType(genericType, MCRMetaDefault.class) && getWrapper(annotations).isPresent(); } private static Optional<String> getWrapper(Annotation... annotations) { return Stream.of(annotations) .filter(a -> XmlElementWrapper.class.isAssignableFrom(a.annotationType())) .findAny() .map(XmlElementWrapper.class::cast) .map(XmlElementWrapper::name); } @Override public void writeTo(List<? extends MCRMetaDefault> mcrMetaDefaults, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { Optional<String> wrapper = getWrapper(annotations); if (!wrapper.isPresent()) { throw new InternalServerErrorException("Could not get XML wrapping element from annotations."); } httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_TYPE); Element root = new Element(wrapper.get()); root.addContent(mcrMetaDefaults.stream() .map(MCRMetaDefault::createXML) .collect(Collectors.toList())); XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); xout.output(root, entityStream); } }
3,458
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRContentJSONWriter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/converter/MCRContentJSONWriter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.converter; import java.io.OutputStream; import org.mycore.common.config.MCRConfigurationException; import org.mycore.common.content.MCRContent; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.ext.Provider; @Provider @Produces({ MediaType.APPLICATION_JSON + ";charset=UTF-8" }) public class MCRContentJSONWriter extends MCRContentAbstractWriter { @Override protected MediaType getTransfomerFormat() { return MediaType.APPLICATION_JSON_TYPE; } @Override protected void handleFallback(MCRContent content, OutputStream entityStream) { String msg = "No Transformer defined to transform MCRContent to JSON"; if (content.getSystemId() != null) { msg = "No Transformer defined to transform MCRContent " + content.getSystemId() + " to JSON"; } throw new MCRConfigurationException(msg); } }
1,659
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRContentAbstractWriter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/converter/MCRContentAbstractWriter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.converter; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Optional; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.mycore.common.content.MCRContent; import org.mycore.common.content.transformer.MCRContentTransformer; import org.mycore.common.content.transformer.MCRContentTransformerFactory; import org.mycore.restapi.annotations.MCRParam; import org.mycore.restapi.annotations.MCRParams; import jakarta.ws.rs.InternalServerErrorException; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.ext.MessageBodyWriter; public abstract class MCRContentAbstractWriter implements MessageBodyWriter<MCRContent> { public static final String PARAM_OBJECTTYPE = "objectType"; private static Optional<String> getTransformerId(Annotation[] annotations, String format, String detail) { return Stream.of(annotations) .filter(a -> MCRParams.class.isAssignableFrom(a.annotationType())) .map(MCRParams.class::cast) .flatMap(p -> Stream.of(p.values())) .filter(p -> p.name().equals(PARAM_OBJECTTYPE)) .findAny() .map(MCRParam::value) .map(objectType -> objectType + "-" + format + "-" + detail); } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return getTransfomerFormat().isCompatible(mediaType) && MCRContent.class.isAssignableFrom(type); } @Override public void writeTo(MCRContent content, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { String format = getTransfomerFormat().getSubtype(); String detail = mediaType.getParameters().getOrDefault(MCRDetailLevel.MEDIA_TYPE_PARAMETER, MCRDetailLevel.normal.toString()); LogManager.getLogger().debug("MediaType={}, format={}, detail={}", mediaType, format, detail); Optional<String> transformerId = getTransformerId(annotations, format, detail); LogManager.getLogger().debug("Transformer for {} would be {}.", content.getSystemId(), transformerId.orElse(null)); Optional<MCRContentTransformer> transformer = transformerId .map(MCRContentTransformerFactory::getTransformer); if (transformer.isPresent()) { transformer.get().transform(content, entityStream); } else if (MCRDetailLevel.normal.toString().equals(detail)) { handleFallback(content, entityStream); } else if (transformerId.isPresent()) { throw new InternalServerErrorException("MCRContentTransformer " + transformerId.get() + " is not defined."); } else { LogManager.getLogger().warn("Could not get MCRContentTransformer from request"); handleFallback(content, entityStream); } } protected abstract MediaType getTransfomerFormat(); protected abstract void handleFallback(MCRContent content, OutputStream entityStream) throws IOException; }
4,091
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRWrappedXMLWriter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/converter/MCRWrappedXMLWriter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.converter; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; import java.util.Locale; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; import jakarta.ws.rs.InternalServerErrorException; import jakarta.ws.rs.Produces; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.ext.MessageBodyWriter; import jakarta.ws.rs.ext.Provider; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBElement; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Marshaller; import jakarta.xml.bind.annotation.XmlElementWrapper; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; @Provider @Produces({ MediaType.APPLICATION_XML, MediaType.TEXT_XML }) public class MCRWrappedXMLWriter implements MessageBodyWriter<Object> { private static final ConcurrentHashMap<Class, JAXBContext> CTX_MAP = new ConcurrentHashMap<>(); private static final Predicate<Class> JAXB_CHECKER = type -> type.isAnnotationPresent(XmlRootElement.class) || type.isAnnotationPresent(XmlType.class); private static boolean verifyArrayType(Class type) { Class componentType = type.getComponentType(); return JAXB_CHECKER.test(componentType) || JAXBElement.class.isAssignableFrom(componentType); } private static boolean verifyGenericType(Type genericType) { if (!(genericType instanceof ParameterizedType pt)) { return false; } if (pt.getActualTypeArguments().length > 1) { return false; } final Type ta = pt.getActualTypeArguments()[0]; if (ta instanceof ParameterizedType lpt) { return (lpt.getRawType() instanceof Class rawType) && JAXBElement.class.isAssignableFrom(rawType); } if (!(pt.getActualTypeArguments()[0] instanceof Class listClass)) { return false; } return JAXB_CHECKER.test(listClass); } private static Class getElementClass(Class<?> type, Type genericType) { Type ta; if (genericType instanceof ParameterizedType parameterizedType) { ta = parameterizedType.getActualTypeArguments()[0]; } else if (genericType instanceof GenericArrayType arrayType) { ta = arrayType.getGenericComponentType(); } else { ta = type.getComponentType(); } if (ta instanceof ParameterizedType parameterizedType) { //JAXBElement ta = parameterizedType.getActualTypeArguments()[0]; } return (Class) ta; } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (Stream.of(annotations).noneMatch(a -> XmlElementWrapper.class.isAssignableFrom(a.annotationType()))) { return false; } if (Collection.class.isAssignableFrom(type)) { return verifyGenericType(genericType) && Stream.of(MediaType.APPLICATION_XML_TYPE, MediaType.TEXT_XML_TYPE) .anyMatch(t -> t.isCompatible(mediaType)); } else { return type.isArray() && verifyArrayType(type) && Stream.of(MediaType.APPLICATION_XML_TYPE, MediaType.TEXT_XML_TYPE) .anyMatch(t -> t.isCompatible(mediaType)); } } @Override public void writeTo(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { Collection collection = (type.isArray()) ? Arrays.asList((Object[]) t) : (Collection) t; Class elementType = getElementClass(type, genericType); Supplier<Marshaller> m = () -> { try { JAXBContext ctx = CTX_MAP.computeIfAbsent(elementType, et -> { try { return JAXBContext.newInstance(et); } catch (JAXBException e) { throw new InternalServerErrorException(e); } }); Marshaller marshaller = ctx.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); return marshaller; } catch (JAXBException e) { throw new InternalServerErrorException(e); } }; try { XmlElementWrapper wrapper = Stream.of(annotations) .filter(a -> XmlElementWrapper.class.isAssignableFrom(a.annotationType())) .map(XmlElementWrapper.class::cast) .findAny() .get(); writeCollection(wrapper, collection, StandardCharsets.UTF_8, m, entityStream); } catch (JAXBException ex) { throw new InternalServerErrorException(ex); } } public final void writeCollection(XmlElementWrapper wrapper, Collection<?> t, Charset c, Supplier<Marshaller> m, OutputStream entityStream) throws JAXBException, IOException { final String rootElement = wrapper.name(); entityStream.write( String.format(Locale.ROOT, "<?xml version=\"1.0\" encoding=\"%s\" standalone=\"yes\"?>", c.name()) .getBytes(c)); if (t.isEmpty()) { entityStream.write(String.format(Locale.ROOT, "<%s />", rootElement).getBytes(c)); } else { entityStream.write(String.format(Locale.ROOT, "<%s>", rootElement).getBytes(c)); Marshaller marshaller = m.get(); for (Object o : t) { marshaller.marshal(o, entityStream); } entityStream.write(String.format(Locale.ROOT, "</%s>", rootElement).getBytes(c)); } } }
7,026
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRConverterUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/converter/MCRConverterUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.converter; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; final class MCRConverterUtils { private MCRConverterUtils() { } static boolean isType(Type genericType, Class<?> targetType) { return genericType instanceof ParameterizedType parameterizedType && parameterizedType.getActualTypeArguments()[0] instanceof Class type && targetType.isAssignableFrom(type); } }
1,198
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDetailLevel.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/converter/MCRDetailLevel.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.converter; public enum MCRDetailLevel { summary, normal, detailed; public static final String MEDIA_TYPE_PARAMETER = "detail"; }
894
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRContentXMLWriter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/converter/MCRContentXMLWriter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.converter; import java.io.IOException; import java.io.OutputStream; import org.mycore.common.content.MCRContent; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.ext.Provider; @Provider @Produces({ MediaType.APPLICATION_XML, MediaType.TEXT_XML + ";charset=UTF-8" }) public class MCRContentXMLWriter extends MCRContentAbstractWriter { @Override protected MediaType getTransfomerFormat() { return MediaType.APPLICATION_XML_TYPE; } @Override protected void handleFallback(MCRContent content, OutputStream entityStream) throws IOException { content.sendTo(entityStream); } }
1,412
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRObjectIDParamConverterProvider.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/converter/MCRObjectIDParamConverterProvider.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.converter; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import org.mycore.common.MCRException; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.restapi.v2.MCRErrorResponse; import jakarta.ws.rs.BadRequestException; import jakarta.ws.rs.ext.ParamConverter; import jakarta.ws.rs.ext.ParamConverterProvider; import jakarta.ws.rs.ext.Provider; @Provider public class MCRObjectIDParamConverterProvider implements ParamConverterProvider { public static final String MSG_INVALID = "Invalid ID supplied"; public static final int CODE_INVALID = 400; //Bad Request @Override public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) throws BadRequestException { if (MCRObjectID.class.isAssignableFrom(rawType)) { return new ParamConverter<>() { @Override public T fromString(String value) { if (value == null) { throw new IllegalArgumentException("value may not be null"); } try { return rawType.cast(MCRObjectID.getInstance(value)); } catch (MCRException e) { throw MCRErrorResponse.fromStatus(CODE_INVALID) .withErrorCode("MCROBJECTID_INVALID") .withMessage(MSG_INVALID) .withDetail(e.getMessage()) .withCause(e) .toException(); } } @Override public String toString(T value) { return value.toString(); } }; } return null; } }
2,575
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetaDefaultListJSONWriter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/converter/MCRMetaDefaultListJSONWriter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.converter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.util.List; import org.apache.logging.log4j.LogManager; import org.mycore.datamodel.metadata.MCRMetaDefault; import com.google.gson.Gson; import com.google.gson.JsonArray; import jakarta.ws.rs.Produces; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.ext.MessageBodyWriter; import jakarta.ws.rs.ext.Provider; @Provider @Produces({ MediaType.APPLICATION_JSON + ";charset=UTF-8" }) public class MCRMetaDefaultListJSONWriter implements MessageBodyWriter<List<? extends MCRMetaDefault>> { public static final String PARAM_XMLWRAPPER = "xmlWrapper"; @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return MediaType.APPLICATION_JSON_TYPE.isCompatible(mediaType) && List.class.isAssignableFrom(type) && MCRConverterUtils.isType(genericType, MCRMetaDefault.class); } @Override public void writeTo(List<? extends MCRMetaDefault> mcrMetaDefaults, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { LogManager.getLogger().info("Writing JSON array of size: " + mcrMetaDefaults.size()); httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_TYPE.withCharset(StandardCharsets.UTF_8.toString())); JsonArray array = new JsonArray(); mcrMetaDefaults.stream() .map(MCRMetaDefault::createJSON) .forEach(array::add); try (OutputStreamWriter streamWriter = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) { Gson gson = new Gson(); gson.toJson(array, streamWriter); } } }
2,900
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRInstantXMLAdapter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/converter/MCRInstantXMLAdapter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.converter; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Year; import java.time.YearMonth; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import jakarta.xml.bind.annotation.adapters.XmlAdapter; public class MCRInstantXMLAdapter extends XmlAdapter<String, Instant> { @Override public Instant unmarshal(String v) { return Instant .from(DateTimeFormatter.ISO_INSTANT.parseBest(v, ZonedDateTime::from, LocalDateTime::from, LocalDate::from, YearMonth::from, Year::from)); } @Override public String marshal(Instant v) { return v.toString(); } }
1,515
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRParam.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/annotations/MCRParam.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.annotations; import java.lang.annotation.Annotation; public @interface MCRParam { String name(); String value(); class Factory { public static MCRParam get(String name, String value) { return new MCRParam() { @Override public String name() { return name; } @Override public String value() { return value; } @Override public Class<? extends Annotation> annotationType() { return MCRParam.class; } @Override public String toString() { return "@" + MCRParam.class.getName() + "(" + name + "=" + value + ")"; } }; } } }
1,606
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRequireTransaction.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/annotations/MCRRequireTransaction.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to mark REST methods that require an active JPA transaction * @author Thomas Scheffler (yagee) */ @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface MCRRequireTransaction { }
1,172
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRApiDraft.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/annotations/MCRApiDraft.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to mark REST methods that are not stable for production. * * Those endpoints maybe changed or removed at a later date. * @author Thomas Scheffler (yagee) * @see org.mycore.restapi.MCRApiDraftFilter */ @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface MCRApiDraft { /** * A simple value to mark a group of endpoints. * * Endpoints belong to the same group if this value is the same. */ String value(); }
1,434
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAccessControlExposeHeaders.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/annotations/MCRAccessControlExposeHeaders.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used by {@link org.mycore.restapi.MCRCORSResponseFilter} to return values for * {@code Access-Control-Expose-Headers} HTTP response header. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MCRAccessControlExposeHeaders { /** * @return values for {@code Access-Control-Expose-Headers} header */ String[] value(); }
1,309
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRParams.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/annotations/MCRParams.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.restapi.annotations; import java.lang.annotation.Annotation; import java.util.Arrays; public @interface MCRParams { MCRParam[] values(); class Factory { public static MCRParams get(MCRParam... params) { return new MCRParams() { @Override public MCRParam[] values() { return params; } @Override public Class<? extends Annotation> annotationType() { return MCRParams.class; } @Override public String toString() { return "@" + MCRParams.class.getName() + Arrays.toString(values()); } @Override public int hashCode() { return ("values".hashCode() * 127) ^ Arrays.hashCode(values()); } @Override public boolean equals(Object obj) { return obj instanceof MCRParams that && Arrays.equals(this.values(), that.values()); } }; } } }
1,870
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRWebCLIContainer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webcli/src/main/java/org/mycore/webcli/container/MCRWebCLIContainer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webcli.container; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Flow; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.SubmissionPublisher; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.config.AbstractConfiguration; import org.apache.logging.log4j.core.config.Property; import org.apache.logging.log4j.core.layout.PatternLayout; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRClassTools; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRTransactionHelper; import org.mycore.common.MCRUsageException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.processing.MCRProcessableCollection; import org.mycore.common.processing.MCRProcessableDefaultCollection; import org.mycore.common.processing.MCRProcessableRegistry; import org.mycore.frontend.cli.MCRCommand; import org.mycore.frontend.ws.common.MCRWebsocketDefaultConfigurator; import org.mycore.util.concurrent.processing.MCRProcessableExecutor; import org.mycore.util.concurrent.processing.MCRProcessableFactory; import org.mycore.util.concurrent.processing.MCRProcessableSupplier; import org.mycore.webcli.cli.MCRWebCLICommandManager; import org.mycore.webcli.flow.MCRCommandListProcessor; import org.mycore.webcli.flow.MCRJSONSubscriber; import org.mycore.webcli.flow.MCRLogEventProcessor; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import jakarta.servlet.http.HttpSession; import jakarta.websocket.CloseReason; import jakarta.websocket.Session; /** * Is a wrapper class around command execution. Commands will be {@link #addCommand(String) queued} and executed in a * seperate thread. * * @author Thomas Scheffler (yagee) * @author Michel Buechner (mcrmibue) * @since 2.0 */ public class MCRWebCLIContainer { private final ReentrantLock lock; MCRProcessableSupplier<Boolean> curFuture; private static Map<String, List<MCRCommand>> knownCommands; private final ProcessCallable processCallable; private static final Logger LOGGER = LogManager.getLogger(); private static final MCRProcessableExecutor EXECUTOR; private static final MCRProcessableCollection PROCESSABLE_COLLECTION; static { PROCESSABLE_COLLECTION = new MCRProcessableDefaultCollection("Web CLI"); MCRProcessableRegistry registry = MCRProcessableRegistry.getSingleInstance(); registry.register(PROCESSABLE_COLLECTION); ExecutorService service = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "WebCLI")); EXECUTOR = MCRProcessableFactory.newPool(service, PROCESSABLE_COLLECTION); } /** * Will instantiate this container with a list of supported commands. * * @param session * the current Session(Websocket) of the user using the gui. */ public MCRWebCLIContainer(Session session) { lock = new ReentrantLock(); processCallable = new ProcessCallable(MCRSessionMgr.getCurrentSession(), session, lock); } public ReentrantLock getWebsocketLock() { return lock; } /** * Adds this <code>cmd</code> to the current command queue. The thread * executing the commands will be started automatically if the queue was * previously empty. * * @param cmd * a valid String representation of a * {@link #MCRWebCLIContainer(Session) known} * <code>MCRCommand</code> */ public void addCommand(String cmd) { LOGGER.info("appending command: {}", cmd); processCallable.commands.add(cmd); if (!isRunning()) { curFuture = EXECUTOR.submit(processCallable); } } /** * Returns the status of the command execution thread. * * @return true if the thread is running */ public boolean isRunning() { return !(curFuture == null || curFuture.isFutureDone()); } public static JsonObject getKnownCommands() { updateKnownCommandsIfNeeded(); JsonObject commandsJSON = new JsonObject(); JsonArray jsonArray = new JsonArray(); commandsJSON.add("commands", jsonArray); for (Map.Entry<String, List<MCRCommand>> entry : knownCommands.entrySet()) { //sort commands for display only (fix for MCR-1594) JsonArray commands = entry.getValue().stream() .sorted((commandA, commandB) -> commandA.getSyntax().compareToIgnoreCase(commandB.getSyntax())) .map(cmd -> { JsonObject command = new JsonObject(); command.add("command", new JsonPrimitive(cmd.getSyntax())); command.add("help", new JsonPrimitive(cmd.getHelpText())); return command; }).collect(JsonArray::new, JsonArray::add, JsonArray::addAll); JsonObject item = new JsonObject(); item.addProperty("name", entry.getKey()); item.add("commands", commands); jsonArray.add(item); } return commandsJSON; } protected static void initializeCommands() { if (knownCommands == null) { knownCommands = new TreeMap<>(); knownCommands.putAll(new MCRWebCLICommandManager().getCommandsMap()); } } private static void updateKnownCommandsIfNeeded() { if (knownCommands == null) { initializeCommands(); } } public void changeWebSocketSession(Session webSocketSession) { this.processCallable.changeWebSocketSession(webSocketSession); } public void webSocketClosed() { this.processCallable.webSocketClosed(); } public void stopLogging() { this.processCallable.stopLogging(true); } public void startLogging() { this.processCallable.startLogging(true); } public void setContinueIfOneFails(boolean con) { this.processCallable.setContinueIfOneFails(con); } public void setContinueIfOneFails(boolean con, boolean sendMessage) { this.processCallable.setContinueIfOneFails(con, sendMessage); } public void clearCommandList() { this.processCallable.clearCommandList(); } private static class ProcessCallable implements Callable<Boolean> { private final ReentrantLock lock; List<String> commands; Session webSocketSession; MCRSession session; Log4JGrabber logGrabber; String currentCommand; boolean continueIfOneFails; boolean stopLogs; private MCRLogEventProcessor logEventProcessor; private final SubmissionPublisher<List<String>> cmdListPublisher; private MCRCommandListProcessor cmdListProcessor; ProcessCallable(MCRSession session, Session webSocketSession, ReentrantLock lock) { this.commands = new ArrayList<>(); this.session = session; this.lock = lock; this.stopLogs = false; this.webSocketSession = webSocketSession; this.logGrabber = new Log4JGrabber(MCRWebCLIContainer.class.getSimpleName() + session.getID(), null, PatternLayout.createDefaultLayout(), true, Property.EMPTY_ARRAY); this.logGrabber.start(); startLogging(true); cmdListPublisher = new SubmissionPublisher<>(ForkJoinPool.commonPool(), 1); this.currentCommand = ""; this.continueIfOneFails = false; startSendingCommandQueue(); } public void stopLogging(boolean remember) { if (remember) { this.stopLogs = true; } this.logEventProcessor.close(); } public void startLogging(boolean remember) { if (remember) { this.stopLogs = false; } if (this.stopLogs) { return; } if (logEventProcessor != null) { logEventProcessor.close(); } MCRLogEventProcessor logEventProcessor = new MCRLogEventProcessor(); MCRJSONSubscriber log2web = new MCRJSONSubscriber(webSocketSession, lock); logEventProcessor.subscribe(log2web); this.logEventProcessor = logEventProcessor; logGrabber.subscribe(logEventProcessor); if (logGrabber.isStopped()) { logGrabber.start(); } } public void setContinueIfOneFails(boolean con) { setContinueIfOneFails(con, false); } public void setContinueIfOneFails(boolean con, boolean sendMessage) { this.continueIfOneFails = con; if (sendMessage) { JsonObject jObject = new JsonObject(); jObject.addProperty("type", "continueIfOneFails"); jObject.addProperty("value", con); try { lock.lock(); webSocketSession.getBasicRemote().sendText(jObject.toString()); } catch (IOException e) { LOGGER.error("Cannot send message to client.", e); } finally { lock.unlock(); } } } public void clearCommandList() { this.commands.clear(); cmdListPublisher.submit(commands); setCurrentCommand(""); } public Boolean call() throws Exception { return processCommands(); } /** * method mainly copied from CLI class * * @return true if command processed successfully */ private boolean processCommand(String command) { if (command.trim().startsWith("#")) { // ignore comment return true; } LOGGER.info("Processing command:'{}' ({} left)", command, commands.size()); setCurrentCommand(command); long start = System.currentTimeMillis(); MCRTransactionHelper.beginTransaction(); try { List<String> commandsReturned = null; for (List<MCRCommand> cmds : knownCommands.values()) { // previous attempt to run command was successful if (commandsReturned != null) { break; } commandsReturned = runCommand(command, cmds); } updateKnownCommandsIfNeeded(); MCRTransactionHelper.commitTransaction(); if (commandsReturned != null) { LOGGER.info("Command processed ({} ms)", System.currentTimeMillis() - start); } else { throw new MCRUsageException("Command not understood: " + command); } } catch (Exception ex) { LOGGER.error("Command '{}' failed. Performing transaction rollback...", command, ex); try { MCRTransactionHelper.rollbackTransaction(); } catch (Exception ex2) { LOGGER.error("Error while perfoming rollback for command '{}'!", command, ex2); } if (!continueIfOneFails) { saveQueue(command, null); } return false; } finally { MCRTransactionHelper.beginTransaction(); MCREntityManagerProvider.getCurrentEntityManager().clear(); MCRTransactionHelper.commitTransaction(); } return true; } private List<String> runCommand(String command, List<MCRCommand> commandList) throws IllegalAccessException, InvocationTargetException, ClassNotFoundException, NoSuchMethodException { List<String> commandsReturned = null; for (MCRCommand currentCommand : commandList) { commandsReturned = currentCommand.invoke(command, MCRClassTools.getClassLoader()); if (commandsReturned != null) { // Command was executed // Add commands to queue if (commandsReturned.size() > 0) { LOGGER.info("Queueing {} commands to process", commandsReturned.size()); commands.addAll(0, commandsReturned); cmdListPublisher.submit(commands); } break; } } return commandsReturned; } protected void saveQueue(String lastCommand, Queue<String> failedQueue) { // lastCommand is null if work is not stopped at first error if (lastCommand == null) { LOGGER.error("Some commands failed."); } else { LOGGER.printf(Level.ERROR, "The following command failed: '%s'", lastCommand); } if (!commands.isEmpty()) { LOGGER.printf(Level.INFO, "There are %d other commands still unprocessed.", commands.size()); } String unprocessedCommandsFile = MCRConfiguration2.getStringOrThrow("MCR.WebCLI.UnprocessedCommandsFile"); File file = new File(unprocessedCommandsFile); LOGGER.info("Writing unprocessed commands to file {}", file.getAbsolutePath()); try { PrintWriter pw = new PrintWriter(file, Charset.defaultCharset()); if (lastCommand != null) { pw.println(lastCommand); } for (String command : commands.toArray(String[]::new)) { pw.println(command); } if (failedQueue != null && !failedQueue.isEmpty()) { for (String failedCommand : failedQueue) { pw.println(failedCommand); } } pw.close(); } catch (IOException ex) { LOGGER.error("Cannot write to {}", file.getAbsolutePath(), ex); } clearCommandList(); } protected boolean processCommands() throws IOException { final LoggerContext logCtx = (LoggerContext) LogManager.getContext(false); final AbstractConfiguration logConf = (AbstractConfiguration) logCtx.getConfiguration(); Queue<String> failedQueue = new ArrayDeque<>(); logGrabber.grabCurrentThread(); // start grabbing logs of this thread logConf.getRootLogger().addAppender(logGrabber, logConf.getRootLogger().getLevel(), null); // register session to MCRSessionMgr MCRSessionMgr.setCurrentSession(session); Optional<HttpSession> httpSession = Optional .ofNullable((HttpSession) webSocketSession.getUserProperties() .get(MCRWebsocketDefaultConfigurator.HTTP_SESSION)); int sessionTime = httpSession.map(HttpSession::getMaxInactiveInterval).orElse(-1); httpSession.ifPresent(s -> s.setMaxInactiveInterval(-1)); try { while (!commands.isEmpty()) { String command = commands.remove(0); cmdListPublisher.submit(commands); if (!processCommand(command)) { if (!continueIfOneFails) { return false; } failedQueue.add(command); } } if (failedQueue.isEmpty()) { setCurrentCommand(""); return true; } else { saveQueue(null, failedQueue); return false; } } finally { // stop grabbing logs of this thread logGrabber.stop(); logConf.removeAppender(logGrabber.getName()); try { if (webSocketSession.isOpen()) { LogManager.getLogger().info("Close session {}", webSocketSession::getId); webSocketSession.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Done")); } } finally { httpSession.ifPresent(s -> s.setMaxInactiveInterval(sessionTime)); // release session MCRSessionMgr.releaseCurrentSession(); } } } public void startSendingCommandQueue() { MCRCommandListProcessor commandListProcessor = new MCRCommandListProcessor(); commandListProcessor.subscribe(new MCRJSONSubscriber(this.webSocketSession, lock)); cmdListPublisher.subscribe(commandListProcessor); this.cmdListProcessor = commandListProcessor; cmdListPublisher.submit(commands); } public void changeWebSocketSession(Session webSocketSession) { webSocketClosed(); this.webSocketSession = webSocketSession; startLogging(false); sendCurrentCommand(); startSendingCommandQueue(); } private void setCurrentCommand(String command) { this.currentCommand = command; sendCurrentCommand(); } private void sendCurrentCommand() { JsonObject jObject = new JsonObject(); jObject.addProperty("type", "currentCommand"); jObject.addProperty("return", currentCommand); if (webSocketSession.isOpen()) { try { lock.lock(); webSocketSession.getBasicRemote().sendText(jObject.toString()); } catch (IOException ex) { LOGGER.error("Cannot send message to client.", ex); } finally { lock.unlock(); } } } @Override public String toString() { return this.commands.stream().findFirst().orElse("no active command"); } public void webSocketClosed() { stopLogging(false); cmdListProcessor.close(); } } private static class Log4JGrabber extends AbstractAppender implements Flow.Publisher<LogEvent> { private SubmissionPublisher<LogEvent> publisher; public String webCLIThread; private static int MAX_BUFFER = 10000; private List<Flow.Subscriber<? super LogEvent>> subscribers; protected Log4JGrabber(String name, Filter filter, Layout<? extends Serializable> layout, final boolean ignoreExceptions, final Property[] properties) { super(name, filter, layout, ignoreExceptions, properties); } @Override public void start() { super.start(); if (this.publisher != null && !this.publisher.isClosed()) { stop(); } this.publisher = new SubmissionPublisher<>(ForkJoinPool.commonPool(), MAX_BUFFER); if (subscribers != null) { subscribers.forEach(publisher::subscribe); } grabCurrentThread(); } @Override public void stop() { while (publisher.estimateMaximumLag() > 0) { if (publisher.getExecutor() instanceof ForkJoinPool forkJoinPool) { forkJoinPool.awaitQuiescence(1, TimeUnit.SECONDS); } else { Thread.yield(); } } this.subscribers = publisher.getSubscribers(); super.stop(); this.publisher.close(); } public void grabCurrentThread() { this.webCLIThread = Thread.currentThread().getName(); } @Override public void append(LogEvent event) { if (webCLIThread.equals(event.getThreadName())) { publisher.submit(event); } } @Override public void subscribe(Flow.Subscriber<? super LogEvent> subscriber) { publisher.subscribe(subscriber); } } }
22,016
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRWebCLIResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webcli/src/main/java/org/mycore/webcli/resources/MCRWebCLIResource.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webcli.resources; import java.io.InputStream; 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.frontend.jersey.MCRStaticContent; import org.mycore.frontend.jersey.filter.access.MCRRestrictedAccess; import jakarta.servlet.http.HttpServletRequest; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; /** * @author Michel Buechner (mcrmibue) * */ @Path("WebCLI") public class MCRWebCLIResource { @Context HttpServletRequest request; private static final Logger LOGGER = LogManager.getLogger(); @GET @MCRRestrictedAccess(MCRWebCLIPermission.class) @Produces(MediaType.TEXT_HTML) public Response start() { InputStream mainGui = getClass().getResourceAsStream("/META-INF/resources/modules/webcli/index.html"); MCRSession mcrSession = MCRSessionMgr.getCurrentSession(); LOGGER.info("MyCore Session REST ID: {}", mcrSession.getID()); LOGGER.info("REST ThreadID: {}", Thread.currentThread().getName()); return Response.ok(mainGui).build(); } @GET @Path("gui/{filename:.*}") @MCRStaticContent public Response getResources(@PathParam("filename") String filename) { if (filename.endsWith(".js")) { return Response.ok(getClass() .getResourceAsStream("/META-INF/resources/modules/webcli/" + filename)) .header("Content-Type", "application/javascript") .build(); } if (filename.endsWith(".css")) { return Response.ok(getClass() .getResourceAsStream("/META-INF/resources/modules/webcli/" + filename)) .header("Content-Type", "text/css") .build(); } return Response.ok(getClass() .getResourceAsStream("/META-INF/resources/modules/webcli/" + filename)) .build(); } }
2,886
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRWebCLIPermission.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webcli/src/main/java/org/mycore/webcli/resources/MCRWebCLIPermission.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webcli.resources; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.access.MCRAccessManager; import org.mycore.frontend.jersey.filter.access.MCRResourceAccessChecker; import jakarta.ws.rs.container.ContainerRequestContext; /** * @author Michel Buechner (mcrmibue) * */ public class MCRWebCLIPermission implements MCRResourceAccessChecker { private static final Logger LOGGER = LogManager.getLogger(); @Override public boolean isPermitted(ContainerRequestContext request) { if (!MCRAccessManager.getAccessImpl().checkPermission("use-webcli")) { LOGGER.info("Permission denied on MCRWebCLI"); return false; } return true; } }
1,496
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRWebCLIResourceSockets.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webcli/src/main/java/org/mycore/webcli/resources/MCRWebCLIResourceSockets.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webcli.resources; import java.io.IOException; import java.net.SocketTimeoutException; import java.net.URI; import java.security.Principal; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.access.MCRAccessManager; import org.mycore.common.MCRSessionMgr; import org.mycore.frontend.ws.common.MCRWebsocketDefaultConfigurator; import org.mycore.frontend.ws.common.MCRWebsocketJSONDecoder; import org.mycore.frontend.ws.endoint.MCRAbstractEndpoint; import org.mycore.webcli.container.MCRWebCLIContainer; import com.google.gson.JsonObject; import jakarta.websocket.CloseReason; import jakarta.websocket.Extension; import jakarta.websocket.MessageHandler; import jakarta.websocket.OnClose; import jakarta.websocket.OnError; import jakarta.websocket.OnMessage; import jakarta.websocket.OnOpen; import jakarta.websocket.RemoteEndpoint; import jakarta.websocket.Session; import jakarta.websocket.WebSocketContainer; import jakarta.websocket.server.ServerEndpoint; /** * @author Michel Buechner (mcrmibue) * */ @ServerEndpoint(value = "/ws/mycore-webcli/socket", configurator = MCRWebsocketDefaultConfigurator.class, decoders = { MCRWebsocketJSONDecoder.class }) public class MCRWebCLIResourceSockets extends MCRAbstractEndpoint { private static final String SESSION_KEY = "MCRWebCLI"; private MCRWebCLIContainer cliCont = null; private static final Logger LOGGER = LogManager.getLogger(); @OnOpen public void open(Session session) { sessionized(session, () -> { LOGGER.info("Socket Session ID: {}", session.getId()); LOGGER.info("MyCore Session ID: {}", MCRSessionMgr.getCurrentSessionID()); cliCont = getCurrentSessionContainer(true, session); LOGGER.info("Open ThreadID: {}", Thread.currentThread().getName()); }); } @OnMessage public void message(Session session, JsonObject request) { sessionized(session, () -> { LOGGER.info("Message ThreadID: {}", Thread.currentThread().getName()); LOGGER.info("MyCore Session ID (message): {}", MCRSessionMgr.getCurrentSessionID()); if (!MCRAccessManager.checkPermission("use-webcli")) { try { session.getBasicRemote().sendText("noPermission"); } catch (IOException ex) { LOGGER.error("Cannot send message to client.", ex); } return; } handleMessage(session, request); }); } private void handleMessage(Session session, JsonObject request) { LOGGER.info("WebSocket Request: {}", request::toString); String type = request.get("type").getAsString(); switch (type) { case "run" -> { String command = request.get("command").getAsString(); cliCont.addCommand(command); } case "getKnownCommands" -> { request.add("return", MCRWebCLIContainer.getKnownCommands()); try { cliCont.getWebsocketLock().lock(); session.getBasicRemote().sendText(request.toString()); } catch (IOException ex) { LOGGER.error("Cannot send message to client.", ex); } finally { cliCont.getWebsocketLock().unlock(); } } case "stopLog" -> cliCont.stopLogging(); case "startLog" -> cliCont.startLogging(); case "continueIfOneFails" -> { boolean value = request.get("value").getAsBoolean(); cliCont.setContinueIfOneFails(value); } case "clearCommandList" -> cliCont.clearCommandList(); default -> LOGGER.warn("Cannot handle request type: " + type); } } @OnClose public void close(Session session) { LOGGER.info("Closing socket {}", session.getId()); if (cliCont != null) { cliCont.webSocketClosed(); } } @OnError public void error(Throwable t) { if (t instanceof SocketTimeoutException) { LOGGER.warn("Socket Session timed out, clossing connection"); } else { LOGGER.error("Error in WebSocket Session", t); } } private MCRWebCLIContainer getCurrentSessionContainer(boolean create, Session session) { MCRWebCLIContainer sessionValue; synchronized (MCRSessionMgr.getCurrentSession()) { sessionValue = (MCRWebCLIContainer) MCRSessionMgr.getCurrentSession().get(SESSION_KEY); if (sessionValue == null && !create) { return null; } Session mySession = new DelegatedSession(session) { @Override public void close() throws IOException { LOGGER.debug("Close session.", new RuntimeException("debug")); super.close(); } @Override public void close(CloseReason closeReason) throws IOException { LOGGER.debug(() -> "Close session: " + closeReason, new RuntimeException("debug")); super.close(closeReason); } }; if (sessionValue == null) { // create object sessionValue = new MCRWebCLIContainer(mySession); MCRSessionMgr.getCurrentSession().put(SESSION_KEY, sessionValue); } else { sessionValue.changeWebSocketSession(mySession); sessionValue.startLogging(); } } return sessionValue; } private static class DelegatedSession implements Session { private Session delegate; DelegatedSession(Session delegate) { this.delegate = delegate; } @Override public WebSocketContainer getContainer() { return delegate.getContainer(); } @Override public void addMessageHandler(MessageHandler handler) throws IllegalStateException { delegate.addMessageHandler(handler); } @Override public <T> void addMessageHandler(Class<T> clazz, MessageHandler.Whole<T> handler) { delegate.addMessageHandler(clazz, handler); } @Override public <T> void addMessageHandler(Class<T> clazz, MessageHandler.Partial<T> handler) { delegate.addMessageHandler(clazz, handler); } @Override public Set<MessageHandler> getMessageHandlers() { return delegate.getMessageHandlers(); } @Override public void removeMessageHandler(MessageHandler handler) { delegate.removeMessageHandler(handler); } @Override public String getProtocolVersion() { return delegate.getProtocolVersion(); } @Override public String getNegotiatedSubprotocol() { return delegate.getNegotiatedSubprotocol(); } @Override public List<Extension> getNegotiatedExtensions() { return delegate.getNegotiatedExtensions(); } @Override public boolean isSecure() { return delegate.isSecure(); } @Override public boolean isOpen() { return delegate.isOpen(); } @Override public long getMaxIdleTimeout() { return delegate.getMaxIdleTimeout(); } @Override public void setMaxIdleTimeout(long milliseconds) { delegate.setMaxIdleTimeout(milliseconds); } @Override public void setMaxBinaryMessageBufferSize(int length) { delegate.setMaxBinaryMessageBufferSize(length); } @Override public int getMaxBinaryMessageBufferSize() { return delegate.getMaxBinaryMessageBufferSize(); } @Override public void setMaxTextMessageBufferSize(int length) { delegate.setMaxTextMessageBufferSize(length); } @Override public int getMaxTextMessageBufferSize() { return delegate.getMaxTextMessageBufferSize(); } @Override public RemoteEndpoint.Async getAsyncRemote() { return delegate.getAsyncRemote(); } @Override public RemoteEndpoint.Basic getBasicRemote() { return delegate.getBasicRemote(); } @Override public String getId() { return delegate.getId(); } @Override public void close() throws IOException { delegate.close(); } @Override public void close(CloseReason closeReason) throws IOException { delegate.close(closeReason); } @Override public URI getRequestURI() { return delegate.getRequestURI(); } @Override public Map<String, List<String>> getRequestParameterMap() { return delegate.getRequestParameterMap(); } @Override public String getQueryString() { return delegate.getQueryString(); } @Override public Map<String, String> getPathParameters() { return delegate.getPathParameters(); } @Override public Map<String, Object> getUserProperties() { return delegate.getUserProperties(); } @Override public Principal getUserPrincipal() { return delegate.getUserPrincipal(); } @Override public Set<Session> getOpenSessions() { return delegate.getOpenSessions(); } } }
10,642
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRWebCLICommandManager.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webcli/src/main/java/org/mycore/webcli/cli/MCRWebCLICommandManager.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webcli.cli; import java.util.List; import java.util.TreeMap; import org.apache.logging.log4j.LogManager; import org.mycore.frontend.cli.MCRCommand; import org.mycore.frontend.cli.MCRCommandManager; /** * @author Thomas Scheffler (yagee) * */ public class MCRWebCLICommandManager extends MCRCommandManager { public MCRWebCLICommandManager() { initCommands(); } @Override protected void handleInitException(Exception ex) { LogManager.getLogger(getClass()).error("Exception while initializing commands.", ex); } @Override protected void initBuiltInCommands() { addAnnotatedCLIClass(MCRBasicWebCLICommands.class); } public TreeMap<String, List<MCRCommand>> getCommandsMap() { return knownCommands; } }
1,528
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRBasicWebCLICommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webcli/src/main/java/org/mycore/webcli/cli/MCRBasicWebCLICommands.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webcli.cli; import java.io.IOException; import java.util.List; import org.mycore.common.MCRSessionMgr; import org.mycore.frontend.cli.MCRCommandLineInterface; import org.mycore.frontend.cli.MCRCommandStatistics; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; import org.mycore.webcli.container.MCRWebCLIContainer; @MCRCommandGroup(name = "Basic commands") public class MCRBasicWebCLICommands { @MCRCommand(syntax = "process resource {0}", help = "Execute the commands listed in the resource file {0}.", order = 10) public static List<String> readCommandsResource(String resource) throws IOException { return MCRCommandLineInterface.readCommandsRessource(resource); } @MCRCommand(syntax = "process {0}", help = "Execute the commands listed in the text file {0}.", order = 20) public static List<String> readCommandsFile(String file) throws IOException { return MCRCommandLineInterface.readCommandsFile(file); } @MCRCommand(syntax = "show command statistics", help = "Show statistics on number of commands processed and execution time needed per command", order = 30) public static void showCommandStatistics() { MCRCommandStatistics.showCommandStatistics(); } @MCRCommand(syntax = "cancel on error", help = "Cancel execution of further commands in case of error", order = 40) public static void cancelonError() { setContinueIfOneFails(false); MCRCommandLineInterface.cancelOnError(); } @MCRCommand(syntax = "skip on error", help = "Skip execution of failed command in case of error", order = 50) public static void skipOnError() { setContinueIfOneFails(true); MCRCommandLineInterface.skipOnError(); } private static void setContinueIfOneFails(boolean value) { Object sessionValue; synchronized (MCRSessionMgr.getCurrentSession()) { sessionValue = MCRSessionMgr.getCurrentSession().get("MCRWebCLI"); ((MCRWebCLIContainer) sessionValue).setContinueIfOneFails(value, true); } } }
2,901
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCommandListProcessor.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webcli/src/main/java/org/mycore/webcli/flow/MCRCommandListProcessor.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webcli.flow; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Flow; import java.util.concurrent.SubmissionPublisher; import org.mycore.common.MCRJSONUtils; import com.google.gson.JsonObject; public class MCRCommandListProcessor extends SubmissionPublisher<JsonObject> implements Flow.Processor<List<String>, JsonObject> { private Flow.Subscription upstreamSubscription; @Override public void onSubscribe(Flow.Subscription subscription) { this.upstreamSubscription = subscription; upstreamSubscription.request(1); } @Override public void onNext(List<String> item) { try { ArrayList<String> copy; synchronized (item) { copy = new ArrayList<>(item); } JsonObject jObject = new JsonObject(); jObject.addProperty("type", "commandQueue"); jObject.add("return", MCRJSONUtils .getJsonArray(copy.subList(0, Math.min(copy.size(), 100)))); jObject.addProperty("size", copy.size()); submit(jObject); } finally { upstreamSubscription.request(1); } } @Override public void onError(Throwable throwable) { super.closeExceptionally(throwable); } @Override public void onComplete() { super.close(); } @Override public void close() { upstreamSubscription.cancel(); super.close(); } }
2,230
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRLogEventProcessor.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webcli/src/main/java/org/mycore/webcli/flow/MCRLogEventProcessor.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webcli.flow; import java.io.PrintWriter; import java.io.StringWriter; import java.util.concurrent.Flow; import java.util.concurrent.SubmissionPublisher; import org.apache.logging.log4j.core.LogEvent; import com.google.gson.JsonObject; public class MCRLogEventProcessor extends SubmissionPublisher<JsonObject> implements Flow.Processor<LogEvent, JsonObject> { private Flow.Subscription upstreamSubscrition; @Override public void onSubscribe(Flow.Subscription subscription) { this.upstreamSubscrition = subscription; subscription.request(1); } @Override public void onNext(LogEvent event) { try { JsonObject logEvent = new JsonObject(); logEvent.addProperty("logLevel", event.getLevel().toString()); logEvent.addProperty("message", event.getMessage().getFormattedMessage()); String exception = null; if (event.getThrownProxy() != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); event.getThrownProxy().getThrowable().printStackTrace(pw); pw.close(); exception = sw.toString(); } logEvent.addProperty("exception", exception); logEvent.addProperty("time", event.getTimeMillis()); JsonObject json = new JsonObject(); json.addProperty("type", "log"); json.add("return", logEvent); submit(json); } finally { upstreamSubscrition.request(1); } } @Override public void onError(Throwable throwable) { super.closeExceptionally(throwable); } @Override public void onComplete() { super.close(); } @Override public void close() { //MCR-2823 upstreamSubscription may not yet be initialized: prevent NPE if (this.upstreamSubscrition != null) { this.upstreamSubscrition.cancel(); } super.close(); } }
2,778
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJSONSubscriber.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webcli/src/main/java/org/mycore/webcli/flow/MCRJSONSubscriber.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webcli.flow; import java.io.IOException; import java.io.UncheckedIOException; import java.util.concurrent.Flow; import java.util.concurrent.locks.ReentrantLock; import org.apache.logging.log4j.LogManager; import com.google.gson.JsonObject; import jakarta.websocket.CloseReason; import jakarta.websocket.Session; public class MCRJSONSubscriber implements Flow.Subscriber<JsonObject> { private final Session session; private final ReentrantLock lock; private Flow.Subscription subscription; public MCRJSONSubscriber(Session session, ReentrantLock lock) { this.session = session; this.lock = lock; } @Override public void onSubscribe(Flow.Subscription subscription) { this.subscription = subscription; subscription.request(1); } @Override public void onNext(JsonObject item) { if (!this.session.isOpen()) { LogManager.getLogger().warn("Session {} closed, cancel further log event subscription!", this.session.getId()); subscription.cancel(); } LogManager.getLogger().debug(() -> "Sending json: " + item.toString()); lock.lock(); try { session.getBasicRemote().sendText(item.toString()); } catch (IOException e) { throw new UncheckedIOException(e); } finally { lock.unlock(); subscription.request(1); } } @Override public void onError(Throwable throwable) { if (this.session.isOpen()) { try { LogManager.getLogger().error("Close session " + session.getId(), throwable); this.session.close(new CloseReason(CloseReason.CloseCodes.CLOSED_ABNORMALLY, throwable.getMessage())); } catch (IOException e) { LogManager.getLogger().warn("Error in Publisher or Subscriber.", throwable); } } } @Override public void onComplete() { LogManager.getLogger().info("Finished sending JSON."); } public void cancel() { this.subscription.cancel(); } }
2,863
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCategoryJsonTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/test/java/org/mycore/frontend/classeditor/json/MCRCategoryJsonTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.json; import org.jdom2.Document; import org.jdom2.input.SAXBuilder; import org.junit.Test; import org.mycore.common.MCRJSONManager; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationBase; import org.mycore.common.config.MCRConfigurationLoader; import org.mycore.common.config.MCRConfigurationLoaderFactory; import org.mycore.datamodel.classifications2.impl.MCRCategoryImpl; import org.mycore.frontend.classeditor.mocks.CategoryDAOMock; import com.google.gson.Gson; public class MCRCategoryJsonTest { @Test public void deserialize() throws Exception { final MCRConfigurationLoader configurationLoader = MCRConfigurationLoaderFactory.getConfigurationLoader(); MCRConfigurationBase.initialize(configurationLoader.loadDeprecated(), configurationLoader.load(), true); MCRConfiguration2.set("MCR.Metadata.DefaultLang", "de"); MCRConfiguration2.set("MCR.Category.DAO", CategoryDAOMock.class.getName()); SAXBuilder saxBuilder = new SAXBuilder(); Document doc = saxBuilder.build(getClass().getResourceAsStream("/classi/categoryJsonErr.xml")); String json = doc.getRootElement().getText(); Gson gson = MCRJSONManager.instance().createGson(); try { gson.fromJson(json, MCRCategoryImpl.class); System.out.println("FOO"); } catch (Exception e) { e.printStackTrace(); } } }
2,217
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
GsonSerializationTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/test/java/org/mycore/frontend/classeditor/json/GsonSerializationTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.json; import java.util.SortedSet; import java.util.TreeSet; import org.junit.Before; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationBase; import org.mycore.common.config.MCRConfigurationLoader; import org.mycore.common.config.MCRConfigurationLoaderFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.MCRLabel; import org.mycore.datamodel.classifications2.impl.MCRCategoryImpl; import org.mycore.frontend.classeditor.mocks.CategoryDAOMock; public class GsonSerializationTest { @Before public void init() { final MCRConfigurationLoader configurationLoader = MCRConfigurationLoaderFactory.getConfigurationLoader(); MCRConfigurationBase.initialize(configurationLoader.loadDeprecated(), configurationLoader.load(), true); MCRConfiguration2.set("MCR.Category.DAO", CategoryDAOMock.class.getName()); } protected MCRCategoryImpl createCateg(String rootID, String id2, String text) { MCRCategoryImpl mcrCategoryImpl = new MCRCategoryImpl(); MCRCategoryID id = new MCRCategoryID(rootID, id2); mcrCategoryImpl.setId(id); SortedSet<MCRLabel> labels = new TreeSet<>(); labels.add(new MCRLabel("de", text + "_de", "desc_" + text + "_de")); labels.add(new MCRLabel("en", text + "_en", "desc_" + text + "_en")); mcrCategoryImpl.setLabels(labels); return mcrCategoryImpl; } }
2,253
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
CategoryDAOMock.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/test/java/org/mycore/frontend/classeditor/mocks/CategoryDAOMock.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.mocks; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAO; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.MCRLabel; import org.mycore.frontend.classeditor.json.MCRJSONCategory; public class CategoryDAOMock implements MCRCategoryDAO { HashMap<MCRCategoryID, MCRCategory> categMap = null; HashMap<MCRCategoryID, MCRCategory> rootCategMap = null; private void buildTestCategs() { MCRJSONCategory root_01 = createCategory("rootID_01", "", null); MCRJSONCategory root_02 = createCategory("rootID_02", "", null); MCRJSONCategory categ_01 = createCategory("rootID_01", "categ_01", null); MCRJSONCategory categ_02 = createCategory("rootID_01", "categ_02", null); List<MCRCategory> children = new ArrayList<>(); children.add(categ_01); children.add(categ_02); root_01.setChildren(children); rootCategMap.put(root_01.getId(), root_01); rootCategMap.put(root_02.getId(), root_02); categMap.put(root_01.getId(), root_01); categMap.put(root_02.getId(), root_02); categMap.put(categ_01.getId(), categ_01); categMap.put(categ_02.getId(), categ_02); } public void init() { categMap = new HashMap<>(); rootCategMap = new HashMap<>(); buildTestCategs(); } public Set<MCRCategoryID> getIds() { return categMap.keySet(); } public Collection<MCRCategory> getCategs() { return categMap.values(); } private MCRJSONCategory createCategory(String rootID, String categID, MCRCategoryID parentID) { MCRCategoryID id = new MCRCategoryID(rootID, categID); SortedSet<MCRLabel> labels = new TreeSet<>(); labels.add(new MCRLabel("de", id + "_text", id + "_descr")); labels.add(new MCRLabel("en", id + "_text", id + "_descr")); MCRJSONCategory newCategory = new MCRJSONCategory(); newCategory.setId(id); newCategory.setLabels(labels); newCategory.setParentID(parentID); return newCategory; } @Override public MCRCategory addCategory(MCRCategoryID parentID, MCRCategory category) { categMap.put(category.getId(), category); return categMap.get(parentID); } @Override public MCRCategory addCategory(MCRCategoryID parentID, MCRCategory category, int position) { categMap.put(category.getId(), category); return categMap.get(parentID); } @Override public void deleteCategory(MCRCategoryID id) { MCRCategory mcrCategory = categMap.get(id); for (MCRCategory child : mcrCategory.getChildren()) { categMap.remove(child.getId()); } categMap.remove(id); } @Override public boolean exist(MCRCategoryID id) { return categMap.containsKey(id); } @Override public List<MCRCategory> getCategoriesByLabel(MCRCategoryID baseID, String lang, String text) { return null; } @Override public MCRCategory getCategory(MCRCategoryID id, int childLevel) { return categMap.get(id); } @Override public List<MCRCategory> getChildren(MCRCategoryID id) { return new ArrayList<>(); } @Override public List<MCRCategory> getParents(MCRCategoryID id) { return null; } @Override public List<MCRCategoryID> getRootCategoryIDs() { return null; } @Override public List<MCRCategory> getRootCategories() { return new ArrayList<>(rootCategMap.values()); } @Override public MCRCategory getRootCategory(MCRCategoryID baseID, int childLevel) { return null; } @Override public boolean hasChildren(MCRCategoryID id) { return false; } @Override public void moveCategory(MCRCategoryID id, MCRCategoryID newParentID) { } @Override public void moveCategory(MCRCategoryID id, MCRCategoryID newParentID, int index) { if (index < 0) { throw new IllegalArgumentException("Index should be greater than 0."); } } @Override public MCRCategory removeLabel(MCRCategoryID id, String lang) { return categMap.get(id); } @Override public Collection<MCRCategory> replaceCategory(MCRCategory newCategory) throws IllegalArgumentException { if (!categMap.containsKey(newCategory.getId())) { throw new IllegalArgumentException(); } categMap.put(newCategory.getId(), newCategory); return categMap.values(); } @Override public MCRCategory setLabel(MCRCategoryID id, MCRLabel label) { return categMap.get(id); } @Override public MCRCategory setLabels(MCRCategoryID id, SortedSet<MCRLabel> labels) { return categMap.get(id); } @Override public MCRCategory setURI(MCRCategoryID id, URI uri) { return categMap.get(id); } @Override public long getLastModified() { return 0; } @Override public List<MCRCategory> getCategoriesByLabel(String lang, String text) { return null; } @Override public long getLastModified(String root) { return 0; } }
6,274
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
CategoryLinkServiceMock.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/test/java/org/mycore/frontend/classeditor/mocks/CategoryLinkServiceMock.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.mocks; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.mycore.datamodel.classifications2.MCRCategLinkReference; import org.mycore.datamodel.classifications2.MCRCategLinkService; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.MCRCategoryLink; public class CategoryLinkServiceMock implements MCRCategLinkService { @Override public Map<MCRCategoryID, Boolean> hasLinks(MCRCategory category) { List<MCRCategory> categories; if (category == null) { categories = MCRCategoryDAOFactory.getInstance().getRootCategories(); } else { categories = category.getChildren(); } Map<MCRCategoryID, Boolean> linkMap = new HashMap<>(); int i = 0; for (MCRCategory mcrCategory : categories) { boolean haslink = false; if (i++ % 2 == 0) { haslink = true; } linkMap.put(mcrCategory.getId(), haslink); } return linkMap; } @Override public boolean hasLink(MCRCategory classif) { return false; } @Override public Map<MCRCategoryID, Number> countLinks(MCRCategory category, boolean childrenOnly) { return null; } @Override public Map<MCRCategoryID, Number> countLinksForType(MCRCategory category, String type, boolean childrenOnly) { return null; } @Override public Collection<String> getLinksFromCategory(MCRCategoryID id) { return null; } @Override public Collection<String> getLinksFromCategoryForType(MCRCategoryID id, String type) { return null; } @Override public void setLinks(MCRCategLinkReference objectReference, Collection<MCRCategoryID> categories) { } @Override public void deleteLinks(Collection<MCRCategLinkReference> ids) { } @Override public void deleteLink(MCRCategLinkReference id) { } @Override public boolean isInCategory(MCRCategLinkReference reference, MCRCategoryID id) { return false; } @Override public Collection<MCRCategoryID> getLinksFromReference(MCRCategLinkReference reference) { return null; } @Override public Collection<MCRCategLinkReference> getReferences(String type) { return null; } @Override public Collection<String> getTypes() { return null; } @Override public Collection<MCRCategoryLink> getLinks(String type) { return null; } }
3,487
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
LinkTableStoreMock.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/test/java/org/mycore/frontend/classeditor/mocks/LinkTableStoreMock.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.mocks; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.mycore.datamodel.common.MCRLinkTableInterface; public class LinkTableStoreMock implements MCRLinkTableInterface { @Override public void create(String from, String to, String type, String attr) { } @Override public void delete(String from, String to, String type) { } @Override public int countTo(String fromtype, String to, String type, String restriction) { return 0; } @Override public Map<String, Number> getCountedMapOfMCRTO(String mcrtoPrefix) { return new HashMap<>(); } @Override public Collection<String> getSourcesOf(String to, String type) { return new ArrayList<>(); } @Override public Collection<String> getDestinationsOf(String from, String type) { return new ArrayList<>(); } }
1,697
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRClassificationEditorResourceTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/test/java/org/mycore/frontend/classeditor/resources/MCRClassificationEditorResourceTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.resources; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.text.MessageFormat; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.jdom2.Document; import org.jdom2.input.SAXBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mycore.access.MCRAccessBaseImpl; import org.mycore.common.MCRJSONManager; import org.mycore.common.MCRTestCase; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.ifs2.MCRMetadataStore; import org.mycore.datamodel.ifs2.MCRStoreManager; import org.mycore.frontend.classeditor.MCRCategoryIDTypeAdapter; import org.mycore.frontend.classeditor.MCRCategoryListTypeAdapter; import org.mycore.frontend.classeditor.MCRCategoryTypeAdapter; import org.mycore.frontend.classeditor.MCRLabelSetTypeAdapter; import org.mycore.frontend.classeditor.json.MCRJSONCategory; import org.mycore.frontend.classeditor.mocks.CategoryDAOMock; import org.mycore.frontend.classeditor.mocks.CategoryLinkServiceMock; import org.mycore.frontend.classeditor.mocks.LinkTableStoreMock; import org.mycore.frontend.classeditor.wrapper.MCRCategoryListWrapper; import org.mycore.frontend.jersey.filter.MCRSessionHookFilter; import org.mycore.frontend.jersey.resources.MCRJerseyTestFeature; import jakarta.ws.rs.client.Entity; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; public class MCRClassificationEditorResourceTest extends MCRTestCase { private MCRJerseyTestFeature jersey; private CategoryDAOMock categDAO; static Logger LOGGER = LogManager.getLogger(MCRClassificationEditorResourceTest.class); @Override protected Map<String, String> getTestProperties() { Map<String, String> map = super.getTestProperties(); map.put("MCR.Metadata.Store.BaseDir", "/tmp"); map.put("MCR.Metadata.Store.SVNBase", "/tmp/versions"); map.put("MCR.IFS2.Store.ClasseditorTempStore.BaseDir", "jimfs:"); map.put("MCR.IFS2.Store.ClasseditorTempStore.SlotLayout", "4-2-2"); map.put("MCR.EventHandler.MCRObject.2.Class", "org.mycore.datamodel.common.MCRXMLMetadataEventHandler"); map.put("MCR.Persistence.LinkTable.Store.Class", LinkTableStoreMock.class.getName()); map.put("MCR.Category.DAO", CategoryDAOMock.class.getName()); map.put("MCR.Category.LinkService", CategoryLinkServiceMock.class.getName()); map.put("MCR.Access.Class", MCRAccessBaseImpl.class.getName()); map.put("MCR.Access.Cache.Size", "200"); return map; } @Before public void init() throws Exception { jersey = new MCRJerseyTestFeature(); jersey.setUp(Set.of( MCRClassificationEditorResource.class, MCRSessionHookFilter.class, MultiPartFeature.class)); MCRJSONManager mg = MCRJSONManager.instance(); mg.registerAdapter(new MCRCategoryTypeAdapter()); mg.registerAdapter(new MCRCategoryIDTypeAdapter()); mg.registerAdapter(new MCRLabelSetTypeAdapter()); mg.registerAdapter(new MCRCategoryListTypeAdapter()); try { MCRStoreManager.createStore("ClasseditorTempStore", MCRMetadataStore.class); } catch (ReflectiveOperationException e) { LOGGER.error("while creating store ClasseditorTempStore", e); } try { /* its important to set the daomock via this method because the factory could be called * by a previous test. In this case a class cast exception occur because MCRCategoryDAOImpl * was loaded. */ MCRCategoryDAOFactory.set(CategoryDAOMock.class); categDAO = (CategoryDAOMock) MCRCategoryDAOFactory.getInstance(); categDAO.init(); } catch (Exception exc) { fail(); } } @After public void cleanUp() throws Exception { MCRStoreManager.removeStore("ClasseditorTempStore"); this.jersey.tearDown(); } @Test public void getRootCategories() { final String categoryJsonStr = jersey.target("classifications").request().get(String.class); MCRCategoryListWrapper categListWrapper = MCRJSONManager.instance().createGson().fromJson(categoryJsonStr, MCRCategoryListWrapper.class); List<MCRCategory> categList = categListWrapper.getList(); assertEquals("Wrong number of root categories.", 2, categList.size()); } @Test public void getSingleCategory() { Collection<MCRCategory> categs = categDAO.getCategs(); for (MCRCategory mcrCategory : categs) { MCRCategoryID id = mcrCategory.getId(); String path = id.getRootID(); String categID = id.getId(); if (categID != null && !categID.isEmpty()) { path = path + "/" + categID; } String categoryJsonStr = jersey.target("/classifications/" + path).request().get(String.class); MCRJSONCategory retrievedCateg = MCRJSONManager.instance().createGson().fromJson(categoryJsonStr, MCRJSONCategory.class); String errorMsg = new MessageFormat("We want to retrieve the category {0} but it was {1}", Locale.ROOT) .format(new Object[] { id, retrievedCateg.getId() }); assertEquals(errorMsg, id, retrievedCateg.getId()); } } @Test public void saveClassification() throws Exception { SAXBuilder saxBuilder = new SAXBuilder(); Document doc = saxBuilder.build(getClass().getResourceAsStream("/classi/classiEditor_OneClassification.xml")); String json = doc.getRootElement().getText(); Response response = jersey.target("/classifications/save").request().post(Entity.json(json)); assertEquals(Status.OK.getStatusCode(), response.getStatus()); } @Test public void saveClassiWithSub() throws Exception { SAXBuilder saxBuilder = new SAXBuilder(); Document doc = saxBuilder.build(getClass().getResourceAsStream("/classi/classiEditor_ClassiSub.xml")); String json = doc.getRootElement().getText(); Response response = jersey.target("/classifications/save").request().post(Entity.json(json)); assertEquals(Status.OK.getStatusCode(), response.getStatus()); } @Test public void saveClass2ndSub() throws Exception { SAXBuilder saxBuilder = new SAXBuilder(); Document doc = saxBuilder.build(getClass().getResourceAsStream("/classi/classiEditor_Classi2Sub.xml")); String json = doc.getRootElement().getText(); Response response = jersey.target("/classifications/save").request().post(Entity.json(json)); assertEquals(Status.OK.getStatusCode(), response.getStatus()); } @Test public void saveClass2ndSubJsonErr() throws Exception { SAXBuilder saxBuilder = new SAXBuilder(); Document doc = saxBuilder.build(getClass().getResourceAsStream("/classi/classiEditor_Classi2Sub_JsonErr.xml")); String json = doc.getRootElement().getText(); Response response = jersey.target("/classifications/save").request().post(Entity.json(json)); assertEquals(Status.OK.getStatusCode(), response.getStatus()); } @Test public void forceException() { String json = """ [{ "item":{"id":{"rootid":"rootID_01","categid":"categ_01"}}, "state":"update", "parentId":{"rootid":"rootID_02"}, "depthLevel":3, "index":-1 }] """; Response response = jersey.target("/classifications/save").request().post(Entity.json(json)); assertEquals(500, response.getStatus()); } }
8,915
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCategoryIDTypeAdapter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/MCRCategoryIDTypeAdapter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_CATEGID; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_ROOTID; import java.lang.reflect.Type; import java.util.Objects; import org.mycore.common.MCRJSONTypeAdapter; import org.mycore.datamodel.classifications2.MCRCategoryID; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; public class MCRCategoryIDTypeAdapter extends MCRJSONTypeAdapter<MCRCategoryID> { @Override public MCRCategoryID deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject idJsonObj = json.getAsJsonObject(); JsonElement rootIDObj = idJsonObj.get(PROP_ROOTID); JsonElement categIDObj = idJsonObj.get(PROP_CATEGID); String rootID = rootIDObj.getAsString(); String categID = categIDObj == null ? "" : categIDObj.getAsString(); return new MCRCategoryID(rootID, categID); } @Override public JsonElement serialize(MCRCategoryID id, Type typeOfSrc, JsonSerializationContext context) { String rootID = id.getRootID(); String categID = id.getId(); JsonObject idJsonObj = new JsonObject(); idJsonObj.addProperty(PROP_ROOTID, rootID); if (categID != null && !Objects.equals(categID, "")) { idJsonObj.addProperty(PROP_CATEGID, categID); } return idJsonObj; } }
2,384
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCategoryTypeAdapter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/MCRCategoryTypeAdapter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_CHILDREN; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_HAS_LINK; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_ID; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_LABELS; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_PARENTID; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_POSITION; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_URISTR; import java.lang.reflect.Type; import java.net.URI; import java.util.List; import java.util.Map; import java.util.SortedSet; import org.mycore.common.MCRJSONTypeAdapter; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.classifications2.MCRCategLinkService; import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.MCRLabel; import org.mycore.frontend.classeditor.json.MCRJSONCategory; import org.mycore.frontend.classeditor.wrapper.MCRCategoryListWrapper; import org.mycore.frontend.classeditor.wrapper.MCRLabelSetWrapper; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; public class MCRCategoryTypeAdapter extends MCRJSONTypeAdapter<MCRJSONCategory> { private MCRCategLinkService linkService; @Override public MCRJSONCategory deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject categJsonObject = json.getAsJsonObject(); MCRJSONCategory deserializedCateg = new MCRJSONCategory(); JsonElement idJsonElement = categJsonObject.get(PROP_ID); if (idJsonElement != null) { MCRCategoryID id = context.deserialize(idJsonElement, MCRCategoryID.class); deserializedCateg.setId(id); } JsonElement parentIdJsonElement = categJsonObject.get(PROP_PARENTID); if (parentIdJsonElement != null) { MCRCategoryID parentId = context.deserialize(parentIdJsonElement, MCRCategoryID.class); deserializedCateg.setParentID(parentId); } JsonElement positionJsonElem = categJsonObject.get(PROP_POSITION); if (positionJsonElem != null) { deserializedCateg.setPositionInParent(positionJsonElem.getAsInt()); } JsonElement labelSetWrapperElem = categJsonObject.get(PROP_LABELS); if (labelSetWrapperElem != null) { MCRLabelSetWrapper labelSetWrapper = context.deserialize(labelSetWrapperElem, MCRLabelSetWrapper.class); deserializedCateg.setLabels(labelSetWrapper.getSet()); } JsonElement uriJsonElement = categJsonObject.get(PROP_URISTR); if (uriJsonElement != null) { String uriStr = uriJsonElement.getAsString(); deserializedCateg.setURI(URI.create(uriStr)); } return deserializedCateg; } @Override public JsonElement serialize(MCRJSONCategory category, Type arg1, JsonSerializationContext contextSerialization) { JsonObject rubricJsonObject = new JsonObject(); MCRCategoryID id = category.getId(); if (id != null) { rubricJsonObject.add(PROP_ID, contextSerialization.serialize(id)); } SortedSet<MCRLabel> labels = category.getLabels(); rubricJsonObject.add(PROP_LABELS, contextSerialization.serialize(new MCRLabelSetWrapper(labels))); URI uri = category.getURI(); if (uri != null) { rubricJsonObject.addProperty(PROP_URISTR, uri.toString()); } if (category.hasChildren()) { List<MCRCategory> children = category.getChildren(); Map<MCRCategoryID, Boolean> linkMap = getLinkService().hasLinks(category); if (linkMap.containsValue(true)) { rubricJsonObject.addProperty(PROP_HAS_LINK, true); } rubricJsonObject.add(PROP_CHILDREN, contextSerialization.serialize(new MCRCategoryListWrapper(children, linkMap))); } return rubricJsonObject; } private MCRCategLinkService getLinkService() { if (linkService == null) { linkService = MCRConfiguration2.<MCRCategLinkService>getInstanceOf("Category.Link.Service") .orElseGet(MCRCategLinkServiceFactory::getInstance); } return linkService; } }
5,545
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRLabelSetTypeAdapter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/MCRLabelSetTypeAdapter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_DESCRIPTION; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_LANG; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_TEXT; import java.lang.reflect.Type; import java.util.Objects; import java.util.SortedSet; import java.util.TreeSet; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRJSONTypeAdapter; import org.mycore.datamodel.classifications2.MCRLabel; import org.mycore.frontend.classeditor.wrapper.MCRLabelSetWrapper; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; public class MCRLabelSetTypeAdapter extends MCRJSONTypeAdapter<MCRLabelSetWrapper> { private static final Logger LOGGER = LogManager.getLogger(MCRLabelSetTypeAdapter.class); @Override public JsonElement serialize(MCRLabelSetWrapper labelSetWrapper, Type typeOfSrc, JsonSerializationContext context) { return labelsToJsonArray(labelSetWrapper.getSet()); } private JsonArray labelsToJsonArray(SortedSet<MCRLabel> labels) { JsonArray labelJsonArray = new JsonArray(); for (MCRLabel label : labels) { JsonObject labelJsonObj = labelToJsonObj(label); labelJsonArray.add(labelJsonObj); } return labelJsonArray; } private JsonObject labelToJsonObj(MCRLabel label) { JsonObject labelJsonObj = new JsonObject(); labelJsonObj.addProperty(PROP_LANG, label.getLang()); labelJsonObj.addProperty(PROP_TEXT, label.getText()); String description = label.getDescription(); if (description != null && !Objects.equals(description, "")) { labelJsonObj.addProperty(PROP_DESCRIPTION, description); } return labelJsonObj; } @Override public MCRLabelSetWrapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { SortedSet<MCRLabel> labels = new TreeSet<>(); for (JsonElement jsonElement : json.getAsJsonArray()) { JsonObject labelJsonObject = jsonElement.getAsJsonObject(); MCRLabel label = jsonLabelToMCRLabel(labelJsonObject); if (label != null) { labels.add(label); } else { LOGGER.warn("Unable to add label with empty lang or text: {}", labelJsonObject); } } return new MCRLabelSetWrapper(labels); } private MCRLabel jsonLabelToMCRLabel(JsonObject labelJsonObject) { String lang = labelJsonObject.get(PROP_LANG).getAsString(); String text = labelJsonObject.get(PROP_TEXT).getAsString(); JsonElement jsonElement = labelJsonObject.get(PROP_DESCRIPTION); String description = null; if (jsonElement != null) { description = jsonElement.getAsString(); } if (lang == null || lang.trim().equals("") || text == null || text.trim().equals("")) { return null; } return new MCRLabel(lang, text, description); } }
4,099
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCategoryListTypeAdapter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/MCRCategoryListTypeAdapter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_HAS_CHILDREN; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_HAS_LINK; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_ID; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_LABELS; import static org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper.PROP_URISTR; import java.lang.reflect.Type; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.SortedSet; import org.mycore.common.MCRJSONTypeAdapter; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.MCRLabel; import org.mycore.frontend.classeditor.json.MCRJSONCategory; import org.mycore.frontend.classeditor.wrapper.MCRCategoryListWrapper; import org.mycore.frontend.classeditor.wrapper.MCRLabelSetWrapper; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import jakarta.ws.rs.WebApplicationException; public class MCRCategoryListTypeAdapter extends MCRJSONTypeAdapter<MCRCategoryListWrapper> { private JsonSerializationContext serializationContext; @Override public JsonElement serialize(MCRCategoryListWrapper categListWrapper, Type typeOfSrc, JsonSerializationContext context) { this.serializationContext = context; Map<MCRCategoryID, Boolean> linkMap = categListWrapper.getLinkMap(); if (linkMap == null) { throw new WebApplicationException("For serializing link map must not be null."); } return categListToJsonArray(categListWrapper.getList(), linkMap); } private JsonElement categListToJsonArray(List<MCRCategory> categList, Map<MCRCategoryID, Boolean> linkMap) { JsonArray categJsonArray = new JsonArray(); for (MCRCategory categ : categList) { Boolean hasLink = linkMap.get(categ.getId()); JsonElement element = createCategRefJSONObj(categ, hasLink); categJsonArray.add(element); } return categJsonArray; } private JsonElement createCategRefJSONObj(MCRCategory categ, Boolean hasLink) { JsonObject categRefJsonObject = new JsonObject(); categRefJsonObject.add(PROP_ID, serializationContext.serialize(categ.getId())); SortedSet<MCRLabel> labels = categ.getLabels(); categRefJsonObject.add(PROP_LABELS, serializationContext.serialize(new MCRLabelSetWrapper(labels))); URI uri = categ.getURI(); if (uri != null) { categRefJsonObject.addProperty(PROP_URISTR, uri.toString()); } categRefJsonObject.addProperty(PROP_HAS_CHILDREN, categ.hasChildren()); categRefJsonObject.addProperty(PROP_HAS_LINK, hasLink); return categRefJsonObject; } @Override public MCRCategoryListWrapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { List<MCRCategory> categList = new ArrayList<>(); for (JsonElement categRef : json.getAsJsonArray()) { JsonObject categRefJsonObject = categRef.getAsJsonObject(); MCRCategory categ = context.deserialize(categRefJsonObject, MCRJSONCategory.class); categList.add(categ); } return new MCRCategoryListWrapper(categList); } }
4,428
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRLabelSetWrapper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/wrapper/MCRLabelSetWrapper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.wrapper; import java.util.SortedSet; import org.mycore.datamodel.classifications2.MCRLabel; public class MCRLabelSetWrapper { private SortedSet<MCRLabel> labelSet; public MCRLabelSetWrapper(SortedSet<MCRLabel> labels) { this.labelSet = labels; } public SortedSet<MCRLabel> getSet() { return labelSet; } }
1,115
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCategoryListWrapper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/wrapper/MCRCategoryListWrapper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.wrapper; import java.util.List; import java.util.Map; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryID; public class MCRCategoryListWrapper { private List<MCRCategory> categList; private Map<MCRCategoryID, Boolean> linkMap = null; public MCRCategoryListWrapper(List<MCRCategory> categList) { this.categList = categList; } public MCRCategoryListWrapper(List<MCRCategory> categList, Map<MCRCategoryID, Boolean> linkMap) { this.categList = categList; this.linkMap = linkMap; } public List<MCRCategory> getList() { return categList; } public Map<MCRCategoryID, Boolean> getLinkMap() { return linkMap; } }
1,525
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJSONCategoryHelper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/json/MCRJSONCategoryHelper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.json; public final class MCRJSONCategoryHelper { public static String PROP_ID = "id"; public static String PROP_PARENTID = "parentid"; public static String PROP_POSITION = "position"; public static String PROP_ROOTID = "rootid"; public static String PROP_CATEGID = "categid"; public static String PROP_LABELS = "labels"; public static String PROP_URISTR = "uri"; public static String PROP_CHILDREN = "children"; public static String PROP_HAS_CHILDREN = "haschildren"; public static String PROP_HAS_LINK = "haslink"; public static String PROP_LANG = "lang"; public static String PROP_TEXT = "text"; public static String PROP_DESCRIPTION = "description"; private MCRJSONCategoryHelper() { } }
1,532
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJSONCategoriesSaveList.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/json/MCRJSONCategoriesSaveList.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.json; import java.util.ArrayList; import java.util.Objects; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryID; import jakarta.ws.rs.WebApplicationException; public class MCRJSONCategoriesSaveList { ArrayList<CategorySaveElement> updateList = new ArrayList<>(); ArrayList<CategorySaveElement> deleteList = new ArrayList<>(); public void add(MCRCategory categ, MCRCategoryID parentID, int index, String status) throws WebApplicationException { if (Objects.equals(status, "updated")) { updateList.add(new CategorySaveElement(categ, parentID, index)); } else if (Objects.equals(status, "deleted")) { deleteList.add(new CategorySaveElement(categ, parentID, index)); } else { throw new WebApplicationException("Unknown status."); } } private static class CategorySaveElement { private MCRCategory categ; private MCRCategoryID parentID; private int index; CategorySaveElement(MCRCategory categ, MCRCategoryID parentID, int index) { this.categ = categ; this.parentID = parentID; this.index = index; } } }
2,018
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJSONCategory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/json/MCRJSONCategory.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.json; import java.util.List; import java.util.Optional; import java.util.SortedSet; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.MCRLabel; import org.mycore.datamodel.classifications2.impl.MCRCategoryImpl; /** * GSON Category abstraction. * * @author Chi */ public class MCRJSONCategory implements MCRCategory { private MCRCategoryImpl category; private Boolean hasChildren = null; private int positionInParent; private MCRCategoryID parentID; public void setParent(MCRCategory parent) { category.setParent(parent); } public void setChildren(List<MCRCategory> children) { category.setChildren(children); } public MCRJSONCategory() { category = new MCRCategoryImpl(); } public MCRJSONCategory(MCRCategory category) { this.category = (MCRCategoryImpl) category; } public int getLeft() { return category.getLeft(); } public int getLevel() { return category.getLevel(); } public void setHasChildren(boolean hasChildren) { this.hasChildren = hasChildren; } public boolean hasChildren() { if (hasChildren == null) { hasChildren = category.hasChildren(); } return hasChildren; } public List<MCRCategory> getChildren() { return category.getChildren(); } public int getPositionInParent() { return positionInParent; } public void setPositionInParent(int positionInParent) { this.positionInParent = positionInParent; } public MCRCategoryID getId() { return category.getId(); } public SortedSet<MCRLabel> getLabels() { return category.getLabels(); } public MCRCategory getRoot() { return category.getRoot(); } public java.net.URI getURI() { return category.getURI(); } public void setId(MCRCategoryID id) { category.setId(id); } public void setURI(java.net.URI uri) { category.setURI(uri); } public MCRCategory getParent() { return category.getParent(); } public Optional<MCRLabel> getCurrentLabel() { return category.getCurrentLabel(); } public void setLabels(SortedSet<MCRLabel> labels) { category.setLabels(labels); } public Optional<MCRLabel> getLabel(String lang) { return category.getLabel(lang); } public void setParentID(MCRCategoryID parentID) { this.parentID = parentID; } public MCRCategoryID getParentID() { return parentID; } @Override public boolean isClassification() { return category.isClassification(); } @Override public boolean isCategory() { return category.isCategory(); } public MCRCategoryImpl asMCRImpl() { return category; } }
3,732
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRClassificationListener.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/listener/MCRClassificationListener.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.listener; import org.mycore.common.MCRJSONManager; import org.mycore.frontend.classeditor.MCRCategoryIDTypeAdapter; import org.mycore.frontend.classeditor.MCRCategoryListTypeAdapter; import org.mycore.frontend.classeditor.MCRCategoryTypeAdapter; import org.mycore.frontend.classeditor.MCRLabelSetTypeAdapter; import jakarta.servlet.ServletContextEvent; import jakarta.servlet.ServletContextListener; import jakarta.ws.rs.ext.Provider; @Provider public class MCRClassificationListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent arg0) { MCRJSONManager mg = MCRJSONManager.instance(); mg.registerAdapter(new MCRCategoryTypeAdapter()); mg.registerAdapter(new MCRCategoryIDTypeAdapter()); mg.registerAdapter(new MCRLabelSetTypeAdapter()); mg.registerAdapter(new MCRCategoryListTypeAdapter()); } @Override public void contextDestroyed(ServletContextEvent arg0) { //do nothing } }
1,773
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCategUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/utils/MCRCategUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.utils; import java.util.HashMap; import java.util.SortedSet; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.MCRLabel; import org.mycore.frontend.classeditor.json.MCRJSONCategory; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonStreamParser; public class MCRCategUtils { public static MCRCategory newCategory(MCRCategoryID id, SortedSet<MCRLabel> labels, MCRCategoryID mcrCategoryID) { MCRJSONCategory category = new MCRJSONCategory(); category.setId(id); category.setLabels(labels); category.setParentID(mcrCategoryID); return category; } public static String maskCategID(MCRCategoryID categoryID) { String rootID = categoryID.getRootID(); String id = categoryID.getId(); return rootID + "." + (id == null ? "" : id); } public static HashMap<MCRCategoryID, String> getCategoryIDMap(String json) { HashMap<MCRCategoryID, String> categories = new HashMap<>(); JsonStreamParser jsonStreamParser = new JsonStreamParser(json); if (jsonStreamParser.hasNext()) { JsonArray saveObjArray = jsonStreamParser.next().getAsJsonArray(); for (JsonElement jsonElement : saveObjArray) { //jsonObject.item.id.rootid JsonObject root = jsonElement.getAsJsonObject(); String rootId = root.getAsJsonObject("item").getAsJsonObject("id").getAsJsonPrimitive("rootid") .getAsString(); String state = root.getAsJsonPrimitive("state").getAsString(); JsonElement parentIdJSON = root.get("parentId"); if (parentIdJSON != null && parentIdJSON.isJsonPrimitive() && "_placeboid_".equals(parentIdJSON.getAsString())) { state = "new"; } categories.put(MCRCategoryID.rootID(rootId), state); } } else { return null; } return categories; } }
2,953
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
TestResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/resources/TestResource.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.resources; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; @Path("xxx") public class TestResource { @GET @Produces(MediaType.TEXT_PLAIN) @Path("test") public String test() { return "Hallo"; } }
1,066
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRClassificationEditorResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/resources/MCRClassificationEditorResource.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.resources; import static org.mycore.access.MCRAccessManager.PERMISSION_DELETE; import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE; import java.io.IOException; import java.io.InputStream; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.UUID; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.params.ModifiableSolrParams; import org.glassfish.jersey.media.multipart.FormDataParam; import org.mycore.access.MCRAccessException; import org.mycore.access.MCRAccessManager; import org.mycore.common.MCRJSONManager; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.classifications2.MCRCategLinkService; import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAO; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.utils.MCRClassificationUtils; import org.mycore.frontend.classeditor.access.MCRClassificationWritePermission; import org.mycore.frontend.classeditor.access.MCRNewClassificationPermission; import org.mycore.frontend.classeditor.json.MCRJSONCategory; import org.mycore.frontend.classeditor.json.MCRJSONCategoryHelper; import org.mycore.frontend.classeditor.wrapper.MCRCategoryListWrapper; import org.mycore.frontend.jersey.filter.access.MCRRestrictedAccess; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.classification.MCRSolrClassificationUtil; import org.mycore.solr.search.MCRSolrSearchUtils; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.google.gson.JsonStreamParser; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.core.UriInfo; /** * This class is responsible for CRUD-operations of MCRCategories. It accepts * JSON objects of the form <code> * [{ "ID":{"rootID":"abcd","categID":"1234"} * "label":[ * {"lang":"de","text":"Rubriken Test 2 fuer MyCoRe","descriptions":"test de"}, * {"lang":"en","text":"Rubric test 2 for MyCoRe","descriptions":"test en"} * ], * "parentID":{"rootID":"abcd","categID":"parent"} * "children:"URL" * * } * ... * ] * </code> * * @author chi * */ @Path("classifications") public class MCRClassificationEditorResource { private static final MCRCategoryDAO CATEGORY_DAO = MCRCategoryDAOFactory.getInstance(); private static final MCRCategLinkService CATEG_LINK_SERVICE = MCRCategLinkServiceFactory.getInstance(); @Context UriInfo uriInfo; @GET @Produces(MediaType.TEXT_PLAIN) @Path("test") public String test() { return "Hallo"; } /** * @param rootidStr * rootID.categID */ @GET @Path("{rootidStr}") @Produces(MediaType.APPLICATION_JSON) public String get(@PathParam("rootidStr") String rootidStr) { if (rootidStr == null || Objects.equals(rootidStr, "")) { throw new WebApplicationException(Status.NOT_FOUND); } MCRCategoryID id = MCRCategoryID.rootID(rootidStr); return getCategory(id); } /** * @param rootidStr * rootID.categID */ @GET @Path("{rootidStr}/{categidStr}") @Produces(MediaType.APPLICATION_JSON) public String get(@PathParam("rootidStr") String rootidStr, @PathParam("categidStr") String categidStr) { if (rootidStr == null || Objects.equals(rootidStr, "") || categidStr == null || Objects.equals(categidStr, "")) { throw new WebApplicationException(Status.NOT_FOUND); } MCRCategoryID id = new MCRCategoryID(rootidStr, categidStr); return getCategory(id); } @GET @Path("newID/{rootID}") @Produces(MediaType.APPLICATION_JSON) public String newIDJson(@PathParam("rootID") String rootID) { Gson gson = MCRJSONManager.instance().createGson(); return gson.toJson(newRandomUUID(rootID)); } @GET @Path("newID") @MCRRestrictedAccess(MCRNewClassificationPermission.class) @Produces(MediaType.APPLICATION_JSON) public String newRootIDJson() { Gson gson = MCRJSONManager.instance().createGson(); return gson.toJson(newRootID()); } @GET @Path("export/{rootidStr}") @Produces(MediaType.APPLICATION_XML) public String export(@PathParam("rootidStr") String rootidStr) { if (rootidStr == null || Objects.equals(rootidStr, "")) { throw new WebApplicationException(Status.NOT_FOUND); } String classAsString = MCRClassificationUtils.asString(rootidStr); if (classAsString == null) { throw new WebApplicationException(Status.NOT_FOUND); } return classAsString; } @GET @Produces(MediaType.APPLICATION_JSON) public Response getClassification() { Gson gson = MCRJSONManager.instance().createGson(); List<MCRCategory> rootCategories = new ArrayList<>(CATEGORY_DAO.getRootCategories()); rootCategories.removeIf( category -> !MCRAccessManager.checkPermission(category.getId().getRootID(), PERMISSION_WRITE)); if (rootCategories.isEmpty() && !MCRAccessManager.checkPermission(MCRClassificationUtils.CREATE_CLASS_PERMISSION)) { return Response.status(Status.UNAUTHORIZED).build(); } Map<MCRCategoryID, Boolean> linkMap = CATEG_LINK_SERVICE.hasLinks(null); String json = gson.toJson(new MCRCategoryListWrapper(rootCategories, linkMap)); return Response.ok(json).build(); } @DELETE @Consumes(MediaType.APPLICATION_JSON) public Response deleteCateg(String json) { MCRJSONCategory category = parseJson(json); DeleteOp deleteOp = new DeleteOp(category); deleteOp.run(); return deleteOp.getResponse(); } @POST @Path("save") @MCRRestrictedAccess(MCRClassificationWritePermission.class) @Consumes(MediaType.APPLICATION_JSON) public Response save(String json) { JsonStreamParser jsonStreamParser = new JsonStreamParser(json); if (jsonStreamParser.hasNext()) { JsonArray saveObjArray = jsonStreamParser.next().getAsJsonArray(); List<JsonObject> saveList = new ArrayList<>(); for (JsonElement jsonElement : saveObjArray) { saveList.add(jsonElement.getAsJsonObject()); } saveList.sort(new IndexComperator()); for (JsonObject jsonObject : saveList) { String status = getStatus(jsonObject); SaveElement categ = getCateg(jsonObject); MCRJSONCategory parsedCateg = parseJson(categ.getJson()); if (Objects.equals(status, "update")) { new UpdateOp(parsedCateg, jsonObject).run(); } else if (Objects.equals(status, "delete")) { deleteCateg(categ.getJson()); } else { return Response.status(Status.BAD_REQUEST).build(); } } // Status.CONFLICT return Response.status(Status.OK).build(); } else { return Response.status(Status.BAD_REQUEST).build(); } } @POST @Path("import") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.TEXT_HTML) public Response importClassification(@FormDataParam("classificationFile") InputStream uploadedInputStream) { try { MCRClassificationUtils.fromStream(uploadedInputStream); } catch (MCRAccessException accessExc) { return Response.status(Status.UNAUTHORIZED).build(); } catch (Exception exc) { throw new WebApplicationException(exc); } // This is a hack to support iframe loading via ajax. // The benefit is to load file input form data without reloading the page. // Maybe its better to create a separate method importClassificationIFrame. // @see http://livedocs.dojotoolkit.org/dojo/io/iframe - Additional Information return Response.ok("<html><body><textarea>200</textarea></body></html>").build(); } @GET @Path("filter/{text}") @Produces(MediaType.APPLICATION_JSON) public Response filter(@PathParam("text") String text) { SolrClient solrClient = MCRSolrClassificationUtil.getCore().getClient(); ModifiableSolrParams p = new ModifiableSolrParams(); p.set("q", "*" + text + "*"); p.set("fl", "id,ancestors"); JsonArray docList = new JsonArray(); MCRSolrSearchUtils.stream(solrClient, p).flatMap(document -> { List<String> ids = new ArrayList<>(); ids.add(document.getFirstValue("id").toString()); Collection<Object> fieldValues = document.getFieldValues("ancestors"); if (fieldValues != null) { for (Object anc : fieldValues) { ids.add(anc.toString()); } } return ids.stream(); }).distinct().map(JsonPrimitive::new).forEach(docList::add); return Response.ok().entity(docList.toString()).build(); } @GET @Path("link/{id}") @Produces(MediaType.APPLICATION_JSON) public Response retrieveLinkedObjects(@PathParam("id") String id, @QueryParam("start") Integer start, @QueryParam("rows") Integer rows) throws SolrServerException, IOException { // do solr query SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient(); ModifiableSolrParams params = new ModifiableSolrParams(); params.set("start", start != null ? start : 0); params.set("rows", rows != null ? rows : 50); params.set("fl", "id"); String configQuery = MCRConfiguration2.getString("MCR.Solr.linkQuery").orElse("category.top:{0}"); String query = new MessageFormat(configQuery, Locale.ROOT).format(new String[] { id.replaceAll(":", "\\\\:") }); params.set("q", query); QueryResponse solrResponse = solrClient.query(params); SolrDocumentList solrResults = solrResponse.getResults(); // build json response JsonObject response = new JsonObject(); response.addProperty("numFound", solrResults.getNumFound()); response.addProperty("start", solrResults.getStart()); JsonArray docList = new JsonArray(); for (SolrDocument doc : solrResults) { docList.add(new JsonPrimitive((String) doc.getFieldValue("id"))); } response.add("docs", docList); return Response.ok().entity(response.toString()).build(); } protected MCRCategoryID newRootID() { String uuid = UUID.randomUUID().toString().replaceAll("-", ""); return MCRCategoryID.rootID(uuid); } private MCRCategoryID newRandomUUID(String rootID) { String newRootID = rootID; if (rootID == null) { newRootID = UUID.randomUUID().toString(); } return new MCRCategoryID(newRootID, UUID.randomUUID().toString()); } private String getCategory(MCRCategoryID id) { if (!CATEGORY_DAO.exist(id)) { throw new WebApplicationException(Status.NOT_FOUND); } MCRCategory category = CATEGORY_DAO.getCategory(id, 1); if (!(category instanceof MCRJSONCategory)) { category = new MCRJSONCategory(category); } Gson gson = MCRJSONManager.instance().createGson(); return gson.toJson(category); } private SaveElement getCateg(JsonElement jsonElement) { JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonObject categ = jsonObject.get("item").getAsJsonObject(); JsonElement parentID = jsonObject.get("parentId"); JsonElement position = jsonObject.get("index"); boolean hasParent = false; if (parentID != null && !parentID.toString().contains("_placeboid_") && position != null) { categ.add(MCRJSONCategoryHelper.PROP_PARENTID, parentID); categ.add(MCRJSONCategoryHelper.PROP_POSITION, position); hasParent = true; } return new SaveElement(categ.toString(), hasParent); } private String getStatus(JsonElement jsonElement) { return jsonElement.getAsJsonObject().get("state").getAsString(); } private boolean isAdded(JsonElement jsonElement) { JsonElement added = jsonElement.getAsJsonObject().get("added"); return added != null && jsonElement.getAsJsonObject().get("added").getAsBoolean(); } private MCRJSONCategory parseJson(String json) { Gson gson = MCRJSONManager.instance().createGson(); return gson.fromJson(json, MCRJSONCategory.class); } protected String buildJsonError(String errorType, MCRCategoryID mcrCategoryID) { Gson gson = MCRJSONManager.instance().createGson(); JsonObject error = new JsonObject(); error.addProperty("type", errorType); error.addProperty("rootid", mcrCategoryID.getRootID()); error.addProperty("categid", mcrCategoryID.getId()); return gson.toJson(error); } private static class SaveElement { private String categJson; private boolean hasParent; SaveElement(String categJson, boolean hasParent) { this.setCategJson(categJson); this.setHasParent(hasParent); } private void setHasParent(boolean hasParent) { this.hasParent = hasParent; } @SuppressWarnings("unused") public boolean hasParent() { return hasParent; } private void setCategJson(String categJson) { this.categJson = categJson; } public String getJson() { return categJson; } } private static class IndexComperator implements Comparator<JsonElement> { @Override public int compare(JsonElement jsonElement1, JsonElement jsonElement2) { if (!jsonElement1.isJsonObject()) { return 1; } if (!jsonElement2.isJsonObject()) { return -1; } // compare level first JsonPrimitive depthLevel1 = jsonElement1.getAsJsonObject().getAsJsonPrimitive("depthLevel"); JsonPrimitive depthLevel2 = jsonElement2.getAsJsonObject().getAsJsonPrimitive("depthLevel"); if (depthLevel1 == null) { return 1; } if (depthLevel2 == null) { return -1; } if (depthLevel1.getAsInt() != depthLevel2.getAsInt()) { return Integer.compare(depthLevel1.getAsInt(), depthLevel2.getAsInt()); } // compare index JsonPrimitive index1 = jsonElement1.getAsJsonObject().getAsJsonPrimitive("index"); JsonPrimitive index2 = jsonElement2.getAsJsonObject().getAsJsonPrimitive("index"); if (index1 == null) { return 1; } if (index2 == null) { return -1; } return Integer.compare(index1.getAsInt(), index2.getAsInt()); } } interface OperationInSession { void run(); } private static class DeleteOp implements OperationInSession { private MCRJSONCategory category; private Response response; DeleteOp(MCRJSONCategory category) { this.category = category; } @Override public void run() { MCRCategoryID categoryID = category.getId(); if (CATEGORY_DAO.exist(categoryID)) { if (categoryID.isRootID() && !MCRAccessManager.checkPermission(categoryID.getRootID(), PERMISSION_DELETE)) { throw new WebApplicationException(Status.UNAUTHORIZED); } CATEGORY_DAO.deleteCategory(categoryID); setResponse(Response.status(Status.GONE).build()); } else { setResponse(Response.notModified().build()); } } public Response getResponse() { return response; } private void setResponse(Response response) { this.response = response; } } private class UpdateOp implements OperationInSession { private MCRJSONCategory category; private JsonObject jsonObject; UpdateOp(MCRJSONCategory category, JsonObject jsonObject) { this.category = category; this.jsonObject = jsonObject; } @Override public void run() { MCRCategoryID mcrCategoryID = category.getId(); boolean isAdded = isAdded(jsonObject); if (isAdded && MCRCategoryDAOFactory.getInstance().exist(mcrCategoryID)) { // an added category already exist -> throw conflict error throw new WebApplicationException( Response.status(Status.CONFLICT).entity(buildJsonError("duplicateID", mcrCategoryID)).build()); } MCRCategoryID newParentID = category.getParentID(); if (newParentID != null && !CATEGORY_DAO.exist(newParentID)) { throw new WebApplicationException(Status.NOT_FOUND); } if (CATEGORY_DAO.exist(category.getId())) { CATEGORY_DAO.setLabels(category.getId(), category.getLabels()); CATEGORY_DAO.setURI(category.getId(), category.getURI()); if (newParentID != null) { CATEGORY_DAO.moveCategory(category.getId(), newParentID, category.getPositionInParent()); } } else { CATEGORY_DAO.addCategory(newParentID, category.asMCRImpl(), category.getPositionInParent()); } } } }
19,696
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-classeditor/src/main/java/org/mycore/frontend/classeditor/access/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Thomas Scheffler (yagee) * Classes for access permission checks */ package org.mycore.frontend.classeditor.access;
859
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRNewClassificationPermission.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/access/MCRNewClassificationPermission.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.access; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.access.MCRAccessManager; import org.mycore.datamodel.classifications2.utils.MCRClassificationUtils; import org.mycore.frontend.jersey.filter.access.MCRResourceAccessChecker; import jakarta.ws.rs.container.ContainerRequestContext; /** * @author Thomas Scheffler (yagee) * */ public class MCRNewClassificationPermission implements MCRResourceAccessChecker { private static final Logger LOGGER = LogManager.getLogger(MCRNewClassificationPermission.class); /* (non-Javadoc) * @see org.mycore.frontend.jersey.filter.access.MCRResourceAccessChecker * #isPermitted(com.sun.jersey.spi.container.ContainerRequest) */ @Override public boolean isPermitted(ContainerRequestContext request) { LOGGER.info("{} has permission {}?", request.getUriInfo().getPath(), MCRClassificationUtils.CREATE_CLASS_PERMISSION); return MCRAccessManager.checkPermission(MCRClassificationUtils.CREATE_CLASS_PERMISSION); } }
1,841
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRClassificationWritePermission.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-classeditor/src/main/java/org/mycore/frontend/classeditor/access/MCRClassificationWritePermission.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classeditor.access; import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE; 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.mycore.access.MCRAccessManager; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.frontend.classeditor.utils.MCRCategUtils; import org.mycore.frontend.jersey.filter.access.MCRResourceAccessChecker; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; /** * @author Thomas Scheffler (yagee) * */ public class MCRClassificationWritePermission implements MCRResourceAccessChecker { public static final String PERMISSION_CREATE = "create-class"; private static Logger LOGGER = LogManager.getLogger(MCRClassificationWritePermission.class); /* (non-Javadoc) * @see org.mycore.frontend.jersey.filter.access.MCRResourceAccessChecker * #isPermitted(com.sun.jersey.spi.container.ContainerRequest) */ @Override public boolean isPermitted(ContainerRequestContext request) { String value = convertStreamToString(request.getEntityStream()); try { // Set<MCRCategoryID> categories = MCRCategUtils.getRootCategoryIDs(value); HashMap<MCRCategoryID, String> categories = MCRCategUtils.getCategoryIDMap(value); if (categories == null) { LOGGER.error("Could not parse {}", value); return false; } for (Map.Entry<MCRCategoryID, String> categoryEntry : categories.entrySet()) { MCRCategoryID category = categoryEntry.getKey(); String state = categoryEntry.getValue(); if (!hasPermission(category, state)) { LOGGER.info("Permission {} denied on classification {}", category.getRootID(), category); return false; } } return true; } catch (Exception exc) { throw new WebApplicationException(exc, Response.status(Status.INTERNAL_SERVER_ERROR) .entity("Unable to check permission for request " + request.getUriInfo().getRequestUri() + " containing entity value " + value) .build()); } } private boolean hasPermission(MCRCategoryID category, String state) { if (Objects.equals(state, "new")) { return MCRAccessManager.checkPermission(PERMISSION_CREATE); } return MCRAccessManager.checkPermission(category.getRootID(), PERMISSION_WRITE); } }
3,528
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRVueRootServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/vue/MCRVueRootServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.vue; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.jdom2.Content; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Entities; import org.mycore.common.MCRException; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.content.MCRURLContent; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.servlets.MCRContentServlet; import org.mycore.tools.MyCoReWebPageProvider; import org.xml.sax.SAXException; import javax.xml.transform.TransformerException; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.Stream; /** * <p>This Servlet can be bound to a URL where a Vue Build App with a createWebHistory() router is present.</p> * <pre> * <code> * * &lt;servlet&gt; * &lt;servlet-name&gt;MCRVueRootServlet&lt;/servlet-name&gt; * &lt;servlet-class&gt;org.mycore.webtools.vue.MCRVueRootServlet&lt;/servlet-class&gt; * &lt;/servlet&gt; * &lt;servlet-mapping&gt; * &lt;servlet-name&gt;MCRVueRootServlet&lt;/servlet-name&gt; * &lt;url-pattern&gt;/modules/webtools/texteditor/*&lt;/url-pattern&gt; * &lt;/servlet-mapping&gt; * </code> * </pre> * <p>It will pass through resources that exists at this path like javascript and css, but at every other path it will * deliver a modified version of the index.html. * The index.html is convert to xhtml and then will be wrapped with a MyCoReWebPage, which will produce the surrounding * default layout.</p> * <p>In the example the vue app is located in: src/main/vue/texteditor</p> * <p>The Router needs to be configured like this:</p> * <pre> * <code> * * function getContext() { * if (import.meta.env.DEV) { * return import.meta.env.BASE_URL; * } * const el = document.createElement('a'); * el.href = getWebApplicationBaseURL(); * return el.pathname + "modules/webtools/texteditor/"; * } * const router = createRouter({ * history: createWebHistory(getContext()), * routes * }) * </code> * </pre> * <p>The String "modules/webtools/texteditor/" is the location of the vue app below the java application context.</p> * <p>To change the output destination of the vue compiler process you need to change the vue.config.js, * if you use vue-cli</p> * <pre> * <code> * * const { defineConfig } = require('@vue/cli-service') * module.exports = defineConfig({ * transpileDependencies: true, * outputDir: "../../../../target/classes/META-INF/resources/modules/webtools/texteditor", * publicPath: "./" * }); * </code> * </pre> * <p>If you use vite you have to change the vite.config.ts, to change the output destination of the vite compiler * process.</p> * <a href="https://vitejs.dev/config/">vite config</a> * <pre> * <code> * export default defineConfig({ * ... * build: { * outDir: "../../../../target/classes/META-INF/resources/modules/webtools/texteditor", * }, * base: "./" * }); * </code> * </pre> * * @author Sebastian Hofmann * @author Matthias Eichner */ public class MCRVueRootServlet extends MCRContentServlet { private static final long serialVersionUID = 1L; @Override public MCRContent getContent(HttpServletRequest req, HttpServletResponse resp) throws IOException { String pathInfo = req.getPathInfo(); String indexHtmlPage = getIndexPage(); String indexHtmlPath = req.getServletPath() + "/" + indexHtmlPage; URL resource = getServletContext().getResource(req.getServletPath() + pathInfo); if (resource != null && !pathInfo.endsWith("/") && !pathInfo.endsWith(indexHtmlPage)) { return new MCRURLContent(resource); } else { URL indexResource = getServletContext().getResource(indexHtmlPath); org.jdom2.Document mycoreWebpage = getIndexDocument(indexResource, getAbsoluteServletPath(req)); if (pathInfo != null && pathInfo.endsWith("/404")) { /* if there is a requested route which does not exist, the app should * redirect to this /404 route the get the actual 404 Code. * see also https://www.youtube.com/watch?v=vjj8B4sq0UI&t=1815s * */ resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } try { return getLayoutService().getTransformedContent(req, resp, new MCRJDOMContent(mycoreWebpage)); } catch (TransformerException | SAXException e) { throw new IOException(e); } } } protected String getIndexPage() { return "index.html"; } protected String getAbsoluteServletPath(HttpServletRequest req) { String servletPath = req.getServletPath(); servletPath = servletPath.startsWith("/") ? servletPath.substring(1) : servletPath; return MCRFrontendUtil.getBaseURL() + servletPath; } protected org.jdom2.Document getIndexDocument(URL indexResource, String absoluteServletPath) throws IOException { try (InputStream indexFileStream = indexResource.openStream()) { Document document = Jsoup.parse(indexFileStream, StandardCharsets.UTF_8.toString(), ""); document.outputSettings().escapeMode(Entities.EscapeMode.xhtml); document.outputSettings().syntax(Document.OutputSettings.Syntax.xml); document.outerHtml(); return buildMCRWebpage(absoluteServletPath, new StringReader(document.outerHtml())); } catch (JDOMException e) { throw new MCRException(e); } } /** * Injects properties into the script. Override if you want to use own properties. By default, only the * webApplicationBaseURL is provided. * * @return properties for javascript injection */ protected Properties getProperties() { Properties properties = new Properties(); properties.setProperty("webApplicationBaseURL", MCRFrontendUtil.getBaseURL()); return properties; } protected org.jdom2.Document buildMCRWebpage(String absoluteServletPath, Reader reader) throws JDOMException, IOException { org.jdom2.Document jdom = new SAXBuilder().build(reader); Element jdomRoot = jdom.getRootElement(); List<Content> scriptAndLinks = buildScriptAndLinks(absoluteServletPath, jdomRoot); List<Content> bodyContent = buildBodyContent(jdomRoot); List<Content> content = Stream.of(scriptAndLinks, bodyContent) .flatMap(Collection::stream) .toList(); MyCoReWebPageProvider mycoreWebPage = new MyCoReWebPageProvider(); mycoreWebPage.addSection("", content, "de"); return mycoreWebPage.getXML(); } protected List<Content> buildBodyContent(Element root) { List<Element> body = root.getChild("body").getChildren(); return new ArrayList<>(body).stream() .map(Element::detach) .collect(Collectors.toList()); } protected List<Content> buildScriptAndLinks(String absoluteServletPath, Element root) { // inject properties Element propertiesScript = buildPropertiesScript(); // script and links from vue's index.html List<Element> vueScriptAndLink = buildVueScriptAndLink(absoluteServletPath, root); // combine List<Content> scriptAndLinks = new ArrayList<>(); scriptAndLinks.add(propertiesScript); scriptAndLinks.addAll(vueScriptAndLink); return scriptAndLinks; } /** * Creates a new script tag embedding the given {@link #getProperties()} as javascript variables. The variables * are stored under the mycore variable e.g. 'mycore.webApplicationBaseURL'. * * @return script element tag with properties javascript variables */ protected Element buildPropertiesScript() { Element propertiesScript = new Element("script"); propertiesScript.setAttribute("type", "text/javascript"); StringBuilder propertiesJson = new StringBuilder("var mycore = mycore || {};"); propertiesJson.append(System.lineSeparator()); getProperties().forEach((key, value) -> propertiesJson.append("mycore.").append(key).append("=\"").append(value) .append("\";").append(System.lineSeparator())); propertiesScript.setText(propertiesJson.toString()); return propertiesScript; } /** * Extracts the script and link elements out of the vue index.html. * * @param absoluteServletPath the absolute servlet path * @param root the root element * @return list of script and link elements */ protected List<Element> buildVueScriptAndLink(String absoluteServletPath, Element root) { return root.getChild("head").getChildren().stream() .filter(el -> "script".equals(el.getName()) || "link".equals(el.getName())) .toList() .stream().map(Element::detach).peek(el -> { String hrefAttr = el.getAttributeValue("href"); if (hrefAttr != null) { el.setAttribute("href", absoluteServletPath + "/" + hrefAttr); } String srcAttr = el.getAttributeValue("src"); if (srcAttr != null) { el.setAttribute("src", absoluteServletPath + "/" + srcAttr); } }).toList(); } }
10,593
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPropertyHelperContentServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/properties/MCRPropertyHelperContentServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.properties; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.jdom2.Element; import org.mycore.common.MCRException; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRSystemUserInformation; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.frontend.servlets.MCRContentServlet; import org.xml.sax.SAXException; import javax.xml.transform.TransformerException; import java.io.IOException; import java.util.List; import java.util.Map; public class MCRPropertyHelperContentServlet extends MCRContentServlet { @Override public MCRContent getContent(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (!MCRSessionMgr.getCurrentSession().getUserInformation().getUserID() .equals(MCRSystemUserInformation.getSuperUserInstance().getUserID())) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return null; } MCRPropertyHelper propertyHelper = new MCRPropertyHelper(); Map<String, List<MCRProperty>> map = propertyHelper.analyzeProperties(); Element propertiesElement = new Element("properties-analyze"); for (String component : map.keySet()) { Element componentElement = new Element("component"); componentElement.setAttribute("name", component); propertiesElement.addContent(componentElement); for (MCRProperty property : map.get(component)) { Element propertyElement = new Element("property"); propertyElement.setAttribute("name", property.name()); if (property.oldValue() != null) { propertyElement.setAttribute("oldValue", property.oldValue()); } propertyElement.setAttribute("newValue", property.newValue()); propertyElement.setAttribute("component", property.component()); componentElement.addContent(propertyElement); } } try { return getLayoutService().getTransformedContent(req, resp, new MCRJDOMContent(propertiesElement)); } catch (TransformerException | SAXException e) { throw new MCRException(e); } } }
3,088
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPropertyHelper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/properties/MCRPropertyHelper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.properties; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; import org.mycore.common.config.MCRConfigurationInputStream; import org.mycore.common.config.MCRProperties; class MCRPropertyHelper { private final LinkedHashMap<String, byte[]> configFileContents; MCRPropertyHelper() throws IOException { configFileContents = MCRConfigurationInputStream.getConfigFileContents("mycore.properties"); } public Map<String, List<MCRProperty>> analyzeProperties() { Properties properties = new MCRProperties(); Properties currentProperties = new MCRProperties(); final AtomicReference<Properties> oldProperties = new AtomicReference<Properties>(null); LinkedHashMap<String, List<MCRProperty>> analyzedProperties = new LinkedHashMap<>(); for (Map.Entry<String, byte[]> componentContentEntry : configFileContents.entrySet()) { String component = componentContentEntry.getKey(); byte[] value = componentContentEntry.getValue(); List<MCRProperty> componentList = analyzedProperties.computeIfAbsent(component, k1 -> new LinkedList<>()); try(ByteArrayInputStream bais = new ByteArrayInputStream(value)){ properties.load(bais); bais.reset(); currentProperties.load(bais); } catch (IOException e) { // can't happen ByteArrayInputStream does not throw IOException } currentProperties.forEach((k, v) -> { String propertyName = (String) k; String propertyValue = properties.getProperty(propertyName); String oldValue = Optional.ofNullable(oldProperties.get()).map(op -> op.getProperty(propertyName)) .orElse(null); componentList.add(new MCRProperty(component, propertyName, oldValue, propertyValue)); currentProperties.put(propertyName, propertyValue); }); currentProperties.clear(); oldProperties.set((Properties) properties.clone()); } return analyzedProperties; } }
3,117
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRProperty.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/properties/MCRProperty.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.properties; record MCRProperty(String component, String name, String oldValue, String newValue) { }
856
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUploadResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/upload/MCRUploadResource.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.upload; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.text.Normalizer; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRUtils; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import org.mycore.frontend.fileupload.MCRPostUploadFileProcessor; import org.mycore.webtools.upload.exception.MCRInvalidFileException; import org.mycore.webtools.upload.exception.MCRInvalidUploadParameterException; import org.mycore.webtools.upload.exception.MCRMissingParameterException; import org.mycore.webtools.upload.exception.MCRUploadForbiddenException; import org.mycore.webtools.upload.exception.MCRUploadServerException; import jakarta.ws.rs.BadRequestException; import jakarta.ws.rs.GET; 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.container.ContainerRequestContext; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; @Path("files/upload/") public class MCRUploadResource { private static final String FILE_PROCESSOR_PROPERTY = "MCR.MCRUploadHandlerIFS.FileProcessors"; private static final List<MCRPostUploadFileProcessor> FILE_PROCESSORS = initProcessorList(); private static final Logger LOGGER = LogManager.getLogger(); @Context ContainerRequestContext request; private static List<MCRPostUploadFileProcessor> initProcessorList() { List<String> fileProcessorList = MCRConfiguration2.getString(FILE_PROCESSOR_PROPERTY) .map(MCRConfiguration2::splitValue) .map(s -> s.collect(Collectors.toList())) .orElseGet(Collections::emptyList); return fileProcessorList.stream().map(fpClassName -> { try { @SuppressWarnings("unchecked") Class<MCRPostUploadFileProcessor> aClass = (Class<MCRPostUploadFileProcessor>) Class .forName(fpClassName); Constructor<MCRPostUploadFileProcessor> constructor = aClass.getConstructor(); return constructor.newInstance(); } catch (ClassNotFoundException e) { throw new MCRConfigurationException( "The class " + fpClassName + " defined in " + FILE_PROCESSOR_PROPERTY + " was not found!", e); } catch (NoSuchMethodException e) { throw new MCRConfigurationException( "The class " + fpClassName + " defined in " + FILE_PROCESSOR_PROPERTY + " has no default constructor!", e); } catch (IllegalAccessException e) { throw new MCRConfigurationException( "The class " + fpClassName + " defined in " + FILE_PROCESSOR_PROPERTY + " has a private/protected constructor!", e); } catch (InstantiationException e) { throw new MCRConfigurationException( "The class " + fpClassName + " defined in " + FILE_PROCESSOR_PROPERTY + " is abstract!", e); } catch (InvocationTargetException e) { throw new MCRConfigurationException( "The constrcutor of class " + fpClassName + " defined in " + FILE_PROCESSOR_PROPERTY + " threw a exception on invoke!", e); } }).collect(Collectors.toList()); } @PUT @Path("begin") public Response begin(@QueryParam("uploadHandler") String uploadHandlerID) throws MCRUploadServerException { MultivaluedMap<String, String> parameters = request.getUriInfo().getQueryParameters(); MCRUploadHandler uploadHandler = getUploadHandler(uploadHandlerID); String bucketID; try { bucketID = uploadHandler.begin(parameters); MCRFileUploadBucket.createBucket(bucketID, parameters, uploadHandler); } catch (MCRUploadForbiddenException e) { return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build(); } catch (MCRInvalidUploadParameterException | MCRMissingParameterException e) { return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); } catch (MCRUploadServerException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } return Response.ok().entity(bucketID).build(); } @PUT @Path("{buckedID}/commit") public Response commit(@PathParam("buckedID") String buckedID) { final MCRFileUploadBucket bucket = MCRFileUploadBucket.getBucket(buckedID); if (bucket == null) { throw new BadRequestException("buckedID " + buckedID + " is invalid!"); } URI location; try { location = bucket.getUploadHandler().commit(bucket); } catch (MCRUploadServerException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } finally { try { MCRFileUploadBucket.releaseBucket(bucket.getBucketID()); } catch (MCRUploadServerException e) { LOGGER.error("Error while releasing bucket " + bucket.getBucketID(), e); } } if (location == null) { return Response.ok().build(); } return Response.created(location).build(); } public static MCRUploadHandler getUploadHandler(String uploadHandlerID) { Optional<MCRUploadHandler> uploadHandler = MCRConfiguration2 .getSingleInstanceOf("MCR.Upload.Handler." + Optional.ofNullable(uploadHandlerID).orElse("Default")); if (uploadHandler.isEmpty()) { throw new BadRequestException("The UploadHandler " + uploadHandlerID + " is invalid!"); } return uploadHandler.get(); } @GET @Path("{uploadHandler}/{path:.+}") @Produces(MediaType.TEXT_PLAIN) public Response validateFile( @PathParam("uploadHandler") String uploadHandlerID, @PathParam("path") String path, @QueryParam("size") String size) { String fileName = Paths.get(path).getFileName().toString(); String unicodeNormalizedFileName = Normalizer.normalize(fileName, Normalizer.Form.NFC); try { getUploadHandler(uploadHandlerID).validateFileMetadata(unicodeNormalizedFileName, Long.parseLong(size)); } catch (MCRUploadForbiddenException e) { return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build(); } catch (MCRInvalidFileException e) { return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); } catch (MCRUploadServerException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } return Response.ok().build(); } @PUT @Path("{buckedID}/{path:.+}") public Response uploadFile(@PathParam("path") String path, @PathParam("buckedID") String buckedID, @QueryParam(("isDirectory")) boolean isDirectory, InputStream contents) throws IOException { final MCRFileUploadBucket bucket = MCRFileUploadBucket.getBucket(buckedID); if (bucket == null) { throw new BadRequestException("buckedID " + buckedID + " is invalid!"); } String unicodeNormalizedPath = Normalizer.normalize(path, Normalizer.Form.NFC); final java.nio.file.Path filePath = MCRUtils.safeResolve(bucket.getRoot(), unicodeNormalizedPath); createBucketRootIfNotExist(filePath); String actualStringFileName = bucket.getRoot().relativize(filePath).getFileName().toString(); MCRUploadHandler uploadHandler = bucket.getUploadHandler(); String contentLengthStr = request.getHeaderString(HttpHeaders.CONTENT_LENGTH); long contentLength = contentLengthStr == null ? 0 : Long.parseLong(contentLengthStr); try { uploadHandler.validateFileMetadata(actualStringFileName, contentLength); } catch (MCRUploadForbiddenException e) { return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build(); } catch (MCRInvalidFileException e) { return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); } catch (MCRUploadServerException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } if (isDirectory) { Files.createDirectory(filePath); } else { final List<MCRPostUploadFileProcessor> processors = FILE_PROCESSORS.stream() .filter(processor -> processor.isProcessable(unicodeNormalizedPath)) .toList(); if (processors.size() == 0) { Files.copy(contents, filePath, StandardCopyOption.REPLACE_EXISTING); } else { java.nio.file.Path input = Files.createTempFile("processing", ".temp"); Files.copy(contents, input, StandardCopyOption.REPLACE_EXISTING); for (MCRPostUploadFileProcessor processor : processors) { final java.nio.file.Path tempFile2 = Files.createTempFile("processing", ".temp"); final java.nio.file.Path result = processor.processFile(unicodeNormalizedPath, input, () -> tempFile2); if (result != null) { Files.deleteIfExists(input); input = result; } } Files.copy(input, filePath, StandardCopyOption.REPLACE_EXISTING); Files.deleteIfExists(input); } } return Response.noContent().build(); } private static void createBucketRootIfNotExist(java.nio.file.Path filePath) throws IOException { if (filePath.getNameCount() > 1) { java.nio.file.Path parentDirectory = filePath.getParent(); if (!Files.exists(parentDirectory)) { Files.createDirectories(parentDirectory); } } } }
11,584
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDefaultUploadHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/upload/MCRDefaultUploadHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.upload; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.UUID; 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.common.MCRException; import org.mycore.common.MCRPersistenceException; import org.mycore.common.MCRUtils; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetaClassification; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.datamodel.niofs.utils.MCRTreeCopier; import org.mycore.frontend.fileupload.MCRUploadHelper; import org.mycore.webtools.upload.exception.MCRInvalidFileException; import org.mycore.webtools.upload.exception.MCRInvalidUploadParameterException; import org.mycore.webtools.upload.exception.MCRMissingParameterException; import org.mycore.webtools.upload.exception.MCRUploadForbiddenException; import org.mycore.webtools.upload.exception.MCRUploadServerException; /** * Default implementation of the {@link MCRUploadHandler} interface. * This implementation uploads files to a derivate and assigns a mainfile if none is set. * * <dl> * <dt>{@link #OBJ_OR_DERIVATE_ID_PARAMETER_NAME}</dt> * <dd>The derivate id where the files should be uploaded to. It can also be an object id, in this case a new * derivate will be created.</dd> * <dt>{@link #CLASSIFICATIONS_PARAMETER_NAME}</dt> * <dd>A comma separated list of classifications that should be added to the new derivate.</dd> * </dl> * * The following configuration properties are used: * <dl> * <dt>MCR.Upload.NotPreferredFiletypeForMainfile</dt> * <dd>A comma separated list of file extensions that should not be used as mainfile. </dd> * </dl> */ public class MCRDefaultUploadHandler implements MCRUploadHandler { public static final String OBJ_OR_DERIVATE_ID_PARAMETER_NAME = "object"; public static final String CLASSIFICATIONS_PARAMETER_NAME = "classifications"; private static final Logger LOGGER = LogManager.getLogger(); public static final String UNIQUE_OBJECT_TRANSLATION_KEY = "component.webtools.upload.invalid.parameter.unique"; public static final String INVALID_OBJECT_TRANSLATION_KEY = "component.webtools.upload.invalid.parameter.object"; public static final String OBJECT_DOES_NOT_EXIST_TRANSLATION_KEY = "component.webtools.upload.invalid.parameter.object.not.exist"; public static final String INVALID_FILE_NAME_TRANSLATION_KEY = "component.webtools.upload.invalid.fileName"; public static final String INVALID_FILE_SIZE_TRANSLATION_KEY = "component.webtools.upload.invalid.fileSize"; public static void setDefaultMainFile(MCRDerivate derivate) { MCRPath path = MCRPath.getPath(derivate.getId().toString(), "/"); try { MCRUploadHelper.detectMainFile(path).ifPresent(file -> { LOGGER.info("Setting main file to {}", file.toUri().toString()); derivate.getDerivate().getInternals().setMainDoc(file.getOwnerRelativePath()); try { MCRMetadataManager.update(derivate); } catch (MCRPersistenceException | MCRAccessException e) { LOGGER.error("Could not set main file!", e); } }); } catch (IOException e) { LOGGER.error("Could not set main file!", e); } } @Override public URI commit(MCRFileUploadBucket bucket) throws MCRUploadServerException { Map<String, List<String>> parameters = bucket.getParameters(); final MCRObjectID objOrDerivateID = getObjectID(parameters); final List<MCRMetaClassification> classifications = getClassifications(parameters); final Path root = bucket.getRoot(); final boolean isDerivate = "derivate".equals(objOrDerivateID.getTypeId()); final MCRPath targetDerivateRoot; MCRObjectID derivateID = objOrDerivateID; if (isDerivate) { targetDerivateRoot = MCRPath.getPath(objOrDerivateID.toString(), "/"); } else { try { derivateID = MCRUploadHelper.createDerivate(objOrDerivateID, classifications).getId(); targetDerivateRoot = MCRPath.getPath(derivateID.toString(), "/"); } catch (MCRAccessException e) { throw new MCRUploadServerException("mcr.upload.create.derivate.failed", e); } // check if we have write access to the newly created derivate if (!MCRAccessManager.checkPermission(derivateID, MCRAccessManager.PERMISSION_WRITE)) { throw new MCRUploadServerException("No write access to newly created derivate " + derivateID); } } final MCRTreeCopier copier; try { copier = new MCRTreeCopier(root, targetDerivateRoot, false, true); } catch (NoSuchFileException e) { throw new MCRException(e); } try { Files.walkFileTree(root, copier); } catch (IOException e) { throw new MCRUploadServerException("mcr.upload.import.failed", e); } MCRDerivate theDerivate = MCRMetadataManager.retrieveMCRDerivate(derivateID); String mainDoc = theDerivate.getDerivate().getInternals().getMainDoc(); if (mainDoc == null || mainDoc.isEmpty()) { setDefaultMainFile(theDerivate); } return null; // We don´t want to redirect to the derivate, so we return null } private static void checkPermissions(MCRObjectID oid) throws MCRInvalidUploadParameterException, MCRUploadForbiddenException { if (!MCRMetadataManager.exists(oid)) { throw new MCRInvalidUploadParameterException(OBJ_OR_DERIVATE_ID_PARAMETER_NAME, oid.toString(), OBJECT_DOES_NOT_EXIST_TRANSLATION_KEY, true); } if (!oid.getTypeId().equals("derivate")) { try { String formattedNewDerivateIDString = MCRObjectID.formatID(oid.getProjectId(), "derivate", 0); MCRObjectID newDerivateId = MCRObjectID.getInstance(formattedNewDerivateIDString); MCRMetadataManager.checkCreatePrivilege(newDerivateId); } catch (MCRAccessException e) { throw new MCRUploadForbiddenException(); } } if (!MCRAccessManager.checkPermission(oid, MCRAccessManager.PERMISSION_WRITE)) { throw new MCRUploadForbiddenException(); } } @Override public void validateFileMetadata(String name, long size) throws MCRInvalidFileException { try { MCRUploadHelper.checkPathName(name); } catch (MCRException e) { throw new MCRInvalidFileException(name, INVALID_FILE_NAME_TRANSLATION_KEY, true); } long maxSize = MCRConfiguration2.getOrThrow("MCR.FileUpload.MaxSize", Long::parseLong); if (size > maxSize) { throw new MCRInvalidFileException(name, INVALID_FILE_SIZE_TRANSLATION_KEY, true, MCRUtils.getSizeFormatted(size), MCRUtils.getSizeFormatted(maxSize)); } } @Override public String begin(Map<String, List<String>> parameters) throws MCRUploadForbiddenException, MCRMissingParameterException, MCRInvalidUploadParameterException { if (!parameters.containsKey(OBJ_OR_DERIVATE_ID_PARAMETER_NAME)) { throw new MCRMissingParameterException(OBJ_OR_DERIVATE_ID_PARAMETER_NAME); } List<String> oidList = parameters.get(OBJ_OR_DERIVATE_ID_PARAMETER_NAME); if (oidList.size() != 1) { throw new MCRInvalidUploadParameterException(OBJ_OR_DERIVATE_ID_PARAMETER_NAME, String.join(",", oidList), UNIQUE_OBJECT_TRANSLATION_KEY, true); } String oidString = oidList.get(0); if (!MCRObjectID.isValid(oidString)) { throw new MCRInvalidUploadParameterException(OBJ_OR_DERIVATE_ID_PARAMETER_NAME, oidString, INVALID_OBJECT_TRANSLATION_KEY, true); } MCRObjectID oid = MCRObjectID.getInstance(oidString); checkPermissions(oid); return UUID.randomUUID().toString(); } /** * returns the object id from the parameters under the key {@link #OBJ_OR_DERIVATE_ID_PARAMETER_NAME} * @param parameters the parameters * @return the object id */ public static MCRObjectID getObjectID(Map<String, List<String>> parameters) { return MCRObjectID.getInstance(parameters.get(OBJ_OR_DERIVATE_ID_PARAMETER_NAME).get(0)); } /** * Gets the classifications from the parameters under the key {@link #CLASSIFICATIONS_PARAMETER_NAME}. * @param parameters the parameters * @return the classifications */ public static List<MCRMetaClassification> getClassifications(Map<String, List<String>> parameters) { List<String> classificationParameters = parameters.get(CLASSIFICATIONS_PARAMETER_NAME); return MCRUploadHelper .getClassifications(classificationParameters != null ? String.join(",", classificationParameters) : null); } }
10,257
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRFileUploadBucket.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/upload/MCRFileUploadBucket.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.upload; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.mycore.common.MCRException; import org.mycore.common.MCRSessionMgr; import org.mycore.common.events.MCRSessionEvent; import org.mycore.common.events.MCRSessionListener; import org.mycore.common.events.MCRShutdownHandler; import org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter; import org.mycore.webtools.upload.exception.MCRUploadServerException; /** * A MCRFileUploadBucket is a temporary directory for file uploads. It is created on demand and deleted when the session * is closed or the application is shut down or the bucket is closed. * The bucket is identified by a bucketID. It also contains a root directory, where the uploaded files are stored, * the parameters and the upload handler used for the upload. * */ public class MCRFileUploadBucket implements MCRSessionListener, MCRShutdownHandler.Closeable { private static final ConcurrentHashMap<String, MCRFileUploadBucket> BUCKET_MAP = new ConcurrentHashMap<>(); private final String bucketID; private final Path root; private final String sessionID; private final Map<String, List<String>> parameters; private final MCRUploadHandler uploadHandler; /** * * @param bucketID of the bucket */ private MCRFileUploadBucket(String bucketID, Map<String, List<String>> parameters, MCRUploadHandler uploadHandler) throws MCRUploadServerException { this.bucketID = bucketID; this.parameters = parameters; this.uploadHandler = uploadHandler; this.sessionID = MCRSessionMgr.getCurrentSessionID(); try { this.root = Files.createTempDirectory("mycore_" + bucketID); } catch (IOException e) { throw new MCRUploadServerException("component.webtools.upload.temp.create.failed", e); } MCRSessionMgr.addSessionListener(this); MCRShutdownHandler.getInstance().addCloseable(this); } public static MCRFileUploadBucket getBucket(String bucketID) { return BUCKET_MAP.get(bucketID); } public static synchronized MCRFileUploadBucket createBucket(String bucketID, Map<String, List<String>> parameters, MCRUploadHandler uploadHandler) throws MCRUploadServerException { try { return BUCKET_MAP.computeIfAbsent(bucketID, (id) -> { try { return new MCRFileUploadBucket(id, parameters, uploadHandler); } catch (MCRUploadServerException e) { throw new MCRException(e); } }); } catch (MCRException e) { if (e.getCause() instanceof MCRUploadServerException use) { throw use; } throw e; } } public static synchronized void releaseBucket(String bucketID) throws MCRUploadServerException { if (BUCKET_MAP.containsKey(bucketID)) { final MCRFileUploadBucket bucket = BUCKET_MAP.get(bucketID); if (Files.exists(bucket.root)) { try { Files.walkFileTree(bucket.root, MCRRecursiveDeleter.instance()); } catch (IOException e) { throw new MCRUploadServerException("component.webtools.upload.temp.delete.failed", e); } } BUCKET_MAP.remove(bucketID); } } public String getBucketID() { return bucketID; } public Map<String, List<String>> getParameters() { return Collections.unmodifiableMap(parameters); } public MCRUploadHandler getUploadHandler() { return uploadHandler; } public Path getRoot() { return root; } @Override public void sessionEvent(MCRSessionEvent event) { if (event.getType().equals(MCRSessionEvent.Type.destroyed)) { final String sessionID = event.getSession().getID(); if (sessionID.equals(this.sessionID)) { close(); } } } @Override public void close() { try { releaseBucket(this.bucketID); } catch (MCRUploadServerException e) { throw new MCRException("Error while releasing bucket on close", e); } } }
5,194
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUploadHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/upload/MCRUploadHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.upload; import java.net.URI; import java.util.List; import java.util.Map; import org.mycore.datamodel.metadata.MCRMetaClassification; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.webtools.upload.exception.MCRInvalidFileException; import org.mycore.webtools.upload.exception.MCRInvalidUploadParameterException; import org.mycore.webtools.upload.exception.MCRMissingParameterException; import org.mycore.webtools.upload.exception.MCRUploadForbiddenException; import org.mycore.webtools.upload.exception.MCRUploadServerException; /** * Handles uploaded {@link MCRFileUploadBucket}s */ public interface MCRUploadHandler { /** * Checks if the upload is allowed for the current user and if the parameters are valid * @param parameters the parameters that were passed to the upload, eg. the {@link MCRObjectID} * @throws MCRUploadForbiddenException if the upload is not allowed * @throws MCRUploadServerException if something went wrong serverside while begin */ String begin(Map<String, List<String>> parameters) throws MCRUploadForbiddenException, MCRUploadServerException, MCRMissingParameterException, MCRInvalidUploadParameterException; /** * Traverses the given {@link MCRFileUploadBucket} and creates or updates the corresponding * {@link org.mycore.datamodel.metadata.MCRObject} * * {@link MCRMetaClassification} that should be assigned to the new * {@link org.mycore.datamodel.metadata.MCRDerivate} * @param bucket the {@link MCRFileUploadBucket} to traverse * @throws MCRUploadServerException if something went wrong serverside while commiting */ URI commit(MCRFileUploadBucket bucket) throws MCRUploadServerException; /** * Validates if the file name and size * @param name the file name * @param size the size of the file * @throws MCRUploadForbiddenException if the user is not allowed to upload the file * @throws MCRInvalidFileException if the file bad * @throws MCRUploadServerException if something went wrong serverside while uploading */ void validateFileMetadata(String name, long size) throws MCRUploadForbiddenException, MCRInvalidFileException, MCRUploadServerException; }
3,026
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUploadForbiddenException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/upload/exception/MCRUploadForbiddenException.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.upload.exception; public class MCRUploadForbiddenException extends MCRUploadException { private static final long serialVersionUID = 1L; public MCRUploadForbiddenException(String reason) { super("component.webtools.upload.forbidden", reason); } public MCRUploadForbiddenException() { super("component.webtools.upload.forbidden.noReason"); } }
1,141
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUploadException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/upload/exception/MCRUploadException.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.upload.exception; import org.mycore.services.i18n.MCRTranslation; public class MCRUploadException extends Exception { private static final long serialVersionUID = 1L; public MCRUploadException(String messageKey) { super(MCRTranslation.translate(messageKey)); } public MCRUploadException(String messageKey, String... translationParams) { super(MCRTranslation.translate(messageKey, (Object[]) translationParams)); } public MCRUploadException(String messageKey, Throwable throwable) { super(MCRTranslation.translate(messageKey), throwable); } }
1,355
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRInvalidUploadParameterException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/upload/exception/MCRInvalidUploadParameterException.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.upload.exception; import org.mycore.services.i18n.MCRTranslation; /** * Should be thrown if a parameter required by an upload handler is not valid. E.g. a classification does not exist. */ public class MCRInvalidUploadParameterException extends MCRUploadException { private static final long serialVersionUID = 1L; private final String parameterName; private final String wrongReason; private final String badValue; public MCRInvalidUploadParameterException(String parameterName, String badValue, String wrongReason) { this(parameterName, badValue, wrongReason, false); } public MCRInvalidUploadParameterException(String parameterName, String badValue, String wrongReason, boolean translateReason) { super("component.webtools.upload.invalid.parameter", parameterName, badValue, translateReason ? MCRTranslation.translate(wrongReason) : wrongReason); this.parameterName = parameterName; this.wrongReason = wrongReason; this.badValue = badValue; } public String getParameterName() { return parameterName; } public String getWrongReason() { return wrongReason; } public String getBadValue() { return badValue; } }
2,019
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMissingParameterException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/upload/exception/MCRMissingParameterException.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.upload.exception; /** * Should be thrown if a parameter required by an upload handler is missing. */ public class MCRMissingParameterException extends MCRUploadException { private static final long serialVersionUID = 1L; private final String parameterName; public MCRMissingParameterException(String parameterName) { super("component.webtools.upload.invalid.parameter.missing", parameterName); this.parameterName = parameterName; } public String getParameterName() { return parameterName; } }
1,303
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUploadServerException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/upload/exception/MCRUploadServerException.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.upload.exception; public class MCRUploadServerException extends MCRUploadException { private static final long serialVersionUID = 1L; public MCRUploadServerException(String messageKey) { super(messageKey); } public MCRUploadServerException(String messageKey, Throwable throwable) { super(messageKey, throwable); } }
1,111
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRInvalidFileException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/upload/exception/MCRInvalidFileException.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.upload.exception; import org.mycore.services.i18n.MCRTranslation; /** * Should be thrown if the file is not valid. E.g. the size is too big or the file name contains invalid characters. */ public class MCRInvalidFileException extends MCRUploadException { private static final long serialVersionUID = 1L; private final String fileName; private final String reason; public MCRInvalidFileException(String fileName) { super("component.webtools.upload.invalid.file.noReason", fileName); this.fileName = fileName; this.reason = null; } public MCRInvalidFileException(String fileName, String reason) { this(fileName, reason, false); } public MCRInvalidFileException(String fileName, String reason, boolean translateReason, Object... translationParams) { super("component.webtools.upload.invalid.file", fileName, translateReason ? MCRTranslation.translate(reason, translationParams) : reason); this.fileName = fileName; this.reason = reason; } public String getFileName() { return fileName; } public String getReason() { return reason; } }
1,943
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRXHTML2PDFTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/pdf/MCRXHTML2PDFTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.pdf; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.Normalizer; import org.mycore.common.MCRClassTools; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import org.mycore.common.content.MCRByteContent; import org.mycore.common.content.MCRContent; import org.mycore.common.content.transformer.MCRContentTransformer; import com.itextpdf.html2pdf.ConverterProperties; import com.itextpdf.html2pdf.HtmlConverter; import com.itextpdf.layout.font.FontProvider; /** * Takes XHTML as input and transforms it to a PDF file */ public class MCRXHTML2PDFTransformer extends MCRContentTransformer { private String id; protected FontProvider fontProvider; @Override public void init(String id) { this.id = id; super.init(id); } @Override public MCRContent transform(MCRContent source) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); String s = source.asString(); s = Normalizer.normalize(s, Normalizer.Form.NFC); // required because some data is not normalized s = s.replace(" ", ""); // required because itext cant handle these ConverterProperties converterProperties = new ConverterProperties(); converterProperties.setFontProvider(lazyInitFontProvider()); HtmlConverter.convertToPdf(s, baos, converterProperties); return new MCRByteContent(baos.toByteArray()); } protected synchronized FontProvider lazyInitFontProvider() { if (fontProvider == null) { fontProvider = new FontProvider(); final ClassLoader cl = MCRClassTools.getClassLoader(); MCRConfiguration2.getString("MCR.ContentTransformer." + id + ".FontResources") .stream() .flatMap(MCRConfiguration2::splitValue) .forEach((path) -> { try (InputStream is = cl.getResource(path).openStream()) { fontProvider.addFont(is.readAllBytes()); } catch (IOException e) { throw new MCRConfigurationException("Error while loading configured fonts!", e); } }); } return fontProvider; } @Override public String getFileExtension() { return "pdf"; } @Override public String getMimeType() { return "application/pdf"; } }
3,272
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRProcessableWebsocketSender.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/processing/socket/MCRProcessableWebsocketSender.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.processing.socket; import org.mycore.common.processing.MCRProcessable; import org.mycore.common.processing.MCRProcessableCollection; import org.mycore.common.processing.MCRProcessableRegistry; import jakarta.websocket.Session; /** * Base interface to send processables, collections and the registry over the wire. * * @author Matthias Eichner */ public interface MCRProcessableWebsocketSender { /** * Sends an error code. * * @param session the websocket session * @param errorCode the error code */ void sendError(Session session, Integer errorCode); /** * Sends the whole registry. * * @param session the websocket session * @param registry the registry to send */ void sendRegistry(Session session, MCRProcessableRegistry registry); /** * Appends the given collection to the registry. * * @param session the websocket session * @param registry where to add the collection * @param collection the collection to add */ void addCollection(Session session, MCRProcessableRegistry registry, MCRProcessableCollection collection); /** * Removes the given collection. * * @param session the websocket session * @param collection the collection to remove */ void removeCollection(Session session, MCRProcessableCollection collection); /** * Appends the given processable to the collection. * * @param session the websocket session * @param collection where to add the processable * @param processable the processable to add */ void addProcessable(Session session, MCRProcessableCollection collection, MCRProcessable processable); /** * Removes the given processable. * * @param session the websocket session * @param processable the processable to remove */ void removeProcessable(Session session, MCRProcessable processable); /** * Updates the content of the given processable. * * @param session the websocket session * @param processable the processable to update */ void updateProcessable(Session session, MCRProcessable processable); /** * Updates a property of the given processable collection. * * @param session the websocket session * @param collection the collection to update * @param name name of the property * @param value value of the property */ void updateProperty(Session session, MCRProcessableCollection collection, String name, Object value); }
3,324
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRProcessingEndpoint.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/processing/socket/MCRProcessingEndpoint.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.processing.socket; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.Collections; 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.mycore.access.MCRAccessManager; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.processing.MCRProcessable; import org.mycore.common.processing.MCRProcessableCollection; import org.mycore.common.processing.MCRProcessableCollectionListener; import org.mycore.common.processing.MCRProcessableRegistry; import org.mycore.common.processing.MCRProcessableRegistryListener; import org.mycore.common.processing.MCRProcessableStatus; import org.mycore.common.processing.MCRProcessableStatusListener; import org.mycore.common.processing.MCRProgressable; import org.mycore.common.processing.MCRProgressableListener; import org.mycore.frontend.ws.common.MCRWebsocketDefaultConfigurator; import org.mycore.frontend.ws.common.MCRWebsocketJSONDecoder; import org.mycore.frontend.ws.endoint.MCRAbstractEndpoint; import com.google.gson.JsonObject; import jakarta.websocket.CloseReason; import jakarta.websocket.CloseReason.CloseCodes; import jakarta.websocket.OnClose; import jakarta.websocket.OnError; import jakarta.websocket.OnMessage; import jakarta.websocket.Session; import jakarta.websocket.server.ServerEndpoint; @ServerEndpoint(value = "/ws/mycore-webtools/processing", configurator = MCRWebsocketDefaultConfigurator.class, decoders = { MCRWebsocketJSONDecoder.class }) public class MCRProcessingEndpoint extends MCRAbstractEndpoint { private static final Logger LOGGER = LogManager.getLogger(); private static Map<String, SessionListener> SESSIONS; static { SESSIONS = Collections.synchronizedMap(new HashMap<>()); } private MCRProcessableRegistry registry = MCRProcessableRegistry.getSingleInstance(); private MCRProcessableWebsocketSender sender = MCRConfiguration2 .<MCRProcessableWebsocketSender>getInstanceOf("MCR.Processable.WebsocketSender.Class").orElseThrow(); @OnMessage public void onMessage(Session session, JsonObject request) { sessionized(session, () -> { if (!MCRAccessManager.checkPermission("use-processable")) { this.sender.sendError(session, 403); return; } handleMessage(session, request); }); } @OnError public void onError(Session session, Throwable error) { if (error instanceof SocketTimeoutException) { this.close(session); LOGGER.warn("Websocket error {}: websocket timeout", session.getId()); return; } LOGGER.error("Websocket error {}", session.getId(), error); } @OnClose public void close(Session session) { SessionListener sessionListener = SESSIONS.get(session.getId()); if (sessionListener != null) { sessionListener.detachListeners(this.registry); SESSIONS.remove(session.getId()); } } private void handleMessage(Session session, JsonObject request) { String type = request.get("type").getAsString(); if (Objects.equals(type, "connect")) { connect(session); } } private void connect(Session session) { this.sender.sendRegistry(session, this.registry); if (SESSIONS.containsKey(session.getId())) { return; } final SessionListener sessionListener = new SessionListener(session, this.sender); registry.addListener(sessionListener); this.registry.stream().forEach(sessionListener::attachCollection); SESSIONS.put(session.getId(), sessionListener); } private static class SessionListener implements MCRProcessableRegistryListener, MCRProcessableCollectionListener, MCRProcessableStatusListener, MCRProgressableListener { private Session session; private MCRProcessableWebsocketSender sender; SessionListener(Session session, MCRProcessableWebsocketSender sender) { this.session = session; this.sender = sender; } @Override public void onProgressChange(MCRProgressable source, Integer oldProgress, Integer newProgress) { if (isClosed()) { return; } if (source instanceof MCRProcessable processable) { this.sender.updateProcessable(session, processable); } } @Override public void onProgressTextChange(MCRProgressable source, String oldProgressText, String newProgressText) { if (isClosed()) { return; } if (source instanceof MCRProcessable processable) { this.sender.updateProcessable(session, processable); } } @Override public void onStatusChange(MCRProcessable source, MCRProcessableStatus oldStatus, MCRProcessableStatus newStatus) { if (isClosed()) { return; } this.sender.updateProcessable(session, source); } @Override public void onAdd(MCRProcessableRegistry source, MCRProcessableCollection collection) { if (isClosed()) { return; } this.attachCollection(collection); this.sender.addCollection(session, source, collection); } @Override public void onRemove(MCRProcessableRegistry source, MCRProcessableCollection collection) { if (isClosed()) { return; } this.sender.removeCollection(session, collection); } @Override public void onAdd(MCRProcessableCollection source, MCRProcessable processable) { if (isClosed()) { return; } attachProcessable(processable); this.sender.addProcessable(session, source, processable); } @Override public void onRemove(MCRProcessableCollection source, MCRProcessable processable) { processable.removeStatusListener(this); if (isClosed()) { return; } this.sender.removeProcessable(session, processable); } @Override public void onPropertyChange(MCRProcessableCollection source, String name, Object oldValue, Object newValue) { if (isClosed()) { return; } this.sender.updateProperty(session, source, name, newValue); } protected boolean isClosed() { if (!this.session.isOpen()) { try { this.session.close(new CloseReason(CloseCodes.GOING_AWAY, "client disconnected")); } catch (IOException ioExc) { LOGGER.error("Websocket error {}: Unable to close websocket connection", session.getId(), ioExc); } return true; } return false; } /** * Attaches the given collection to this {@link SessionListener} object by * adding all relevant listeners. * * @param collection the collection to attach to this object */ public void attachCollection(MCRProcessableCollection collection) { collection.addListener(this); collection.stream().forEach(this::attachProcessable); } /** * Attaches the given processable to this {@link SessionListener} object by * adding all relevant listeners. * * @param processable the processable to attach to this object */ private void attachProcessable(MCRProcessable processable) { processable.addStatusListener(this); processable.addProgressListener(this); } /** * Removes this session data object from all listeners of the given registry. * * @param registry the registry to detach from */ public void detachListeners(MCRProcessableRegistry registry) { registry.removeListener(this); registry.stream().forEach(collection -> { collection.removeListener(this); collection.stream().forEach(processable -> { processable.removeProgressListener(this); processable.removeStatusListener(this); }); }); } } }
9,402
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAddCollectionMessage.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/processing/socket/impl/MCRAddCollectionMessage.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.processing.socket.impl; import java.util.Map; /** * @author Sebastian Hofmann */ class MCRAddCollectionMessage extends MCRWebSocketMessage { public Integer id; public String name; public Map<String, Object> properties; MCRAddCollectionMessage(Integer id, String name, Map<String, Object> properties) { super(MCRMessageType.addCollection); this.id = id; this.name = name; this.properties = properties; } }
1,221
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRemoveCollectionMessage.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/processing/socket/impl/MCRRemoveCollectionMessage.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.processing.socket.impl; /** * @author Sebastian Hofmann */ class MCRRemoveCollectionMessage extends MCRWebSocketMessage { public Integer id; MCRRemoveCollectionMessage(Integer id) { super(MCRMessageType.removeCollection); this.id = id; } public Integer getId() { return id; } }
1,082
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUpdateCollectionMessage.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/processing/socket/impl/MCRUpdateCollectionMessage.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.processing.socket.impl; /** * @author Sebastian Hofmann */ class MCRUpdateCollectionMessage extends MCRWebSocketMessage { MCRUpdateCollectionMessage() { super(MCRMessageType.updateCollectionProperty); } }
981
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMessageType.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/processing/socket/impl/MCRMessageType.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.processing.socket.impl; enum MCRMessageType { error, registry, addCollection, removeCollection, updateProcessable, updateCollectionProperty }
922
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRegistryMessage.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/processing/socket/impl/MCRRegistryMessage.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.processing.socket.impl; /** * @author Sebastian Hofmann */ class MCRRegistryMessage extends MCRWebSocketMessage { MCRRegistryMessage() { super(MCRMessageType.registry); } }
948
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRProcessableMessage.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/processing/socket/impl/MCRProcessableMessage.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.processing.socket.impl; import java.util.Map; import java.util.stream.Collectors; import org.mycore.common.MCRUtils; import org.mycore.common.processing.MCRProcessable; /** * @author Sebastian Hofmann */ class MCRProcessableMessage extends MCRWebSocketMessage { public Integer id; public Integer collectionId; public String name; public String user; public String status; public Long createTime; public Long startTime; public Long endTime; public Long took; public String errorMessage; public String stackTrace; public Integer progress; public String progressText; public Map<String, String> properties; MCRProcessableMessage(MCRProcessable processable, Integer processableId, Integer collectionId) { super(MCRMessageType.updateProcessable); this.id = processableId; this.collectionId = collectionId; this.name = processable.getName(); this.user = processable.getUserId(); this.status = processable.getStatus().toString(); this.createTime = processable.getCreateTime().toEpochMilli(); if (!processable.isCreated()) { this.startTime = processable.getStartTime().toEpochMilli(); if (processable.isDone()) { this.endTime = processable.getEndTime().toEpochMilli(); this.took = processable.took().toMillis(); } } Throwable error = processable.getError(); if (processable.isFailed() && error != null) { this.errorMessage = error.getMessage(); this.stackTrace = MCRUtils.getStackTraceAsString(error); } if (processable.getProgress() != null) { this.progress = processable.getProgress(); } if (processable.getProgressText() != null) { this.progressText = processable.getProgressText(); } this.properties = processable.getProperties().entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, v -> v.getValue().toString())); } }
2,842
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUpdateCollectionPropertyMessage.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/processing/socket/impl/MCRUpdateCollectionPropertyMessage.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.processing.socket.impl; /** * @author Sebastian Hofmann */ class MCRUpdateCollectionPropertyMessage extends MCRWebSocketMessage { public Integer id; public String propertyName; public Object propertyValue; MCRUpdateCollectionPropertyMessage(Integer id, String propertyName, Object propertyValue) { super(MCRMessageType.updateCollectionProperty); this.id = id; this.propertyName = propertyName; this.propertyValue = propertyValue; } }
1,249
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRWebSocketMessage.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/processing/socket/impl/MCRWebSocketMessage.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.processing.socket.impl; /** * @author Sebastian Hofmann */ class MCRWebSocketMessage { public MCRMessageType type; MCRWebSocketMessage(MCRMessageType type) { this.type = type; } public MCRMessageType getType() { return type; } }
1,026
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRErrorMessage.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/processing/socket/impl/MCRErrorMessage.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.processing.socket.impl; /** * @author Sebastian Hofmann */ class MCRErrorMessage extends MCRWebSocketMessage { public final int error; MCRErrorMessage(int errorCode) { super(MCRMessageType.error); this.error = errorCode; } }
1,013
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRProcessableWebsocketSenderImpl.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/processing/socket/impl/MCRProcessableWebsocketSenderImpl.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.processing.socket.impl; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.events.MCRShutdownHandler; import org.mycore.common.processing.MCRProcessable; import org.mycore.common.processing.MCRProcessableCollection; import org.mycore.common.processing.MCRProcessableRegistry; import org.mycore.webtools.processing.socket.MCRProcessableWebsocketSender; import com.google.gson.Gson; import jakarta.websocket.Session; /** * Websocket implementation of sending processable objects. * * @author Matthias Eichner */ public class MCRProcessableWebsocketSenderImpl implements MCRProcessableWebsocketSender { private static final AtomicInteger ID_GENERATOR; private static final Map<Object, Integer> ID_MAP; private static final Map<Integer, Integer> PROCESSABLE_COLLECTION_MAP; static { ID_GENERATOR = new AtomicInteger(); ID_MAP = Collections.synchronizedMap(new HashMap<>()); PROCESSABLE_COLLECTION_MAP = Collections.synchronizedMap(new HashMap<>()); } @Override public void sendError(Session session, Integer errorCode) { MCRWebSocketMessage errorMessage = new MCRErrorMessage(errorCode); send(session, errorMessage); } @Override public void sendRegistry(Session session, MCRProcessableRegistry registry) { send(session, new MCRRegistryMessage()); registry.stream().forEach(collection -> addCollection(session, registry, collection)); } @Override public void addCollection(Session session, MCRProcessableRegistry registry, MCRProcessableCollection collection) { MCRAddCollectionMessage message = new MCRAddCollectionMessage(getId(collection), collection.getName(), collection.getProperties()); send(session, message); collection.stream().forEach(processable -> addProcessable(session, collection, processable)); } @Override public void removeCollection(Session session, MCRProcessableCollection collection) { Integer id = remove(collection); if (id == null) { return; } collection.stream().forEach(processable -> removeProcessable(session, processable)); send(session, new MCRRemoveCollectionMessage(id)); } @Override public void addProcessable(Session session, MCRProcessableCollection collection, MCRProcessable processable) { Integer processableId = getId(processable); Integer collectionId = getId(collection); PROCESSABLE_COLLECTION_MAP.put(processableId, collectionId); updateProcessable(session, processable, processableId, collectionId); } @Override public void updateProcessable(Session session, MCRProcessable processable) { Integer processableId = getId(processable); Integer collectionId = PROCESSABLE_COLLECTION_MAP.get(processableId); updateProcessable(session, processable, processableId, collectionId); } protected void updateProcessable(Session session, MCRProcessable processable, Integer processableId, Integer collectionId) { MCRProcessableMessage message = new MCRProcessableMessage(processable, processableId, collectionId); send(session, message); } @Override public void removeProcessable(Session session, MCRProcessable processable) { remove(processable); } @Override public void updateProperty(Session session, MCRProcessableCollection collection, String name, Object value) { send(session, new MCRUpdateCollectionPropertyMessage(getId(collection), name, value)); } public synchronized Integer getId(Object object) { return ID_MAP.computeIfAbsent(object, k -> ID_GENERATOR.incrementAndGet()); } public synchronized Integer remove(Object object) { Integer id = ID_MAP.remove(object); if (id == null) { return null; } if (object instanceof MCRProcessable) { PROCESSABLE_COLLECTION_MAP.remove(id); } else if (object instanceof MCRProcessableCollection) { PROCESSABLE_COLLECTION_MAP.values().removeIf(id::equals); } return id; } private void send(Session session, MCRWebSocketMessage responseMessage) { String msg = new Gson().toJson(responseMessage); AsyncSenderHelper.send(session, msg); } /** * Tomcat does not support async sending of messages. We have to implement * our own sender. * * <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=56026">tomcat bug</a> */ private static class AsyncSenderHelper { private static Logger LOGGER = LogManager.getLogger(); private static ExecutorService SERVICE; static { SERVICE = Executors.newSingleThreadExecutor(); MCRShutdownHandler.getInstance().addCloseable(new MCRShutdownHandler.Closeable() { @Override public void prepareClose() { SERVICE.shutdown(); } @Override public void close() { if (!SERVICE.isTerminated()) { try { SERVICE.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { LOGGER.warn("Error while waiting for shutdown.", e); } } } }); } /** * Sends a text to the session * * @param session session to send to * @param msg the message */ public static void send(Session session, String msg) { SERVICE.submit(() -> { if (session == null || !session.isOpen()) { return; } try { session.getBasicRemote().sendText(msg); } catch (Exception exc) { LOGGER.error("Websocket error {}: Unable to send message {}", session.getId(), msg); } }); } } }
7,168
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSessionResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-webtools/src/main/java/org/mycore/webtools/session/MCRSessionResource.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.session; import java.awt.Color; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRUserInformation; import org.mycore.frontend.jersey.MCRJerseyUtil; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import jakarta.ws.rs.DefaultValue; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; 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.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; /** * Resource which provides information about mycore sessions. * * @author Matthias Eichner */ @Path("session") public class MCRSessionResource { /** * Lists all {@link MCRSession}'s in json format. * * @param resolveHostname (false) if the host names are resolved. Resolving host names takes some * time, so this is deactivated by default * @return list of sessions */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("list") public Response list(@DefaultValue("false") @QueryParam("resolveHostname") Boolean resolveHostname) { // check permissions MCRJerseyUtil.checkPermission("manage-sessions"); // get all sessions JsonArray rootJSON = new ArrayList<>(MCRSessionMgr.getAllSessions().values()).parallelStream() .map(s -> generateSessionJSON(s, resolveHostname)) .collect(JsonArray::new, JsonArray::add, JsonArray::addAll); return Response.status(Status.OK).entity(rootJSON.toString()).build(); } /** * Kills the session with the specified session identifier. * * @return 200 OK if the session could be killed */ @POST @Path("kill/{id}") public Response kill(@PathParam("id") String sessionID) { // check permissions MCRJerseyUtil.checkPermission("manage-sessions"); // kill MCRSession session = MCRSessionMgr.getSession(sessionID); session.close(); return Response.status(Status.OK).build(); } /** * Builds the session JSON object. * * @param session the session to represent in JSON format * @param resolveHostname if host names should be resolved, adds the property 'hostName' * @return a gson JsonObject containing all session information */ private static JsonObject generateSessionJSON(MCRSession session, boolean resolveHostname) { JsonObject sessionJSON = new JsonObject(); String userID = session.getUserInformation().getUserID(); String ip = session.getCurrentIP(); sessionJSON.addProperty("id", session.getID()); sessionJSON.addProperty("login", userID); sessionJSON.addProperty("ip", ip); if (resolveHostname) { String hostname = resolveHostName(ip); if (hostname != null) { sessionJSON.addProperty("hostname", hostname); } } String userRealName = session.getUserInformation().getUserAttribute(MCRUserInformation.ATT_REAL_NAME); if (userRealName != null) { sessionJSON.addProperty("realName", userRealName); } sessionJSON.addProperty("createTime", session.getCreateTime()); sessionJSON.addProperty("lastAccessTime", session.getLastAccessedTime()); sessionJSON.addProperty("loginTime", session.getLoginTime()); session.getFirstURI().ifPresent(u -> sessionJSON.addProperty("firstURI", u.toString())); sessionJSON.add("constructingStacktrace", buildStacktrace(session)); return sessionJSON; } /** * Resolves the host name by the given ip. * * @param ip the ip to resolve * @return the host name or null if the ip couldn't be resolved */ private static String resolveHostName(String ip) { try { InetAddress inetAddress = InetAddress.getByName(ip); return inetAddress.getHostName(); } catch (UnknownHostException unknownHostException) { return null; } } /** * Builds the constructing stack trace for the given session. * Containing the class, file, method and line. * * @param session session * @return json array containing all {@link StackTraceElement} as json */ private static JsonElement buildStacktrace(MCRSession session) { JsonObject containerJSON = new JsonObject(); JsonArray stacktraceJSON = new JsonArray(); StackTraceElement[] constructingStackTrace = session.getConstructingStackTrace(); for (StackTraceElement stackTraceElement : constructingStackTrace) { // build json JsonObject lineJSON = new JsonObject(); lineJSON.addProperty("class", stackTraceElement.getClassName()); lineJSON.addProperty("file", stackTraceElement.getFileName()); lineJSON.addProperty("method", stackTraceElement.getMethodName()); lineJSON.addProperty("line", stackTraceElement.getLineNumber()); stacktraceJSON.add(lineJSON); } containerJSON.addProperty("color", hashToColor(Arrays.hashCode(constructingStackTrace))); containerJSON.add("stacktrace", stacktraceJSON); return containerJSON; } /** * Converts an hash code to a hex color code (e.g. #315a4f). * * @param hashCode the hash code to convert * @return a hex color code as string */ private static String hashToColor(int hashCode) { Color c = new Color(hashCode); return String.format(Locale.ROOT, "#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue()); } }
6,718
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJobStateTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/test/java/org/mycore/iview2/services/MCRJobStateTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.iview2.services; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Assert; import org.junit.Test; public class MCRJobStateTest { @Test public final void testJobStates() { Set<MCRJobState> allStates = Stream.of(MCRJobState.values()).collect(Collectors.toSet()); Set<MCRJobState> notCompleteStates = MCRJobState.notCompleteStates(); Set<MCRJobState> completeStates = MCRJobState.completeStates(); boolean notCompleteContainsComplete = notCompleteStates.stream().filter(completeStates::contains).findAny() .isPresent(); boolean completeContainsNotComplete = completeStates.stream().filter(notCompleteStates::contains).findAny() .isPresent(); boolean allStatesPresent = Stream.concat(notCompleteStates.stream(), completeStates.stream()).distinct() .count() == allStates.size(); Assert.assertFalse("There is a element in MCRJobState.COMPLETE_STATES and MCRJobState.NOT_COMPLETE_STATES", notCompleteContainsComplete || completeContainsNotComplete); Assert.assertTrue( "Not every JobState is present in MCRJobState.NOT_COMPLETE_STATES or MCRJobState.COMPLETE_STATES", allStatesPresent); } }
2,046
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPDFThumbnailJobAction.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/backend/MCRPDFThumbnailJobAction.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.iview2.backend; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Locale; import javax.imageio.ImageIO; import org.mycore.common.MCRException; 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.imagetiler.MCRImage; import org.mycore.iview2.frontend.MCRPDFTools; import org.mycore.iview2.services.MCRIView2Tools; import org.mycore.services.queuedjob.MCRJob; import org.mycore.services.queuedjob.MCRJobAction; public class MCRPDFThumbnailJobAction extends MCRJobAction { public static final String DERIVATE_PARAMETER = "derivate"; public MCRPDFThumbnailJobAction(MCRJob job) { super(job); } @Override public boolean isActivated() { return true; } @Override public String name() { return getClass().getName(); } @Override public void execute() { final String derivateIDString = this.job.getParameter(DERIVATE_PARAMETER); final MCRObjectID derivateID = MCRObjectID.getInstance(derivateIDString); if (!MCRMetadataManager.exists(derivateID)) { // Derivate was deleted, so nothing todo return; } final MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateID); MCRTileInfo tileInfo = new MCRTileInfo(derivate.getId().toString(), derivate.getDerivate().getInternals().getMainDoc(), null); if (tileInfo.getImagePath().toLowerCase(Locale.ROOT).endsWith(".pdf")) { try { Path p = MCRPath.getPath(tileInfo.getDerivate(), tileInfo.getImagePath()); BufferedImage bImage = MCRPDFTools.getThumbnail(-1, p, false); Path pImg = Files.createTempFile("MyCoRe-Thumbnail-", ".png"); try (OutputStream os = Files.newOutputStream(pImg)) { ImageIO.write(bImage, "png", os); MCRImage mcrImage = MCRImage.getInstance(pImg, tileInfo.getDerivate(), tileInfo.getImagePath()); mcrImage.setTileDir(MCRIView2Tools.getTileDir()); mcrImage.tile(); } finally { //delete temp file (see MCR-2404) //The method Files.deleteIfExists(pImg) does not work here under Windows, //because it looks like the file is still locked when the method is called //DELETE_ON_CLOSE on the outer try{} does not work //because ImageIO.write() closes the stream and the file will be deleted to early try (InputStream is = Files.newInputStream(pImg, StandardOpenOption.DELETE_ON_CLOSE)) { is.read(); // read one byte } } } catch (IOException e) { throw new MCRException("Error creating thumbnail for PDF", e); } } } @Override public void rollback() { // do need to rollback } }
4,028
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDefaultTileFileProvider.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/backend/MCRDefaultTileFileProvider.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.iview2.backend; import java.nio.file.Path; import java.util.Optional; import org.mycore.imagetiler.MCRImage; import org.mycore.iview2.services.MCRIView2Tools; public class MCRDefaultTileFileProvider implements MCRTileFileProvider { @Override public Optional<Path> getTileFile(MCRTileInfo tileInfo) { return Optional.of( MCRImage.getTiledFile(MCRIView2Tools.getTileDir(), tileInfo.getDerivate(), tileInfo.getImagePath())); } }
1,208
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTileFileProvider.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/backend/MCRTileFileProvider.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.iview2.backend; import java.nio.file.Path; import java.util.Optional; public interface MCRTileFileProvider { Optional<Path> getTileFile(MCRTileInfo tileInfo); }
913
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTileInfo.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/backend/MCRTileInfo.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.iview2.backend; /** * Holds all attributes for a specific tile. * @author Thomas Scheffler (yagee) * */ public class MCRTileInfo { private String derivate; private String imagePath; private String tile; public MCRTileInfo(final String derivate, final String imagePath, final String tile) { this.derivate = derivate; this.imagePath = imagePath; this.tile = tile; } /** * returns "TileInfo [derivate=" + derivate + ", imagePath=" + imagePath + ", tile=" + tile + "]" */ @Override public String toString() { return "TileInfo [derivate=" + derivate + ", imagePath=" + imagePath + ", tile=" + tile + "]"; } public String getDerivate() { return derivate; } public String getImagePath() { return imagePath; } public String getTile() { return tile; } }
1,630
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-iview2/src/main/java/org/mycore/iview2/frontend/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** * Servlets, Commands and Xalan extensions */ package org.mycore.iview2.frontend;
814
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTileServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRTileServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.iview2.frontend; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.config.MCRConfiguration2; import org.mycore.iview2.backend.MCRDefaultTileFileProvider; import org.mycore.iview2.backend.MCRTileFileProvider; import org.mycore.iview2.backend.MCRTileInfo; import org.mycore.iview2.services.MCRIView2Tools; import jakarta.servlet.ServletOutputStream; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Get a specific tile of an image. * @author Thomas Scheffler (yagee) * */ public class MCRTileServlet extends HttpServlet { /** * how long should a tile be cached by the client */ static final int MAX_AGE = 60 * 60 * 24 * 365; // one year private static final long serialVersionUID = 3805114872438336791L; private static final Logger LOGGER = LogManager.getLogger(MCRTileServlet.class); private static MCRTileFileProvider TFP = MCRConfiguration2.<MCRDefaultTileFileProvider>getInstanceOf( "MCR.IIIFImage.Iview.TileFileProvider").orElseGet(MCRDefaultTileFileProvider::new); /** * Extracts tile or image properties from iview2 file and transmits it. * * Uses {@link HttpServletRequest#getPathInfo()} (see {@link #getTileInfo(String)}) to get tile attributes. * Also uses {@link #MAX_AGE} to tell the client how long it could cache the information. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { final MCRTileInfo tileInfo = getTileInfo(getPathInfo(req)); Path iviewFile = TFP.getTileFile(tileInfo).orElse(null); if (iviewFile == null) { LOGGER.info("TileFile not found: " + tileInfo); return; } if (!Files.exists(iviewFile)) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "File does not exist: " + iviewFile); return; } try (FileSystem iviewFS = MCRIView2Tools.getFileSystem(iviewFile)) { Path root = iviewFS.getRootDirectories().iterator().next(); Path tilePath = root.resolve(tileInfo.getTile()); BasicFileAttributes fileAttributes; try { fileAttributes = Files.readAttributes(tilePath, BasicFileAttributes.class); } catch (IOException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Tile not found: " + tileInfo); return; } resp.setHeader("Cache-Control", "max-age=" + MAX_AGE); resp.setDateHeader("Last-Modified", fileAttributes.lastModifiedTime().toMillis()); if (tileInfo.getTile().endsWith("xml")) { resp.setContentType("text/xml"); } else { resp.setContentType("image/jpeg"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Extracting {} size {}", tilePath, fileAttributes.size()); } //size of a tile or imageinfo.xml file is always smaller than Integer.MAX_VALUE resp.setContentLength((int) fileAttributes.size()); try (ServletOutputStream out = resp.getOutputStream()) { Files.copy(tilePath, out); } } LOGGER.debug("Ending MCRTileServlet"); } /** * Returns at which time the specified tile (see {@link #doGet(HttpServletRequest, HttpServletResponse)} * was last modified. */ @Override protected long getLastModified(final HttpServletRequest req) { final MCRTileInfo tileInfo = getTileInfo(getPathInfo(req)); try { return Files .getLastModifiedTime( TFP.getTileFile(tileInfo).orElseThrow(() -> new IOException("Could not get file for " + tileInfo))) .toMillis(); } catch (IOException e) { LOGGER.warn("Could not get lastmodified time.", e); return -1; } } /** * returns PathInfo from request including ";" */ private static String getPathInfo(final HttpServletRequest request) { return request.getPathInfo(); } /** * returns a {@link MCRTileInfo} for this <code>pathInfo</code>. * The format of <code>pathInfo</code> is * <code>/{derivateID}/{absoluteImagePath}/{tileCoordinate}</code> * where <code>tileCoordinate</code> is either {@value org.mycore.imagetiler.MCRTiledPictureProps#IMAGEINFO_XML} * or <code>{z}/{y}/{x}</code> as zoomLevel and x-y-coordinates. * @param pathInfo of the described format * @return a {@link MCRTileInfo} instance for <code>pathInfo</code> */ static MCRTileInfo getTileInfo(final String pathInfo) { LOGGER.debug("Starting MCRTileServlet: {}", pathInfo); String path = pathInfo.startsWith("/") ? pathInfo.substring(1) : pathInfo; final String derivate = path.contains("/") ? path.substring(0, path.indexOf('/')) : null; String imagePath = path.substring(derivate.length()); String tile; if (imagePath.endsWith(".xml")) { tile = imagePath.substring(imagePath.lastIndexOf('/') + 1); imagePath = imagePath.substring(0, imagePath.length() - tile.length() - 1); } else { int pos = imagePath.length(); int cnt = 0; while (--pos > 0 && cnt < 3) { if (imagePath.charAt(pos) == '/') { cnt++; } } tile = imagePath.substring(pos + 2); imagePath = imagePath.substring(0, ++pos); } return new MCRTileInfo(derivate, imagePath, tile); } }
6,678
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIView2Commands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRIView2Commands.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.iview2.frontend; import java.io.IOException; import java.io.InputStream; import java.nio.file.DirectoryStream; import java.nio.file.FileSystem; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javax.imageio.ImageReader; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRException; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter; import org.mycore.frontend.cli.MCRAbstractCommands; import org.mycore.frontend.cli.MCRCommandUtils; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; import org.mycore.imagetiler.MCRImage; import org.mycore.imagetiler.MCRTiledPictureProps; import org.mycore.iview2.services.MCRIView2Tools; import org.mycore.iview2.services.MCRImageTiler; import org.mycore.iview2.services.MCRTileJob; import org.mycore.iview2.services.MCRTilingQueue; import jakarta.persistence.EntityManager; import jakarta.persistence.TypedQuery; /** * Provides commands for Image Viewer. * @author Thomas Scheffler (yagee) * */ @MCRCommandGroup(name = "IView2 Tile Commands") public class MCRIView2Commands extends MCRAbstractCommands { private static final Logger LOGGER = LogManager.getLogger(MCRIView2Commands.class); private static final String TILE_DERIVATE_TILES_COMMAND_SYNTAX = "tile images of derivate {0}"; private static final String CHECK_TILES_OF_DERIVATE_COMMAND_SYNTAX = "check tiles of derivate {0}"; private static final String CHECK_TILES_OF_IMAGE_COMMAND_SYNTAX = "check tiles of image {0} {1}"; private static final String TILE_IMAGE_COMMAND_SYNTAX = "tile image {0} {1}"; private static final String DEL_DERIVATE_TILES_COMMAND_SYNTAX = "delete tiles of derivate {0}"; /** * meta command to tile all images of all derivates. * @return list of commands to execute. */ // tile images @MCRCommand(syntax = "tile images of all derivates", help = "tiles all images of all derivates with a supported image type as main document", order = 40) public static List<String> tileAll() { MessageFormat syntaxMF = new MessageFormat(TILE_DERIVATE_TILES_COMMAND_SYNTAX, Locale.ROOT); return MCRCommandUtils.getIdsForType("derivate") .map(id -> syntaxMF.format(new Object[] { id })) .collect(Collectors.toList()); } /** * meta command to check (and repair) tiles of all images of all derivates. * @return list of commands to execute. */ @MCRCommand(syntax = "check tiles of all derivates", help = "checks if all images have valid iview2 files and start tiling if not", order = 10) public static List<String> checkAll() { MessageFormat syntaxMF = new MessageFormat(CHECK_TILES_OF_DERIVATE_COMMAND_SYNTAX, Locale.ROOT); return MCRCommandUtils.getIdsForType("derivate") .map(id -> syntaxMF.format(new Object[] { id })) .collect(Collectors.toList()); } /** * meta command to tile all images of derivates of a project. * @return list of commands to execute. */ @MCRCommand(syntax = "tile images of derivates of project {0}", help = "tiles all images of derivates of a project with a supported image type as main document", order = 41) public static List<String> tileAllOfProject(String project) { MessageFormat syntaxMF = new MessageFormat(TILE_DERIVATE_TILES_COMMAND_SYNTAX, Locale.ROOT); return MCRCommandUtils.getIdsForProjectAndType(project, "derivate") .map(id -> syntaxMF.format(new Object[] { id })) .collect(Collectors.toList()); } /** * meta command to check (and repair) tiles of all images of derivates of a project. * @return list of commands to execute. */ @MCRCommand(syntax = "check tiles of derivates of project {0}", help = "checks if all images have valid iview2 files and start tiling if not", order = 11) public static List<String> checkAllOfProject(String project) { MessageFormat syntaxMF = new MessageFormat(CHECK_TILES_OF_DERIVATE_COMMAND_SYNTAX, Locale.ROOT); return MCRCommandUtils.getIdsForProjectAndType(project, "derivate") .map(id -> syntaxMF.format(new Object[] { id })) .collect(Collectors.toList()); } /** * meta command to tile all images of derivates of an object . * @param objectID a object ID * @return list of commands to execute. */ @MCRCommand(syntax = "tile images of object {0}", help = "tiles all images of derivates of object {0} with a supported image type as main document", order = 50) public static List<String> tileDerivatesOfObject(String objectID) { return forAllDerivatesOfObject(objectID, TILE_DERIVATE_TILES_COMMAND_SYNTAX); } /** * meta command to tile all images of this derivate. * @param derivateID a derivate ID * @return list of commands to execute. */ @MCRCommand(syntax = TILE_DERIVATE_TILES_COMMAND_SYNTAX, help = "tiles all images of derivate {0} with a supported image type as main document", order = 60) public static List<String> tileDerivate(String derivateID) throws IOException { return forAllImages(derivateID, TILE_IMAGE_COMMAND_SYNTAX); } /** * meta command to check (and repair) all tiles of all images of this derivate. * @param derivateID a derivate ID * @return list of commands to execute. */ @MCRCommand(syntax = CHECK_TILES_OF_DERIVATE_COMMAND_SYNTAX, help = "checks if all images of derivate {0} with a supported image type as main document have valid iview2" + " files and start tiling if not ", order = 20) public static List<String> checkTilesOfDerivate(String derivateID) throws IOException { return forAllImages(derivateID, CHECK_TILES_OF_IMAGE_COMMAND_SYNTAX); } private static List<String> forAllImages(String derivateID, String batchCommandSyntax) throws IOException { if (!MCRIView2Tools.isDerivateSupported(derivateID)) { LOGGER.info("Skipping tiling of derivate {} as it's main file is not supported by IView2.", derivateID); return null; } MCRPath derivateRoot = MCRPath.getPath(derivateID, "/"); if (!Files.exists(derivateRoot)) { throw new MCRException("Derivate " + derivateID + " does not exist or is not a directory!"); } List<MCRPath> supportedFiles = getSupportedFiles(derivateRoot); return supportedFiles.stream() .map( image -> new MessageFormat(batchCommandSyntax, Locale.ROOT).format( new Object[] { derivateID, image.getOwnerRelativePath() })) .collect(Collectors.toList()); } @MCRCommand(syntax = "fix dead tile jobs", help = "Deletes entries for files which dont exist anymore!") public static void fixDeadEntries() { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); TypedQuery<MCRTileJob> allTileJobQuery = em.createNamedQuery("MCRTileJob.all", MCRTileJob.class); List<MCRTileJob> tiles = allTileJobQuery.getResultList(); tiles.stream() .filter(tj -> { MCRPath path = MCRPath.getPath(tj.getDerivate(), tj.getPath()); return !Files.exists(path); }) .peek(tj -> LOGGER.info("Delete TileJob {}:{}", tj.getDerivate(), tj.getPath())) .forEach(em::remove); } /** * checks and repairs tile of this derivate. * @param derivate derivate ID * @param absoluteImagePath absolute path to image file */ @MCRCommand(syntax = CHECK_TILES_OF_IMAGE_COMMAND_SYNTAX, help = "checks if tiles a specific file identified by its derivate {0} and absolute path {1} are valid or" + " generates new one", order = 30) public static void checkImage(String derivate, String absoluteImagePath) throws IOException { Path iviewFile = MCRImage.getTiledFile(MCRIView2Tools.getTileDir(), derivate, absoluteImagePath); //file checks if (!Files.exists(iviewFile)) { LOGGER.warn("IView2 file does not exist: {}", iviewFile); tileImage(derivate, absoluteImagePath); return; } MCRTiledPictureProps props; try { props = MCRTiledPictureProps.getInstanceFromFile(iviewFile); } catch (Exception e) { LOGGER.warn("Error while reading image metadata. Recreating tiles.", e); tileImage(derivate, absoluteImagePath); return; } if (props == null) { LOGGER.warn("Could not get tile metadata"); tileImage(derivate, absoluteImagePath); return; } ZipFile iviewImage; try { iviewImage = new ZipFile(iviewFile.toFile()); validateZipFile(iviewImage); } catch (Exception e) { LOGGER.warn("Error while reading Iview2 file: {}", iviewFile, e); tileImage(derivate, absoluteImagePath); return; } try (FileSystem fs = MCRIView2Tools.getFileSystem(iviewFile)) { Path iviewFileRoot = fs.getRootDirectories().iterator().next(); //structure and metadata checks int tilesCount = iviewImage.size() - 1; //one for metadata if (props.getTilesCount() != tilesCount) { LOGGER.warn("Metadata tile count does not match stored tile count: {}", iviewFile); tileImage(derivate, absoluteImagePath); return; } int x = props.getWidth(); int y = props.getHeight(); if (MCRImage.getTileCount(x, y) != tilesCount) { LOGGER.warn("Calculated tile count does not match stored tile count: {}", iviewFile); tileImage(derivate, absoluteImagePath); return; } try { ImageReader imageReader = MCRIView2Tools.getTileImageReader(); MCRIView2Tools.getZoomLevel(iviewFileRoot, props, imageReader, 0); int maxX = (int) Math.ceil((double) props.getWidth() / MCRImage.getTileSize()); int maxY = (int) Math.ceil((double) props.getHeight() / MCRImage.getTileSize()); LOGGER.debug("Image size:{}x{}, tiles:{}x{}", props.getWidth(), props.getHeight(), maxX, maxY); try { MCRIView2Tools.readTile(iviewFileRoot, imageReader, props.getZoomlevel(), maxX - 1, 0); } finally { imageReader.dispose(); } } catch (IOException e) { LOGGER.warn("Could not read thumbnail of {}", iviewFile, e); tileImage(derivate, absoluteImagePath); } } } private static void validateZipFile(ZipFile iviewImage) throws IOException { Enumeration<? extends ZipEntry> entries = iviewImage.entries(); CRC32 crc = new CRC32(); byte[] data = new byte[4096]; int read; while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); try (InputStream is = iviewImage.getInputStream(entry)) { while ((read = is.read(data, 0, data.length)) != -1) { crc.update(data, 0, read); } } if (entry.getCrc() != crc.getValue()) { throw new IOException("CRC32 does not match for entry: " + entry.getName()); } crc.reset(); } } /** * Tiles this image. * @param derivate derivate ID * @param absoluteImagePath absolute path to image file */ @MCRCommand(syntax = TILE_IMAGE_COMMAND_SYNTAX, help = "tiles a specific file identified by its derivate {0} and absolute path {1}", order = 70) public static void tileImage(String derivate, String absoluteImagePath) { MCRTileJob job = new MCRTileJob(); job.setDerivate(derivate); job.setPath(absoluteImagePath); MCRTilingQueue.getInstance().offer(job); startMasterTilingThread(); } /** * Tiles this {@link MCRPath} */ public static void tileImage(MCRPath file) throws IOException { if (MCRIView2Tools.isFileSupported(file)) { MCRTileJob job = new MCRTileJob(); job.setDerivate(file.getOwner()); job.setPath(file.getOwnerRelativePath()); MCRTilingQueue.getInstance().offer(job); LOGGER.info("Added to TilingQueue: {}", file); startMasterTilingThread(); } } private static void startMasterTilingThread() { if (!MCRImageTiler.isRunning()) { LOGGER.info("Starting Tiling thread."); final Thread tiling = new Thread(MCRImageTiler.getInstance()); tiling.start(); } } /** * Deletes all image tiles. */ @MCRCommand(syntax = "delete all tiles", help = "removes all tiles of all derivates", order = 80) public static void deleteAllTiles() throws IOException { Path storeDir = MCRIView2Tools.getTileDir(); Files.walkFileTree(storeDir, MCRRecursiveDeleter.instance()); MCRTilingQueue.getInstance().clear(); } /** * Deletes all image tiles of derivates of this object. * @param objectID a object ID */ @MCRCommand(syntax = "delete tiles of object {0}", help = "removes tiles of a specific file identified by its object ID {0}", order = 90) public static List<String> deleteDerivateTilesOfObject(String objectID) { return forAllDerivatesOfObject(objectID, DEL_DERIVATE_TILES_COMMAND_SYNTAX); } private static List<String> forAllDerivatesOfObject(String objectID, String batchCommandSyntax) { MCRObjectID mcrobjid; try { mcrobjid = MCRObjectID.getInstance(objectID); } catch (Exception e) { LOGGER.error("The object ID {} is wrong", objectID); return null; } List<MCRObjectID> derivateIds = MCRMetadataManager.getDerivateIds(mcrobjid, 0, TimeUnit.MILLISECONDS); if (derivateIds == null) { LOGGER.error("Object does not exist: {}", mcrobjid); } ArrayList<String> cmds = new ArrayList<>(derivateIds.size()); for (MCRObjectID derId : derivateIds) { cmds.add(new MessageFormat(batchCommandSyntax, Locale.ROOT).format(new String[] { derId.toString() })); } return cmds; } /** * Deletes all image tiles of this derivate. * @param derivateID a derivate ID */ @MCRCommand(syntax = DEL_DERIVATE_TILES_COMMAND_SYNTAX, help = "removes tiles of a specific file identified by its derivate ID {0}", order = 100) public static void deleteDerivateTiles(String derivateID) throws IOException { Path derivateDir = MCRImage.getTiledFile(MCRIView2Tools.getTileDir(), derivateID, null); Files.walkFileTree(derivateDir, MCRRecursiveDeleter.instance()); MCRTilingQueue.getInstance().remove(derivateID); } /** * Deletes all image tiles of this derivate. * @param derivate derivate ID * @param absoluteImagePath absolute path to image file */ @MCRCommand(syntax = "delete tiles of image {0} {1}", help = "removes tiles of a specific file identified by its derivate ID {0} and absolute path {1}", order = 110) public static void deleteImageTiles(String derivate, String absoluteImagePath) throws IOException { Path tileFile = MCRImage.getTiledFile(MCRIView2Tools.getTileDir(), derivate, absoluteImagePath); deleteFileAndEmptyDirectories(tileFile); int removed = MCRTilingQueue.getInstance().remove(derivate, absoluteImagePath); LOGGER.info("removed tiles from {} images", removed); } private static void deleteFileAndEmptyDirectories(Path file) throws IOException { if (Files.isRegularFile(file)) { Files.delete(file); } if (Files.isDirectory(file)) { try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(file)) { for (@SuppressWarnings("unused") Path entry : directoryStream) { return; } Files.delete(file); } } Path parent = file.getParent(); if (parent != null && parent.getNameCount() > 0) { deleteFileAndEmptyDirectories(parent); } } private static List<MCRPath> getSupportedFiles(MCRPath rootNode) throws IOException { final ArrayList<MCRPath> files = new ArrayList<>(); SimpleFileVisitor<Path> test = new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Objects.requireNonNull(file); Objects.requireNonNull(attrs); if (MCRIView2Tools.isFileSupported(file)) { files.add(MCRPath.toMCRPath(file)); } return FileVisitResult.CONTINUE; } }; Files.walkFileTree(rootNode, test); return files; } }
18,918
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPDFTools.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRPDFTools.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.iview2.frontend; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.pdfbox.Loader; import org.apache.pdfbox.io.RandomAccessRead; import org.apache.pdfbox.io.RandomAccessReadBuffer; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.common.PDDestinationOrAction; import org.apache.pdfbox.pdmodel.interactive.action.PDActionGoTo; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination; import org.apache.pdfbox.rendering.PDFRenderer; import org.mycore.common.content.MCRContent; import org.mycore.tools.MCRPNGTools; /** * @author Thomas Scheffler (yagee) */ public class MCRPDFTools implements AutoCloseable { static final int PDF_DEFAULT_DPI = 72; // from private org.apache.pdfbox.pdmodel.PDPage.DEFAULT_USER_SPACE_UNIT_DPI private static final Logger LOGGER = LogManager.getLogger(MCRPDFTools.class); private final MCRPNGTools pngTools; MCRPDFTools() { this.pngTools = new MCRPNGTools(); } /** * The old method did not take the thumbnail size into account, if centered = * false; * * @see #getThumbnail(int, Path, boolean) */ @Deprecated public static BufferedImage getThumbnail(Path pdfFile, int thumbnailSize, boolean centered) throws IOException { return getThumbnail(-1, pdfFile, false); } /** * This method returns a Buffered Image as thumbnail if an initial page was set, * it will be return - if not the first page * * @param thumbnailSize - the size: size = max(width, height) * a size &lt; 0 will return the original size and centered parameter will be ignored * @param pdfFile - the file from which the thumbnail will be taken * @param centered - if true, a square (thumbnail with same width and * height) will be returned * @return a BufferedImage as thumbnail * */ public static BufferedImage getThumbnail(int thumbnailSize, Path pdfFile, boolean centered) throws IOException { try (InputStream fileIS = Files.newInputStream(pdfFile); RandomAccessRead readBuffer = new RandomAccessReadBuffer(fileIS); PDDocument pdf = Loader.loadPDF(readBuffer)) { PDFRenderer pdfRenderer = new PDFRenderer(pdf); final PDPage page = resolveOpenActionPage(pdf); int pageIndex = pdf.getPages().indexOf(page); if (pageIndex == -1) { // Iterating per page and use equals does also not work in the case I had, so fall back to first page LOGGER.warn("Could not resolve initial page, using first page."); pageIndex = 0; } BufferedImage level1Image = pdfRenderer.renderImage(pageIndex); if (thumbnailSize < 0) { return level1Image; } return scalePage(thumbnailSize, centered, level1Image); } } private static BufferedImage scalePage(int thumbnailSize, boolean centered, BufferedImage level1Image) { int imageType = BufferedImage.TYPE_INT_ARGB; final double width = level1Image.getWidth(); final double height = level1Image.getHeight(); LOGGER.info("new PDFBox: {}x{}", width, height); LOGGER.info("temporary image dimensions: {}x{}", width, height); final int newWidth = calculateNewWidth(thumbnailSize, width, height); final int newHeight = calculateNewHeight(thumbnailSize, width, height); // if centered make thumbnailSize x thumbnailSize image final BufferedImage bicubicScaledPage = new BufferedImage(centered ? thumbnailSize : newWidth, centered ? thumbnailSize : newHeight, imageType); LOGGER.info("target image dimensions: {}x{}", bicubicScaledPage.getWidth(), bicubicScaledPage.getHeight()); final Graphics2D bg = bicubicScaledPage.createGraphics(); try { bg.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); int x = centered ? (thumbnailSize - newWidth) / 2 : 0; int y = centered ? (thumbnailSize - newHeight) / 2 : 0; if (x != 0 && y != 0) { LOGGER.warn("Writing at position {},{}", x, y); } bg.drawImage(level1Image, x, y, x + newWidth, y + newHeight, 0, 0, (int) Math.ceil(width), (int) Math.ceil(height), null); } finally { bg.dispose(); } return bicubicScaledPage; } private static int calculateNewHeight(int thumbnailSize, double width, double height) { return width < height ? thumbnailSize : (int) Math.ceil(thumbnailSize * height / width); } private static int calculateNewWidth(int thumbnailSize, double width, double height) { return width < height ? (int) Math.ceil(thumbnailSize * width / height) : thumbnailSize; } /** * * @param pdf - the pdf document * @see org.mycore.media.services.MCRPdfThumbnailGenerator */ private static PDPage resolveOpenActionPage(PDDocument pdf) throws IOException { PDDestinationOrAction openAction = pdf.getDocumentCatalog().getOpenAction(); if (openAction instanceof PDActionGoTo goTo && goTo.getDestination() instanceof PDPageDestination destination) { openAction = destination; } if (openAction instanceof PDPageDestination namedDestination) { final PDPage pdPage = namedDestination.getPage(); if (pdPage != null) { return pdPage; } else { int pageNumber = namedDestination.getPageNumber(); if (pageNumber != -1) { return pdf.getPage(pageNumber); } } } return pdf.getPage(0); } MCRContent getThumnail(Path pdfFile, BasicFileAttributes attrs, int thumbnailSize, boolean centered) throws IOException { BufferedImage thumbnail = MCRPDFTools.getThumbnail(pdfFile, thumbnailSize, centered); MCRContent pngContent = pngTools.toPNGContent(thumbnail); BasicFileAttributes fattrs = attrs != null ? attrs : Files.readAttributes(pdfFile, BasicFileAttributes.class); pngContent.setLastModified(fattrs.lastModifiedTime().toMillis()); return pngContent; } @Override public void close() { this.pngTools.close(); } }
7,577
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRThumbnailServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRThumbnailServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.iview2.frontend; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.text.MessageFormat; import java.util.Date; import java.util.Locale; import java.util.Objects; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.datamodel.niofs.MCRPathUtils; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.imagetiler.MCRImage; import org.mycore.imagetiler.MCRTiledPictureProps; import org.mycore.iview2.services.MCRIView2Tools; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import jakarta.servlet.ServletException; import jakarta.servlet.ServletOutputStream; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author Thomas Scheffler (yagee) * */ public class MCRThumbnailServlet extends MCRServlet { private static final long serialVersionUID = 1506443527774956290L; //stores max png size for byte array buffer of output private AtomicInteger maxPngSize = new AtomicInteger(64 * 1024); private ImageWriteParam imageWriteParam; private ConcurrentLinkedQueue<ImageWriter> imageWriters = new ConcurrentLinkedQueue<>(); private static Logger LOGGER = LogManager.getLogger(MCRThumbnailServlet.class); private int thumbnailSize = MCRImage.getTileSize(); private static LoadingCache<String, Long> modifiedCache = CacheBuilder.newBuilder().maximumSize(5000) .expireAfterWrite(MCRTileServlet.MAX_AGE, TimeUnit.SECONDS).weakKeys().build(new CacheLoader<>() { @Override public Long load(String id) { ThumnailInfo thumbnailInfo = getThumbnailInfo(id); Path iviewFile = MCRImage.getTiledFile(MCRIView2Tools.getTileDir(), thumbnailInfo.derivate, thumbnailInfo.imagePath); try { return Files.readAttributes(iviewFile, BasicFileAttributes.class).lastModifiedTime().toMillis(); } catch (IOException x) { return -1L; } } }); @Override public void init() throws ServletException { super.init(); imageWriters = new ConcurrentLinkedQueue<>(); imageWriteParam = ImageIO.getImageWritersBySuffix("png").next().getDefaultWriteParam(); try { imageWriteParam.setProgressiveMode(ImageWriteParam.MODE_DEFAULT); } catch (UnsupportedOperationException e) { LOGGER.warn("Your PNG encoder does not support progressive PNGs."); } String thSize = getInitParameter("thumbnailSize"); if (thSize != null) { thumbnailSize = Integer.parseInt(thSize); } LOGGER.info("{}: setting thumbnail size to {}", getServletName(), thumbnailSize); } @Override public void destroy() { for (ImageWriter imageWriter : imageWriters) { imageWriter.dispose(); } super.destroy(); } @Override protected long getLastModified(HttpServletRequest request) { return modifiedCache.getUnchecked(request.getPathInfo()); } @Override protected void render(MCRServletJob job, Exception ex) throws IOException { try { ThumnailInfo thumbnailInfo = getThumbnailInfo(job.getRequest().getPathInfo()); Path iviewFile = MCRImage.getTiledFile(MCRIView2Tools.getTileDir(), thumbnailInfo.derivate, thumbnailInfo.imagePath); LOGGER.info("IView2 file: {}", iviewFile); BasicFileAttributes fileAttributes = MCRPathUtils.getAttributes(iviewFile, BasicFileAttributes.class); if (fileAttributes == null) { job.getResponse().sendError( HttpServletResponse.SC_NOT_FOUND, new MessageFormat("Could not find iview2 file for {0}{1}", Locale.ROOT) .format(new Object[] { thumbnailInfo.derivate, thumbnailInfo.imagePath })); return; } String centerThumb = job.getRequest().getParameter("centerThumb"); //defaults to "yes" boolean centered = !Objects.equals(centerThumb, "no"); BufferedImage thumbnail = getThumbnail(iviewFile, centered); if (thumbnail != null) { job.getResponse().setHeader("Cache-Control", "max-age=" + MCRTileServlet.MAX_AGE); job.getResponse().setContentType("image/png"); job.getResponse().setDateHeader("Last-Modified", fileAttributes.lastModifiedTime().toMillis()); Date expires = new Date(System.currentTimeMillis() + MCRTileServlet.MAX_AGE * 1000); LOGGER.debug("Last-Modified: {}, expire on: {}", fileAttributes.lastModifiedTime(), expires); job.getResponse().setDateHeader("Expires", expires.getTime()); ImageWriter imageWriter = getImageWriter(); try (ServletOutputStream sout = job.getResponse().getOutputStream(); ByteArrayOutputStream bout = new ByteArrayOutputStream(maxPngSize.get()); ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(bout)) { imageWriter.setOutput(imageOutputStream); //tile = addWatermark(scaleBufferedImage(tile)); IIOImage iioImage = new IIOImage(thumbnail, null, null); imageWriter.write(null, iioImage, imageWriteParam); int contentLength = bout.size(); maxPngSize.set(Math.max(maxPngSize.get(), contentLength)); job.getResponse().setContentLength(contentLength); bout.writeTo(sout); } finally { imageWriter.reset(); imageWriters.add(imageWriter); } } else { job.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND); } } finally { LOGGER.debug("Finished sending {}", job.getRequest().getPathInfo()); } } private static ThumnailInfo getThumbnailInfo(String pathInfo) { String pInfo = pathInfo; if (pInfo.startsWith("/")) { pInfo = pInfo.substring(1); } final String derivate = pInfo.substring(0, pInfo.indexOf('/')); String imagePath = pInfo.substring(derivate.length()); LOGGER.debug("derivate: {}, image: {}", derivate, imagePath); return new ThumnailInfo(derivate, imagePath); } private BufferedImage getThumbnail(Path iviewFile, boolean centered) throws IOException { BufferedImage level1Image; try (FileSystem fs = MCRIView2Tools.getFileSystem(iviewFile)) { Path iviewFileRoot = fs.getRootDirectories().iterator().next(); MCRTiledPictureProps props = MCRTiledPictureProps.getInstanceFromDirectory(iviewFileRoot); //get next bigger zoomLevel and scale image to THUMBNAIL_SIZE ImageReader reader = MCRIView2Tools.getTileImageReader(); try { level1Image = MCRIView2Tools.getZoomLevel(iviewFileRoot, props, reader, Math.min(1, props.getZoomlevel())); } finally { reader.dispose(); } } final double width = level1Image.getWidth(); final double height = level1Image.getHeight(); final int newWidth = width < height ? (int) Math.ceil(thumbnailSize * width / height) : thumbnailSize; final int newHeight = width < height ? thumbnailSize : (int) Math.ceil(thumbnailSize * height / width); //if centered make transparent image int imageType = centered ? BufferedImage.TYPE_INT_ARGB : MCRImage.getImageType(level1Image); //if centered make thumbnailSize x thumbnailSize image final BufferedImage bicubic = new BufferedImage(centered ? thumbnailSize : newWidth, centered ? thumbnailSize : newHeight, imageType); final Graphics2D bg = bicubic.createGraphics(); try { bg.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); int x = centered ? (thumbnailSize - newWidth) / 2 : 0; int y = centered ? (thumbnailSize - newHeight) / 2 : 0; if (x != 0 && y != 0) { LOGGER.warn("Writing at position {},{}", x, y); } bg.drawImage(level1Image, x, y, x + newWidth, y + newHeight, 0, 0, (int) Math.ceil(width), (int) Math.ceil(height), null); } finally { bg.dispose(); } return bicubic; } private ImageWriter getImageWriter() { ImageWriter imageWriter = imageWriters.poll(); if (imageWriter == null) { imageWriter = ImageIO.getImageWritersBySuffix("png").next(); } return imageWriter; } private static class ThumnailInfo { String derivate, imagePath; ThumnailInfo(final String derivate, final String imagePath) { this.derivate = derivate; this.imagePath = imagePath; } @Override public String toString() { return "TileInfo [derivate=" + derivate + ", imagePath=" + imagePath + "]"; } } }
10,813
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTileCombineServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRTileCombineServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.iview2.frontend; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.nio.file.FileSystem; import java.nio.file.Path; import java.text.MessageFormat; import java.time.Instant; import java.util.Locale; import java.util.concurrent.TimeUnit; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.plugins.jpeg.JPEGImageWriteParam; import javax.imageio.stream.ImageOutputStream; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRClassTools; import org.mycore.common.xml.MCRXMLFunctions; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.imagetiler.MCRImage; import org.mycore.imagetiler.MCRTiledPictureProps; import org.mycore.iview2.services.MCRIView2Tools; import jakarta.servlet.ServletException; import jakarta.servlet.ServletOutputStream; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Combines tiles of an image in specific resolutions. * @author Thomas Scheffler (yagee) * */ public class MCRTileCombineServlet extends MCRServlet { /** key of request attribute for {@link BufferedImage}. */ protected static final String IMAGE_KEY = MCRTileCombineServlet.class.getName() + ".image"; /** key of request attribute for iview2-{@link File}. */ protected static final String THUMBNAIL_KEY = MCRTileCombineServlet.class.getName() + ".thumb"; private static final long serialVersionUID = 7924934677622546958L; private static final float QUALITY = 0.75f; private static final Logger LOGGER = LogManager.getLogger(MCRTileCombineServlet.class); private ThreadLocal<ImageWriter> imageWriter = ThreadLocal.withInitial( () -> ImageIO.getImageWritersBySuffix("jpeg").next()); private JPEGImageWriteParam imageWriteParam; private MCRFooterInterface footerImpl = null; /** * Initializes this instance. * * Use parameter <code>org.mycore.iview2.frontend.MCRFooterInterface</code> to specify implementation of * {@link MCRFooterInterface} (can be omitted). */ @Override public void init() throws ServletException { super.init(); imageWriteParam = new JPEGImageWriteParam(Locale.getDefault()); try { imageWriteParam.setProgressiveMode(ImageWriteParam.MODE_DEFAULT); } catch (UnsupportedOperationException e) { LOGGER.warn("Your JPEG encoder does not support progressive JPEGs."); } imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); imageWriteParam.setCompressionQuality(QUALITY); String footerClassName = getInitParameter(MCRFooterInterface.class.getName()); if (footerClassName != null) { try { footerImpl = (MCRFooterInterface) MCRClassTools.forName(footerClassName).getDeclaredConstructor() .newInstance(); } catch (Exception e) { throw new ServletException("Could not initialize MCRFooterInterface", e); } } } /** * prepares render process and gets IView2 file and combines tiles. * The image dimensions and path are determined from {@link HttpServletRequest#getPathInfo()}: * <code>/{zoomAlias}/{derivateID}/{absoluteImagePath}</code> * where <code>zoomAlias</code> is mapped like this: * <table> * <caption>Mapping of zoomAlias to actual zoom level</caption> * <tr><th>zoomAlias</th><th>zoom level</th></tr> * <tr><td>'MIN'</td><td>1</td></tr> * <tr><td>'MID'</td><td>2</td></tr> * <tr><td>'MAX'</td><td>3</td></tr> * <tr><td>default and all others</td><td>0</td></tr> * </table> * * See {@link #init()} how to attach a footer to every generated image. */ @Override protected void think(final MCRServletJob job) throws IOException, URISyntaxException { final HttpServletRequest request = job.getRequest(); try { String pathInfo = request.getPathInfo(); if (pathInfo.startsWith("/")) { pathInfo = pathInfo.substring(1); } String zoomAlias = pathInfo.substring(0, pathInfo.indexOf('/')); pathInfo = pathInfo.substring(zoomAlias.length() + 1); final String derivate = pathInfo.substring(0, pathInfo.indexOf('/')); String imagePath = pathInfo.substring(derivate.length()); LOGGER.info("Zoom-Level: {}, derivate: {}, image: {}", zoomAlias, derivate, imagePath); final Path iviewFile = MCRImage.getTiledFile(MCRIView2Tools.getTileDir(), derivate, imagePath); try (FileSystem fs = MCRIView2Tools.getFileSystem(iviewFile)) { Path iviewFileRoot = fs.getRootDirectories().iterator().next(); final MCRTiledPictureProps pictureProps = MCRTiledPictureProps.getInstanceFromDirectory(iviewFileRoot); final int maxZoomLevel = pictureProps.getZoomlevel(); request.setAttribute(THUMBNAIL_KEY, iviewFile); LOGGER.info("IView2 file: {}", iviewFile); int zoomLevel = switch (zoomAlias) { case "MIN" -> 1; case "MID" -> 2; case "MAX" -> 3; default -> 0; }; HttpServletResponse response = job.getResponse(); if (zoomLevel > maxZoomLevel) { zoomAlias = switch (maxZoomLevel) { case 2 -> "MID"; case 1 -> "MIN"; default -> "THUMB"; }; if (!imagePath.startsWith("/")) { imagePath = "/" + imagePath; } String redirectURL = response.encodeRedirectURL(new MessageFormat("{0}{1}/{2}/{3}{4}", Locale.ROOT) .format(new Object[] { request.getContextPath(), request.getServletPath(), zoomAlias, derivate, MCRXMLFunctions.encodeURIPath(imagePath) })); response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", redirectURL); response.flushBuffer(); return; } if (zoomLevel == 0 && footerImpl == null) { //we're done, sendThumbnail is called in render phase return; } ImageReader reader = MCRIView2Tools.getTileImageReader(); try { BufferedImage combinedImage = MCRIView2Tools.getZoomLevel(iviewFileRoot, pictureProps, reader, zoomLevel); if (combinedImage != null) { if (footerImpl != null) { BufferedImage footer = footerImpl.getFooter(combinedImage.getWidth(), derivate, imagePath); combinedImage = attachFooter(combinedImage, footer); } request.setAttribute(IMAGE_KEY, combinedImage); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } finally { reader.dispose(); } } } finally { LOGGER.info("Finished sending {}", request.getPathInfo()); } } /** * Transmits combined file or sends thumbnail. * Uses {@link HttpServletRequest#getAttribute(String)} to retrieve information generated * by {@link #think(MCRServletJob)}. * <table> * <caption>description of {@link HttpServletRequest} attributes</caption> * <tr><th>keyName</th><th>type</th><th>description</th></tr> * <tr><td>{@link #THUMBNAIL_KEY}</td><td>{@link File}</td><td>.iview2 File with all tiles in it</td></tr> * <tr><td>{@link #IMAGE_KEY}</td><td>{@link BufferedImage}</td> * <td>generated image if <code>zoomLevel != 0</code> and no implementation * of {@link MCRFooterInterface} defined</td></tr> * </table> */ @Override protected void render(final MCRServletJob job, final Exception ex) throws Exception { if (job.getResponse().isCommitted()) { return; } if (ex != null) { throw ex; } //check for thumnail final File iviewFile = ((Path) job.getRequest().getAttribute(THUMBNAIL_KEY)).toFile(); final BufferedImage combinedImage = (BufferedImage) job.getRequest().getAttribute(IMAGE_KEY); if (iviewFile != null && combinedImage == null) { sendThumbnail(iviewFile, job.getResponse()); return; } //send combined image job.getResponse().setHeader("Cache-Control", "max-age=" + MCRTileServlet.MAX_AGE); job.getResponse().setContentType("image/jpeg"); job.getResponse().setDateHeader("Last-Modified", iviewFile.lastModified()); final Instant expires = Instant.now().plus(MCRTileServlet.MAX_AGE, TimeUnit.SECONDS.toChronoUnit()); LOGGER.info("Last-Modified: {}, expire on: {}", Instant.ofEpochMilli(iviewFile.lastModified()), expires); job.getResponse().setDateHeader("Expires", expires.toEpochMilli()); final ImageWriter curImgWriter = imageWriter.get(); try (ServletOutputStream sout = job.getResponse().getOutputStream(); ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(sout)) { curImgWriter.setOutput(imageOutputStream); final IIOImage iioImage = new IIOImage(combinedImage, null, null); curImgWriter.write(null, iioImage, imageWriteParam); } finally { curImgWriter.reset(); } } /** * attaches <code>footer</code> to <code>combinedImage</code>. * @param combinedImage image to attach footer to * @param footer image of same with as <code>combinedImage</code> * @return a {@link BufferedImage} with <code>footer</code> attached to <code>combinedImage</code> */ protected static BufferedImage attachFooter(final BufferedImage combinedImage, final BufferedImage footer) { final BufferedImage resultImage = new BufferedImage(combinedImage.getWidth(), combinedImage.getHeight() + footer.getHeight(), combinedImage.getType()); final Graphics2D graphics = resultImage.createGraphics(); try { graphics.drawImage(combinedImage, 0, 0, null); graphics.drawImage(footer, 0, combinedImage.getHeight(), null); return resultImage; } finally { graphics.dispose(); } } private void sendThumbnail(final File iviewFile, final HttpServletResponse response) throws IOException { try (ZipFile zipFile = new ZipFile(iviewFile)) { final ZipEntry ze = zipFile.getEntry("0/0/0.jpg"); if (ze != null) { response.setHeader("Cache-Control", "max-age=" + MCRTileServlet.MAX_AGE); response.setContentType("image/jpeg"); response.setContentLength((int) ze.getSize()); try (ServletOutputStream out = response.getOutputStream(); InputStream zin = zipFile.getInputStream(ze)) { IOUtils.copy(zin, out); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } } }
12,705
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPDFThumbnailServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRPDFThumbnailServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.iview2.frontend; import java.io.IOException; import java.nio.file.Files; import java.nio.file.attribute.BasicFileAttributes; import java.util.Date; import java.util.Locale; import java.util.Objects; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.content.MCRContent; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.frontend.servlets.MCRContentServlet; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author Thomas Scheffler (yagee) * */ public class MCRPDFThumbnailServlet extends MCRContentServlet { private static final long serialVersionUID = 1L; private static Logger LOGGER = LogManager.getLogger(MCRPDFThumbnailServlet.class); private int thumbnailSize = 256; static final int MAX_AGE = 60 * 60 * 24 * 365; // one year private MCRPDFTools pdfTools; /* (non-Javadoc) * @see org.mycore.frontend.servlets.MCRContentServlet#getContent(jakarta.servlet.http.HttpServletRequest, * jakarta.servlet.http.HttpServletResponse) */ @Override public MCRContent getContent(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { ThumnailInfo thumbnailInfo = getThumbnailInfo(req.getPathInfo()); MCRPath pdfFile = MCRPath.getPath(thumbnailInfo.derivate, thumbnailInfo.filePath); LOGGER.info("PDF file: {}", pdfFile); if (Files.notExists(pdfFile)) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, String.format(Locale.ENGLISH, "Could not find pdf file for %s%s", thumbnailInfo.derivate, thumbnailInfo.filePath)); return null; } String centerThumb = req.getParameter("centerThumb"); String imgSize = req.getParameter("ts"); //defaults to "yes" boolean centered = !Objects.equals(centerThumb, "no"); int thumbnailSize = imgSize == null ? this.thumbnailSize : Integer.parseInt(imgSize); BasicFileAttributes attrs = Files.readAttributes(pdfFile, BasicFileAttributes.class); MCRContent imageContent = pdfTools.getThumnail(pdfFile, attrs, thumbnailSize, centered); if (imageContent != null) { resp.setHeader("Cache-Control", "max-age=" + MAX_AGE); Date expires = new Date(System.currentTimeMillis() + MAX_AGE * 1000); LOGGER.debug("Last-Modified: {}, expire on: {}", new Date(attrs.lastModifiedTime().toMillis()), expires); resp.setDateHeader("Expires", expires.getTime()); } return imageContent; } finally { LOGGER.debug("Finished sending {}", req.getPathInfo()); } } @Override public void init() throws ServletException { super.init(); String thSize = getInitParameter("thumbnailSize"); if (thSize != null) { thumbnailSize = Integer.parseInt(thSize); } pdfTools = new MCRPDFTools(); LOGGER.info("{}: setting thumbnail size to {}", getServletName(), thumbnailSize); } @Override public void destroy() { try { pdfTools.close(); } catch (Exception e) { LOGGER.error("Error while closing PDF tools.", e); } super.destroy(); } private static ThumnailInfo getThumbnailInfo(String pathInfo) { String pInfo = pathInfo; if (pInfo.startsWith("/")) { pInfo = pInfo.substring(1); } final String derivate = pInfo.substring(0, pInfo.indexOf('/')); String imagePath = pInfo.substring(derivate.length()); LOGGER.debug("derivate: {}, image: {}", derivate, imagePath); return new ThumnailInfo(derivate, imagePath); } private static class ThumnailInfo { String derivate, filePath; ThumnailInfo(final String derivate, final String imagePath) { this.derivate = derivate; this.filePath = imagePath; } @Override public String toString() { return "TileInfo [derivate=" + derivate + ", filePath=" + filePath + "]"; } } }
5,052
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIView2XSLFunctions.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRIView2XSLFunctions.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.iview2.frontend; import static org.mycore.common.MCRConstants.XLINK_NAMESPACE; import java.util.List; import java.util.Objects; import java.util.stream.IntStream; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRMetaEnrichedLinkID; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * @author Thomas Scheffler (yagee) */ public class MCRIView2XSLFunctions { private static final String METS_NAMESPACE_URI = "http://www.loc.gov/METS/"; private static final MCRIView2XSLFunctionsAdapter ADAPTER = MCRIView2XSLFunctionsAdapter.getInstance(); public static boolean hasMETSFile(String derivateID) { return ADAPTER.hasMETSFile(derivateID); } public static String getSupportedMainFile(String derivateID) { return ADAPTER.getSupportedMainFile(derivateID); } public static String getOptions(String derivateID, String extensions) { return ADAPTER.getOptions(derivateID, extensions); } /** * Get the full path of the main file of the first derivate. * * @return the mainfile of the first derivate related to the given mcrid or * null if there are no derivates related to the given mcrid */ public static String getSupportedMainFileByOwner(String mcrID) { MCRObjectID objectID = null; try { objectID = MCRObjectID.getInstance(mcrID); } catch (Exception e) { return null; } MCRObject obj = MCRMetadataManager.retrieveMCRObject(objectID); List<MCRMetaEnrichedLinkID> derivates = obj.getStructure().getDerivates(); if (derivates.size() > 0) { return derivates.get(0) + "/" + ADAPTER.getSupportedMainFile(derivates.get(0).toString()); } return null; } public static String getThumbnailURL(String derivate, String imagePath) { String[] baseURLs = MCRConfiguration2.getStringOrThrow("MCR.Module-iview2.BaseURL").split(","); int index = imagePath.hashCode() % baseURLs.length; StringBuilder baseURL = new StringBuilder(baseURLs[index]); baseURL.append('/').append(derivate); if (imagePath.charAt(0) != '/') { baseURL.append('/'); } int dotPos = imagePath.lastIndexOf('.'); String imgPath = imagePath; if (dotPos > 0) { imgPath = imagePath.substring(0, dotPos); } baseURL.append(imgPath).append(".iview2/0/0/0.jpg"); return baseURL.toString(); } public static int getOrder(Node metsDiv) { Document document = metsDiv.getOwnerDocument(); if (metsDiv.getLocalName().equals("smLink")) { return getSmLinkOrder(document, metsDiv); } Node structLink = document.getElementsByTagNameNS(METS_NAMESPACE_URI, "structLink").item(0); return getLowestOrder(document, metsDiv, structLink); } private static int getLowestOrder(Document document, Node metsDiv, Node structLink) { int order = Integer.MAX_VALUE; NodeList childDivs = metsDiv.getChildNodes(); for (int i = 0; i < childDivs.getLength(); i++) { Node childDiv = childDivs.item(i); if (childDiv.getNodeType() != Node.ELEMENT_NODE || !childDiv.getLocalName().equals("div")) { continue; } order = Math.min(order, getLowestOrder(document, childDiv, structLink)); } String logId = metsDiv.getAttributes().getNamedItem("ID").getNodeValue(); NodeList smLinks = structLink.getChildNodes(); for (int i = 0; i < smLinks.getLength(); i++) { Node smLink = smLinks.item(i); Node xlinkFrom = smLink.getAttributes().getNamedItemNS(XLINK_NAMESPACE.getURI(), "from"); if (xlinkFrom == null || !xlinkFrom.getNodeValue().equals(logId)) { continue; } int smLinkOrder = getSmLinkOrder(document, smLink); order = Math.min(order, smLinkOrder); } return order; } private static int getSmLinkOrder(Document document, Node smLink) { Node xlinkTo = smLink.getAttributes().getNamedItemNS(XLINK_NAMESPACE.getURI(), "to"); Node physDiv = getElementById(document.getDocumentElement(), xlinkTo.getNodeValue()); String orderValue = physDiv.getAttributes().getNamedItem("ORDER").getNodeValue(); return Integer.parseInt(orderValue); } private static Node getElementById(Node base, String id) { NamedNodeMap attributes = base.getAttributes(); if (IntStream.range(0, attributes.getLength()) .mapToObj(i -> (Attr) attributes.item(i)) .anyMatch(attr -> attr.getLocalName().equalsIgnoreCase("id") && attr.getNodeValue().equals(id))) { return base; } NodeList childNodes = base.getChildNodes(); return IntStream.range(0, childNodes.getLength()) .mapToObj(childNodes::item) .filter(child -> child.getNodeType() == Node.ELEMENT_NODE) .map(child -> getElementById(child, id)) .filter(Objects::nonNull) .findFirst() .orElse(null); } }
6,196
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z