use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.
the class MCRDerivateCommands method transformXMLMatchingPatternWithStylesheet.
@MCRCommand(syntax = "transform xml matching file name pattern {0} in derivate {1} with stylesheet {2}", help = "Finds all files in Derivate {1} which match the pattern {0} (the complete path with regex: or glob:*.xml syntax) and transforms them with stylesheet {2}")
public static void transformXMLMatchingPatternWithStylesheet(String pattern, String derivate, String stylesheet) throws IOException {
MCRXSLTransformer transformer = new MCRXSLTransformer(stylesheet);
MCRPath derivateRoot = MCRPath.getPath(derivate, "/");
PathMatcher matcher = derivateRoot.getFileSystem().getPathMatcher(pattern);
Files.walkFileTree(derivateRoot, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (matcher.matches(file)) {
LOGGER.info("The file {} matches the pattern {}", file, pattern);
MCRContent sourceContent = new MCRPathContent(file);
MCRContent resultContent = transformer.transform(sourceContent);
try {
Document source = sourceContent.asXML();
Document result = resultContent.asXML();
LOGGER.info("Transforming complete!");
if (!MCRXMLHelper.deepEqual(source, result)) {
LOGGER.info("Writing result..");
resultContent.sendTo(file, StandardCopyOption.REPLACE_EXISTING);
} else {
LOGGER.info("Result and Source is the same..");
}
} catch (JDOMException | SAXException e) {
throw new IOException("Error while processing file : " + file, e);
}
}
return FileVisitResult.CONTINUE;
}
});
}
use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.
the class MCRDerivateCommands method setMainFile.
@MCRCommand(syntax = "set main file of {0} to {1}", help = "Sets the main file of the derivate with the id {0} to " + "the file with the path {1}")
public static void setMainFile(final String derivateIDString, final String filePath) {
if (!MCRObjectID.isValid(derivateIDString)) {
LOGGER.error("{} is not valid. ", derivateIDString);
return;
}
// check for derivate exist
final MCRObjectID derivateID = MCRObjectID.getInstance(derivateIDString);
if (!MCRMetadataManager.exists(derivateID)) {
LOGGER.error("{} does not exist!", derivateIDString);
return;
}
// remove leading slash
String cleanPath = filePath;
if (filePath.startsWith(String.valueOf(MCRAbstractFileSystem.SEPARATOR))) {
cleanPath = filePath.substring(1, filePath.length());
}
// check for file exist
final MCRPath path = MCRPath.getPath(derivateID.toString(), cleanPath);
if (!Files.exists(path)) {
LOGGER.error("File {} does not exist!", cleanPath);
return;
}
final MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateID);
derivate.getDerivate().getInternals().setMainDoc(cleanPath);
MCRMetadataManager.updateMCRDerivateXML(derivate);
LOGGER.info("The main file of {} is now '{}'!", derivateIDString, cleanPath);
}
use of org.mycore.datamodel.niofs.MCRPath 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.datamodel.niofs.MCRPath 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.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.
the class MCRSwordMediaHandler method addResource.
public void addResource(String derivateId, String requestFilePath, Deposit deposit) throws SwordError, SwordServerException {
MCRPath ifsRootPath = MCRPath.getPath(derivateId, requestFilePath);
final boolean pathIsDirectory = Files.isDirectory(ifsRootPath);
final String depositFilename = deposit.getFilename();
final String packaging = deposit.getPackaging();
if (!MCRAccessManager.checkPermission(derivateId, MCRAccessManager.PERMISSION_WRITE)) {
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "You dont have the right to write to the derivate!");
}
Path tempFile = null;
try {
try {
tempFile = MCRSwordUtil.createTempFileFromStream(deposit.getFilename(), deposit.getInputStream(), deposit.getMd5());
} catch (IOException e) {
throw new SwordServerException("Could not store deposit to temp files", e);
}
if (packaging != null && packaging.equals(UriRegistry.PACKAGE_SIMPLE_ZIP)) {
if (pathIsDirectory && deposit.getMimeType().equals(MCRSwordConstants.MIME_TYPE_APPLICATION_ZIP)) {
ifsRootPath = MCRPath.getPath(derivateId, requestFilePath);
try {
List<MCRSwordUtil.MCRValidationResult> invalidResults = MCRSwordUtil.validateZipFile(this, tempFile).stream().filter(validationResult -> !validationResult.isValid()).collect(Collectors.toList());
if (invalidResults.size() > 0) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_BAD_REQUEST, invalidResults.stream().map(MCRSwordUtil.MCRValidationResult::getMessage).filter(Optional::isPresent).map(Optional::get).collect(Collectors.joining(System.lineSeparator())));
}
MCRSwordUtil.extractZipToPath(tempFile, ifsRootPath);
} catch (IOException | NoSuchAlgorithmException | URISyntaxException e) {
throw new SwordServerException("Error while extracting ZIP.", e);
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_BAD_REQUEST, "The Request makes no sense. (mime type must be " + MCRSwordConstants.MIME_TYPE_APPLICATION_ZIP + " and path must be a directory)");
}
} else if (packaging != null && packaging.equals(UriRegistry.PACKAGE_BINARY)) {
try {
MCRSwordUtil.MCRValidationResult validationResult = validate(tempFile);
if (!validationResult.isValid()) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, HttpServletResponse.SC_BAD_REQUEST, validationResult.getMessage().get());
}
ifsRootPath = MCRPath.getPath(derivateId, requestFilePath + depositFilename);
try (InputStream is = Files.newInputStream(tempFile)) {
Files.copy(is, ifsRootPath, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
throw new SwordServerException("Error while adding file " + ifsRootPath, e);
}
}
} finally {
if (tempFile != null) {
try {
LOGGER.info("Delete temp file: {}", tempFile);
Files.delete(tempFile);
} catch (IOException e) {
LOGGER.error("Could not delete temp file: {}", tempFile, e);
}
}
}
}
Aggregations