use of org.jdom2.filter.Filter in project mycore by MyCoRe-Org.
the class MCRAutoDeploy method deployWebResources.
private void deployWebResources(final ServletContext servletContext, final MCRComponent comp) {
final String webRoot = servletContext.getRealPath("/");
if (webRoot != null) {
try {
final JarFile jar = new JarFile(comp.getJarFile());
LOGGER.info("Deploy web resources to {}...", webRoot);
Collections.list(jar.entries()).stream().filter(file -> file.getName().startsWith(RESOURCE_DIR)).forEach(file -> {
final String fileName = file.getName().substring(RESOURCE_DIR.length());
LOGGER.debug("...deploy {}", fileName);
final File f = new File(webRoot + File.separator + fileName);
if (file.isDirectory()) {
f.mkdir();
} else {
try {
final InputStream is = jar.getInputStream(file);
final FileOutputStream fos = new FileOutputStream(f);
while (is.available() > 0) {
fos.write(is.read());
}
fos.close();
} catch (IOException e) {
LOGGER.error("Couldn't deploy file {}.", fileName, e);
}
}
});
LOGGER.info("...done.");
jar.close();
} catch (final IOException e) {
LOGGER.error("Couldn't parse JAR!", e);
}
}
}
use of org.jdom2.filter.Filter in project mycore by MyCoRe-Org.
the class MCRAutoDeploy method registerWebFragment.
private void registerWebFragment(final ServletContext servletContext, final MCRComponent comp) {
if (!isHandledByServletContainer(servletContext, comp)) {
try {
final JarFile jar = new JarFile(comp.getJarFile());
Collections.list(jar.entries()).stream().filter(file -> file.getName().equals(WEB_FRAGMENT)).findFirst().ifPresent(file -> {
final SAXBuilder builder = new SAXBuilder();
try {
final InputStream is = jar.getInputStream(file);
final Document doc = builder.build(is);
final Element root = doc.getRootElement();
final Namespace ns = root.getNamespace();
final List<Element> filters = root.getChildren("filter", ns);
final List<Element> fmaps = root.getChildren("filter-mapping", ns);
filters.forEach(filter -> {
final String name = filter.getChildText("filter-name", ns);
final String className = filter.getChildText("filter-class", ns);
fmaps.stream().filter(mapping -> mapping.getChildText("filter-name", ns).equals(name)).findFirst().ifPresent(mapping -> {
LOGGER.info("Register Filter {} ({})...", name, className);
Optional.ofNullable(servletContext.addFilter(name, className)).<Runnable>map(fr -> () -> {
final List<Element> dispatchers = mapping.getChildren("dispatcher", ns);
final EnumSet<DispatcherType> eDT = dispatchers.isEmpty() ? null : dispatchers.stream().map(d -> DispatcherType.valueOf(d.getTextTrim())).collect(Collectors.toCollection(() -> EnumSet.noneOf(DispatcherType.class)));
final List<Element> servletNames = mapping.getChildren("servlet-name", ns);
if (!servletNames.isEmpty()) {
fr.addMappingForServletNames(eDT, false, servletNames.stream().map(sn -> {
LOGGER.info("...add servlet mapping: {}", sn.getTextTrim());
return sn.getTextTrim();
}).toArray(String[]::new));
}
final List<Element> urlPattern = mapping.getChildren("url-pattern", ns);
if (!urlPattern.isEmpty()) {
fr.addMappingForUrlPatterns(eDT, false, urlPattern.stream().map(url -> {
LOGGER.info("...add url mapping: {}", url.getTextTrim());
return url.getTextTrim();
}).toArray(String[]::new));
}
}).orElse(() -> LOGGER.warn("Filter {} already registered!", name)).run();
});
});
final List<Element> servlets = root.getChildren("servlet", ns);
final List<Element> smaps = root.getChildren("servlet-mapping", ns);
servlets.forEach(servlet -> {
final String name = servlet.getChildText("servlet-name", ns);
final String className = servlet.getChildText("servlet-class", ns);
smaps.stream().filter(mapping -> mapping.getChildText("servlet-name", ns).equals(name)).findFirst().ifPresent(mapping -> {
LOGGER.info("Register Servlet {} ({})...", name, className);
Optional.ofNullable(servletContext.addServlet(name, className)).<Runnable>map(sr -> () -> mapping.getChildren("url-pattern", ns).stream().forEach(url -> {
LOGGER.info("...add url mapping: {}", url.getTextTrim());
sr.addMapping(url.getTextTrim());
})).orElse(() -> LOGGER.error("Servlet{} already registered!", name)).run();
});
});
} catch (IOException | JDOMException e) {
LOGGER.error("Couldn't parse " + WEB_FRAGMENT, e);
}
});
jar.close();
} catch (final IOException e) {
LOGGER.error("Couldn't parse JAR!", e);
}
}
}
use of org.jdom2.filter.Filter 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);
}
}
}
}
use of org.jdom2.filter.Filter in project mycore by MyCoRe-Org.
the class MCRMetsSave method updateFiles.
/**
* Call this method to update the mets.xml if files of the derivate have changed. Files will be added or removed
* from the mets:fileSec and mets:StructMap[@type=PHYSICAL]. The mets:structLink part will be rebuild after.
*
* <p>This method takes care of the group assignment. For example: image files will be added to the MASTER
* group and ALTO files to the ALTO group. It will also bundle files with the same name e.g. sample1.tiff and
* alto/sample1.xml to the same physical struct map div.</p>
*
* <p><b>Important:</b> This method does not update the mets.xml in the derivate, its just updating the given mets
* instance.</p>
*
* @param mets the mets to update
* @param derivatePath path to the derivate -> required for looking up new files
* @throws IOException derivate couldn't be read
*/
public static void updateFiles(Mets mets, final MCRPath derivatePath) throws IOException {
List<String> metsFiles = mets.getFileSec().getFileGroups().stream().flatMap(g -> g.getFileList().stream()).map(File::getFLocat).map(FLocat::getHref).collect(Collectors.toList());
List<String> derivateFiles = Files.walk(derivatePath).filter(MCRStreamUtils.not(Files::isDirectory)).map(MCRPath::toMCRPath).map(MCRPath::getOwnerRelativePath).map(path -> path.substring(1)).filter(href -> !"mets.xml".equals(href)).collect(Collectors.toList());
ArrayList<String> removedFiles = new ArrayList<>(metsFiles);
removedFiles.removeAll(derivateFiles);
ArrayList<String> addedFiles = new ArrayList<>(derivateFiles);
Collections.sort(addedFiles);
addedFiles.removeAll(metsFiles);
StructLink structLink = mets.getStructLink();
PhysicalStructMap physicalStructMap = mets.getPhysicalStructMap();
List<String> unlinkedLogicalIds = new ArrayList<>();
// remove files
PhysicalDiv physicalDiv = physicalStructMap.getDivContainer();
removedFiles.forEach(href -> {
File file = null;
// remove from fileSec
for (FileGrp grp : mets.getFileSec().getFileGroups()) {
file = grp.getFileByHref(href);
if (file != null) {
grp.removeFile(file);
break;
}
}
if (file == null) {
return;
}
// remove from physical
PhysicalSubDiv physicalSubDiv = physicalDiv.byFileId(file.getId());
physicalSubDiv.remove(physicalSubDiv.getFptr(file.getId()));
if (physicalSubDiv.getChildren().isEmpty()) {
physicalDiv.remove(physicalSubDiv);
}
// remove from struct link
structLink.getSmLinkByTo(physicalSubDiv.getId()).forEach(smLink -> {
structLink.removeSmLink(smLink);
if (structLink.getSmLinkByFrom(smLink.getFrom()).isEmpty()) {
unlinkedLogicalIds.add(smLink.getFrom());
}
});
});
// fix unlinked logical divs
if (!unlinkedLogicalIds.isEmpty()) {
// get first physical div
List<PhysicalSubDiv> physicalChildren = physicalStructMap.getDivContainer().getChildren();
String firstPhysicalID = physicalChildren.isEmpty() ? physicalStructMap.getDivContainer().getId() : physicalChildren.get(0).getId();
// a logical div is not linked anymore -> link with first physical div
unlinkedLogicalIds.forEach(from -> structLink.addSmLink(new SmLink(from, firstPhysicalID)));
}
// get last logical div
LogicalDiv divContainer = mets.getLogicalStructMap().getDivContainer();
List<LogicalDiv> descendants = divContainer.getDescendants();
LogicalDiv lastLogicalDiv = descendants.isEmpty() ? divContainer : descendants.get(descendants.size() - 1);
// add files
addedFiles.forEach(href -> {
MCRPath filePath = (MCRPath) derivatePath.resolve(href);
String fileBase = getFileBase(href);
try {
String fileGroupUse = MCRMetsSave.getFileGroupUse(filePath);
// build file
String mimeType = MCRContentTypes.probeContentType(filePath);
String fileId = fileGroupUse.toLowerCase(Locale.ROOT) + "_" + fileBase;
File file = new File(fileId, mimeType);
file.setFLocat(new FLocat(LOCTYPE.URL, href));
// fileSec
FileGrp fileGroup = mets.getFileSec().getFileGroup(fileGroupUse);
if (fileGroup == null) {
fileGroup = new FileGrp(fileGroupUse);
mets.getFileSec().addFileGrp(fileGroup);
}
fileGroup.addFile(file);
// structMap physical
String existingFileID = mets.getFileSec().getFileGroups().stream().filter(grp -> !grp.getUse().equals(fileGroupUse)).flatMap(grp -> grp.getFileList().stream()).filter(brotherFile -> fileBase.equals(getFileBase(brotherFile.getFLocat().getHref()))).map(File::getId).findAny().orElse(null);
PhysicalSubDiv physicalSubDiv;
if (existingFileID != null) {
// there is a file (e.g. img or alto) which the same file base -> add the file to this mets:div
physicalSubDiv = physicalDiv.byFileId(existingFileID);
physicalSubDiv.add(new Fptr(file.getId()));
} else {
// there is no mets:div with this file
physicalSubDiv = new PhysicalSubDiv(PhysicalSubDiv.ID_PREFIX + fileBase, PhysicalSubDiv.TYPE_PAGE);
physicalSubDiv.add(new Fptr(file.getId()));
physicalDiv.add(physicalSubDiv);
}
// add to struct link
structLink.addSmLink(new SmLink(lastLogicalDiv.getId(), physicalSubDiv.getId()));
} catch (Exception exc) {
LOGGER.error("Unable to add file {} to mets.xml of {}", href, derivatePath.getOwner(), exc);
}
});
}
use of org.jdom2.filter.Filter in project mycore by MyCoRe-Org.
the class MCRMigrationCommands method fixMCR1717.
@MCRCommand(syntax = "fix MCR-1717", help = "Fixes wrong entries in tile job table (see MCR-1717 comments)")
public static void fixMCR1717() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<MCRTileJob> allTileJobQuery = em.createNamedQuery("MCRTileJob.all", MCRTileJob.class);
List<MCRTileJob> tiles = allTileJobQuery.getResultList();
tiles.stream().filter(tj -> !tj.getPath().startsWith("/")).peek(tj -> LOGGER.info("Fixing TileJob {}:{}", tj.getDerivate(), tj.getPath())).forEach(tj -> {
String newPath = "/" + tj.getPath();
tj.setPath(newPath);
});
}
Aggregations