use of org.mycore.access.MCRAccessException in project mycore by MyCoRe-Org.
the class MCRObjectCommands method mergeDerivatesOfObject.
@MCRCommand(syntax = "merge derivates of object {0}", help = "Retrieves the MCRObject with the MCRObjectID {0} and if it has more then one MCRDerivate, then all" + " Files will be copied to the first Derivate and all other will be deleted.", order = 190)
public static void mergeDerivatesOfObject(String id) {
MCRObjectID objectID = MCRObjectID.getInstance(id);
if (!MCRMetadataManager.exists(objectID)) {
LOGGER.error("The object with the id {} does not exist!", id);
return;
}
MCRObject object = MCRMetadataManager.retrieveMCRObject(objectID);
List<MCRMetaLinkID> derivateLinkIDs = object.getStructure().getDerivates();
List<MCRObjectID> derivateIDs = derivateLinkIDs.stream().map(MCRMetaLinkID::getXLinkHrefID).collect(Collectors.toList());
if (derivateIDs.size() <= 1) {
LOGGER.error("The object with the id {} has no Derivates to merge!", id);
return;
}
String mainID = derivateIDs.get(0).toString();
MCRPath mainDerivateRootPath = MCRPath.getPath(mainID, "/");
derivateIDs.stream().skip(1).forEach(derivateID -> {
LOGGER.info("Merge {} into {}...", derivateID, mainID);
MCRPath copyRootPath = MCRPath.getPath(derivateID.toString(), "/");
try {
MCRTreeCopier treeCopier = new MCRTreeCopier(copyRootPath, mainDerivateRootPath);
Files.walkFileTree(copyRootPath, treeCopier);
Files.walkFileTree(copyRootPath, MCRRecursiveDeleter.instance());
MCRMetadataManager.deleteMCRDerivate(derivateID);
} catch (IOException | MCRAccessException e) {
throw new MCRException(e);
}
});
}
use of org.mycore.access.MCRAccessException in project mycore by MyCoRe-Org.
the class MCRObjectCommands method replaceParent.
/**
* Moves object to new parent.
*
* @param sourceId
* object that should be attached to new parent
* @param newParentId
* the ID of the new parent
* @throws MCRAccessException see {@link MCRMetadataManager#update(MCRObject)}
*/
@MCRCommand(syntax = "set parent of {0} to {1}", help = "replaces a parent of an object (first parameter) to the given new one (second parameter)", order = 300)
public static void replaceParent(String sourceId, String newParentId) throws MCRPersistenceException, MCRActiveLinkException, MCRAccessException {
// child
MCRObject sourceMCRObject = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance(sourceId));
// old parent
MCRObjectID oldParentId = sourceMCRObject.getStructure().getParentID();
MCRObjectID newParentObjectID = MCRObjectID.getInstance(newParentId);
if (newParentObjectID.equals(oldParentId)) {
LOGGER.info("Object {} is already child of {}", sourceId, newParentId);
return;
}
MCRObject oldParentMCRObject = null;
if (oldParentId != null) {
try {
oldParentMCRObject = MCRMetadataManager.retrieveMCRObject(oldParentId);
} catch (Exception exc) {
LOGGER.error("Unable to get old parent object {}, its probably deleted.", oldParentId, exc);
}
}
// change href to new parent
LOGGER.info("Setting link in \"{}\" to parent \"{}\"", sourceId, newParentObjectID);
MCRMetaLinkID parentLinkId = new MCRMetaLinkID("parent", 0);
parentLinkId.setReference(newParentObjectID, null, null);
sourceMCRObject.getStructure().setParent(parentLinkId);
if (oldParentMCRObject != null) {
// remove Child in old parent
LOGGER.info("Remove child \"{}\" in old parent \"{}\"", sourceId, oldParentId);
oldParentMCRObject.getStructure().removeChild(sourceMCRObject.getId());
LOGGER.info("Update old parent \"{}\n", oldParentId);
MCRMetadataManager.update(oldParentMCRObject);
}
LOGGER.info("Update \"{}\" in datastore (saving new link)", sourceId);
MCRMetadataManager.update(sourceMCRObject);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Structure: {}", sourceMCRObject.getStructure().isValid());
LOGGER.debug("Object: {}", sourceMCRObject.isValid());
}
}
use of org.mycore.access.MCRAccessException in project mycore by MyCoRe-Org.
the class MCRUploadHandlerIFS method receiveFile.
@Override
public synchronized long receiveFile(String path, InputStream in, long length, String checksum) throws IOException, MCRPersistenceException, MCRAccessException {
LOGGER.debug("incoming receiveFile request: {} {} {} bytes", path, checksum, length);
this.setProgressText(path);
List<Path> tempFiles = new LinkedList<>();
Supplier<Path> tempFileSupplier = () -> {
try {
Path tempFile = Files.createTempFile(derivateID + "-" + path.hashCode(), ".upload");
tempFiles.add(tempFile);
return tempFile;
} catch (IOException e) {
throw new UncheckedIOException("Error while creating temp File!", e);
}
};
try (InputStream fIn = preprocessInputStream(path, in, length, tempFileSupplier)) {
if (rootDir == null) {
// MCR-1376: Create derivate only if at least one file was successfully uploaded
prepareUpload();
}
MCRPath file = getFile(path);
LOGGER.info("Creating file {}.", file);
Files.copy(fIn, file, StandardCopyOption.REPLACE_EXISTING);
return tempFiles.isEmpty() ? length : Files.size(tempFiles.stream().reduce((a, b) -> b).get());
} finally {
tempFiles.stream().filter(Files::exists).forEach((tempFilePath) -> {
try {
Files.delete(tempFilePath);
} catch (IOException e) {
LOGGER.error("Could not delete temp file {}", tempFilePath);
}
});
this.filesUploaded++;
int progress = (int) (((float) this.filesUploaded / (float) getNumFiles()) * 100f);
this.setProgress(progress);
}
}
use of org.mycore.access.MCRAccessException in project mycore by MyCoRe-Org.
the class MCRSwordMediaHandler method deleteMediaResource.
public void deleteMediaResource(String derivateId, String requestFilePath) throws SwordError, SwordServerException {
if (!MCRAccessManager.checkPermission(derivateId, MCRAccessManager.PERMISSION_DELETE)) {
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "You dont have the right to delete (from) the derivate!");
}
if (requestFilePath == null || requestFilePath.equals("/")) {
final MCRObjectID derivateID = MCRObjectID.getInstance(derivateId);
if (MCRMetadataManager.exists(derivateID)) {
final MCRDerivate mcrDerivate = MCRMetadataManager.retrieveMCRDerivate(derivateID);
try {
MCRMetadataManager.delete(mcrDerivate);
} catch (MCRAccessException e) {
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, e);
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_NOT_FOUND, "The requested Object '" + requestFilePath + "' does not exists.");
}
} else {
final MCRPath path = MCRPath.getPath(derivateId, requestFilePath);
checkFile(path);
try {
if (Files.isDirectory(path)) {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
} else {
Files.delete(path);
}
} catch (IOException e) {
throw new SwordServerException("Error while deleting media resource!", e);
}
}
}
use of org.mycore.access.MCRAccessException in project mycore by MyCoRe-Org.
the class MCRIIIFImageResource method getImage.
@GET
@Path("{" + IDENTIFIER_PARAM + "}/{region}/{size}/{rotation}/{quality}.{format}")
public Response getImage(@PathParam(IMPL_PARAM) String implStr, @PathParam(IDENTIFIER_PARAM) String identifier, @PathParam("region") String region, @PathParam("size") String size, @PathParam("rotation") String rotation, @PathParam("quality") String quality, @PathParam("format") String format) {
try {
MCRIIIFImageImpl impl = getImpl(implStr);
MCRIIIFImageInformation information = impl.getInformation(identifier);
MCRIIIFRegionParser rp = new MCRIIIFRegionParser(region, information.width, information.height);
MCRIIIFImageSourceRegion sourceRegion = rp.parseImageRegion();
MCRIIIFScaleParser sp = new MCRIIIFScaleParser(size, sourceRegion.getX2() - sourceRegion.getX1(), sourceRegion.getY2() - sourceRegion.getY1());
MCRIIIFImageTargetSize targetSize = sp.parseTargetScale();
MCRIIIFRotationParser rotationParser = new MCRIIIFRotationParser(rotation);
MCRIIIFImageTargetRotation parsedRotation = rotationParser.parse();
MCRIIIFImageQuality imageQuality = MCRIIIFImageQuality.fromString(quality);
BufferedImage provide = impl.provide(identifier, sourceRegion, targetSize, parsedRotation, imageQuality, format);
Response.Status status = rp.isCompleteValid() ? Response.Status.OK : Response.Status.BAD_REQUEST;
Response.ResponseBuilder responseBuilder = Response.status(status);
return responseBuilder.header("Link", buildCanonicalURL(impl, identifier)).header("Profile", buildProfileURL()).type("image/" + format).entity((StreamingOutput) outputStream -> ImageIO.write(provide, format, outputStream)).build();
} catch (MCRIIIFImageNotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (IllegalArgumentException | MCRIIIFUnsupportedFormatException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (MCRAccessException e) {
return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build();
} catch (Exception e) {
LOGGER.error(() -> "Error while getting Image " + identifier + " from " + implStr + " with region: " + region + ", size: " + size + ", rotation: " + rotation + ", quality: " + quality + ", format: " + format, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
Aggregations