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
MCRIView2XSLFunctionsAdapter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRIView2XSLFunctionsAdapter.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.nio.file.Files; import java.util.Collection; 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.datamodel.common.MCRLinkTableManager; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.iview2.services.MCRIView2Tools; /** * Adapter that can be extended to work with different internal files systems. * To get the extending class invoked, one need to define a MyCoRe property, which defaults to: * <code>MCR.Module-iview2.MCRIView2XSLFunctionsAdapter=org.mycore.iview2.frontend.MCRIView2XSLFunctionsAdapter</code> * @author Thomas Scheffler (yagee) * */ public class MCRIView2XSLFunctionsAdapter { private static Logger LOGGER = LogManager.getLogger(MCRIView2XSLFunctionsAdapter.class); private static final MCRLinkTableManager LINK_TABLE_MANAGER = MCRLinkTableManager.instance(); public static MCRIView2XSLFunctionsAdapter getInstance() { return MCRConfiguration2 .<MCRIView2XSLFunctionsAdapter>getInstanceOf(MCRIView2Tools.CONFIG_PREFIX + "MCRIView2XSLFunctionsAdapter") .orElseGet(MCRIView2XSLFunctionsAdapter::new); } public boolean hasMETSFile(String derivateID) { return Files.exists(MCRPath.getPath(derivateID, "/mets.xml")); } public String getSupportedMainFile(String derivateID) { return MCRIView2Tools.getSupportedMainFile(derivateID); } public String getOptions(String derivateID, String extensions) { final Collection<String> sources = LINK_TABLE_MANAGER.getSourceOf(derivateID, "derivate"); String objectID = (sources != null && !sources.isEmpty()) ? sources.iterator().next() : ""; StringBuilder options = new StringBuilder(); options.append('{'); options.append("\"derivateId\":").append('\"').append(derivateID).append("\","); options.append("\"objectId\":").append('\"').append(objectID).append("\","); options.append("\"webappBaseUri\":").append('\"').append(MCRFrontendUtil.getBaseURL()).append("\","); String baseUris = MCRConfiguration2.getString("MCR.Module-iview2.BaseURL").orElse(""); if (baseUris.length() < 10) { baseUris = MCRServlet.getServletBaseURL() + "MCRTileServlet"; } options.append("\"baseUri\":").append('\"').append(baseUris).append("\".split(\",\")"); if (MCRAccessManager.checkPermission(derivateID, "create-pdf")) { options.append(",\"pdfCreatorURI\":").append('\"') .append(MCRConfiguration2.getString("MCR.Module-iview2.PDFCreatorURI").orElse("")).append("\","); options.append("\"pdfCreatorStyle\":").append('\"') .append(MCRConfiguration2.getString("MCR.Module-iview2.PDFCreatorStyle").orElse("")).append('\"'); } if (extensions != null && !extensions.equals("")) { options.append(','); options.append(extensions); } options.append('}'); LOGGER.debug(options.toString()); return options.toString(); } }
4,009
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRFooterInterface.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/frontend/MCRFooterInterface.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.image.BufferedImage; /** * The MCRFooterInterface adds the possibility to write a different implementations and combine them for example with * the {@link MCRTileCombineServlet}. * @author Thomas Scheffler (yagee) * */ public interface MCRFooterInterface { /** * generates a footer image that is pinned below the master image * * Implementors can use <code>derivateID</code> and <code>imagePath</code> information * to add some informations to the image footer, e.g. URNs. * @param imageWidth image width of the master image * @param derivateID derivate ID * @param imagePath path to image relative to derivate root * @return an image of any height but with width of <code>imageWidth</code> px. */ BufferedImage getFooter(int imageWidth, String derivateID, String imagePath); }
1,618
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIViewZipResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/frontend/resources/MCRIViewZipResource.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.resources; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Objects; import java.util.zip.Deflater; import javax.imageio.ImageIO; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.mycore.access.MCRAccessManager; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRTransactionHelper; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.imagetiler.MCRImage; import org.mycore.imagetiler.MCRTiledPictureProps; import org.mycore.iview2.services.MCRIView2Tools; import jakarta.ws.rs.GET; 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.Response; import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.core.StreamingOutput; @Path("/iview/zip") public class MCRIViewZipResource { /** * Zips a derivate and its containing iview images as jpg's. All other files are ignored. * * @param derivateID the derivate to zip * @param zoom if undefined the base resolution is assumed * @return zip file */ @GET @Produces("application/zip") @Path("{derivateID}") public Response zip(@PathParam("derivateID") String derivateID, @QueryParam("zoom") Integer zoom) { if (!MCRAccessManager.checkDerivateContentPermission(MCRObjectID.getInstance(derivateID), MCRAccessManager.PERMISSION_READ)) { throw new WebApplicationException(Status.UNAUTHORIZED); } MCRPath derivateRoot = MCRPath.getPath(derivateID, "/"); if (!Files.exists(derivateRoot)) { throw new WebApplicationException(Status.NOT_FOUND); } ZipStreamingOutput stream = new ZipStreamingOutput(derivateRoot, zoom); return Response.ok(stream).header("Content-Disposition", "attachnment; filename=\"" + derivateID + ".zip\"") .build(); } public static class ZipStreamingOutput implements StreamingOutput { protected MCRPath derivateRoot; protected Integer zoom; public ZipStreamingOutput(MCRPath derivateRoot, Integer zoom) { this.derivateRoot = derivateRoot; this.zoom = zoom; } @Override public void write(OutputStream out) throws WebApplicationException { MCRSessionMgr.getCurrentSession(); MCRTransactionHelper.beginTransaction(); try { final ZipArchiveOutputStream zipStream = new ZipArchiveOutputStream(new BufferedOutputStream(out)); zipStream.setLevel(Deflater.BEST_SPEED); SimpleFileVisitor<java.nio.file.Path> zipper = new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(java.nio.file.Path file, BasicFileAttributes attrs) throws IOException { Objects.requireNonNull(file); Objects.requireNonNull(attrs); MCRPath mcrPath = MCRPath.toMCRPath(file); if (MCRIView2Tools.isFileSupported(file)) { java.nio.file.Path iviewFile = MCRImage.getTiledFile(MCRIView2Tools.getTileDir(), mcrPath.getOwner(), mcrPath.getOwnerRelativePath()); if (!Files.exists(iviewFile)) { return super.visitFile(iviewFile, attrs); } MCRTiledPictureProps imageProps = MCRTiledPictureProps.getInstanceFromFile(iviewFile); int zoomLevel = (zoom == null || zoom > imageProps.getZoomlevel()) ? imageProps .getZoomlevel() : zoom; BufferedImage image = MCRIView2Tools.getZoomLevel(iviewFile, zoomLevel); ZipArchiveEntry entry = new ZipArchiveEntry(file.getFileName() + ".jpg"); zipStream.putArchiveEntry(entry); ImageIO.write(image, "jpg", zipStream); zipStream.closeArchiveEntry(); } return FileVisitResult.CONTINUE; } }; Files.walkFileTree(derivateRoot, zipper); zipStream.close(); } catch (Exception exc) { throw new WebApplicationException(exc); } finally { MCRSessionMgr.getCurrentSession(); MCRTransactionHelper.commitTransaction(); } } } }
5,799
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIVIEWIIIFImageImpl.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/iiif/MCRIVIEWIIIFImageImpl.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.iiif; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystemNotFoundException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import javax.imageio.ImageIO; import javax.imageio.ImageReader; 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.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import org.mycore.iiif.image.MCRIIIFImageUtil; import org.mycore.iiif.image.impl.MCRIIIFImageImpl; import org.mycore.iiif.image.impl.MCRIIIFImageNotFoundException; import org.mycore.iiif.image.impl.MCRIIIFImageProvidingException; import org.mycore.iiif.image.impl.MCRIIIFUnsupportedFormatException; import org.mycore.iiif.image.model.MCRIIIFFeatures; import org.mycore.iiif.image.model.MCRIIIFImageInformation; import org.mycore.iiif.image.model.MCRIIIFImageProfile; import org.mycore.iiif.image.model.MCRIIIFImageQuality; import org.mycore.iiif.image.model.MCRIIIFImageSourceRegion; import org.mycore.iiif.image.model.MCRIIIFImageTargetRotation; import org.mycore.iiif.image.model.MCRIIIFImageTargetSize; import org.mycore.iiif.image.model.MCRIIIFImageTileInformation; import org.mycore.iiif.model.MCRIIIFBase; import org.mycore.imagetiler.MCRTiledPictureProps; import org.mycore.iview2.backend.MCRDefaultTileFileProvider; import org.mycore.iview2.backend.MCRTileFileProvider; import org.mycore.iview2.backend.MCRTileInfo; import org.mycore.iview2.services.MCRIView2Tools; public class MCRIVIEWIIIFImageImpl extends MCRIIIFImageImpl { public static final String DEFAULT_PROTOCOL = "http://iiif.io/api/image"; public static final double LOG_HALF = Math.log(1.0 / 2.0); public static final java.util.List<String> SUPPORTED_FORMATS = Arrays.asList(ImageIO.getReaderFileSuffixes()); public static final String MAX_BYTES_PROPERTY = "MaxImageBytes"; private static final String TILE_FILE_PROVIDER_PROPERTY = "TileFileProvider"; private static final String IDENTIFIER_SEPARATOR_PROPERTY = "IdentifierSeparator"; private static final Logger LOGGER = LogManager.getLogger(MCRIVIEWIIIFImageImpl.class); private final java.util.List<String> transparentFormats; protected final MCRTileFileProvider tileFileProvider; public MCRIVIEWIIIFImageImpl(String implName) { super(implName); Map<String, String> properties = getProperties(); String tileFileProviderClassName = properties.get(TILE_FILE_PROVIDER_PROPERTY); if (tileFileProviderClassName == null) { tileFileProvider = new MCRDefaultTileFileProvider(); } else { Optional<MCRTileFileProvider> optTFP = MCRConfiguration2 .getInstanceOf(getConfigPrefix() + TILE_FILE_PROVIDER_PROPERTY); if (optTFP.isPresent()) { tileFileProvider = optTFP.get(); } else { throw new MCRConfigurationException( "Configurated class (" + TILE_FILE_PROVIDER_PROPERTY + ") not found: " + tileFileProviderClassName); } } transparentFormats = Arrays.asList(properties.get("TransparentFormats").split(",")); } private String buildURL(String identifier) { return MCRIIIFImageUtil.getIIIFURL(this) + MCRIIIFImageUtil.encodeImageIdentifier(identifier); } @Override public BufferedImage provide(String identifier, MCRIIIFImageSourceRegion region, MCRIIIFImageTargetSize targetSize, MCRIIIFImageTargetRotation rotation, MCRIIIFImageQuality imageQuality, String format) throws MCRIIIFImageNotFoundException, MCRIIIFImageProvidingException, MCRIIIFUnsupportedFormatException, MCRAccessException { long resultingSize = (long) targetSize.height() * targetSize.width() * (imageQuality.equals(MCRIIIFImageQuality.color) ? 3 : 1); long maxImageSize = Optional.ofNullable(getProperties().get(MAX_BYTES_PROPERTY)).map(Long::parseLong) .orElseThrow(() -> MCRConfiguration2.createConfigurationException(getConfigPrefix() + MAX_BYTES_PROPERTY)); if (resultingSize > maxImageSize) { throw new MCRIIIFImageProvidingException("Maximal image size is " + (maxImageSize / 1024 / 1024) + "MB. [" + resultingSize + "/" + maxImageSize + "]"); } if (!SUPPORTED_FORMATS.contains(format.toLowerCase(Locale.ENGLISH))) { throw new MCRIIIFUnsupportedFormatException(format); } MCRTileInfo tileInfo = createTileInfo(identifier); Optional<Path> oTileFile = tileFileProvider.getTileFile(tileInfo); if (oTileFile.isEmpty()) { throw new MCRIIIFImageNotFoundException(identifier); } checkTileFile(identifier, tileInfo, oTileFile.get()); MCRTiledPictureProps tiledPictureProps = getTiledPictureProps(oTileFile.get()); int sourceWidth = region.x2() - region.x1(); int sourceHeight = region.y2() - region.y1(); double targetWidth = targetSize.width(); double targetHeight = targetSize.height(); double rotatationRadians = Math.toRadians(rotation.degrees()); double sinRotation = Math.sin(rotatationRadians); double cosRotation = Math.cos(rotatationRadians); final int height = (int) (Math.abs(targetWidth * sinRotation) + Math.abs(targetHeight * cosRotation)); final int width = (int) (Math.abs(targetWidth * cosRotation) + Math.abs(targetHeight * sinRotation)); final int imageType = switch (imageQuality) { case bitonal -> BufferedImage.TYPE_BYTE_BINARY; case gray -> BufferedImage.TYPE_BYTE_GRAY; //color is also default case default -> transparentFormats.contains(format) ? BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR; }; BufferedImage targetImage = new BufferedImage(width, height, imageType); // this value determines the zoom level! double largestScaling = Math.max(targetWidth / sourceWidth, targetHeight / sourceHeight); // We always want to use the the best needed zoom level! int sourceZoomLevel = (int) Math.min( Math.max(0, Math.ceil(tiledPictureProps.getZoomlevel() - Math.log(largestScaling) / LOG_HALF)), tiledPictureProps.getZoomlevel()); // largestScaling is the real scale which is needed! zoomLevelScale is the scale of the nearest zoom level! double zoomLevelScale = Math.min(1.0, Math.pow(0.5, tiledPictureProps.getZoomlevel() - sourceZoomLevel)); // this is the scale which is needed from the nearest zoom level to the required size of image double drawScaleX = (targetWidth / (sourceWidth * zoomLevelScale)), drawScaleY = (targetHeight / (sourceHeight * zoomLevelScale)); // absolute region in zoom level this nearest zoom level double x1 = region.x1() * zoomLevelScale, x2 = region.x2() * zoomLevelScale, y1 = region.y1() * zoomLevelScale, y2 = region.y2() * zoomLevelScale; // now we detect the tiles to draw! int x1Tile = (int) Math.floor(x1 / 256), y1Tile = (int) Math.floor(y1 / 256), x2Tile = (int) Math.ceil(x2 / 256), y2Tile = (int) Math.ceil(y2 / 256); try (FileSystem zipFileSystem = MCRIView2Tools.getFileSystem(oTileFile.get())) { Path rootPath = zipFileSystem.getPath("/"); Graphics2D graphics = targetImage.createGraphics(); if (rotation.mirrored()) { graphics.scale(-1, 1); graphics.translate(-width, 0); } int xt = (int) ((targetWidth - 1) / 2), yt = (int) ((targetHeight - 1) / 2); graphics.translate((width - targetWidth) / 2, (height - targetHeight) / 2); graphics.rotate(rotatationRadians, xt, yt); graphics.scale(drawScaleX, drawScaleY); graphics.translate(-x1, -y1); graphics.scale(zoomLevelScale, zoomLevelScale); graphics.setClip(region.x1(), region.y1(), sourceWidth, sourceHeight); graphics.scale(1 / zoomLevelScale, 1 / zoomLevelScale); LOGGER.info(String.format(Locale.ROOT, "Using zoom-level: %d and scales %s/%s!", sourceZoomLevel, drawScaleX, drawScaleY)); for (int x = x1Tile; x < x2Tile; x++) { for (int y = y1Tile; y < y2Tile; y++) { ImageReader imageReader = MCRIView2Tools.getTileImageReader(); BufferedImage tile = MCRIView2Tools.readTile(rootPath, imageReader, sourceZoomLevel, x, y); graphics.drawImage(tile, x * 256, y * 256, null); } } } catch (IOException e) { throw new MCRIIIFImageProvidingException("Error while reading tiles!", e); } return targetImage; } public MCRIIIFImageInformation getInformation(String identifier) throws MCRIIIFImageNotFoundException, MCRIIIFImageProvidingException, MCRAccessException { try { MCRTileInfo tileInfo = createTileInfo(identifier); Optional<Path> oTiledFile = tileFileProvider.getTileFile(tileInfo); if (oTiledFile.isEmpty()) { throw new MCRIIIFImageNotFoundException(identifier); } final Path tileFilePath = oTiledFile.get(); checkTileFile(identifier, tileInfo, tileFilePath); MCRTiledPictureProps tiledPictureProps = getTiledPictureProps(tileFilePath); MCRIIIFImageInformation imageInformation = new MCRIIIFImageInformation(MCRIIIFBase.API_IMAGE_2, buildURL(identifier), DEFAULT_PROTOCOL, tiledPictureProps.getWidth(), tiledPictureProps.getHeight(), Files.getLastModifiedTime(tileFilePath).toMillis()); MCRIIIFImageTileInformation tileInformation = new MCRIIIFImageTileInformation(256, 256, MCRIIIFImageTileInformation.scaleFactorsAsPowersOfTwo(tiledPictureProps.getZoomlevel())); imageInformation.tiles.add(tileInformation); return imageInformation; } catch (FileSystemNotFoundException | IOException e) { LOGGER.error("Could not find Iview ZIP for {}", identifier, e); throw new MCRIIIFImageNotFoundException(identifier); } } @Override public MCRIIIFImageProfile getProfile() { MCRIIIFImageProfile mcriiifImageProfile = new MCRIIIFImageProfile(); mcriiifImageProfile.formats = SUPPORTED_FORMATS.stream().filter(s -> !s.isEmpty()) .collect(Collectors.toSet()); mcriiifImageProfile.qualities.add("color"); mcriiifImageProfile.qualities.add("bitonal"); mcriiifImageProfile.qualities.add("gray"); mcriiifImageProfile.supports.add(MCRIIIFFeatures.mirroring); mcriiifImageProfile.supports.add(MCRIIIFFeatures.regionByPct); mcriiifImageProfile.supports.add(MCRIIIFFeatures.regionByPx); mcriiifImageProfile.supports.add(MCRIIIFFeatures.rotationArbitrary); mcriiifImageProfile.supports.add(MCRIIIFFeatures.rotationBy90s); mcriiifImageProfile.supports.add(MCRIIIFFeatures.sizeAboveFull); mcriiifImageProfile.supports.add(MCRIIIFFeatures.sizeByWhListed); mcriiifImageProfile.supports.add(MCRIIIFFeatures.sizeByForcedWh); mcriiifImageProfile.supports.add(MCRIIIFFeatures.sizeByH); mcriiifImageProfile.supports.add(MCRIIIFFeatures.sizeByPct); mcriiifImageProfile.supports.add(MCRIIIFFeatures.sizeByW); mcriiifImageProfile.supports.add(MCRIIIFFeatures.sizeByWh); return mcriiifImageProfile; } private MCRTiledPictureProps getTiledPictureProps(Path tiledFile) throws MCRIIIFImageProvidingException { MCRTiledPictureProps tiledPictureProps = null; try (FileSystem fileSystem = MCRIView2Tools.getFileSystem(tiledFile)) { tiledPictureProps = MCRTiledPictureProps.getInstanceFromDirectory(fileSystem.getPath("/")); } catch (IOException e) { throw new MCRIIIFImageProvidingException("Could not provide image information!", e); } return tiledPictureProps; } protected MCRTileInfo createTileInfo(String identifier) throws MCRIIIFImageNotFoundException { MCRTileInfo tileInfo = null; String id = identifier.contains(":/") ? identifier.replaceFirst(":/", "/") : identifier; String separator = getProperties().getOrDefault(IDENTIFIER_SEPARATOR_PROPERTY, "/"); String[] splittedIdentifier = id.split(separator, 2); tileInfo = switch (splittedIdentifier.length) { case 1 -> new MCRTileInfo(null, identifier, null); case 2 -> new MCRTileInfo(splittedIdentifier[0], splittedIdentifier[1], null); default -> throw new MCRIIIFImageNotFoundException(identifier); }; return tileInfo; } private void checkTileFile(String identifier, MCRTileInfo tileInfo, Path tileFilePath) throws MCRAccessException, MCRIIIFImageNotFoundException { if (!Files.exists(tileFilePath)) { throw new MCRIIIFImageNotFoundException(identifier); } if (tileInfo.getDerivate() != null && !checkPermission(identifier, tileInfo)) { throw MCRAccessException.missingPermission( "View the file " + tileInfo.getImagePath() + " in " + tileInfo.getDerivate(), tileInfo.getDerivate(), MCRAccessManager.PERMISSION_VIEW); } } protected boolean checkPermission(String identifier, MCRTileInfo tileInfo) { return MCRAccessManager.checkPermission(tileInfo.getDerivate(), MCRAccessManager.PERMISSION_VIEW) || MCRAccessManager.checkPermission(tileInfo.getDerivate(), MCRAccessManager.PERMISSION_READ); } }
15,025
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRThumbnailImageImpl.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/iiif/MCRThumbnailImageImpl.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.iiif; import java.nio.file.Files; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.mycore.access.MCRAccessManager; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.common.MCRLinkTableManager; import org.mycore.datamodel.metadata.MCRDerivate; 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.mycore.iiif.image.impl.MCRIIIFImageNotFoundException; import org.mycore.iview2.backend.MCRTileInfo; public class MCRThumbnailImageImpl extends MCRIVIEWIIIFImageImpl { protected static final String DERIVATE_TYPES = "Derivate.Types"; private Set<String> derivateTypes; public MCRThumbnailImageImpl(String implName) { super(implName); derivateTypes = new HashSet<>(); derivateTypes.addAll(Arrays.asList(getProperties().get(DERIVATE_TYPES).split(","))); } @Override protected MCRTileInfo createTileInfo(String id) throws MCRIIIFImageNotFoundException { MCRObjectID mcrID = calculateMCRObjectID(id).orElseThrow(() -> new MCRIIIFImageNotFoundException(id)); if (mcrID.getTypeId().equals("derivate")) { MCRDerivate mcrDer = MCRMetadataManager.retrieveMCRDerivate(mcrID); return new MCRTileInfo(mcrID.toString(), mcrDer.getDerivate().getInternals().getMainDoc(), null); } else { Optional<MCRTileInfo> tileInfoForMCRObject = createTileInfoForMCRObject(mcrID); if (tileInfoForMCRObject.isPresent()) { return tileInfoForMCRObject.get(); } Optional<MCRTileInfo> tileInfoForDerivateLink = createTileInfoForDerivateLink(mcrID); if (tileInfoForDerivateLink.isPresent()) { return tileInfoForDerivateLink.get(); } } throw new MCRIIIFImageNotFoundException(id); } @Override protected boolean checkPermission(String identifier, MCRTileInfo tileInfo) { Optional<MCRObjectID> mcrObjId = calculateMCRObjectID(identifier); if (mcrObjId.isPresent()) { return MCRAccessManager.checkPermission(mcrObjId.get(), MCRAccessManager.PERMISSION_PREVIEW) || MCRAccessManager.checkPermission(tileInfo.getDerivate(), MCRAccessManager.PERMISSION_VIEW) || MCRAccessManager.checkPermission(tileInfo.getDerivate(), MCRAccessManager.PERMISSION_READ); } return false; } /** * Builds a MyCoRe Object ID from the given IIIF image id parameter. * * Subclasses may override it. * * @param id the IIIF image id parameter * @return an Optional containing the MyCoRe ID */ protected Optional<MCRObjectID> calculateMCRObjectID(String id) { return MCRObjectID.isValid(id) ? Optional.of(MCRObjectID.getInstance(id)) : Optional.empty(); } private Optional<MCRTileInfo> createTileInfoForMCRObject(MCRObjectID mcrID) { MCRObject mcrObj = MCRMetadataManager.retrieveMCRObject(mcrID); for (MCRMetaEnrichedLinkID derLink : mcrObj.getStructure().getDerivates()) { if (derLink.getClassifications().stream() .map(MCRCategoryID::toString) .anyMatch(derivateTypes::contains)) { final String maindoc = derLink.getMainDoc(); if (maindoc != null) { Optional<MCRTileInfo> tileInfoForFile = createTileInfoForFile(derLink.getXLinkHref(), maindoc); if (tileInfoForFile.isPresent()) { return tileInfoForFile; } } } } return Optional.empty(); } private Optional<MCRTileInfo> createTileInfoForDerivateLink(MCRObjectID mcrID) { Collection<String> linkedImages = MCRLinkTableManager.instance() .getDestinationOf(mcrID, MCRLinkTableManager.ENTRY_TYPE_DERIVATE_LINK); for (String linkedImage : linkedImages) { MCRObjectID deriID = MCRObjectID.getInstance( linkedImage.substring(0, linkedImage.indexOf("/"))); MCRDerivate deri = MCRMetadataManager.retrieveMCRDerivate(deriID); if (deri.getDerivate().getClassifications().stream() .map(classi -> classi.getClassId() + ":" + classi.getCategId()) .anyMatch(derivateTypes::contains)) { Optional<MCRTileInfo> tileInfoForFile = createTileInfoForFile(deriID.toString(), linkedImage.substring(linkedImage.indexOf("/") + 1)); if (tileInfoForFile.isPresent()) { return tileInfoForFile; } } } return Optional.empty(); } private Optional<MCRTileInfo> createTileInfoForFile(String derID, String file) { final MCRTileInfo mcrTileInfo = new MCRTileInfo(derID, file, null); return Optional.of(mcrTileInfo) .filter(t -> this.tileFileProvider.getTileFile(t).filter(Files::exists).isPresent()); } }
5,979
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/services/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/>. */ /** * Service classes for IView2 */ package org.mycore.iview2.services;
801
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIView2Tools.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRIView2Tools.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.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.nio.channels.SeekableByteChannel; import java.nio.file.FileStore; import java.nio.file.FileSystem; import java.nio.file.FileSystemAlreadyExistsException; import java.nio.file.FileSystemNotFoundException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.text.MessageFormat; import java.util.Collections; import java.util.Locale; import java.util.Optional; import java.util.stream.Collectors; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRClassTools; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRAbstractFileStore; import org.mycore.datamodel.niofs.MCRContentTypes; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.imagetiler.MCRImage; import org.mycore.imagetiler.MCRTiledPictureProps; import jakarta.activation.FileTypeMap; import jakarta.persistence.EntityManager; import jakarta.persistence.TypedQuery; /** * Tools class with common methods for IView2. * * @author Thomas Scheffler (yagee) */ public class MCRIView2Tools { public static final String CONFIG_PREFIX = "MCR.Module-iview2."; private static String SUPPORTED_CONTENT_TYPE = MCRConfiguration2.getString(CONFIG_PREFIX + "SupportedContentTypes") .orElse(""); private static Path TILE_DIR = Paths.get(MCRIView2Tools.getIView2Property("DirectoryForTiles")); private static Logger LOGGER = LogManager.getLogger(MCRIView2Tools.class); /** * @return directory for tiles */ public static Path getTileDir() { return TILE_DIR; } /** * @param derivateID * ID of derivate * @return empty String or absolute path to main file of derivate if file is supported. */ public static String getSupportedMainFile(String derivateID) { try { MCRDerivate deriv = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(derivateID)); String nameOfMainFile = deriv.getDerivate().getInternals().getMainDoc(); // verify support if (nameOfMainFile != null && !nameOfMainFile.equals("")) { MCRPath mainFile = MCRPath.getPath(derivateID, '/' + nameOfMainFile); if (isFileSupported(mainFile)) { return mainFile.getRoot().relativize(mainFile).toString(); } } } catch (Exception e) { LOGGER.warn("Could not get main file of derivate.", e); } return ""; } /** * @param derivateID * ID of derivate * @return true if {@link #getSupportedMainFile(String)} is not an empty String. */ public static boolean isDerivateSupported(String derivateID) { if (derivateID == null || derivateID.trim().length() == 0) { return false; } return getSupportedMainFile(derivateID).length() > 0; } /** * @param file * image file * @return if content type is in property <code>MCR.Module-iview2.SupportedContentTypes</code> * @see MCRContentTypes#probeContentType(Path) */ public static boolean isFileSupported(Path file) throws IOException { try { return Optional.ofNullable(file) .map(path -> { try { return MCRContentTypes.probeContentType(path); } catch (IOException e) { throw new UncheckedIOException(e); } }) .or(() -> Optional.of("application/octet-stream")) .map(SUPPORTED_CONTENT_TYPE::contains) .orElse(Boolean.FALSE); } catch (UncheckedIOException e) { throw e.getCause(); } } /** * @return true if the file is supported, false otherwise */ public static boolean isFileSupported(String filename) { return SUPPORTED_CONTENT_TYPE.contains(FileTypeMap.getDefaultFileTypeMap().getContentType( filename.toLowerCase(Locale.ROOT))); } /** * Checks for a given derivate id whether all files in that derivate are tiled. * * @return true if all files in belonging to the derivate are tiled, false otherwise */ public static boolean isCompletelyTiled(String derivateId) { if (!MCRMetadataManager.exists(MCRObjectID.getInstance(derivateId))) { return false; } EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); TypedQuery<Number> namedQuery = em .createNamedQuery("MCRTileJob.countByStateListByDerivate", Number.class) .setParameter("derivateId", derivateId) .setParameter("states", MCRJobState.notCompleteStates().stream().map(MCRJobState::toChar).collect( Collectors.toSet())); return namedQuery.getSingleResult().intValue() == 0; } /** * combines image tiles of specified zoomLevel to one image. * * @param iviewFile * .iview2 file * @param zoomLevel * the zoom level where 0 is thumbnail size * @return a combined image * @throws IOException * any IOException while reading tiles */ public static BufferedImage getZoomLevel(Path iviewFile, int zoomLevel) throws IOException { ImageReader reader = getTileImageReader(); try (FileSystem zipFileSystem = getFileSystem(iviewFile)) { Path iviewFileRoot = zipFileSystem.getRootDirectories().iterator().next(); MCRTiledPictureProps imageProps = MCRTiledPictureProps.getInstanceFromDirectory(iviewFileRoot); if (zoomLevel < 0 || zoomLevel > imageProps.getZoomlevel()) { throw new IndexOutOfBoundsException( "Zoom level " + zoomLevel + " is not in range 0 - " + imageProps.getZoomlevel()); } return getZoomLevel(iviewFileRoot, imageProps, reader, zoomLevel); } finally { reader.dispose(); } } /** * combines image tiles of specified zoomLevel to one image. * * @param iviewFileRoot * root directory of .iview2 file * @param imageProperties * imageProperties, if available or null * @param zoomLevel * the zoom level where 0 is thumbnail size * @return a combined image * @throws IOException * any IOException while reading tiles */ public static BufferedImage getZoomLevel(final Path iviewFileRoot, final MCRTiledPictureProps imageProperties, final ImageReader reader, final int zoomLevel) throws IOException { if (zoomLevel == 0) { return readTile(iviewFileRoot, reader, 0, 0, 0); } MCRTiledPictureProps imageProps = imageProperties == null ? MCRTiledPictureProps.getInstanceFromDirectory(iviewFileRoot) : imageProperties; double zoomFactor = Math.pow(2, (imageProps.getZoomlevel() - zoomLevel)); int maxX = (int) Math.ceil((imageProps.getWidth() / zoomFactor) / MCRImage.getTileSize()); int maxY = (int) Math.ceil((imageProps.getHeight() / zoomFactor) / MCRImage.getTileSize()); LOGGER.debug("Image size:{}x{}, tiles:{}x{}", imageProps.getWidth(), imageProps.getHeight(), maxX, maxY); int imageType = getImageType(iviewFileRoot, reader, zoomLevel, 0, 0); int xDim = ((maxX - 1) * MCRImage.getTileSize() + readTile(iviewFileRoot, reader, zoomLevel, maxX - 1, 0).getWidth()); int yDim = ((maxY - 1) * MCRImage.getTileSize() + readTile(iviewFileRoot, reader, zoomLevel, 0, maxY - 1).getHeight()); BufferedImage resultImage = new BufferedImage(xDim, yDim, imageType); Graphics graphics = resultImage.getGraphics(); try { for (int x = 0; x < maxX; x++) { for (int y = 0; y < maxY; y++) { BufferedImage tile = readTile(iviewFileRoot, reader, zoomLevel, x, y); graphics.drawImage(tile, x * MCRImage.getTileSize(), y * MCRImage.getTileSize(), null); } } return resultImage; } finally { graphics.dispose(); } } public static FileSystem getFileSystem(Path iviewFile) throws IOException { URI uri = URI.create("jar:" + iviewFile.toUri()); try { return FileSystems.newFileSystem(uri, Collections.emptyMap(), MCRClassTools.getClassLoader()); } catch (FileSystemAlreadyExistsException exc) { // block until file system is closed try { FileSystem fileSystem = FileSystems.getFileSystem(uri); while (fileSystem.isOpen()) { try { Thread.sleep(10); } catch (InterruptedException ie) { // get out of here throw new IOException(ie); } } } catch (FileSystemNotFoundException fsnfe) { // seems closed now -> do nothing and try to return the file system again LOGGER.debug("Filesystem not found", fsnfe); } return getFileSystem(iviewFile); } } public static ImageReader getTileImageReader() { return ImageIO.getImageReadersByMIMEType("image/jpeg").next(); } public static BufferedImage readTile(Path iviewFileRoot, ImageReader imageReader, int zoomLevel, int x, int y) throws IOException { String tileName = new MessageFormat("{0}/{1}/{2}.jpg", Locale.ROOT).format(new Object[] { zoomLevel, y, x }); Path tile = iviewFileRoot.resolve(tileName); if (Files.exists(tile)) { try (SeekableByteChannel fileChannel = Files.newByteChannel(tile)) { ImageInputStream iis = ImageIO.createImageInputStream(fileChannel); if (iis == null) { throw new IOException("Could not acquire ImageInputStream from SeekableByteChannel: " + tile); } imageReader.setInput(iis, true); BufferedImage image = imageReader.read(0); imageReader.reset(); iis.close(); return image; } } else { throw new NoSuchFileException(iviewFileRoot.toString(), tileName, null); } } public static int getImageType(Path iviewFileRoot, ImageReader imageReader, int zoomLevel, int x, int y) throws IOException { String tileName = new MessageFormat("{0}/{1}/{2}.jpg", Locale.ROOT).format(new Object[] { zoomLevel, y, x }); Path tile = iviewFileRoot.resolve(tileName); if (Files.exists(tile)) { try (SeekableByteChannel fileChannel = Files.newByteChannel(tile)) { ImageInputStream iis = ImageIO.createImageInputStream(fileChannel); if (iis == null) { throw new IOException("Could not acquire ImageInputStream from SeekableByteChannel: " + tile); } imageReader.setInput(iis, true); int imageType = MCRImage.getImageType(imageReader); imageReader.reset(); iis.close(); return imageType; } } else { throw new NoSuchFileException(iviewFileRoot.toString(), tileName, null); } } /** * short for {@link MCRIView2Tools}{@link #getIView2Property(String, String)} defaultProp = null */ public static String getIView2Property(String propName) { return getIView2Property(propName, null); } /** * short for <code>MCRConfiguration2.getString("MCR.Module-iview2." + propName).orElse(defaultProp);</code> * * @param propName * any suffix * @return null or property value */ public static String getIView2Property(String propName, String defaultProp) { return MCRConfiguration2.getString(CONFIG_PREFIX + propName).orElse(defaultProp); } public static String getFilePath(String derID, String derPath) throws IOException { MCRPath mcrPath = MCRPath.getPath(derID, derPath); Path physicalPath = mcrPath.toPhysicalPath(); for (FileStore fs : mcrPath.getFileSystem().getFileStores()) { if (fs instanceof MCRAbstractFileStore mcrFileStore) { Path basePath = mcrFileStore.getBaseDirectory(); if (physicalPath.startsWith(basePath)) { return basePath.relativize(physicalPath).toString(); } } } return physicalPath.toString(); } }
14,150
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRImageTiler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRImageTiler.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.lang.reflect.Constructor; import java.util.Arrays; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import javax.imageio.ImageIO; 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.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRSystemUserInformation; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.events.MCRShutdownHandler; import org.mycore.common.events.MCRShutdownHandler.Closeable; import org.mycore.common.processing.MCRProcessableDefaultCollection; import org.mycore.common.processing.MCRProcessableRegistry; import org.mycore.util.concurrent.processing.MCRProcessableExecutor; import org.mycore.util.concurrent.processing.MCRProcessableFactory; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityTransaction; import jakarta.persistence.PersistenceException; /** * Master image tiler thread. * * @author Thomas Scheffler (yagee) */ public class MCRImageTiler implements Runnable, Closeable { private static MCRImageTiler instance = null; private static Logger LOGGER = LogManager.getLogger(MCRImageTiler.class); private static final MCRTilingQueue TQ = MCRTilingQueue.getInstance(); private MCRProcessableExecutor tilingServe; private volatile boolean running = true; private ReentrantLock runLock; private Constructor<? extends MCRTilingAction> tilingActionConstructor; private volatile Thread waiter; private MCRImageTiler() { MCRShutdownHandler.getInstance().addCloseable(this); runLock = new ReentrantLock(); try { Class<? extends MCRTilingAction> tilingActionImpl = MCRConfiguration2.<MCRTilingAction>getClass( MCRIView2Tools.CONFIG_PREFIX + "MCRTilingActionImpl").orElse(MCRTilingAction.class); tilingActionConstructor = tilingActionImpl.getConstructor(MCRTileJob.class); } catch (Exception e) { LOGGER.error("Error while initializing", e); throw new MCRException(e); } } /** * @return true if image tiler thread is running. */ public static boolean isRunning() { return instance != null; } /** * @return an instance of this class. */ public static MCRImageTiler getInstance() { if (instance == null) { instance = new MCRImageTiler(); } return instance; } /** * Starts local tiler threads ( {@link MCRTilingAction}) and gives {@link MCRTileJob} instances to them. Use * property <code>MCR.Module-iview2.TilingThreads</code> to specify how many concurrent threads should be running. */ public void run() { waiter = Thread.currentThread(); Thread.currentThread().setName("TileMaster"); //get this MCRSession a speaking name MCRSessionMgr.unlock(); MCRSession mcrSession = MCRSessionMgr.getCurrentSession(); mcrSession.setUserInformation(MCRSystemUserInformation.getSystemUserInstance()); boolean activated = MCRConfiguration2.getBoolean(MCRIView2Tools.CONFIG_PREFIX + "LocalTiler.activated") .orElse(true) && MCRConfiguration2.getBoolean("MCR.Persistence.Database.Enable").orElse(true) && MCREntityManagerProvider.getEntityManagerFactory() != null; LOGGER.info("Local Tiling is {}", activated ? "activated" : "deactivated"); ImageIO.scanForPlugins(); LOGGER.info("Supported image file types for reading: {}", Arrays.toString(ImageIO.getReaderFormatNames())); MCRProcessableDefaultCollection imageTilerCollection = new MCRProcessableDefaultCollection("Image Tiler"); MCRProcessableRegistry registry = MCRProcessableRegistry.getSingleInstance(); registry.register(imageTilerCollection); if (activated) { int tilingThreadCount = Integer.parseInt(MCRIView2Tools.getIView2Property("TilingThreads")); ThreadFactory slaveFactory = new ThreadFactory() { AtomicInteger tNum = new AtomicInteger(); ThreadGroup tg = new ThreadGroup("MCR slave tiling thread group"); public Thread newThread(Runnable r) { return new Thread(tg, r, "TileSlave#" + tNum.incrementAndGet()); } }; final AtomicInteger activeThreads = new AtomicInteger(); final LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(); ThreadPoolExecutor baseExecutor = new ThreadPoolExecutor(tilingThreadCount, tilingThreadCount, 1, TimeUnit.DAYS, workQueue, slaveFactory) { @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); activeThreads.decrementAndGet(); } @Override protected void beforeExecute(Thread t, Runnable r) { super.beforeExecute(t, r); activeThreads.incrementAndGet(); } }; this.tilingServe = MCRProcessableFactory.newPool(baseExecutor, imageTilerCollection); imageTilerCollection.setProperty("running", running); LOGGER.info("TilingMaster is started"); while (running) { try { while (activeThreads.get() < tilingThreadCount) { runLock.lock(); try { if (!running) { break; } EntityTransaction transaction = null; MCRTileJob job = null; try (EntityManager em = MCREntityManagerProvider.getCurrentEntityManager()) { transaction = em.getTransaction(); transaction.begin(); job = TQ.poll(); imageTilerCollection.setProperty("queue", TQ.stream().map(MCRTileJob::getPath).collect(Collectors.toList())); transaction.commit(); } catch (PersistenceException e) { LOGGER.error("Error while getting next tiling job.", e); if (transaction != null) { try { transaction.rollback(); } catch (RuntimeException re) { LOGGER.warn("Could not rollback transaction.", re); } } } if (job != null && !tilingServe.getExecutor().isShutdown()) { LOGGER.info("Creating:{}", job.getPath()); tilingServe.submit(getTilingAction(job)); } else { try { synchronized (TQ) { if (running) { LOGGER.debug("No Picture in TilingQueue going to sleep"); //fixes a race conditioned deadlock situation //do not wait longer than 60 sec. for a new MCRTileJob TQ.wait(60000); } } } catch (InterruptedException e) { LOGGER.error("Image Tiling thread was interrupted.", e); } } } finally { runLock.unlock(); } } // while(tilingServe.getActiveCount() < tilingServe.getCorePoolSize()) if (activeThreads.get() < tilingThreadCount) { try { LOGGER.info("Waiting for a tiling job to finish"); Thread.sleep(1000); } catch (InterruptedException e) { if (running) { LOGGER.error("Image Tiling thread was interrupted.", e); } } } } catch (Throwable e) { LOGGER.error("Keep running while catching exceptions.", e); } } // while(running) imageTilerCollection.setProperty("running", false); } LOGGER.info("Tiling thread finished"); MCRSessionMgr.releaseCurrentSession(); waiter = null; } private MCRTilingAction getTilingAction(MCRTileJob job) { try { return tilingActionConstructor.newInstance(job); } catch (Exception e) { throw new MCRException(e); } } /** * stops transmitting {@link MCRTileJob} to {@link MCRTilingAction} and prepares shutdown. */ public void prepareClose() { LOGGER.info("Closing master image tiling thread"); //signal master thread to stop now running = false; //Wake up, Neo! synchronized (TQ) { LOGGER.debug("Wake up tiling queue"); TQ.notifyAll(); } runLock.lock(); try { if (tilingServe != null) { LOGGER.debug("Shutdown tiling executor jobs."); tilingServe.getExecutor().shutdown(); try { LOGGER.debug("Await termination of tiling executor jobs."); tilingServe.getExecutor().awaitTermination(60, TimeUnit.SECONDS); LOGGER.debug("All jobs finished."); } catch (InterruptedException e) { LOGGER.debug("Could not wait 60 seconds...", e); } } } finally { runLock.unlock(); } } /** * Shuts down this thread and every local tiling threads spawned by {@link #run()}. */ public void close() { if (tilingServe != null && !tilingServe.getExecutor().isShutdown()) { LOGGER.info("We are in a hurry, closing tiling service right now"); tilingServe.getExecutor().shutdownNow(); try { tilingServe.getExecutor().awaitTermination(60, TimeUnit.SECONDS); } catch (InterruptedException e) { LOGGER.debug("Could not wait 60 seconds...", e); } } if (waiter != null && waiter.isAlive()) { //thread still running LOGGER.info("{} is still running.", waiter.getName()); Thread masterThread = waiter; waiter = null; masterThread.interrupt(); try { masterThread.join(); LOGGER.info("{} has died.", masterThread.getName()); } catch (InterruptedException e) { e.printStackTrace(System.err); } } } @Override public int getPriority() { return MCRShutdownHandler.Closeable.DEFAULT_PRIORITY - 1; } }
12,623
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTileJob.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRTileJob.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.text.MessageFormat; import java.util.Date; import java.util.Locale; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Index; import jakarta.persistence.NamedQueries; import jakarta.persistence.NamedQuery; import jakarta.persistence.Table; import jakarta.persistence.UniqueConstraint; /** * Container class handled by hibernate to store and retrieve job information for the next tiling request. * @author Thomas Scheffler (yagee) * */ @Entity @Table(name = "MCRTileJob", uniqueConstraints = { @UniqueConstraint(columnNames = { "derivate", "path" }), }, indexes = { @Index(columnList = "derivate,status") }) @NamedQueries({ @NamedQuery(name = "MCRTileJob.all", query = "SELECT job FROM MCRTileJob as job"), @NamedQuery(name = "MCRTileJob.countByStateListByDerivate", query = "SELECT count(job) FROM MCRTileJob as job WHERE job.derivate= :derivateId AND job.status IN (:states)") }) public class MCRTileJob implements Cloneable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column private long id; @Column(length = 64) private String derivate; @Column private String path; @Column private char status; @Column private Date added; @Column private Date start; @Column private Date finished; @Column private long tiles; @Column private long width; @Column private long height; @Column private long zoomLevel; /** * @return the date when this job was created */ public Date getAdded() { return added; } public void setAdded(Date added) { this.added = added; } /** * @return derivate ID */ public String getDerivate() { return derivate; } public void setDerivate(String derivate) { this.derivate = derivate; } /** * @return the date when this job was finished */ public Date getFinished() { return finished; } public void setFinished(Date finished) { this.finished = finished; } /** * @return height of the image */ public long getHeight() { return height; } public void setHeight(long height) { this.height = height; } /** * @return internal id */ public long getId() { return id; } public void setId(long id) { this.id = id; } /** * @return absolute image path rooted by derivate */ public String getPath() { return path; } public void setPath(String path) { this.path = path; } /** * @return the date when the job was last started */ public Date getStart() { return start; } public void setStart(Date start) { this.start = start; } /** * @return {@link MCRJobState#toChar()} of current status */ public char getStatus() { return status; } public void setStatus(MCRJobState status) { this.status = status.toChar(); } private void setStatus(char status) { this.status = status; } /** * @return number of generated tiles */ public long getTiles() { return tiles; } public void setTiles(long tiles) { this.tiles = tiles; } /** * @return image width */ public long getWidth() { return width; } public void setWidth(long width) { this.width = width; } /** * @return number of zoom levels */ public long getZoomLevel() { return zoomLevel; } public void setZoomLevel(long zoomLevel) { this.zoomLevel = zoomLevel; } /* (non-Javadoc) * @see java.lang.Object#clone() */ @Override public MCRTileJob clone() { MCRTileJob clone = new MCRTileJob(); clone.setAdded(getAdded()); clone.setDerivate(getDerivate()); clone.setFinished(getFinished()); clone.setHeight(getHeight()); clone.setId(getId()); clone.setPath(getPath()); clone.setStart(getStart()); clone.setStatus(getStatus()); clone.setTiles(getTiles()); clone.setWidth(getWidth()); clone.setZoomLevel(getZoomLevel()); return clone; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return new MessageFormat("MCRTileJob [derivate:{0}, path:{1}, added:{2}]", Locale.ROOT).format( new Object[] { getDerivate(), getPath(), getAdded() }); } }
5,563
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTilingAction.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRTilingAction.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.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Date; import java.util.concurrent.atomic.AtomicReference; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRSystemUserInformation; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.imagetiler.MCRImage; import org.mycore.imagetiler.MCRTileEventHandler; import org.mycore.imagetiler.MCRTiledPictureProps; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityTransaction; /** * A slave thread of {@link MCRImageTiler} * * This class can be extended. Any extending class should provide and implementation for {@link #getMCRImage()}. * To get the extending class invoked, one need to define a MyCoRe property, which defaults to: * <code>MCR.Module-iview2.MCRTilingActionImpl=org.mycore.iview2.services.MCRTilingAction</code> * @author Thomas Scheffler (yagee) * */ public class MCRTilingAction implements Runnable { private static final Logger LOGGER = LogManager.getLogger(MCRTilingAction.class); protected MCRTileJob tileJob = null; public MCRTilingAction(MCRTileJob image) { this.tileJob = image; } /** * takes a {@link MCRTileJob} and tiles the referenced {@link MCRImage} instance. * * Also this updates tileJob properties of {@link MCRTileJob} in the database. */ public void run() { tileJob.setStart(new Date()); MCRImage image; Path tileDir = MCRIView2Tools.getTileDir(); image = getMCRImage(); image.setTileDir(tileDir); MCRSessionMgr.unlock(); MCRSession mcrSession = MCRSessionMgr.getCurrentSession(); mcrSession.setUserInformation(MCRSystemUserInformation.getSystemUserInstance()); AtomicReference<EntityTransaction> imageReaderTransactionReference = new AtomicReference<>(); EntityTransaction mergeTransaction = null; try (EntityManager em = MCREntityManagerProvider.getCurrentEntityManager()) { MCRTileEventHandler tileEventHandler = new MCRTileEventHandler() { @Override public void preImageReaderCreated() { imageReaderTransactionReference.set(em.getTransaction()); imageReaderTransactionReference.get().begin(); } @Override public void postImageReaderCreated() { em.clear(); //beside tileJob, no write access so far if (imageReaderTransactionReference.get().isActive()) { imageReaderTransactionReference.get().commit(); } } }; try { MCRTiledPictureProps picProps = image.tile(tileEventHandler); tileJob.setFinished(new Date()); tileJob.setStatus(MCRJobState.FINISHED); tileJob.setHeight(picProps.getHeight()); tileJob.setWidth(picProps.getWidth()); tileJob.setTiles(picProps.getTilesCount()); tileJob.setZoomLevel(picProps.getZoomlevel()); } catch (IOException e) { LOGGER.error("IOException occured while tiling a queued picture", e); throw e; } mergeTransaction = em.getTransaction(); mergeTransaction.begin(); em.merge(tileJob); mergeTransaction.commit(); } catch (Exception e) { LOGGER.error("Error while getting next tiling job.", e); EntityTransaction imageReaderTransaction = imageReaderTransactionReference.get(); if (imageReaderTransaction != null && imageReaderTransaction.isActive()) { imageReaderTransaction.rollback(); } if (mergeTransaction != null && mergeTransaction.isActive()) { mergeTransaction.rollback(); } try { Files.deleteIfExists(MCRImage.getTiledFile(tileDir, tileJob.getDerivate(), tileJob.getPath())); } catch (IOException e1) { LOGGER.error("Could not delete tile file after error!", e); } } finally { MCRSessionMgr.releaseCurrentSession(); mcrSession.close(); } } /** * @return MCRImage instance based on the information provided by {@link #tileJob} */ protected MCRImage getMCRImage() { MCRPath file = MCRPath.getPath(tileJob.getDerivate(), tileJob.getPath()); return MCRImage.getInstance(file, file.getOwner(), file.getOwnerRelativePath()); } @Override public String toString() { if (tileJob == null) { return "unassigned tiling action"; } return tileJob.toString(); } }
5,751
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIview2URIResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRIview2URIResolver.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 javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import org.jdom2.Element; import org.jdom2.transform.JDOMSource; public class MCRIview2URIResolver implements URIResolver { @Override public Source resolve(String href, String base) throws TransformerException { String[] params = href.split(":"); if (params.length != 3) { throw new TransformerException("Invalid href: " + href); } switch (params[1]) { case "isCompletelyTiled" -> { boolean completelyTiled = MCRIView2Tools.isCompletelyTiled(params[2]); return new JDOMSource(new Element(String.valueOf(completelyTiled))); } case "isFileSupported" -> { final boolean supported = MCRIView2Tools.isFileSupported(params[2]); return new JDOMSource(new Element(String.valueOf(supported))); } default -> throw new TransformerException("Invalid href: " + href); } } }
1,841
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJobState.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRJobState.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; /** * Represents the status of tiling jobs * @author Thomas Scheffler (yagee) * */ public enum MCRJobState { /** * job is added to tiling queue */ NEW('n'), /** * job is currently being processed by an image tiler */ PROCESSING('p'), /** * image tiling process is complete */ FINISHED('f'), /** * image tiling process is complete */ ERROR('e'); private static final Set<MCRJobState> NOT_COMPLETE_STATES = Set.of(MCRJobState.ERROR, MCRJobState.PROCESSING, MCRJobState.NEW); private static final Set<MCRJobState> COMPLETE_STATES = Set.of(MCRJobState.FINISHED); private final char status; public static Set<MCRJobState> notCompleteStates() { return NOT_COMPLETE_STATES; } public static Set<MCRJobState> completeStates() { return COMPLETE_STATES; } MCRJobState(char status) { this.status = status; } /** * returns character representing the status * @return * <table> * <caption>returned characters depending on current state</caption> * <tr> * <th>{@link #NEW}</th> * <td>'n'</td> * </tr> * <tr> * <th>{@link #PROCESSING}</th> * <td>'p'</td> * </tr> * <tr> * <th>{@link #FINISHED}</th> * <td>'f'</td> * </tr> * <tr> * <th>{@link #ERROR}</th> * <td>'e'</td> * </tr> * </table> */ public char toChar() { return status; } }
2,311
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRImageThumbnailGenerator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRImageThumbnailGenerator.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.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Path; import java.util.Optional; import java.util.regex.Pattern; import javax.imageio.ImageReader; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.imagetiler.MCRImage; import org.mycore.imagetiler.MCRTiledPictureProps; import org.mycore.media.services.MCRThumbnailGenerator; public class MCRImageThumbnailGenerator implements MCRThumbnailGenerator { private static final Pattern MATCHING_MIMETYPE = Pattern.compile("^image\\/.*"); @Override public boolean matchesFileType(String mimeType, MCRPath path) { return MATCHING_MIMETYPE.matcher(mimeType).matches(); } @Override public Optional<BufferedImage> getThumbnail(MCRPath path, int size) throws IOException { Path iviewFile = MCRImage.getTiledFile(MCRIView2Tools.getTileDir(), path.getOwner(), path.getOwnerRelativePath()); MCRTiledPictureProps iviewFileProps = getIviewFileProps(iviewFile); final double width = iviewFileProps.getWidth(); final double height = iviewFileProps.getHeight(); final int newWidth = width > height ? (int) Math.ceil(size * width / height) : size; final int newHeight = width > height ? size : (int) Math.ceil(size * height / width); // this value determines the zoom level! final double scale = newWidth / width; // We always want to use the the best needed zoom level! int sourceZoomLevel = (int) Math.min( Math.max(0, Math.ceil(iviewFileProps.getZoomlevel() - Math.log(scale) / Math.log(1.0 / 2.0))), iviewFileProps.getZoomlevel()); // scale is the real scale which is needed! zoomLevelScale is the scale of the nearest zoom level! double zoomLevelScale = Math.min(1.0, Math.pow(0.5, iviewFileProps.getZoomlevel() - sourceZoomLevel)); // this is the scale which is needed from the nearest zoom level to the required size of image double drawScale = (newWidth / (width * zoomLevelScale)); try (FileSystem zipFileSystem = MCRIView2Tools.getFileSystem(iviewFile)) { Path rootPath = zipFileSystem.getPath("/"); ImageReader imageReader = MCRIView2Tools.getTileImageReader(); BufferedImage testTile = MCRIView2Tools.readTile(rootPath, imageReader, sourceZoomLevel, 0, 0); BufferedImage targetImage = getTargetImage(newWidth, newHeight, testTile); Graphics2D graphics = targetImage.createGraphics(); graphics.scale(drawScale, drawScale); for (int x = 0; x < Math.ceil(width * zoomLevelScale / 256); x++) { for (int y = 0; y < Math.ceil(height * zoomLevelScale / 256); y++) { BufferedImage tile = MCRIView2Tools.readTile(rootPath, imageReader, sourceZoomLevel, x, y); graphics.drawImage(tile, x * 256, y * 256, null); } } return Optional.of(targetImage); } } private MCRTiledPictureProps getIviewFileProps(Path tiledFile) throws IOException { MCRTiledPictureProps tiledPictureProps = null; try (FileSystem fileSystem = MCRIView2Tools.getFileSystem(tiledFile)) { tiledPictureProps = MCRTiledPictureProps.getInstanceFromDirectory(fileSystem.getPath("/")); } catch (IOException e) { throw new IOException("Could not provide image information!", e); } return tiledPictureProps; } private BufferedImage getTargetImage(int width, int height, BufferedImage firstTile) { return new BufferedImage(width, height, firstTile.getType()); } }
4,507
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTilingQueue.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRTilingQueue.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.AbstractQueue; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.events.MCRShutdownHandler; import org.mycore.common.events.MCRShutdownHandler.Closeable; import jakarta.persistence.EntityManager; import jakarta.persistence.NoResultException; import jakarta.persistence.Query; import jakarta.persistence.TypedQuery; public class MCRTilingQueue extends AbstractQueue<MCRTileJob> implements Closeable { private static MCRTilingQueue instance = new MCRTilingQueue(); private static Queue<MCRTileJob> preFetch; private static ScheduledExecutorService StalledJobScheduler; private static Logger LOGGER = LogManager.getLogger(MCRTilingQueue.class); private final ReentrantLock pollLock; private boolean running; private MCRTilingQueue() { // periodische Ausführung von runProcess int waitTime = Integer.parseInt(MCRIView2Tools.getIView2Property("TimeTillReset")) * 60; StalledJobScheduler = Executors.newSingleThreadScheduledExecutor(); StalledJobScheduler.scheduleAtFixedRate(MCRStalledJobResetter.getInstance(), waitTime, waitTime, TimeUnit.SECONDS); preFetch = new ConcurrentLinkedQueue<>(); running = true; pollLock = new ReentrantLock(); MCRShutdownHandler.getInstance().addCloseable(this); } /** * @return singleton instance of this class */ public static MCRTilingQueue getInstance() { if (!instance.running) { return null; } return instance; } /** * @return next available tile job instance */ public MCRTileJob poll() { if (!running) { return null; } try { pollLock.lock(); MCRTileJob job = getElement(); if (job != null) { job.setStart(new Date(System.currentTimeMillis())); job.setStatus(MCRJobState.PROCESSING); if (!updateJob(job)) { job = null; } } return job; } finally { pollLock.unlock(); } } /** * removes next job. * same as {@link #poll()} but never returns null * @throws NoSuchElementException if {@link #poll()} would return null */ @Override public MCRTileJob remove() throws NoSuchElementException { if (!running) { return null; } MCRTileJob job = poll(); if (job == null) { throw new NoSuchElementException(); } return job; } /** * get next job without modifying it state to {@link MCRJobState#PROCESSING} */ public MCRTileJob peek() { if (!running) { return null; } return getElement(); } /** * removes next job. * same as {@link #peek()} but never returns null * @throws NoSuchElementException if {@link #peek()} would return null */ @Override public MCRTileJob element() throws NoSuchElementException { if (!running) { return null; } MCRTileJob job = peek(); if (job == null) { throw new NoSuchElementException(); } return job; } /** * adds <code>job</code> to queue. * alters date added to current time and status of job to {@link MCRJobState#NEW} */ public boolean offer(MCRTileJob job) { MCRTileJob newJob = job; if (!running) { return false; } MCRTileJob oldJob = getJob(newJob.getDerivate(), newJob.getPath()); if (oldJob != null) { newJob = oldJob; } else { newJob.setAdded(new Date()); } newJob.setStatus(MCRJobState.NEW); newJob.setStart(null); if (addJob(newJob)) { notifyListener(); return true; } else { return false; } } /** * Deletes all tile jobs no matter what the current state is. */ @Override public void clear() { if (!running) { return; } EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); Query query = em.createQuery("DELETE FROM MCRTileJob"); query.executeUpdate(); } /** * iterates of jobs of status {@link MCRJobState#NEW} * * does not change the status. */ @Override public Iterator<MCRTileJob> iterator() { if (!running) { List<MCRTileJob> empty = Collections.emptyList(); return empty.iterator(); } EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); TypedQuery<MCRTileJob> query = em.createQuery("FROM MCRTileJob WHERE status='" + MCRJobState.NEW.toChar() + "' ORDER BY added ASC", MCRTileJob.class); List<MCRTileJob> result = query.getResultList(); return result.iterator(); } /** * returns the current size of this queue */ @Override public int size() { if (!running) { return 0; } EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); TypedQuery<Number> query = em .createQuery("SELECT count(*) FROM MCRTileJob WHERE status='" + MCRJobState.NEW.toChar() + "'", Number.class); return query.getSingleResult().intValue(); } /** * get the specific job and alters it status to {@link MCRJobState#PROCESSING} */ public MCRTileJob getElementOutOfOrder(String derivate, String path) throws NoSuchElementException { if (!running) { return null; } MCRTileJob job = getJob(derivate, path); if (job == null) { return null; } job.setStart(new Date(System.currentTimeMillis())); job.setStatus(MCRJobState.PROCESSING); if (!updateJob(job)) { throw new NoSuchElementException(); } return job; } private MCRTileJob getJob(String derivate, String path) { if (!running) { return null; } EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); TypedQuery<MCRTileJob> query = em.createQuery("FROM MCRTileJob WHERE derivate= :derivate AND path = :path", MCRTileJob.class); query.setParameter("derivate", derivate); query.setParameter("path", path); try { MCRTileJob job = query.getSingleResult(); clearPreFetch(); return job; } catch (NoResultException e) { return null; } } private MCRTileJob getElement() { if (!running) { return null; } MCRTileJob job = getNextPrefetchedElement(); if (job != null) { return job; } LOGGER.debug("No prefetched jobs available"); if (preFetch(100) == 0) { return null; } return getNextPrefetchedElement(); } private MCRTileJob getNextPrefetchedElement() { MCRTileJob job = preFetch.poll(); LOGGER.debug("Fetched job: {}", job); return job; } private int preFetch(int amount) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); TypedQuery<MCRTileJob> query = em.createQuery( "FROM MCRTileJob WHERE status='" + MCRJobState.NEW.toChar() + "' ORDER BY added ASC", MCRTileJob.class) .setMaxResults(amount); Iterator<MCRTileJob> queryResult = query.getResultList().iterator(); int i = 0; while (queryResult.hasNext()) { i++; MCRTileJob job = queryResult.next(); preFetch.add(job.clone()); em.detach(job); } LOGGER.debug("prefetched {} tile jobs", i); return i; } private void clearPreFetch() { preFetch.clear(); } private boolean updateJob(MCRTileJob job) { if (!running) { return false; } EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); em.merge(job); return true; } private boolean addJob(MCRTileJob job) { if (!running) { return false; } EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); em.persist(job); return true; } /** * every attached listener is informed that something happened to the state of the queue. */ public synchronized void notifyListener() { this.notifyAll(); } /** * removes specific job from queue no matter what its current status is. * @param derivate ID of derivate * @param path absolute image path * @return the number of jobs deleted */ public int remove(String derivate, String path) { if (!running) { return 0; } EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); Query query = em.createQuery("DELETE FROM " + MCRTileJob.class.getName() + " WHERE derivate = :derivate AND path = :path"); query.setParameter("derivate", derivate); query.setParameter("path", path); try { return query.executeUpdate(); } finally { clearPreFetch(); } } /** * removes all jobs from queue for that <code>derivate</code> its current status is. * @param derivate ID of derivate * @return the number of jobs deleted */ public int remove(String derivate) { if (!running) { return 0; } EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); Query query = em .createQuery("DELETE FROM " + MCRTileJob.class.getName() + " WHERE derivate = :derivate"); query.setParameter("derivate", derivate); try { return query.executeUpdate(); } finally { clearPreFetch(); } } /** * Shuts down {@link MCRStalledJobResetter} and does not alter any job anymore. */ public void prepareClose() { StalledJobScheduler.shutdownNow(); running = false; try { StalledJobScheduler.awaitTermination(60, TimeUnit.SECONDS); } catch (InterruptedException e) { LOGGER.info("Could not wait for 60 seconds..."); StalledJobScheduler.shutdownNow(); } } /** * does nothing */ public void close() { //nothing to be done in this phase } /** * @return "MCRTilingQueue" */ @Override public String toString() { return "MCRTilingQueue"; } }
12,045
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRStalledJobResetter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/services/MCRStalledJobResetter.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.Date; import java.util.HashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.backend.jpa.MCREntityManagerProvider; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityTransaction; import jakarta.persistence.PersistenceException; import jakarta.persistence.TypedQuery; /** * Resets jobs that took to long to tile. * Set property <code>MCR.Module-iview2.TimeTillReset</code> to alter grace period. * Set property <code>MCR.Module-iview2.MaxResetCount</code> to alter maximum tries per job. * @author Thomas Scheffler (yagee) */ public class MCRStalledJobResetter implements Runnable { private static MCRStalledJobResetter instance = new MCRStalledJobResetter(); private static int maxTimeDiff = Integer.parseInt(MCRIView2Tools.getIView2Property("TimeTillReset")); private static Logger LOGGER = LogManager.getLogger(MCRStalledJobResetter.class); private static int maxResetCount = Integer.parseInt(MCRIView2Tools.getIView2Property("MaxResetCount")); private HashMap<Long, Integer> jobCounter; private MCRStalledJobResetter() { jobCounter = new HashMap<>(); } public static MCRStalledJobResetter getInstance() { return instance; } /** * Resets jobs to {@link MCRJobState#NEW} that where in status {@link MCRJobState#PROCESSING} for to long time. */ public void run() { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); EntityTransaction executorTransaction = em.getTransaction(); LOGGER.info("MCRTileJob is Checked for dead Entries"); executorTransaction.begin(); TypedQuery<MCRTileJob> query = em.createQuery("FROM MCRTileJob WHERE status='" + MCRJobState.PROCESSING.toChar() + "' ORDER BY id ASC", MCRTileJob.class); long current = new Date(System.currentTimeMillis()).getTime() / 60000; boolean reset = query .getResultList() .stream() .map(job -> { long start = job.getStart().getTime() / 60000; boolean ret = false; LOGGER.debug("checking {} {} ...", job.getDerivate(), job.getPath()); if (current - start >= maxTimeDiff) { if (hasPermanentError(job)) { LOGGER.warn("Job has permanent errors: {}", job); job.setStatus(MCRJobState.ERROR); jobCounter.remove(job.getId()); } else { LOGGER.debug("->Resetting too long in queue"); job.setStatus(MCRJobState.NEW); job.setStart(null); ret = true; } } else { LOGGER.debug("->ok"); } return ret; }) .reduce(Boolean::logicalOr) .orElse(false); try { executorTransaction.commit(); } catch (PersistenceException e) { LOGGER.error(e); if (executorTransaction != null) { executorTransaction.rollback(); reset = false;//No changes are applied, so no notification is needed as well } } //Only notify Listeners on TilingQueue if really something is set back if (reset) { synchronized (MCRTilingQueue.getInstance()) { MCRTilingQueue.getInstance().notifyListener(); } } em.close(); LOGGER.info("MCRTileJob checking is done"); } private boolean hasPermanentError(MCRTileJob job) { int runs = 0; if (jobCounter.containsKey(job.getId())) { runs = jobCounter.get(job.getId()); } if (++runs >= maxResetCount) { return true; } jobCounter.put(job.getId(), runs); return false; } }
4,754
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIView2TilingThreadStarter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/events/MCRIView2TilingThreadStarter.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.events; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.events.MCRStartupHandler; import org.mycore.iview2.services.MCRImageTiler; import jakarta.servlet.ServletContext; /** * Handles tiling process in a web application. * @author Thomas Scheffler (yagee) * */ public class MCRIView2TilingThreadStarter implements MCRStartupHandler.AutoExecutable { private static Logger LOGGER = LogManager.getLogger(MCRIView2TilingThreadStarter.class); @Override public String getName() { return "Image Viewer Tiling Thread"; } @Override public int getPriority() { return 0; } @Override public void startUp(ServletContext servletContext) { if (servletContext != null && !MCRImageTiler.isRunning()) { LOGGER.info("Starting Tiling thread."); System.setProperty("java.awt.headless", "true"); Thread tilingThread = new Thread(MCRImageTiler.getInstance()); tilingThread.start(); } } }
1,810
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/events/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/>. */ /** * Handling various kinds of events */ package org.mycore.iview2.events;
806
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRImageTileEventHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/events/MCRImageTileEventHandler.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.events; import java.io.IOException; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import org.mycore.common.MCRException; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandlerBase; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.iview2.frontend.MCRIView2Commands; import org.mycore.iview2.services.MCRTilingQueue; /** * Handles {@link org.mycore.datamodel.ifs2.MCRFile} events to keep image tiles up-to-date. * @author Thomas Scheffler (yagee) * */ public class MCRImageTileEventHandler extends MCREventHandlerBase { MCRTilingQueue tq = MCRTilingQueue.getInstance(); /** * creates image tiles if <code>file</code> is an image file. */ @Override public void handlePathCreated(MCREvent evt, Path file, BasicFileAttributes attrs) { if (!(file instanceof MCRPath)) { return; } try { MCRIView2Commands.tileImage(MCRPath.toMCRPath(file)); } catch (IOException e) { throw new MCRException(e); } } /** * deletes image tiles for <code>file</code>. */ @Override public void handlePathDeleted(MCREvent evt, Path file, BasicFileAttributes attrs) { if (!(file instanceof MCRPath)) { return; } MCRPath path = MCRPath.toMCRPath(file); try { MCRIView2Commands.deleteImageTiles(path.getOwner(), path.getOwnerRelativePath()); } catch (IOException e) { throw new MCRException(e); } } /** * updates image times if <code>file</code> is an image file. */ @Override public void handlePathUpdated(MCREvent evt, Path file, BasicFileAttributes attrs) { handlePathDeleted(evt, file, attrs); handlePathCreated(evt, file, attrs); } }
2,609
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRThumbnailForPdfEventHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iview2/src/main/java/org/mycore/iview2/events/MCRThumbnailForPdfEventHandler.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.events; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Locale; 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.config.MCRConfiguration2; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandlerBase; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetaClassification; import org.mycore.iview2.backend.MCRDefaultTileFileProvider; import org.mycore.iview2.backend.MCRPDFThumbnailJobAction; import org.mycore.iview2.backend.MCRTileInfo; import org.mycore.services.queuedjob.MCRJob; import org.mycore.services.queuedjob.MCRJobQueue; import org.mycore.services.queuedjob.MCRJobQueueManager; /** * This event handler creates iview2 files for title pages in PDFs which can be * used as thumbnails in IIIF API * * @author Robert Stephan */ public class MCRThumbnailForPdfEventHandler extends MCREventHandlerBase { public static final MCRDefaultTileFileProvider TILE_FILE_PROVIDER = new MCRDefaultTileFileProvider(); private static final Logger LOGGER = LogManager.getLogger(MCRThumbnailForPdfEventHandler.class); private static final MCRJobQueue PDF_THUMBNAIL_JOB_QUEUE = initializeJobQueue(); private static final List<String> DERIVATE_TYPES_FOR_CONTENT = MCRConfiguration2 .getOrThrow("MCR.IIIFImage.Iview.ThumbnailForPdfEventHandler.Derivate.Types", MCRConfiguration2::splitValue) .collect(Collectors.toList()); private static MCRJobQueue initializeJobQueue() { LOGGER.info("Initializing jobQueue for PDF Thumbnail generation!"); return MCRJobQueueManager.getInstance().getJobQueue(MCRPDFThumbnailJobAction.class); } @Override protected void handleDerivateCreated(MCREvent evt, MCRDerivate der) { updateThumbnail(der); } @Override protected void handleDerivateRepaired(MCREvent evt, MCRDerivate der) { updateThumbnail(der); } @Override protected void handleDerivateUpdated(MCREvent evt, MCRDerivate der) { updateThumbnail(der); } @Override protected void handleDerivateDeleted(MCREvent evt, MCRDerivate der) { deleteThumbnail(der); } private void updateThumbnail(MCRDerivate der) { deleteThumbnail(der); if (isQualifyingDerivate(der)) { final MCRJob job = new MCRJob(MCRPDFThumbnailJobAction.class); job.setParameter(MCRPDFThumbnailJobAction.DERIVATE_PARAMETER, der.getId().toString()); PDF_THUMBNAIL_JOB_QUEUE.add(job); } } private void deleteThumbnail(MCRDerivate der) { String mainDoc = der.getDerivate().getInternals().getMainDoc(); if (mainDoc != null && mainDoc.toLowerCase(Locale.ROOT).endsWith(".pdf")) { MCRTileInfo tileInfo = new MCRTileInfo(der.getId().toString(), mainDoc, null); Optional<Path> oPIview2File = TILE_FILE_PROVIDER.getTileFile(tileInfo); if (oPIview2File.isPresent()) { try { Files.deleteIfExists(oPIview2File.get()); } catch (IOException e) { LOGGER.error(e); } } } } private boolean isQualifyingDerivate(MCRDerivate der) { for (MCRMetaClassification c : der.getDerivate().getClassifications()) { String classid = c.getClassId() + ":" + c.getCategId(); if (DERIVATE_TYPES_FOR_CONTENT.contains(classid)) { String mainDoc = der.getDerivate().getInternals().getMainDoc(); return (mainDoc != null && mainDoc.toLowerCase(Locale.ROOT).endsWith(".pdf")); } } return false; } }
4,623
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSPagesHelperTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/MCRMODSPagesHelperTest.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.mods; import static org.junit.Assert.assertEquals; import org.jdom2.Element; import org.junit.Test; import org.mycore.common.MCRConstants; import org.mycore.common.MCRTestCase; public class MCRMODSPagesHelperTest extends MCRTestCase { @Test public void testPages2Extent() { testPattern("4-8", "start=4", "end=8"); testPattern(" 234 - 238", "start=234", "end=238"); testPattern("S. 234 - 238", "start=234", "end=238"); testPattern("pp. 234 - 238", "start=234", "end=238"); testPattern(" 3ABC8 \u2010 3ABC567", "start=3ABC8", "end=3ABC567"); testPattern("123-45 - 123-49", "start=123-45", "end=123-49"); testPattern("234 (5 pages)", "start=234", "total=5"); testPattern("234 (5 Seiten)", "start=234", "total=5"); testPattern("234 (5 S.)", "start=234", "total=5"); testPattern("p. 234 (5 pages)", "start=234", "total=5"); testPattern("3ABC8 (13 pages)", "start=3ABC8", "total=13"); testPattern("234", "start=234"); testPattern("S. 123", "start=123"); testPattern("S. 123 f.", "start=123"); testPattern("S. 123 ff.", "start=123"); testPattern("S. 123 ff", "start=123"); testPattern("11 pages", "total=11"); testPattern("20 Seiten", "total=20"); testPattern("15 S.", "total=15"); testPattern("3-4 und 7-8", "list=3-4 und 7-8"); } @Test public void testEndPageCompletion() { testPattern("3845 - 53", "start=3845", "end=3853"); testPattern("123 - 7", "start=123", "end=127"); } private void testPattern(String input, String... expected) { Element extent = MCRMODSPagesHelper.buildExtentPages(input); assertEquals(expected.length, extent.getChildren().size()); for (String token : expected) { String name = token.split("=")[0]; String value = token.split("=")[1]; assertEquals(value, extent.getChildText(name, MCRConstants.MODS_NAMESPACE)); } } }
2,771
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSLinkedMetadataTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/MCRMODSLinkedMetadataTest.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.mods; import java.util.List; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.filter.Filters; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.jdom2.xpath.XPathBuilder; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mycore.access.MCRAccessException; import org.mycore.common.MCRConstants; import org.mycore.common.MCRPersistenceException; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRStoreTestCase; import org.mycore.common.MCRSystemUserInformation; import org.mycore.datamodel.common.MCRActiveLinkException; import org.mycore.datamodel.common.MCRLinkTableManager; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.ifs2.MCRStoreManager; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; /** * Tests for MCR-910 (Link MODS documents to other MODS documents) * * @author Thomas Scheffler (yagee) */ public class MCRMODSLinkedMetadataTest extends MCRStoreTestCase { MCRObjectID seriesID, bookID; @Before public void setUp() throws Exception { super.setUp(); seriesID = MCRObjectID.getInstance("junit_mods_00000001"); bookID = MCRObjectID.getInstance("junit_mods_00000002"); MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getSuperUserInstance()); MCRObject series = new MCRObject(getResourceAsURL(seriesID + ".xml").toURI()); MCRObject book = new MCRObject(getResourceAsURL(bookID + ".xml").toURI()); MCRMetadataManager.create(series); MCRMetadataManager.create(book); } @After public void tearDown() throws Exception { MCRXMLMetadataManager mm = MCRXMLMetadataManager.instance(); String seriesBase = seriesID.getBase(); for (List<String> ids = mm.listIDsForBase(seriesBase); !ids.isEmpty(); ids = mm.listIDsForBase(seriesBase)) { for (String id : ids) { final MCRObjectID currentId = MCRObjectID.getInstance(id); System.err.println("Delete " + currentId); try { MCRMetadataManager.deleteMCRObject(currentId); } catch (MCRActiveLinkException | MCRAccessException e) { System.err.println("Cannot delete " + currentId + " at this moment."); } } } MCRStoreManager.removeStore(seriesID.getBase()); super.tearDown(); } @Test public void testLinks() { Assert.assertEquals("There should be a reference link from +" + bookID + " to " + seriesID + ".", 1, MCRLinkTableManager.instance().countReferenceLinkTo(seriesID)); } @Test public void testUpdate() throws Exception { MCRObject seriesNew = new MCRObject(getResourceAsURL(seriesID + "-updated.xml").toURI()); MCRMetadataManager.update(seriesNew); Document bookNew = MCRXMLMetadataManager.instance().retrieveXML(bookID); XPathBuilder<Element> builder = new XPathBuilder<>( "/mycoreobject/metadata/def.modsContainer/modsContainer/mods:mods/mods:relatedItem/mods:titleInfo/mods:title", Filters.element()); builder.setNamespace(MCRConstants.MODS_NAMESPACE); XPathExpression<Element> seriesTitlePath = builder.compileWith(XPathFactory.instance()); Element titleElement = seriesTitlePath.evaluateFirst(bookNew); Assert.assertNotNull( "No title element in related item: " + new XMLOutputter(Format.getPrettyFormat()).outputString(bookNew), titleElement); Assert.assertEquals("Title update from series was not promoted to book of series.", "Updated series title", titleElement.getText()); } @Test(expected = MCRPersistenceException.class) public void testHierarchyDirect() throws Exception { MCRObjectID book2ID = MCRObjectID.getInstance("junit_mods_00000003"); MCRObject book2 = new MCRObject(getResourceAsURL(book2ID + ".xml").toURI()); MCRMetadataManager.create(book2); book2 = new MCRObject(getResourceAsURL(book2ID + "-updated.xml").toURI()); MCRMetadataManager.update(book2); } @Test(expected = MCRPersistenceException.class) public void testHierarchyIndirect() throws Exception { MCRObjectID book2ID = MCRObjectID.getInstance("junit_mods_00000003"); MCRObject book2 = new MCRObject(getResourceAsURL(book2ID + ".xml").toURI()); MCRMetadataManager.create(book2); MCRObject series = new MCRObject(getResourceAsURL(seriesID + "-updated2.xml").toURI()); MCRMetadataManager.update(series); } /** * The tests check if the relatedItems with no inherited data are ignored by the hierarchy check of the ShareAgent */ @Test(expected = Test.None.class) public void testHierarchyNoInheritance() throws Exception { MCRObjectID book4ID = MCRObjectID.getInstance("junit_mods_00000004"); MCRObject book2 = new MCRObject(getResourceAsURL(book4ID + ".xml").toURI()); MCRMetadataManager.create(book2); book2 = new MCRObject(getResourceAsURL(book4ID + "-updated.xml").toURI()); MCRMetadataManager.update(book2); } }
6,212
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSDateHelperTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/MCRMODSDateHelperTest.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.mods; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.time.Year; import java.time.ZoneId; import java.time.temporal.ChronoField; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import org.jdom2.Element; import org.junit.Test; import org.mycore.common.MCRTestCase; /** * @author Frank Lützenkirchen */ public class MCRMODSDateHelperTest extends MCRTestCase { @Test public void testNull() { assertNull(MCRMODSDateHelper.getDate(null)); assertNull(MCRMODSDateHelper.getCalendar(null)); Element element = new Element("date"); assertNull(MCRMODSDateHelper.getDate(element)); assertNull(MCRMODSDateHelper.getCalendar(element)); } @Test public void testISO8601yearOnly() { Element element = new Element("date"); int fullYear = Year.now().get(ChronoField.YEAR); MCRMODSDateHelper.setDate(element, new Date(), MCRMODSDateFormat.iso8601_4); int year = Integer.parseInt(element.getText()); assertEquals(fullYear, year); assertEquals("iso8601", element.getAttributeValue("encoding")); Date parsed = MCRMODSDateHelper.getDate(element); assertEquals(year, parsed.toInstant().atZone(ZoneId.systemDefault()).get(ChronoField.YEAR)); element.removeAttribute("encoding"); assertEquals(fullYear, MCRMODSDateHelper.getCalendar(element).get(Calendar.YEAR)); } @Test public void testISO8601Date() { String date = "20110929"; Element element = new Element("date").setText(date); GregorianCalendar parsed = MCRMODSDateHelper.getCalendar(element); assertEquals(2011, parsed.get(Calendar.YEAR)); assertEquals(9 - 1, parsed.get(Calendar.MONTH)); assertEquals(29, parsed.get(Calendar.DAY_OF_MONTH)); MCRMODSDateHelper.setDate(element, parsed, MCRMODSDateFormat.iso8601_8); assertEquals("iso8601", element.getAttributeValue("encoding")); assertEquals(date, element.getText()); } @Test public void testW3CDTFDate10() { String date = "2011-09-29"; Element element = new Element("date").setText(date); GregorianCalendar parsed = MCRMODSDateHelper.getCalendar(element); assertEquals(2011, parsed.get(Calendar.YEAR)); assertEquals(9 - 1, parsed.get(Calendar.MONTH)); assertEquals(29, parsed.get(Calendar.DAY_OF_MONTH)); MCRMODSDateHelper.setDate(element, parsed, MCRMODSDateFormat.w3cdtf_10); assertEquals("w3cdtf", element.getAttributeValue("encoding")); assertEquals(date, element.getText()); } @Test public void testDateFormatsWithoutTimezone() { // Christmas :-) int year = 2015, month = 12, day = 25; GregorianCalendar gIn = new GregorianCalendar(year, month - 1, day); Element element = new Element("date"); MCRMODSDateHelper.setDate(element, gIn, MCRMODSDateFormat.w3cdtf_10); // Not christmas :-( ? assertEquals(year + "-" + month + "-" + day, element.getText()); // Not christmas :-( ? GregorianCalendar gOut = MCRMODSDateHelper.getCalendar(element); assertEquals(day, gOut.get(Calendar.DAY_OF_MONTH)); } @Test public void testW3CDTFDate19() { String date = "2011-09-29T13:14:15"; Element element = new Element("date").setText(date); GregorianCalendar parsed = MCRMODSDateHelper.getCalendar(element); assertEquals(2011, parsed.get(Calendar.YEAR)); assertEquals(9 - 1, parsed.get(Calendar.MONTH)); assertEquals(29, parsed.get(Calendar.DAY_OF_MONTH)); assertEquals(13, parsed.get(Calendar.HOUR_OF_DAY)); assertEquals(14, parsed.get(Calendar.MINUTE)); assertEquals(15, parsed.get(Calendar.SECOND)); MCRMODSDateHelper.setDate(element, parsed, MCRMODSDateFormat.w3cdtf_19); assertEquals("w3cdtf", element.getAttributeValue("encoding")); assertEquals(date, element.getText()); } }
4,826
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSWrapperTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/MCRMODSWrapperTest.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.mods; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.filter.Filters; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.junit.Test; import org.mycore.common.MCRConstants; import org.mycore.common.MCRTestCase; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRURLContent; import org.mycore.common.xml.MCRXMLParserFactory; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; /** * @author Thomas Scheffler (yagee) */ public class MCRMODSWrapperTest extends MCRTestCase { /** * Test method for {@link org.mycore.mods.MCRMODSWrapper#wrapMODSDocument(org.jdom2.Element, java.lang.String)}. */ @Test public void testWrapMODSDocument() throws Exception { Document modsDoc = loadMODSDocument(); MCRObject mcrObj = MCRMODSWrapper.wrapMODSDocument(modsDoc.getRootElement(), "JUnit"); assertTrue("Generated MCRObject is not valid.", mcrObj.isValid()); Document mcrObjXml = mcrObj.createXML(); //check load from XML throws no exception MCRObject mcrObj2 = new MCRObject(mcrObjXml); mcrObjXml = mcrObj2.createXML(); XPathExpression<Element> xpathCheck = XPathFactory.instance().compile("//mods:mods", Filters.element(), null, MCRConstants.MODS_NAMESPACE); assertEquals("Did not find mods data", 1, xpathCheck.evaluate(mcrObjXml).size()); } private Document loadMODSDocument() throws IOException, JDOMException { URL worldClassUrl = this.getClass().getResource("/mods80700998.xml"); return MCRXMLParserFactory.getParser().parseXML(new MCRURLContent(worldClassUrl)); } @Test public void testSetMODS() throws Exception { Element mods = loadMODSDocument().detachRootElement(); MCRMODSWrapper wrapper = new MCRMODSWrapper(); wrapper.setID("JUnit", 4711); wrapper.setMODS(mods); Document mcrObjXml = wrapper.getMCRObject().createXML(); XPathExpression<Element> xpathCheck = XPathFactory.instance().compile("//mods:mods", Filters.element(), null, MCRConstants.MODS_NAMESPACE); assertEquals("Did not find mods data", 1, xpathCheck.evaluate(mcrObjXml).size()); } @Test public void testServiceFlags() { MCRMODSWrapper wrapper = new MCRMODSWrapper(); assertNull(wrapper.getServiceFlag("name")); wrapper.setServiceFlag("name", "value"); assertEquals("value", wrapper.getServiceFlag("name")); } @Test public void setElement() throws Exception { Element mods = loadMODSDocument().detachRootElement(); MCRMODSWrapper wrapper = new MCRMODSWrapper(); wrapper.setID("JUnit", 4711); wrapper.setMODS(mods); Map<String, String> attrMap = new HashMap<>(); attrMap.put("authorityURI", "http://mycore.de/classifications/mir_filetype.xml"); attrMap.put("displayLabel", "mir_filetype"); attrMap.put("valueURI", "http://mycore.de/classifications/mir_filetype.xml#excel"); wrapper.setElement("classification", "", attrMap); Document mcrObjXml = wrapper.getMCRObject().createXML(); String checkXpathString = "//mods:mods/mods:classification[" + "@authorityURI='http://mycore.de/classifications/mir_filetype.xml' and " + "@displayLabel='mir_filetype' and " + "@valueURI='http://mycore.de/classifications/mir_filetype.xml#excel'" + "]"; XPathExpression<Element> xpathCheck = XPathFactory.instance().compile(checkXpathString, Filters.element(), null, MCRConstants.MODS_NAMESPACE); assertTrue(xpathCheck.evaluate(mcrObjXml).size() > 0); } @Test public void testIsSupported() { MCRConfiguration2.set("MCR.Metadata.Type.sthelse", String.valueOf(true)); MCRObjectID mycoreMods = MCRObjectID.getInstance("mycore_mods_00000011"); MCRObjectID mycoreSthelse = MCRObjectID.getInstance("mycore_sthelse_00000011"); assertTrue("Mods type should be supported.", MCRMODSWrapper.isSupported(mycoreMods)); assertFalse("sthesle type should not be supported.", MCRMODSWrapper.isSupported(mycoreSthelse)); } @Test public void testGetLinkedRelatedItems() throws IOException, JDOMException { Element mods = loadMODSDocument().detachRootElement(); MCRMODSWrapper wrapper = new MCRMODSWrapper(); Element relatedItem = new Element("relatedItem", MCRConstants.MODS_NAMESPACE); relatedItem.setAttribute("href", "mir_test_00000001", MCRConstants.XLINK_NAMESPACE); mods.addContent(relatedItem); wrapper.setID("JUnit", 4711); wrapper.setMODS(mods); assertEquals("There should be no related item!", 0, wrapper.getLinkedRelatedItems().size()); relatedItem.setAttribute("type", ""); assertEquals("There should be no related item!", 0, wrapper.getLinkedRelatedItems().size()); relatedItem.setAttribute("type", "series"); assertEquals("There should be one related item!", 1, wrapper.getLinkedRelatedItems().size()); relatedItem.removeAttribute("href", MCRConstants.XLINK_NAMESPACE); assertEquals("There should be no related item!", 0, wrapper.getLinkedRelatedItems().size()); } @Override protected Map<String, String> getTestProperties() { Map<String, String> testProperties = super.getTestProperties(); testProperties.put("MCR.Metadata.Type.mods", "true"); return testProperties; } }
6,693
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAbstractMergerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/merger/MCRAbstractMergerTest.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.mods.merger; import org.junit.Test; import org.mycore.common.MCRTestCase; public class MCRAbstractMergerTest extends MCRTestCase { @Test public void testMerge() throws Exception { String a = "[mods:abstract[@xml:lang='de']='deutsch']"; String b = "[mods:abstract='deutsch'][mods:abstract[@xml:lang='en']='english']"; String e = "[mods:abstract[@xml:lang='de']='deutsch'][mods:abstract[@xml:lang='en']='english']"; MCRMergerTest.test(a, b, e); } @Test public void testXLink() throws Exception { String a = "[mods:abstract[@xlink:href='foo']]"; String b = "[mods:abstract[@xml:lang='de'][@xlink:href='foo']][mods:abstract[@xml:lang='en'][@xlink:href='bar']]"; MCRMergerTest.test(a, b, b); } @Test public void testSimilar() throws Exception { String a = "[mods:abstract[@xml:lang='de']='Dies ist der deutsche Abstract']"; String b = "[mods:abstract='Dies ist der deitsche Abstract']"; MCRMergerTest.test(a, b, a); String a2 = "[mods:abstract[@xml:lang='de']='Dies ist der deutsche Abstract']"; String b2 = "[mods:abstract='Dieses ist der doitsche Äbschträkt']"; String e2 = a2 + b2; MCRMergerTest.test(a2, b2, e2); } }
2,030
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIdentifierMergerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/merger/MCRIdentifierMergerTest.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.mods.merger; import org.junit.Test; import org.mycore.common.MCRTestCase; public class MCRIdentifierMergerTest extends MCRTestCase { @Test public void testMergeDifferent() throws Exception { String a = "[mods:identifier[@type='doi']='10.123/456']"; String b = "[mods:identifier[@type='issn']='1234-5678']"; String e = "[mods:identifier[@type='doi']='10.123/456'][mods:identifier[@type='issn']='1234-5678']"; MCRMergerTest.test(a, b, e); } @Test public void testMergeSame() throws Exception { String a = "[mods:identifier[@type='issn']='12345678']"; String b = "[mods:identifier[@type='issn']='1234-5678']"; MCRMergerTest.test(a, b, b); } @Test public void testMergeMultiple() throws Exception { String a = "[mods:identifier[@type='isbn']='9783836287456'][mods:identifier[@type='isbn']='3836287455']"; String b = "[mods:identifier[@type='isbn']='978-3-8362-8745-6']"; String e = "[mods:identifier[@type='isbn']='978-3-8362-8745-6'][mods:identifier[@type='isbn']='3836287455']"; MCRMergerTest.test(a, b, e); } @Test public void testCaseInsensitiveDOIs() throws Exception { String a = "[mods:identifier[@type='doi']='10.1530/EJE-21-1086']"; String b = "[mods:identifier[@type='doi']='10.1530/eje-21-1086']"; MCRMergerTest.test(a, b, a); } }
2,150
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRelatedItemMergerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/merger/MCRRelatedItemMergerTest.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.mods.merger; import org.junit.Test; import org.mycore.common.MCRTestCase; public class MCRRelatedItemMergerTest extends MCRTestCase { @Test public void testMergeHost() throws Exception { String a = "[mods:relatedItem[@type='host'][mods:identifier='foo']]"; String b = "[mods:relatedItem[@type='host'][mods:note='bar']]"; String e = "[mods:relatedItem[@type='host'][mods:identifier='foo'][mods:note='bar']]"; MCRMergerTest.test(a, b, e); } @Test public void testMergeSeries() throws Exception { String a = "[mods:relatedItem[@type='series'][mods:identifier='foo']]"; String b = "[mods:relatedItem[@type='series'][mods:note='bar']]"; String e = "[mods:relatedItem[@type='series'][mods:identifier='foo']]" + "[mods:relatedItem[@type='series'][mods:note='bar']]"; MCRMergerTest.test(a, b, e); } }
1,643
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRHyphenNormalizerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/merger/MCRHyphenNormalizerTest.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.mods.merger; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.mycore.common.MCRTestCase; public class MCRHyphenNormalizerTest extends MCRTestCase { private static final char HYPHEN_MINUS = '\u002D'; private static final char SOFT_HYPHEN = '\u00AD'; private static final char ARMENIAN_HYPHEN = '\u058A'; private static final char HEBREW_PUNCTUATION_MAQAF = '\u05BE'; private static final char HYPHEN = '\u2010'; private static final char NON_BREAKING_HYPHEN = '\u2011'; private static final char FIGURE_DASH = '\u2012'; private static final char EN_DASH = '\u2013'; private static final char EM_DASH = '\u2014'; private static final char HORIZONTAL_BAR = '\u2015'; private static final char MINUS_SIGN = '\u2212'; private static final char TWO_EM_DASH = '\u2E3A'; private static final char THREE_EM_DASH = '\u2E3B'; private static final char SMALL_EM_DASH = '\uFE58'; private static final char SMALL_HYPHEN_MINUS = '\uFE63'; private static final char FULLWIDTH_HYPHEN_MINUS = '\uFF0D'; public static final char[] ALL_HYPHEN_VARIANTS = { HYPHEN_MINUS, SOFT_HYPHEN, ARMENIAN_HYPHEN, HEBREW_PUNCTUATION_MAQAF, HYPHEN, NON_BREAKING_HYPHEN, FIGURE_DASH, EN_DASH, EM_DASH, HORIZONTAL_BAR, MINUS_SIGN, TWO_EM_DASH, THREE_EM_DASH, SMALL_EM_DASH, SMALL_HYPHEN_MINUS, FULLWIDTH_HYPHEN_MINUS }; @Test public void testNormalize() { for (char variant : ALL_HYPHEN_VARIANTS) { assertEquals("A-B-C", MCRHyphenNormalizer.normalizeHyphen(getTestString(variant))); } } @Test public void testNormalizeWithReplacement() { for (char variant : ALL_HYPHEN_VARIANTS) { assertEquals("A~B~C", MCRHyphenNormalizer.normalizeHyphen(getTestString(variant), '~')); } } private String getTestString(char testCharacter) { String characterString = Character.toString(testCharacter); return "A" + characterString + "B" + characterString + "C"; } }
2,800
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMergerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/merger/MCRMergerTest.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.mods.merger; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.jaxen.JaxenException; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.junit.Ignore; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.xml.MCRNodeBuilder; import org.mycore.common.xml.MCRXMLHelper; public class MCRMergerTest extends MCRTestCase { @Test public void testAddingNew() throws Exception { String a = "[mods:note[@xml:lang='de']='deutsch']"; String b = "[mods:note[@xml:lang='de']='deutsch'][mods:note[@xml:lang='en']='english']"; test(a, b, b); } @Test public void testJoiningDifferent() throws JaxenException, IOException { String a = "[mods:titleInfo[mods:title='test']]"; String b = "[mods:abstract='abstract']"; String e = "[mods:titleInfo[mods:title='test']][mods:abstract='abstract']"; test(a, b, e); } @Ignore static void test(String xPathA, String xPathB, String xPathExpected) throws JaxenException, IOException { test(new String[]{xPathA, xPathB}, xPathExpected); } @Ignore static void test(String[] xPaths, String xPathExpected) throws JaxenException, IOException { Element[] elements = new Element[xPaths.length]; for (int i=0, n=xPaths.length; i<n; i++) { elements[i] = new MCRNodeBuilder().buildElement("mods:mods" + xPaths[i], null, null); } Element e = new MCRNodeBuilder().buildElement("mods:mods" + xPathExpected, null, null); for (int i=1, n=xPaths.length; i<n; i++) { MCRMergeTool.merge(elements[0], elements[i]); } boolean asExpected = MCRXMLHelper.deepEqual(e, elements[0]); if (!asExpected) { System.out.println("actual result:"); logXML(elements[0]); System.out.println("expected result:"); logXML(e); } assertTrue(asExpected); } @Ignore private static void logXML(Element r) throws IOException { System.out.println(); new XMLOutputter(Format.getPrettyFormat()).output(r, System.out); System.out.println(); } }
2,993
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTitleInfoMergerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/merger/MCRTitleInfoMergerTest.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.mods.merger; import java.io.IOException; import org.jaxen.JaxenException; import org.junit.Test; import org.mycore.common.MCRTestCase; public class MCRTitleInfoMergerTest extends MCRTestCase { @Test public void testLongerWins() throws Exception { String a = "[mods:titleInfo[mods:title='Applied Physics A']]"; String b = "[mods:titleInfo[mods:title='Applied Physics A : Materials Science & Processing']]"; MCRMergerTest.test(a, b, b); MCRMergerTest.test(b, a, b); } @Test public void testMergingSubtitleWins() throws JaxenException, IOException { String a = "[mods:titleInfo[mods:title='testing: all you have to know about']]"; String b = "[mods:titleInfo[mods:title='Testing'][mods:subTitle='All You have to know about']]"; MCRMergerTest.test(a, b, b); MCRMergerTest.test(b, a, b); } @Test public void testMergingAttributes() throws JaxenException, IOException { String a = "[mods:titleInfo[mods:title='first'][@xml:lang='de']]" + "[mods:titleInfo[mods:title='second']]"; String b = "[mods:titleInfo[mods:title='first']" + "][mods:titleInfo[mods:title='second'][@xml:lang='en'][@type='alternative']]"; String e = "[mods:titleInfo[mods:title='first'][@xml:lang='de']]" + "[mods:titleInfo[mods:title='second']]" + "[mods:titleInfo[mods:title='second'][@xml:lang='en'][@type='alternative']]"; MCRMergerTest.test(a, b, e); } @Test public void testMergingDifferent() throws JaxenException, IOException { String a = "[mods:titleInfo[mods:title='a']]"; String b = "[mods:titleInfo[mods:title='b']]"; String e = "[mods:titleInfo[mods:title='a']][mods:titleInfo[mods:title='b']]"; MCRMergerTest.test(a, b, e); } @Test public void testMergingIdentical() throws JaxenException, IOException { String a = "[mods:titleInfo[mods:title='test']]"; MCRMergerTest.test(a, a, a); } @Test public void testMergingSameAttribute() throws JaxenException, IOException { String a = "[mods:titleInfo[mods:title='Chemistry - A European Journal'][@type='abbreviated']]"; String b = "[mods:titleInfo[mods:title='Chemistry'][@type='abbreviated']]"; String e = "[mods:titleInfo[mods:title='Chemistry - A European Journal'][@type='abbreviated']]"; MCRMergerTest.test(a, b, e); } @Test public void testMergingOneAttribute() throws JaxenException, IOException { String a = "[mods:titleInfo[mods:title='Chemistry - A European Journal']]"; String b = "[mods:titleInfo[mods:title='Chemistry'][@type='abbreviated']]"; String e = "[mods:titleInfo[mods:title='Chemistry - A European Journal']]" + "[mods:titleInfo[mods:title='Chemistry'][@type='abbreviated']]"; MCRMergerTest.test(a, b, e); } @Test public void testMergingHtmlVariants() throws JaxenException, IOException { // from importing 10.1002/cplu.202200022 String a = "[mods:titleInfo[mods:title='The Dynamic Covalent Chemistry of Amidoboronates: " + "Tuning the rac<sub>5</sub> /rac<sub>6</sub> Ratio via " + "the B-N and B-O Dynamic Covalent Bonds.']]"; String b = "[mods:titleInfo[mods:title='The Dynamic Covalent Chemistry of Amidoboronates: " + "Tuning the <i>rac</i><sub>5</sub>/<i>rac</i><sub>6</sub> Ratio " + "via the B−N and B−O Dynamic Covalent Bonds']]"; String c = "[mods:titleInfo[mods:title='The Dynamic Covalent Chemistry of Amidoboronates: " + "Tuning the rac5/rac6 Ratio " + "via the B‑N and B‐O Dynamic Covalent Bonds']]"; MCRMergerTest.test(new String[]{a, b, c}, b); } }
4,544
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRExtentMergerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/merger/MCRExtentMergerTest.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.mods.merger; import org.junit.Test; import org.mycore.common.MCRTestCase; public class MCRExtentMergerTest extends MCRTestCase { @Test public void testPhysicalDescriptionExtent() throws Exception { String a = "[mods:physicalDescription[mods:extent='360 pages']]"; String b = "[mods:physicalDescription[mods:extent='7\" x 9\"']]"; MCRMergerTest.test(a, b, a); } @Test public void testPartExtentList() throws Exception { String a = "[mods:part[mods:extent[@unit='pages'][mods:list='S. 64-67']]]"; String b = "[mods:part[mods:extent[@unit='pages'][mods:list='pp. 64-67']]]"; MCRMergerTest.test(a, b, a); } @Test public void testPartExtentStartEnd() throws Exception { String a = "[mods:part[mods:extent[@unit='pages'][mods:list='S. 64-67']]]"; String b = "[mods:part[mods:extent[@unit='pages'][mods:start='64'][mods:end='67']]]"; MCRMergerTest.test(a, b, b); MCRMergerTest.test(b, a, b); } }
1,756
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROriginInfoMergerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/merger/MCROriginInfoMergerTest.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.mods.merger; import org.junit.Test; import org.mycore.common.MCRTestCase; public class MCROriginInfoMergerTest extends MCRTestCase { @Test public void testMerge() throws Exception { String a = "[mods:originInfo[mods:dateIssued='2017'][mods:publisher='Elsevier']]"; String b = "[mods:originInfo[mods:dateIssued[@encoding='w3cdtf']='2017']" + "[mods:edition='4. Aufl.'][mods:place='Berlin']]"; String e = "[mods:originInfo[mods:dateIssued[@encoding='w3cdtf']='2017']" + "[mods:publisher='Elsevier'][mods:edition='4. Aufl.'][mods:place='Berlin']]"; MCRMergerTest.test(a, b, e); } @Test public void testDateOther() throws Exception { String a = "[mods:originInfo[mods:dateOther[@type='accepted']='2017']]"; String b = "[mods:originInfo[mods:dateOther[@type='submitted']='2018']]"; String e = "[mods:originInfo[mods:dateOther[@type='accepted']='2017']" + "[mods:dateOther[@type='submitted']='2018']]"; MCRMergerTest.test(a, b, e); } }
1,804
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCategoryMergerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/merger/MCRCategoryMergerTest.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.mods.merger; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.junit.Test; import org.mycore.common.MCRJPATestCase; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRTransactionHelper; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.utils.MCRXMLTransformer; public class MCRCategoryMergerTest extends MCRJPATestCase { private static final String TEST_DIRECTORY = "MCRCategoryMergerTest/"; @Override public void setUp() throws Exception { super.setUp(); MCRSessionMgr.getCurrentSession(); MCRTransactionHelper.isTransactionActive(); loadCategory("institutes.xml"); loadCategory("genre.xml"); loadCategory("oa.xml"); } private void loadCategory(String categoryFileName) throws URISyntaxException, JDOMException, IOException { ClassLoader classLoader = getClass().getClassLoader(); SAXBuilder saxBuilder = new SAXBuilder(); InputStream categoryStream = classLoader.getResourceAsStream(TEST_DIRECTORY + categoryFileName); MCRCategory category = MCRXMLTransformer.getCategory(saxBuilder.build(categoryStream)); MCRCategoryDAOFactory.getInstance().addCategory(null, category); } @Test public void testUnsupported() throws Exception { String a = "[mods:classification[@authority='foo']='xy123']"; String b = "[mods:classification[@authority='foo']='yz456']"; MCRMergerTest.test(a, b, a + b); } @Test public void testIdentical() throws Exception { String unsupported = "[mods:classification[@authority='foo']='xy123']"; MCRMergerTest.test(unsupported, unsupported, unsupported); String supported = "[mods:classification[@authority='UDE']='CEN']"; MCRMergerTest.test(supported, supported, supported); } @Test public void testIsDescendantCheck() { MCRCategoryID cen = MCRCategoryID.fromString("institutes:CEN"); MCRCategoryID cinch = MCRCategoryID.fromString("institutes:CINCH"); MCRCategoryID ican = MCRCategoryID.fromString("institutes:ICAN"); assertFalse(MCRCategoryMerger.oneIsDescendantOfTheOther(cinch, ican)); assertFalse(MCRCategoryMerger.oneIsDescendantOfTheOther(ican, cinch)); assertTrue(MCRCategoryMerger.oneIsDescendantOfTheOther(cen, ican)); assertTrue(MCRCategoryMerger.oneIsDescendantOfTheOther(ican, cen)); } @Test public void testMergeNotRedundant() throws Exception { String a = "[mods:classification[@authority='UDE']='CINCH']"; String b = "[mods:classification[@authority='UDE']='ICAN']"; MCRMergerTest.test(a, b, a + b); } @Test public void testMergeRedundant() throws Exception { String a = "[mods:classification[@authority='UDE']='CEN']"; String b = "[mods:classification[@authority='UDE']='ICAN']"; MCRMergerTest.test(a, b, b); MCRMergerTest.test(b, a, b); } @Test public void testMixedClassificationsWithinSameMODSElement() throws Exception { String a = "[mods:genre[@authority='marcgt']='article']"; String b = "[mods:genre[@authority='marcgt']='book']"; MCRMergerTest.test(a, b, a + b); String uri = "http://www.mycore.org/classifications/mir_genres"; String c = "[mods:genre[@authorityURI='" + uri + "'][@valueURI='" + uri + "#collection']]"; String d = "[mods:genre[@authorityURI='" + uri + "'][@valueURI='" + uri + "#proceedings']]"; MCRMergerTest.test(a + c, b + d, a + d + b); } @Test public void testNonRepeatable() throws Exception { MCRConfiguration2.set("MCR.MODS.Merger.CategoryMerger.Repeatable.oa", "false"); String uri = "http://www.mycore.org/classifications/oa"; String green = "[mods:genre[@authorityURI='" + uri + "'][@valueURI='" + uri + "#green']]"; String gold = "[mods:genre[@authorityURI='" + uri + "'][@valueURI='" + uri + "#gold']]"; MCRMergerTest.test(green, gold, green); String platin = "[mods:genre[@authorityURI='" + uri + "'][@valueURI='" + uri + "#platin']]"; MCRMergerTest.test(gold, platin, platin); } }
5,356
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRNameMergerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/merger/MCRNameMergerTest.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.mods.merger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.jaxen.JaxenException; import org.jdom2.Element; import org.junit.Assert; import org.junit.Test; import org.mycore.common.MCRConstants; import org.mycore.common.MCRTestCase; import org.mycore.common.xml.MCRNodeBuilder; public class MCRNameMergerTest extends MCRTestCase { @Test public void testIsProbablySameAs() throws Exception { MCRNameMerger a = buildNameEntry("[mods:namePart='Thomas Müller']"); MCRNameMerger b = buildNameEntry("[mods:namePart='thomas Mueller']"); assertTrue(a.isProbablySameAs(b)); MCRNameMerger c = buildNameEntry("[mods:namePart='Muller, T.']"); assertTrue(a.isProbablySameAs(c)); MCRNameMerger d = buildNameEntry("[mods:namePart='Mueller, T']"); assertTrue(a.isProbablySameAs(d)); MCRNameMerger e = buildNameEntry("[mods:namePart='Müller, Egon']"); assertFalse(a.isProbablySameAs(e)); MCRNameMerger f = buildNameEntry("[mods:namePart='Thorsten Mueller']"); assertTrue(c.isProbablySameAs(f)); assertFalse(a.isProbablySameAs(f)); MCRNameMerger g = buildNameEntry("[mods:namePart='Thorsten Egon Mueller']"); assertTrue(e.isProbablySameAs(g)); assertTrue(f.isProbablySameAs(g)); MCRNameMerger h = buildNameEntry( "[mods:namePart[@type='given']='Thomas'][mods:namePart[@type='family']='Müller']"); assertTrue(h.isProbablySameAs(a)); assertTrue(h.isProbablySameAs(d)); MCRNameMerger i = buildNameEntry("[mods:namePart[@type='given']='T.'][mods:namePart[@type='family']='Müller']" + "[mods:namePart[@type='termsOfAddress']='Jun.']"); assertTrue(i.isProbablySameAs(h)); assertTrue(i.isProbablySameAs(a)); assertTrue(i.isProbablySameAs(d)); try { new MCRNameMerger().setElement(null); Assert.fail("No name should result in NPE while creating a MCRNameMerger"); } catch (NullPointerException ex) { // exception excepted } } @Test public void testEmptyGiven() throws JaxenException { Element a = new MCRNodeBuilder() .buildElement("mods:mods[mods:name[@type='personal'][mods:namePart[@type='given']]]", null, null); Element a2 = new MCRNodeBuilder() .buildElement("mods:mods[mods:name[@type='personal'][mods:namePart[@type='given']]]", null, null); Element b = new MCRNodeBuilder() .buildElement("mods:mods[mods:name[@type='personal'][mods:namePart[@type='given']='T.']]", null, null); MCRMergeTool.merge(a, b); assertEquals("Exactly two mods:name element expected", 2, a.getChildren("name", MCRConstants.MODS_NAMESPACE).size()); MCRMergeTool.merge(b, a2); assertEquals("Exactly two mods:name element expected", 2, b.getChildren("name", MCRConstants.MODS_NAMESPACE).size()); } @Test public void testCompareBasedOnDisplayForm() throws Exception { MCRNameMerger a = buildNameEntry("[mods:displayForm='Thomas Müller']"); MCRNameMerger b = buildNameEntry( "[mods:namePart[@type='given']='Thomas'][mods:namePart[@type='family']='Müller']"); assertTrue(a.isProbablySameAs(b)); } @Test public void testMergeTermsOfAddress() throws JaxenException, IOException { String a = "[mods:name[@type='personal'][mods:namePart[@type='given']='Thomas']" + "[mods:namePart[@type='family']='Müller']]"; String b = "[mods:name[@type='personal'][mods:namePart[@type='given']='T.']" + "[mods:namePart[@type='family']='Müller'][mods:namePart[@type='termsOfAddress']='Jun.']]"; String e = "[mods:name[@type='personal'][mods:namePart[@type='given']='Thomas']" + "[mods:namePart[@type='family']='Müller'][mods:namePart[@type='termsOfAddress']='Jun.']]"; MCRMergerTest.test(a, b, e); } @Test public void testMergeNameIdentifier() throws JaxenException, IOException { String a = "[mods:name[@type='personal'][mods:namePart='Thomas Müller']" + "[mods:nameIdentifier[@type='gnd']='2']]"; String b = "[mods:name[@type='personal'][mods:namePart='Mueller, T']" + "[mods:nameIdentifier[@type='lsf']='1'][mods:nameIdentifier[@type='gnd']='2']]"; String e = "[mods:name[@type='personal'][mods:namePart='Thomas Müller']" + "[mods:nameIdentifier[@type='gnd']='2'][mods:nameIdentifier[@type='lsf']='1']]"; MCRMergerTest.test(a, b, e); } @Test public void testMergeDisplayForm() throws JaxenException, IOException { String a = "[mods:name[@type='personal'][mods:namePart='Thomas Müller'][mods:displayForm='Tommy']]"; String b = "[mods:name[@type='personal'][mods:namePart='Mueller, T'][mods:displayForm='Tom']]"; MCRMergerTest.test(a, b, a); } @Test public void testMergeSubElements() throws JaxenException, IOException { String a = "[mods:name[@type='personal'][mods:namePart='Thomas Müller'][mods:affiliation='UDE']]"; String b = "[mods:name[@type='personal'][mods:namePart='Mueller, T'][mods:affiliation='UB der UDE'][mods:nameIdentifier[@type='gnd']='2']]"; String e = "[mods:name[@type='personal'][mods:namePart='Thomas Müller'][mods:affiliation='UDE'][mods:affiliation='UB der UDE'][mods:nameIdentifier[@type='gnd']='2']]"; MCRMergerTest.test(a, b, e); } @Test public void testMergeFirstLastVsLastFirst() throws JaxenException, IOException { String a = "[mods:name[@type='personal'][mods:namePart='Thomas Müller']]"; String b = "[mods:name[@type='personal'][mods:namePart='Mueller, T']]"; MCRMergerTest.test(a, b, a); } @Test public void testPreferFamilyGiven() throws JaxenException, IOException { String a = "[mods:name[@type='personal'][mods:namePart='Thomas Müller']]"; String b = "[mods:name[@type='personal'][mods:namePart[@type='family']='Müller'][mods:namePart[@type='given']='T.']]"; MCRMergerTest.test(a, b, b); } @Test public void testRetainSame() throws JaxenException, IOException { String a = "[mods:name[@type='personal'][mods:namePart='Thomas Müller']" + "[mods:nameIdentifier[@type='gnd']='1']][mods:name[@type='personal'][mods:namePart='Thomas Müller']" + "[mods:nameIdentifier[@type='gnd']='2']]"; String b = "[mods:name[@type='personal'][mods:namePart='Thomas Müller']" + "[mods:nameIdentifier[@type='scopus']='1']][mods:name[@type='personal'][mods:namePart='Thomas Müller']" + "[mods:nameIdentifier[@type='scopus']='2']]"; String e = "[mods:name[@type='personal'][mods:namePart='Thomas Müller'][mods:nameIdentifier[@type='gnd']='1']" + "[mods:nameIdentifier[@type='scopus']='1']][mods:name[@type='personal'][mods:namePart='Thomas Müller']" + "[mods:nameIdentifier[@type='gnd']='2'][mods:nameIdentifier[@type='scopus']='2']]"; MCRMergerTest.test(a, b, e); } @Test public void testDontMergeConflictingIDs() throws JaxenException, IOException { String a = "[mods:name[@type='personal'][mods:namePart='Thomas Müller']" + "[mods:nameIdentifier[@type='scopus']='1']]"; String b = "[mods:name[@type='personal'][mods:namePart='Thomas Müller']" + "[mods:nameIdentifier[@type='scopus']='2']]"; String e = "[mods:name[@type='personal'][mods:namePart='Thomas Müller']" + "[mods:nameIdentifier[@type='scopus']='1']][mods:name[@type='personal'][mods:namePart='Thomas Müller']" + "[mods:nameIdentifier[@type='scopus']='2']]"; MCRMergerTest.test(a, b, e); } @Test public void testPrioritizeMergeNonConflictingIDs() throws JaxenException, IOException { String a = "[mods:name[@type='personal'][mods:namePart='Thomas Müller'][mods:nameIdentifier[@type='gnd']='1']" + "[mods:nameIdentifier[@type='scopus']='1']]"; String b = "[mods:name[@type='personal'][mods:namePart='Thomas Müller'][mods:nameIdentifier[@type='gnd']='1']" + "[mods:nameIdentifier[@type='scopus']='2']]"; String e = "[mods:name[@type='personal'][mods:namePart='Thomas Müller'][mods:nameIdentifier[@type='gnd']='1']" + "[mods:nameIdentifier[@type='scopus']='1'][mods:nameIdentifier[@type='scopus']='2']]"; MCRMergerTest.test(a, b, e); } private MCRNameMerger buildNameEntry(String predicates) throws JaxenException { Element modsName = new MCRNodeBuilder().buildElement("mods:name[@type='personal']" + predicates, null, null); MCRNameMerger ne = new MCRNameMerger(); ne.setElement(modsName); return ne; } }
9,764
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTextNormalizerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/merger/MCRTextNormalizerTest.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.mods.merger; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.mycore.common.MCRTestCase; public class MCRTextNormalizerTest extends MCRTestCase { private static final char EN_DASH = '\u2013'; private static final char COMBINING_DIAERESIS = '\u0308'; private static final char LATIN_SMALL_LETTER_SHARP_S = '\u00DF'; private static final char LATIN_CAPITAL_LETTER_SHARP_S = '\u1E9E'; private static final char LATIN_SMALL_LIGATURE_FF = '\uFB00'; private static final char LATIN_SMALL_LIGATURE_FFI = '\uFB03'; private static final char LATIN_SMALL_LIGATURE_FFL = '\uFB04'; private static final char LATIN_SMALL_LIGATURE_FI = '\uFB01'; private static final char LATIN_SMALL_LIGATURE_FL = '\uFB02'; private static final char LATIN_SMALL_LIGATURE_IJ = '\u0133'; private static final char LATIN_CAPITAL_LIGATURE_IJ = '\u0132'; private static final char LATIN_SMALL_LIGATURE_ST = '\uFB06'; private static final char LATIN_SMALL_LIGATURE_LONG_ST = '\uFB05'; @Test public void testNormalizeAlphabetical() { assertEquals("abc", MCRTextNormalizer.normalizeText("abc")); } @Test public void testNormalizeNumerical() { assertEquals("123", MCRTextNormalizer.normalizeText("123")); } @Test public void testNormalizeCase() { assertEquals("abc", MCRTextNormalizer.normalizeText("ABC")); } @Test public void testNormalizeHyphens() { assertEquals("a b c", MCRTextNormalizer.normalizeText("a" + EN_DASH + "b" + EN_DASH + "c")); } @Test public void testNormalizeUmlat() { assertEquals("a", MCRTextNormalizer.normalizeText("ä")); assertEquals("a", MCRTextNormalizer.normalizeText("a" + COMBINING_DIAERESIS)); assertEquals("a", MCRTextNormalizer.normalizeText("Ä")); assertEquals("a", MCRTextNormalizer.normalizeText("A" + COMBINING_DIAERESIS)); assertEquals("o", MCRTextNormalizer.normalizeText("ö")); assertEquals("o", MCRTextNormalizer.normalizeText("o" + COMBINING_DIAERESIS)); assertEquals("o", MCRTextNormalizer.normalizeText("Ö")); assertEquals("o", MCRTextNormalizer.normalizeText("O" + COMBINING_DIAERESIS)); assertEquals("u", MCRTextNormalizer.normalizeText("ü")); assertEquals("u", MCRTextNormalizer.normalizeText("u" + COMBINING_DIAERESIS)); assertEquals("u", MCRTextNormalizer.normalizeText("Ü")); assertEquals("u", MCRTextNormalizer.normalizeText("U" + COMBINING_DIAERESIS)); } @Test public void testNormalizeSharpS() { assertEquals("s", MCRTextNormalizer.normalizeText(Character.toString(LATIN_SMALL_LETTER_SHARP_S))); assertEquals("s", MCRTextNormalizer.normalizeText(Character.toString(LATIN_CAPITAL_LETTER_SHARP_S))); } @Test public void testNormalizeDoubleS() { assertEquals("s", MCRTextNormalizer.normalizeText("S")); assertEquals("s", MCRTextNormalizer.normalizeText("SS")); } @Test public void testNormalizeLigature() { assertEquals("ff", MCRTextNormalizer.normalizeText(Character.toString(LATIN_SMALL_LIGATURE_FF))); assertEquals("ffi", MCRTextNormalizer.normalizeText(Character.toString(LATIN_SMALL_LIGATURE_FFI))); assertEquals("ffl", MCRTextNormalizer.normalizeText(Character.toString(LATIN_SMALL_LIGATURE_FFL))); assertEquals("fi", MCRTextNormalizer.normalizeText(Character.toString(LATIN_SMALL_LIGATURE_FI))); assertEquals("fl", MCRTextNormalizer.normalizeText(Character.toString(LATIN_SMALL_LIGATURE_FL))); assertEquals("ij", MCRTextNormalizer.normalizeText(Character.toString(LATIN_SMALL_LIGATURE_IJ))); assertEquals("ij", MCRTextNormalizer.normalizeText(Character.toString(LATIN_CAPITAL_LIGATURE_IJ))); assertEquals("st", MCRTextNormalizer.normalizeText(Character.toString(LATIN_SMALL_LIGATURE_ST))); assertEquals("st", MCRTextNormalizer.normalizeText(Character.toString(LATIN_SMALL_LIGATURE_LONG_ST))); } @Test public void testNormalizePunctuation() { assertEquals("a a", MCRTextNormalizer.normalizeText("<{[(a~!@#$%a)]}>")); } @Test public void testNormalizeSpace() { assertEquals("a a", MCRTextNormalizer.normalizeText(" a a ")); } @Test public void testNormalizeHtml() { assertEquals("a", MCRTextNormalizer.normalizeText("<p>a</p>")); } }
5,202
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCREnrichmentTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/enrichment/MCREnrichmentTest.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.mods.enrichment; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.jaxen.JaxenException; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.junit.Ignore; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.xml.MCRNodeBuilder; import org.mycore.common.xml.MCRURIResolver; import org.mycore.common.xml.MCRXMLHelper; public class MCREnrichmentTest extends MCRTestCase { @Test public void testBasicEnrichment() throws JaxenException, IOException { String enricherID = "BasicTest"; String xPath = "mods:mods[mods:identifier[@type='doi']='10.123/456']"; String resultFile = "testBasicEnrichment-result.xml"; String debugFile = "testBasicEnrichment-debug.xml"; assertTrue(test(enricherID, xPath, resultFile, debugFile)); } @Test public void testMergePriority() throws JaxenException, IOException { String enricherID = "MergePriorityTest"; String xPath = "mods:mods[mods:identifier[@type='foo']='1']"; String resultFile = "testMergePriority-result1.xml"; String debugFile = "testMergePriority-debug1.xml"; assertTrue(test(enricherID, xPath, resultFile, debugFile)); xPath = "mods:mods[mods:identifier[@type='foo']='2']"; resultFile = "testMergePriority-result2.xml"; debugFile = "testMergePriority-debug2.xml"; assertTrue(test(enricherID, xPath, resultFile, debugFile)); } @Test public void testResolvingIteration() throws JaxenException, IOException { String enricherID = "ResolvingIterationTest"; String xPath = "mods:mods[mods:identifier[@type='issn']='1521-3765']"; String resultFile = "testResolvingIteration-result.xml"; String debugFile = "testResolvingIteration-debug.xml"; assertTrue(test(enricherID, xPath, resultFile, debugFile)); } @Test public void testParentIdentifierOnChildLevel() throws JaxenException, IOException { String enricherID = "ParentIdentifierOnChildLevelTest"; String xPath = "mods:mods[mods:identifier[@type='doi']='10.23919/EuMC48046.2021']"; String resultFile = "testParentIdentifierOnChildLevel-result.xml"; //String debugFile = "testResolvingIteration-debug.xml"; assertTrue(test(enricherID, xPath, resultFile, null)); } @Ignore public boolean test(String enricherID, String xPath, String resultFile, String debugFile) throws JaxenException, IOException { Element publication = new MCRNodeBuilder().buildElement(xPath, null, null); MCREnricher enricher = new MCREnricher(enricherID); MCRToXMLEnrichmentDebugger debugger = new MCRToXMLEnrichmentDebugger(); enricher.setDebugger(debugger); enricher.enrich(publication); if (debugFile != null) { boolean debugResult = checkXMLResult(debugFile, debugger.getDebugXML()); assertTrue(debugResult); } else { logXML(debugger.getDebugXML()); } return checkXMLResult(resultFile, publication); } private boolean checkXMLResult(String resultFile, Element result) throws IOException { String uri = "resource:MCREnrichmentTest/" + resultFile; Element expected = MCRURIResolver.instance().resolve(uri); boolean asExpected = MCRXMLHelper.deepEqual(result, expected); if (!asExpected) { System.out.println("actual result:"); logXML(result); System.out.println("expected result:"); logXML(expected); } return asExpected; } @Ignore private static void logXML(Element r) throws IOException { System.out.println(); new XMLOutputter(Format.getPrettyFormat()).output(r, System.out); System.out.println(); } }
4,655
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRVZGURIDetectorTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/identifier/MCRVZGURIDetectorTest.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.mods.identifier; import java.net.URI; import java.net.URISyntaxException; import java.util.Hashtable; import java.util.Map; import java.util.Optional; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class MCRVZGURIDetectorTest { private Hashtable<URI, String> testData; @Before public void prepareTest() throws URISyntaxException { testData = new Hashtable<>(); testData.put(new URI("http://uri.gbv.de/document/gvk:ppn:834532662"), "gvk:ppn:834532662"); testData.put(new URI("http://uri.gbv.de/document/opac-de-28:ppn:826913938"), "opac-de-28:ppn:826913938"); testData.put(new URI("http://gso.gbv.de/DB=2.1/PPNSET?PPN=357619811"), "gvk:ppn:357619811"); } @Test public void testDetect() { MCRGBVURLDetector detector = new MCRGBVURLDetector(); testData.forEach((key, value) -> { Optional<Map.Entry<String, String>> maybeDetectedGND = detector.detect(key); Assert.assertTrue("Should have a detected PPN", maybeDetectedGND.isPresent()); maybeDetectedGND.ifPresent( gnd -> Assert.assertEquals("Should have detected the right type!", gnd.getKey(), "ppn")); maybeDetectedGND.ifPresent( gnd -> Assert.assertEquals("Should have detected the right value!", gnd.getValue(), value)); }); } }
2,131
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSDOIMetadataServiceTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/identifier/MCRMODSDOIMetadataServiceTest.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.mods.identifier; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.Map; import org.jdom2.JDOMException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.pi.MCRPIService; import org.mycore.pi.MCRPersistentIdentifier; import org.mycore.pi.doi.MCRDOIParser; import org.mycore.pi.doi.MCRDigitalObjectIdentifier; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; public class MCRMODSDOIMetadataServiceTest extends MCRTestCase { public static final String TEST_DOI_METADATA_SERVICE_1 = "TestDOI_1"; public static final String TEST_DOI_METADATA_SERVICE_2 = "TestDOI_2"; @Before @Override public void setUp() throws Exception { super.setUp(); } @Test public void testInsert() throws URISyntaxException, IOException, MCRPersistentIdentifierException, JDOMException { final MCRMODSDOIMetadataService service1 = (MCRMODSDOIMetadataService) MCRConfiguration2 .getInstanceOf(MCRPIService.METADATA_SERVICE_CONFIG_PREFIX + TEST_DOI_METADATA_SERVICE_1).get(); final MCRMODSDOIMetadataService service2 = (MCRMODSDOIMetadataService) MCRConfiguration2 .getInstanceOf(MCRPIService.METADATA_SERVICE_CONFIG_PREFIX + TEST_DOI_METADATA_SERVICE_2).get(); final URL modsURL = MCRMODSDOIMetadataService.class.getClassLoader() .getResource("MCRMODSDOIMetadataServiceTest/mods.xml"); final MCRObject object = new MCRObject(modsURL.toURI()); final MCRDOIParser parser = new MCRDOIParser(); final MCRDigitalObjectIdentifier doi1 = parser.parse("10.1/doi").get(); final MCRDigitalObjectIdentifier doi2 = parser.parse("10.2/doi").get(); service1.insertIdentifier(doi1, object, ""); final MCRPersistentIdentifier doi1_read = service1.getIdentifier(object, "").get(); Assert.assertEquals("The dois should match!", doi1.asString(), doi1_read.asString()); service2.insertIdentifier(doi2, object, ""); final MCRPersistentIdentifier doi2_read = service2.getIdentifier(object, "").get(); Assert.assertEquals("The dois should match!", doi2.asString(), doi2_read.asString()); final MCRPersistentIdentifier doi1_read_2 = service1.getIdentifier(object, "").get(); Assert.assertEquals("The dois should match!", doi1.asString(), doi1_read_2.asString()); } @Override protected Map<String, String> getTestProperties() { final Map<String, String> testProperties = super.getTestProperties(); testProperties .put(MCRPIService.METADATA_SERVICE_CONFIG_PREFIX + TEST_DOI_METADATA_SERVICE_1 + ".Type", "doi"); testProperties .put(MCRPIService.METADATA_SERVICE_CONFIG_PREFIX + TEST_DOI_METADATA_SERVICE_1, MCRMODSDOIMetadataService.class.getName()); testProperties .put(MCRPIService.METADATA_SERVICE_CONFIG_PREFIX + TEST_DOI_METADATA_SERVICE_1 + ".Prefix", "10.1"); testProperties .put(MCRPIService.METADATA_SERVICE_CONFIG_PREFIX + TEST_DOI_METADATA_SERVICE_2, MCRMODSDOIMetadataService.class.getName()); testProperties .put(MCRPIService.METADATA_SERVICE_CONFIG_PREFIX + TEST_DOI_METADATA_SERVICE_2 + ".Type", "doi"); testProperties .put(MCRPIService.METADATA_SERVICE_CONFIG_PREFIX + TEST_DOI_METADATA_SERVICE_2 + ".Prefix", "10.2"); return testProperties; } }
4,396
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSCSLTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/csl/MCRMODSCSLTest.java
package org.mycore.mods.csl; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jdom2.Document; import org.jdom2.JDOMException; import org.junit.Before; import org.mycore.common.MCRException; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRStoreTestCase; import org.mycore.common.MCRSystemUserInformation; import org.mycore.common.content.MCRByteContent; import org.mycore.common.content.MCRContent; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; public class MCRMODSCSLTest extends MCRStoreTestCase { private static final String TEST_ID_1 = "junit_mods_00002050"; private static final String TEST_ID_2 = "junit_mods_00002056"; private static final String TEST_ID_3 = "junit_mods_00002489"; private static final String TEST_ID_4 = "junit_mods_00002052"; protected static String getIDFromContent(MCRContent c) { try { return c.asXML().getRootElement().getAttributeValue("ID"); } catch (JDOMException | IOException e) { throw new MCRException(e); } } protected List<MCRContent> getTestContent() throws IOException { return Stream.of(loadContent(TEST_ID_1), loadContent(TEST_ID_2), loadContent(TEST_ID_3), loadContent(TEST_ID_4)) .collect(Collectors.toList()); } @Before public void setUp() throws Exception { super.setUp(); MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getSuperUserInstance()); List<MCRContent> testContent = getTestContent(); for (MCRContent content : testContent) { Document jdom = content.asXML(); MCRXMLMetadataManager.instance().create(MCRObjectID.getInstance(getIDFromContent(content)), jdom, new Date()); } } protected MCRContent loadContent(String id) throws IOException { try (InputStream is = MCRMODSCSLTest.class.getClassLoader().getResourceAsStream("MCRMODSCSLTest/" + id + ".xml")) { byte[] bytes = is.readAllBytes(); return new MCRByteContent(bytes); } } }
2,291
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRModsItemDataProviderTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/csl/MCRModsItemDataProviderTest.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.mods.csl; import java.io.IOException; import java.io.StringReader; import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.junit.Assert; import org.junit.Test; import org.mycore.common.MCRTestCase; import de.undercouch.citeproc.csl.CSLItemData; import de.undercouch.citeproc.csl.CSLItemDataBuilder; public class MCRModsItemDataProviderTest extends MCRTestCase { @Test public void testProcessModsPart() throws IOException, JDOMException { final String testData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<mycoreobject xmlns:xlink=\"http://www.w3.org/1999/xlink\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xsi:noNamespaceSchemaLocation=\"datamodel-mods.xsd\" ID=\"bibthk_mods_00001066\">\n" + " <metadata>\n" + " <def.modsContainer class=\"MCRMetaXML\" heritable=\"false\" notinherit=\"true\">\n" + " <modsContainer inherited=\"0\">\n" + " <mods:mods xmlns:mods=\"http://www.loc.gov/mods/v3\">\n" + " <mods:relatedItem xlink:href=\"bibthk_mods_00001057\" type=\"host\">\n" + " <mods:part>\n" + " <mods:detail type=\"volume\">\n" + " <mods:number>80</mods:number>\n" + " </mods:detail>\n" + " <mods:extent unit=\"pages\">\n" + " <mods:start>711</mods:start>\n" + " <mods:end>718</mods:end>\n" + " </mods:extent>\n" + " </mods:part>\n" + " </mods:relatedItem>\n" + " </mods:mods>\n" + " </modsContainer>\n" + " </def.modsContainer>\n" + " </metadata>\n" + "</mycoreobject>\n"; final String testData2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<mycoreobject xmlns:xlink=\"http://www.w3.org/1999/xlink\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xsi:noNamespaceSchemaLocation=\"datamodel-mods.xsd\" ID=\"bibthk_mods_00001056\">\n" + " <metadata>\n" + " <def.modsContainer class=\"MCRMetaXML\" heritable=\"false\" notinherit=\"true\">\n" + " <modsContainer inherited=\"0\">\n" + " <mods:mods xmlns:mods=\"http://www.loc.gov/mods/v3\">\n" + "<mods:relatedItem type=\"series\">\n" + "<mods:titleInfo>\n" + "<mods:title>Security and Cryptology</mods:title>\n" + "</mods:titleInfo>\n" + "<mods:part>\n" + "<mods:detail type=\"volume\">\n" + "<mods:number>11875</mods:number>\n" + "</mods:detail>\n" + "</mods:part>\n" + "</mods:relatedItem>" + " </mods:mods>\n" + " </modsContainer>\n" + " </def.modsContainer>\n" + " </metadata>\n" + "</mycoreobject>\n"; final String testData3 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<mycoreobject xmlns:xlink=\"http://www.w3.org/1999/xlink\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xsi:noNamespaceSchemaLocation=\"datamodel-mods.xsd\" ID=\"ilm_mods_00001817\">\n" + " <metadata>\n" + " <def.modsContainer class=\"MCRMetaXML\" heritable=\"false\" notinherit=\"true\">\n" + " <modsContainer inherited=\"0\">\n" + " <mods:mods xmlns:mods=\"http://www.loc.gov/mods/v3\">\n" + "<mods:relatedItem type=\"host\">\n" + "<mods:titleInfo>\n" + "<mods:title>Advances in Engineering Research and Application</mods:title>\n" + "</mods:titleInfo>\n" + "<mods:part>\n" + "<mods:extent unit=\"pages\">\n" + "<mods:start>v</mods:start>\n" + "<mods:end>vi</mods:end>\n" + "</mods:extent>\n" + "</mods:part>\n" + "</mods:relatedItem>" + " </mods:mods>\n" + " </modsContainer>\n" + " </def.modsContainer>\n" + " </metadata>\n" + "</mycoreobject>\n"; CSLItemData build1 = testModsPart(testData); CSLItemData build2 = testModsPart(testData2); CSLItemData build3 = testModsPart(testData3); Assert.assertEquals("Volumes should equal", "80", build1.getVolume()); Assert.assertEquals("Page intervall should equal", "711–718", build1.getPage()); Assert.assertEquals("Volumes should equal", "11875", build2.getVolume()); Assert.assertEquals("Page intervall should equal", "v-vi", build3.getPage()); } @Test public void testConference() throws IOException, JDOMException { String conferenceTitle = "International Renewable Energy Storage Conference (IRES) 2021"; String testData = "<mycoreobject xmlns:xlink=\"http://www.w3.org/1999/xlink\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xsi:noNamespaceSchemaLocation=\"datamodel-mods.xsd\" ID=\"bibthk_mods_00001056\">\n" + " <metadata>\n" + " <def.modsContainer class=\"MCRMetaXML\" heritable=\"false\" notinherit=\"true\">\n" + " <modsContainer inherited=\"0\">\n" + " <mods:mods xmlns:mods=\"http://www.loc.gov/mods/v3\">\n" + "<mods:name type=\"conference\">\n" + "<mods:namePart>" + conferenceTitle + "</mods:namePart>\n" + "</mods:name>" + " </mods:mods>\n" + " </modsContainer>\n" + " </def.modsContainer>\n" + " </metadata>\n" + "</mycoreobject>\n"; CSLItemData build1 = testModsNames(testData); Assert.assertEquals("Conference should be equal", conferenceTitle, build1.getEvent()); } @Test public void testInventor() throws IOException, JDOMException { String familyName = "Rolfer"; String givenName = "Rolf"; String testData2 = "<mycoreobject xmlns:xlink=\"http://www.w3.org/1999/xlink\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xsi:noNamespaceSchemaLocation=\"datamodel-mods.xsd\" ID=\"bibthk_mods_00001056\">\n" + " <metadata>\n" + " <def.modsContainer class=\"MCRMetaXML\" heritable=\"false\" notinherit=\"true\">\n" + " <modsContainer inherited=\"0\">\n" + " <mods:mods xmlns:mods=\"http://www.loc.gov/mods/v3\">\n" + "<mods:name type=\"personal\">\n" + "<mods:role>\n" + "<mods:roleTerm type=\"code\" authority=\"marcrelator\">inv</mods:roleTerm>\n" + "</mods:role>\n" + "<mods:namePart type=\"given\">" + givenName + "</mods:namePart>\n" + "<mods:namePart type=\"family\">" + familyName + "</mods:namePart>\n" + "</mods:name>" + " </mods:mods>\n" + " </modsContainer>\n" + " </def.modsContainer>\n" + " </metadata>\n" + "</mycoreobject>\n"; CSLItemData build2 = testModsNames(testData2); Assert.assertEquals("Pantent Inventor should author (family)", familyName, build2.getAuthor()[0].getFamily()); Assert.assertEquals("Pantent Inventor should author (given)", givenName, build2.getAuthor()[0].getGiven()); } private CSLItemData testModsPart(String testData) throws JDOMException, IOException { MCRModsItemDataProvider midp = new MCRModsItemDataProvider(); Document testDataDoc = new SAXBuilder().build(new StringReader(testData)); CSLItemDataBuilder dataBuilder = new CSLItemDataBuilder(); midp.addContent(testDataDoc); midp.processModsPart(dataBuilder); CSLItemData build = dataBuilder.build(); return build; } private CSLItemData testModsNames(String testData) throws JDOMException, IOException { MCRModsItemDataProvider midp = new MCRModsItemDataProvider(); Document testDataDoc = new SAXBuilder().build(new StringReader(testData)); CSLItemDataBuilder dataBuilder = new CSLItemDataBuilder(); midp.addContent(testDataDoc); midp.processNames(dataBuilder); CSLItemData build = dataBuilder.build(); return build; } }
9,351
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRListModsItemDataProviderTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/csl/MCRListModsItemDataProviderTest.java
package org.mycore.mods.csl; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jdom2.Element; import org.jdom2.JDOMException; import org.junit.Assert; import org.junit.Test; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.xml.sax.SAXException; public class MCRListModsItemDataProviderTest extends MCRMODSCSLTest { @Test public void testSorting() throws IOException, JDOMException, SAXException { List<MCRContent> testContent = new ArrayList<>(getTestContent()); MCRListModsItemDataProvider mcrListModsItemDataProvider = new MCRListModsItemDataProvider(); for (int i = 0; i < 10; i++) { Collections.shuffle(testContent); Element root = new Element("root"); for (MCRContent c : testContent) { root.addContent(c.asXML().getRootElement().clone()); } mcrListModsItemDataProvider.addContent(new MCRJDOMContent(root)); List<String> ids = mcrListModsItemDataProvider.getIds().stream().toList(); Assert.assertEquals("The number of ids should match the number of input", testContent.size(), ids.size()); for (int j = 0; j < ids.size(); j++) { String id = ids.get(j); String idFromContent = testContent.get(j).asXML().getRootElement().getAttributeValue("ID"); Assert.assertEquals("The order of output should match input", idFromContent, id); } mcrListModsItemDataProvider.reset(); } } }
1,638
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRBibTeX2MODSTransformerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/bibtex/MCRBibTeX2MODSTransformerTest.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.mods.bibtex; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import org.jdom2.Element; import org.jdom2.JDOMException; import org.junit.Test; import org.mycore.common.MCRConstants; import org.mycore.common.MCRTestCase; import org.mycore.common.content.MCRFileContent; import org.mycore.common.content.MCRJDOMContent; import org.xml.sax.SAXException; public class MCRBibTeX2MODSTransformerTest extends MCRTestCase { @Test public void testTransformation() throws IOException, JDOMException, SAXException { ClassLoader classLoader = getClass().getClassLoader(); File baseDir = new File(classLoader.getResource("BibTeX2MODSTransformerTest").getFile()); int numTests = baseDir.list().length / 2; for (int i = 1; i <= numTests; i++) { // Read BibTeX file File bibTeXFile = new File(baseDir, String.format("test-%s-bibTeX.txt", i)); MCRFileContent bibTeX = new MCRFileContent(bibTeXFile); // Transform BibTeX to MODS MCRJDOMContent resultingContent = new MCRBibTeX2MODSTransformer().transform(bibTeX); Element resultingMODS = resultingContent.asXML().getRootElement().getChildren().get(0).detach(); removeSourceExtension(resultingMODS); // Read expected MODS File modsFile = new File(baseDir, String.format("test-%s-mods.xml", i)); Element mods = new MCRFileContent(modsFile).asXML().detachRootElement(); // Compare transformation output with expected MODS String expected = new MCRJDOMContent(mods).asString(); String result = new MCRJDOMContent(resultingMODS).asString(); String message = "transformation of " + bibTeXFile.getName(); assertEquals(message, expected, result); } } private void removeSourceExtension(Element resultingMODS) { for (Element extension : resultingMODS.getChildren("extension", MCRConstants.MODS_NAMESPACE)) { for (Element source : extension.getChildren("source")) { source.detach(); } if (extension.getChildren().isEmpty()) { extension.detach(); } } } }
3,014
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSCollectionConditionTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/access/facts/condition/MCRMODSCollectionConditionTest.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.mods.access.facts.condition; import static org.mycore.access.facts.condition.fact.MCRFactsTestUtil.hackObjectIntoCache; import java.util.ArrayList; import java.util.Map; import org.jdom2.Element; import org.junit.Assert; import org.junit.Test; import org.mycore.access.facts.MCRFactsHolder; import org.mycore.access.facts.fact.MCRObjectIDFact; import org.mycore.common.MCRConstants; import org.mycore.common.MCRTestCase; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mods.MCRMODSWrapper; public class MCRMODSCollectionConditionTest extends MCRTestCase { @Override protected Map<String, String> getTestProperties() { Map<String, String> testProperties = super.getTestProperties(); testProperties.put("MCR.Metadata.Type.mods", Boolean.TRUE.toString()); return testProperties; } @Test public void testConditionMatch() throws NoSuchFieldException, IllegalAccessException { MCRMODSWrapper mw = new MCRMODSWrapper(); MCRObject object = mw.getMCRObject(); mw.setMODS(new Element("mods", MCRConstants.MODS_NAMESPACE)); MCRObjectID testId = MCRObjectID.getInstance("test_mods_00000001"); object.setId(testId); MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>()); hackObjectIntoCache(object, testId); holder.add(new MCRObjectIDFact("objid", testId.toString(), testId)); Element classification = mw.addElement("classification"); classification.setAttribute("valueURI", "https://mycore.de/classifications/collection#exampleCollection"); MCRMODSCollectionCondition collectionCondition = new MCRMODSCollectionCondition(); collectionCondition.parse(new Element("collection").setText("exampleCollection")); Assert.assertTrue("object should be in collection", collectionCondition.matches(holder)); } @Test public void testConditionNotMatch() throws NoSuchFieldException, IllegalAccessException { MCRMODSWrapper mw = new MCRMODSWrapper(); MCRObject object = mw.getMCRObject(); mw.setMODS(new Element("mods", MCRConstants.MODS_NAMESPACE)); MCRObjectID testId = MCRObjectID.getInstance("test_mods_00000001"); object.setId(testId); MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>()); hackObjectIntoCache(object, testId); holder.add(new MCRObjectIDFact("objid", testId.toString(), testId)); Element classification = mw.addElement("classification"); classification.setAttribute("valueURI", "https://mycore.de/classifications/collection#badCollection"); MCRMODSCollectionCondition collectionCondition = new MCRMODSCollectionCondition(); collectionCondition.parse(new Element("collection").setText("exampleCollection")); Assert.assertFalse("object should be in collection", collectionCondition.matches(holder)); } }
3,709
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSGenreConditionTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/access/facts/condition/MCRMODSGenreConditionTest.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.mods.access.facts.condition; import static org.mycore.access.facts.condition.fact.MCRFactsTestUtil.hackObjectIntoCache; import java.util.ArrayList; import java.util.Map; import org.jdom2.Element; import org.junit.Assert; import org.junit.Test; import org.mycore.access.facts.MCRFactsHolder; import org.mycore.access.facts.fact.MCRObjectIDFact; import org.mycore.common.MCRConstants; import org.mycore.common.MCRTestCase; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mods.MCRMODSWrapper; public class MCRMODSGenreConditionTest extends MCRTestCase { @Override protected Map<String, String> getTestProperties() { Map<String, String> testProperties = super.getTestProperties(); testProperties.put("MCR.Metadata.Type.mods", Boolean.TRUE.toString()); return testProperties; } @Test public void testConditionMatch() throws NoSuchFieldException, IllegalAccessException { MCRMODSWrapper mw = new MCRMODSWrapper(); MCRObject object = mw.getMCRObject(); mw.setMODS(new Element("mods", MCRConstants.MODS_NAMESPACE)); MCRObjectID testId = MCRObjectID.getInstance("test_mods_00000001"); object.setId(testId); MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>()); hackObjectIntoCache(object, testId); holder.add(new MCRObjectIDFact("objid", testId.toString(), testId)); Element genre = mw.addElement("genre"); genre.setAttribute("valueURI", "https://mycore.de/classifications/mir_genres#article"); MCRMODSGenreCondition genreCondition = new MCRMODSGenreCondition(); genreCondition.parse(new Element("genre").setText("article")); Assert.assertTrue("object should be in genre article", genreCondition.matches(holder)); } @Test public void testConditionNotMatch() throws NoSuchFieldException, IllegalAccessException { MCRMODSWrapper mw = new MCRMODSWrapper(); MCRObject object = mw.getMCRObject(); mw.setMODS(new Element("mods", MCRConstants.MODS_NAMESPACE)); MCRObjectID testId = MCRObjectID.getInstance("test_mods_00000001"); object.setId(testId); MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>()); hackObjectIntoCache(object, testId); holder.add(new MCRObjectIDFact("objid", testId.toString(), testId)); Element genre = mw.addElement("genre"); genre.setAttribute("valueURI", "https://mycore.de/classifications/mir_genres#book"); MCRMODSGenreCondition genreCondition = new MCRMODSGenreCondition(); genreCondition.parse(new Element("genre").setText("article")); Assert.assertFalse("object should not be in genre article", genreCondition.matches(holder)); } }
3,562
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSEmbargoConditionTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/access/facts/condition/MCRMODSEmbargoConditionTest.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.mods.access.facts.condition; import static org.mycore.access.facts.condition.fact.MCRFactsTestUtil.hackObjectIntoCache; import java.util.ArrayList; import java.util.Map; import org.jdom2.Element; import org.junit.Assert; import org.junit.Test; import org.mycore.access.facts.MCRFactsHolder; import org.mycore.access.facts.fact.MCRObjectIDFact; import org.mycore.common.MCRConstants; import org.mycore.common.MCRTestCase; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mods.MCRMODSWrapper; public class MCRMODSEmbargoConditionTest extends MCRTestCase { @Override protected Map<String, String> getTestProperties() { Map<String, String> testProperties = super.getTestProperties(); testProperties.put("MCR.Metadata.Type.mods", Boolean.TRUE.toString()); return testProperties; } @Test public void testConditionMatch() throws NoSuchFieldException, IllegalAccessException { MCRMODSWrapper mw = new MCRMODSWrapper(); MCRObject object = mw.getMCRObject(); mw.setMODS(new Element("mods", MCRConstants.MODS_NAMESPACE)); MCRObjectID testId = MCRObjectID.getInstance("test_mods_00000001"); object.setId(testId); MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>()); hackObjectIntoCache(object, testId); holder.add(new MCRObjectIDFact("objid", testId.toString(), testId)); Element classification = mw.addElement("accessCondition"); classification.setAttribute("type", "embargo"); classification.setText("2099-01-01"); MCRMODSEmbargoCondition embargoCondition = new MCRMODSEmbargoCondition(); embargoCondition.parse(new Element("embargo")); Assert.assertTrue("object should have embargo", embargoCondition.matches(holder)); } @Test public void testConditionNotMatch() throws NoSuchFieldException, IllegalAccessException { MCRMODSWrapper mw = new MCRMODSWrapper(); MCRObject object = mw.getMCRObject(); mw.setMODS(new Element("mods", MCRConstants.MODS_NAMESPACE)); MCRObjectID testId = MCRObjectID.getInstance("test_mods_00000001"); object.setId(testId); MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>()); hackObjectIntoCache(object, testId); holder.add(new MCRObjectIDFact("objid", testId.toString(), testId)); Element classification = mw.addElement("accessCondition"); classification.setAttribute("type", "embargo"); classification.setText("2000-01-01"); MCRMODSEmbargoCondition embargoCondition = new MCRMODSEmbargoCondition(); embargoCondition.parse(new Element("embargo")); Assert.assertFalse("object should have embargo", embargoCondition.matches(holder)); } }
3,583
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRClassificationMappingEventHandlerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/test/java/org/mycore/mods/classification/MCRClassificationMappingEventHandlerTest.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.mods.classification; import java.io.IOException; import java.net.URISyntaxException; 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.jdom2.filter.Filters; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.junit.Assert; import org.junit.Test; import org.mycore.common.MCRConstants; import org.mycore.common.MCRJPATestCase; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRTransactionHelper; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAO; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.utils.MCRXMLTransformer; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.mods.MCRMODSWrapper; public class MCRClassificationMappingEventHandlerTest extends MCRJPATestCase { public static final String TEST_DIRECTORY = "MCRClassificationMappingEventHandlerTest/"; private static final Logger LOGGER = LogManager.getLogger(); public MCRCategoryDAO getDAO() { return MCRCategoryDAOFactory.getInstance(); } @Test public void testMapping() throws IOException, JDOMException, URISyntaxException { MCRSessionMgr.getCurrentSession(); MCRTransactionHelper.isTransactionActive(); ClassLoader classLoader = getClass().getClassLoader(); SAXBuilder saxBuilder = new SAXBuilder(); loadCategory("diniPublType.xml"); loadCategory("genre.xml"); Document document = saxBuilder.build(classLoader.getResourceAsStream(TEST_DIRECTORY + "testMods.xml")); MCRObject mcro = new MCRObject(); MCRMODSWrapper mw = new MCRMODSWrapper(mcro); mw.setMODS(document.getRootElement().detach()); mw.setID("junit", 1); MCRClassificationMappingEventHandler mapper = new MCRClassificationMappingEventHandler(); mapper.handleObjectUpdated(null, mcro); String expression = "//mods:classification[contains(@generator,'-mycore') and contains(@valueURI, 'StudyThesis')]"; XPathExpression<Element> expressionObject = XPathFactory.instance() .compile(expression, Filters.element(), null, MCRConstants.MODS_NAMESPACE, MCRConstants.XLINK_NAMESPACE); Document xml = mcro.createXML(); Assert.assertNotNull("The mapped classification should be in the MyCoReObject now!", expressionObject.evaluateFirst( xml)); expression = "//mods:classification[contains(@generator,'-mycore') and contains(@valueURI, 'masterThesis')]"; expressionObject = XPathFactory.instance() .compile(expression, Filters.element(), null, MCRConstants.MODS_NAMESPACE, MCRConstants.XLINK_NAMESPACE); Assert.assertNull("The mapped classification of the child should not be contained in the MyCoReObject now!", expressionObject.evaluateFirst(xml)); LOGGER.info(new XMLOutputter(Format.getPrettyFormat()).outputString(xml)); } private void loadCategory(String categoryFileName) throws URISyntaxException, JDOMException, IOException { ClassLoader classLoader = getClass().getClassLoader(); SAXBuilder saxBuilder = new SAXBuilder(); MCRCategory category = MCRXMLTransformer .getCategory(saxBuilder.build(classLoader.getResourceAsStream(TEST_DIRECTORY + categoryFileName))); getDAO().addCategory(null, category); } }
4,457
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSDateHelper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/MCRMODSDateHelper.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.mods; import static org.mycore.mods.MCRMODSDateFormat.DATE_LOCALE; import static org.mycore.mods.MCRMODSDateFormat.MODS_TIMEZONE; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Objects; import org.jdom2.Element; import org.mycore.common.MCRException; /** * Helper class to parse and build MODS date elements, see * http://www.loc.gov/standards/mods/userguide/generalapp.html#encoding * * @author Frank Lützenkirchen */ public class MCRMODSDateHelper { public static Date getDate(Element element) { if (element == null) { return null; } String text = element.getTextTrim(); if ((text == null) || text.isEmpty()) { return null; } String encoding = element.getAttributeValue("encoding", "unknown").toLowerCase(DATE_LOCALE); String key = encoding + "-" + text.length(); MCRMODSDateFormat format = firstNonNull(MCRMODSDateFormat.getFormat(key), MCRMODSDateFormat.getFormat(encoding)); if (format == null) { throw reportParseException(encoding, text, null); } try { return format.parseDate(text); } catch (ParseException ex) { throw reportParseException(encoding, text, ex); } } @SafeVarargs private static <T> T firstNonNull(T... o) { for (T test : Objects.requireNonNull(o)) { if (test != null) { return test; } } throw new NullPointerException(); } public static GregorianCalendar getCalendar(Element element) { Date date = getDate(element); if (date == null) { return null; } GregorianCalendar cal = new GregorianCalendar(MODS_TIMEZONE, DATE_LOCALE); cal.setTime(date); return cal; } public static void setDate(Element element, Date date, MCRMODSDateFormat encoding) { Objects.requireNonNull(encoding, "encoding is required: " + encoding); element.setText(encoding.formatDate(date)); element.setAttribute("encoding", encoding.asEncodingAttributeValue()); } public static void setDate(Element element, GregorianCalendar cal, MCRMODSDateFormat encoding) { setDate(element, encoding.isDateOnly() ? adjustTimeOffset(cal) : cal.getTime(), encoding); } private static Date adjustTimeOffset(GregorianCalendar cal) { GregorianCalendar clone = new GregorianCalendar(MODS_TIMEZONE, DATE_LOCALE); clone.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)); return clone.getTime(); } private static MCRException reportParseException(String encoding, String text, ParseException ex) { String msg = "Unable to parse MODS date encoded " + encoding + " " + text; return new MCRException(msg, ex); } }
3,726
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIdentifierValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/MCRIdentifierValidator.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.mods; /** * @author Thomas Scheffler (yagee) * */ public class MCRIdentifierValidator { private static final int ISBN13_LENGTH = 13; private static final int ISBN13_WITH_DELIM_LENGTH = 17; public static boolean validate(final String type, String value) { if (value.trim().length() == 0) { //do not check 'required' here return true; } return switch (type) { case "isbn" -> checkISBN(value); case "doi" -> checkDOI(value); default -> true; }; } private static boolean checkDOI(String value) { return value.startsWith("10.") && value.contains("/"); } private static boolean checkISBN(String value) { String isbn = value; if (isbn.length() != ISBN13_WITH_DELIM_LENGTH) { //'-' missing return false; } isbn = isbn.replaceAll("-", ""); isbn = isbn.replace('x', 'X'); // ISBN- 13 if (isbn.length() == ISBN13_LENGTH) { int checkSum = 0; int digit = 0; for (int i = 0; i < ISBN13_LENGTH; ++i) { if (isbn.charAt(i) == 'X') { digit = 10; } else { digit = Character.digit(isbn.charAt(i), 10); } if (i % 2 == 1) { digit *= 3; } checkSum += digit; } return checkSum % 10 == 0; } return false; } }
2,283
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSWrapper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/MCRMODSWrapper.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.mods; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jdom2.Content; import org.jdom2.Element; import org.jdom2.filter.Filters; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.common.MCRConstants; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.metadata.MCRMetaElement; import org.mycore.datamodel.metadata.MCRMetaXML; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.metadata.MCRObjectMetadata; import org.mycore.datamodel.metadata.MCRObjectService; import org.mycore.mods.classification.MCRClassMapper; /** * @author Frank Lützenkirchen * @author Thomas Scheffler */ public class MCRMODSWrapper { //ancestor::mycoreobject required for MCR-927 static final String LINKED_RELATED_ITEMS = "mods:relatedItem[@type='host'" + " and ancestor::mycoreobject/structure/parents/parent or" + " string-length(substring-after(@xlink:href,'_')) > 0 and" + " string-length(substring-after(substring-after(@xlink:href,'_'), '_')) > 0 and" + " number(substring-after(substring-after(@xlink:href,'_'),'_')) > 0 and" + " (" + xPathRelationshipTypeTest() + ")]"; private static final String MODS_CONTAINER = "modsContainer"; private static final String DEF_MODS_CONTAINER = "def.modsContainer"; public static final String MODS_OBJECT_TYPE = MCRConfiguration2.getStringOrThrow("MCR.MODS.NewObjectType"); private static final String MODS_DATAMODEL = "datamodel-mods.xsd"; private static List<String> topLevelElementOrder = new ArrayList<>(); private static Set<String> SUPPORTED_TYPES = MCRConfiguration2 .getOrThrow("MCR.MODS.Types", MCRConfiguration2::splitValue) .collect(Collectors.toSet()); private MCRObject object; static { topLevelElementOrder.add("typeOfResource"); topLevelElementOrder.add("titleInfo"); topLevelElementOrder.add("name"); topLevelElementOrder.add("genre"); topLevelElementOrder.add("originInfo"); topLevelElementOrder.add("language"); topLevelElementOrder.add("abstract"); topLevelElementOrder.add("note"); topLevelElementOrder.add("subject"); topLevelElementOrder.add("classification"); topLevelElementOrder.add("relatedItem"); topLevelElementOrder.add("identifier"); topLevelElementOrder.add("location"); topLevelElementOrder.add("accessCondition"); } private static int getRankOf(Element topLevelElement) { return topLevelElementOrder.indexOf(topLevelElement.getName()); } public static MCRObject wrapMODSDocument(Element modsDefinition, String projectID) { MCRMODSWrapper wrapper = new MCRMODSWrapper(); wrapper.setID(projectID, 0); wrapper.setMODS(modsDefinition); return wrapper.getMCRObject(); } /** * returns true if the given MCRObject can handle MODS metadata * @param obj - the MCRObject * @return true, if mods is supported */ public static boolean isSupported(MCRObject obj) { if (isSupported(obj.getId())) { return true; } return obj.getMetadata() != null && obj.getMetadata().getMetadataElement(DEF_MODS_CONTAINER) != null && obj.getMetadata().getMetadataElement(DEF_MODS_CONTAINER).getElementByName(MODS_CONTAINER) != null; } /** * Returns true of the given {@link MCRObjectID} has a mods type. Does not look at the object. * @param id - the {@link MCRObjectID} * @return true if has a mods type */ public static boolean isSupported(MCRObjectID id) { return SUPPORTED_TYPES.contains(id.getTypeId()); } public MCRMODSWrapper() { this(new MCRObject()); } public MCRMODSWrapper(MCRObject object) { this.object = object; if (object.getSchema() == null || object.getSchema().isEmpty()) { object.setSchema(MODS_DATAMODEL); } } /** * @return the mods:mods Element at /metadata/def.modsContainer/modsContainer */ public Element getMODS() { try { MCRMetaXML mx = (MCRMetaXML) (object.getMetadata().getMetadataElement(DEF_MODS_CONTAINER).getElement(0)); for (Content content : mx.getContent()) { if (content instanceof Element element) { return element; } } } catch (NullPointerException | IndexOutOfBoundsException e) { //do nothing } return null; } public MCRObject getMCRObject() { return object; } public MCRObjectID setID(String projectID, int id) { MCRObjectID objID = MCRObjectID.getInstance(MCRObjectID.formatID(projectID, MODS_OBJECT_TYPE, id)); object.setId(objID); return objID; } public void setMODS(Element mods) { MCRObjectMetadata om = object.getMetadata(); if (om.getMetadataElement(DEF_MODS_CONTAINER) != null) { om.removeMetadataElement(DEF_MODS_CONTAINER); } MCRMetaXML modsContainer = new MCRMetaXML(MODS_CONTAINER, null, 0); List<MCRMetaXML> list = Collections.nCopies(1, modsContainer); MCRMetaElement defModsContainer = new MCRMetaElement(MCRMetaXML.class, DEF_MODS_CONTAINER, false, true, list); om.setMetadataElement(defModsContainer); modsContainer.addContent(mods); } private XPathExpression<Element> buildXPath(String xPath) { return XPathFactory.instance().compile(xPath, Filters.element(), null, MCRConstants.MODS_NAMESPACE, MCRConstants.XLINK_NAMESPACE); } public Element getElement(String xPath) { return buildXPath(xPath).evaluateFirst(getMODS()); } public List<Element> getElements(String xPath) { Element eMODS = getMODS(); if (eMODS != null) { return buildXPath(xPath).evaluate(eMODS); } else { return Collections.emptyList(); } } public List<Element> getLinkedRelatedItems() { return getElements(LINKED_RELATED_ITEMS); } public String getElementValue(String xPath) { Element element = getElement(xPath); return (element == null ? null : element.getTextTrim()); } /** * Sets or adds an element with target name and value. The element name and attributes are used as xpath expression * to filter for an element. The attributes are used with and operation if present. */ public Optional<Element> setElement(String elementName, String elementValue, Map<String, String> attributes) { boolean isAttributeDataPresent = attributes != null && !attributes.isEmpty(); boolean isValuePresent = elementValue != null && !elementValue.isEmpty(); if (!isValuePresent && !isAttributeDataPresent) { return Optional.empty(); } StringBuilder xPath = new StringBuilder("mods:"); xPath.append(elementName); // add attributes to xpath with and operator if (isAttributeDataPresent) { xPath.append('['); Iterator<Map.Entry<String, String>> attributeIterator = attributes.entrySet().iterator(); while (attributeIterator.hasNext()) { Map.Entry<String, String> attribute = attributeIterator.next(); xPath.append('@').append(attribute.getKey()).append("='").append(attribute.getValue()).append('\''); if (attributeIterator.hasNext()) { xPath.append(" and "); } } xPath.append(']'); } Element element = getElement(xPath.toString()); if (element == null) { element = addElement(elementName); if (isAttributeDataPresent) { for (Map.Entry<String, String> entry : attributes.entrySet()) { element.setAttribute(entry.getKey(), entry.getValue()); } } } if (isValuePresent) { element.setText(elementValue.trim()); } return Optional.of(element); } public Optional<Element> setElement(String elementName, String attributeName, String attributeValue, String elementValue) { Map<String, String> attributes = Collections.emptyMap(); if (attributeName != null && attributeValue != null) { attributes = new HashMap<>(); attributes.put(attributeName, attributeValue); } return setElement(elementName, elementValue, attributes); } public Optional<Element> setElement(String elementName, String elementValue) { return setElement(elementName, null, null, elementValue); } public Element addElement(String elementName) { Element element = new Element(elementName, MCRConstants.MODS_NAMESPACE); insertTopLevelElement(element); return element; } public void addElement(Element element) { if (!element.getNamespace().equals(MCRConstants.MODS_NAMESPACE)) { throw new IllegalArgumentException("given element is no mods element"); } insertTopLevelElement(element); } private void insertTopLevelElement(Element element) { int rankOfNewElement = getRankOf(element); List<Element> topLevelElements = getMODS().getChildren(); for (int pos = 0; pos < topLevelElements.size(); pos++) { if (getRankOf(topLevelElements.get(pos)) > rankOfNewElement) { getMODS().addContent(pos, element); return; } } getMODS().addContent(element); } public void removeElements(String xPath) { Iterator<Element> selected; selected = buildXPath(xPath).evaluate(getMODS()).iterator(); while (selected.hasNext()) { Element element = selected.next(); element.detach(); } } public void removeInheritedMetadata() { String xPath = LINKED_RELATED_ITEMS + "/*[local-name()!='part']"; removeElements(xPath); } public String getServiceFlag(String type) { MCRObjectService os = object.getService(); return (os.isFlagTypeSet(type) ? os.getFlags(type).get(0) : null); } public void setServiceFlag(String type, String value) { MCRObjectService os = object.getService(); if (os.isFlagTypeSet(type)) { os.removeFlags(type); } if ((value != null) && !value.trim().isEmpty()) { os.addFlag(type, value.trim()); } } public List<MCRCategoryID> getMcrCategoryIDs() { final List<Element> categoryNodes = getCategoryNodes(); final List<MCRCategoryID> categories = new ArrayList<>(categoryNodes.size()); for (Element node : categoryNodes) { final MCRCategoryID categoryID = MCRClassMapper.getCategoryID(node); if (categoryID != null) { categories.add(categoryID); } } return categories; } private List<Element> getCategoryNodes() { return getElements( "mods:typeOfResource | mods:accessCondition | .//*[(@authority or @authorityURI)" + " and not(ancestor::mods:relatedItem)]"); } private static String xPathRelationshipTypeTest() { return Stream.of(MCRMODSRelationshipType.values()) .map(s -> String.format(Locale.ROOT, "@type='%s'", s)) .collect(Collectors.joining(" or ")); } }
12,720
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSMetadataShareAgent.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/MCRMODSMetadataShareAgent.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.mods; import static org.mycore.mods.MCRMODSWrapper.LINKED_RELATED_ITEMS; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Attribute; import org.jdom2.Content; import org.jdom2.Element; import org.jdom2.filter.Filter; import org.jdom2.filter.Filters; import org.mycore.access.MCRAccessException; import org.mycore.common.MCRConstants; import org.mycore.common.MCRPersistenceException; import org.mycore.common.xml.MCRXMLHelper; import org.mycore.datamodel.common.MCRLinkTableManager; import org.mycore.datamodel.metadata.MCRMetaLinkID; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.metadata.MCRObjectMetadata; import org.mycore.datamodel.metadata.share.MCRMetadataShareAgent; /** * @author Thomas Scheffler (yagee) */ public class MCRMODSMetadataShareAgent implements MCRMetadataShareAgent { private static Logger LOGGER = LogManager.getLogger(MCRMODSMetadataShareAgent.class); private static final String HOST_SECTION_XPATH = "mods:relatedItem[@type='host']"; /* (non-Javadoc) * @see org.mycore.datamodel.metadata.share.MCRMetadataShareAgent * #inheritableMetadataChanged(org.mycore.datamodel.metadata.MCRObject, org.mycore.datamodel.metadata.MCRObject) */ @Override public boolean shareableMetadataChanged(MCRObject oldVersion, MCRObject newVersion) { final MCRObjectMetadata md = newVersion.getMetadata(); final MCRObjectMetadata mdold = oldVersion.getMetadata(); //if any metadata changed we need to update children boolean metadataChanged = !MCRXMLHelper.deepEqual(md.createXML(), mdold.createXML()); if (!metadataChanged) { LOGGER.info("Metadata did not change on update of {}", newVersion.getId()); } return metadataChanged; } /* (non-Javadoc) * @see org.mycore.datamodel.metadata.share.MCRMetadataShareAgent * #inheritMetadata(org.mycore.datamodel.metadata.MCRObject) */ @Override public void distributeMetadata(MCRObject holder) throws MCRPersistenceException { MCRMODSWrapper holderWrapper = new MCRMODSWrapper(holder); distributeInheritedMetadata(holderWrapper); distributeLinkedMetadata(holderWrapper); } /** * Distribute metadata from holder to all children. The metadata is inherited to all children that are supported * by this agent. If {@link #runWithLockedObject(List, Consumer)} is implemented, the children are locked before * the metadata is inherited. * @param holderWrapper the mods wrapper which holds the metadata that should be inherited */ protected void distributeInheritedMetadata(MCRMODSWrapper holderWrapper) { List<MCRMetaLinkID> children = holderWrapper.getMCRObject().getStructure().getChildren(); if (children.isEmpty()) { return; } LOGGER.info("Update inherited metadata"); List<MCRObjectID> childIds = children.stream() .map(MCRMetaLinkID::getXLinkHrefID) .filter(MCRMODSWrapper::isSupported) .collect(Collectors.toList()); runWithLockedObject(childIds, (childId) -> { LOGGER.info("Update: {}", childId); MCRObject child = MCRMetadataManager.retrieveMCRObject(childId); MCRMODSWrapper childWrapper = new MCRMODSWrapper(child); inheritToChild(holderWrapper, childWrapper); LOGGER.info("Saving: {}", childId); try { checkHierarchy(childWrapper); MCRMetadataManager.update(child); } catch (MCRPersistenceException | MCRAccessException e) { throw new MCRPersistenceException("Error while updating inherited metadata", e); } }); } /** * Distribute metadata from holder to linked objects. The metadata is inherited to all linked objects that are * supported by this agent. If {@link #runWithLockedObject(List, Consumer)} is implemented, the linked objects are * locked before the metadata is inherited. * @param holderWrapper the mods wrapper which holds the metadata that should be inherited */ protected void distributeLinkedMetadata(MCRMODSWrapper holderWrapper) { Collection<String> recipientIdsStr = MCRLinkTableManager.instance() .getSourceOf(holderWrapper.getMCRObject().getId(), MCRLinkTableManager.ENTRY_TYPE_REFERENCE); List<MCRObjectID> recipientIds = recipientIdsStr.stream() .map(MCRObjectID::getInstance) .filter(MCRMODSWrapper::isSupported).toList(); if (recipientIds.isEmpty()) { return; } runWithLockedObject(recipientIds, (recipientId) -> { LOGGER.info("distribute metadata to {}", recipientId); MCRObject recipient = MCRMetadataManager.retrieveMCRObject(recipientId); MCRMODSWrapper recipientWrapper = new MCRMODSWrapper(recipient); for (Element relatedItem : recipientWrapper.getLinkedRelatedItems()) { String holderId = relatedItem.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE); if (holderWrapper.getMCRObject().getId().toString().equals(holderId)) { @SuppressWarnings("unchecked") Filter<Content> sharedMetadata = (Filter<Content>) Filters.element("part", MCRConstants.MODS_NAMESPACE).negate(); relatedItem.removeContent(sharedMetadata); List<Content> newRelatedItemContent = getClearContent(holderWrapper); relatedItem.addContent(newRelatedItemContent); LOGGER.info("Saving: {}", recipientId); try { checkHierarchy(recipientWrapper); MCRMetadataManager.update(recipient); } catch (MCRPersistenceException | MCRAccessException e) { throw new MCRPersistenceException("Error while updating shared metadata", e); } } } }); } /** * Determines if the content of the relatedItem should be removed, when it is inserted as related item * @param relatedItem the relatedItem element * @return true if the content should be removed */ protected boolean isClearableRelatedItem(Element relatedItem) { return relatedItem.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE) != null; } /* (non-Javadoc) * @see org.mycore.datamodel.metadata.share.MCRMetadataShareAgent * #inheritMetadata(org.mycore.datamodel.metadata.MCRObject, org.mycore.datamodel.metadata.MCRObject) */ @Override public void receiveMetadata(MCRObject child) { MCRMODSWrapper childWrapper = new MCRMODSWrapper(child); MCRObjectID parentID = child.getStructure().getParentID(); LOGGER.debug("Removing old inherited Metadata."); childWrapper.removeInheritedMetadata(); if (parentID != null && MCRMODSWrapper.isSupported(parentID)) { MCRObject parent = MCRMetadataManager.retrieveMCRObject(parentID); MCRMODSWrapper parentWrapper = new MCRMODSWrapper(parent); inheritToChild(parentWrapper, childWrapper); } for (Element relatedItem : childWrapper.getLinkedRelatedItems()) { String type = relatedItem.getAttributeValue("type"); String holderId = relatedItem.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE); LOGGER.info("receive metadata from {} document {}", type, holderId); if ((holderId == null || parentID != null && parentID.toString().equals(holderId)) && MCRMODSRelationshipType.host.name().equals(type)) { //already received metadata from parent; continue; } MCRObjectID holderObjectID = MCRObjectID.getInstance(holderId); if (MCRMODSWrapper.isSupported(holderObjectID)) { MCRObject targetObject = MCRMetadataManager.retrieveMCRObject(holderObjectID); MCRMODSWrapper targetWrapper = new MCRMODSWrapper(targetObject); List<Content> inheritedData = getClearContent(targetWrapper); relatedItem.addContent(inheritedData); } } checkHierarchy(childWrapper); } /** * @param targetWrapper the wrapper of the target object * @return a list of content that can be added to a relatedItem element as shared metadata */ private List<Content> getClearContent(MCRMODSWrapper targetWrapper) { List<Content> inheritedData = targetWrapper.getMODS().cloneContent(); inheritedData.stream() .filter(c -> c instanceof Element) .map(Element.class::cast) .filter(element -> element.getName().equals("relatedItem")) .filter(this::isClearableRelatedItem) .forEach(Element::removeContent); return inheritedData; } void inheritToChild(MCRMODSWrapper parentWrapper, MCRMODSWrapper childWrapper) { LOGGER.info("Inserting inherited Metadata."); Element hostContainer = childWrapper.getElement(HOST_SECTION_XPATH); if (hostContainer == null) { LOGGER.info("Adding new relatedItem[@type='host'])"); hostContainer = new Element("relatedItem", MCRConstants.MODS_NAMESPACE) .setAttribute("href", parentWrapper.getMCRObject().getId().toString(), MCRConstants.XLINK_NAMESPACE) .setAttribute("type", "host"); childWrapper.addElement(hostContainer); } hostContainer.addContent(parentWrapper.getMODS().cloneContent()); } void checkHierarchy(MCRMODSWrapper mods) throws MCRPersistenceException { final MCRObjectID modsId = Objects.requireNonNull(mods.getMCRObject().getId()); LOGGER.info("Checking relatedItem hierarchy of {}.", modsId); final List<Element> relatedItemLeaves = mods .getElements(".//" + LINKED_RELATED_ITEMS + "[not(mods:relatedItem)]"); try { relatedItemLeaves.forEach(e -> checkHierarchy(e, new HashSet<>(Set.of(modsId)))); } catch (MCRPersistenceException e) { throw new MCRPersistenceException("Hierarchy of mods:relatedItem in " + modsId + " contains circuits.", e); } } /** * Recursivly checks <code>relatedItem</code> and parent &lt;mods:relatedItem&gt; elements for multiple {@link MCRObjectID}s. * @param relatedItem &lt;mods:relatedItem&gt; * @param idCollected of IDs collected so far * @throws MCRPersistenceException if {@link MCRObjectID} of <code>relatedItem</code> is in <code>idCollected</code> */ private void checkHierarchy(Element relatedItem, Set<MCRObjectID> idCollected) throws MCRPersistenceException { final Attribute href = relatedItem.getAttribute("href", MCRConstants.XLINK_NAMESPACE); if (href != null) { final String testId = href.getValue(); LOGGER.debug("Checking relatedItem {}.", testId); if (MCRObjectID.isValid(testId)) { final MCRObjectID relatedItemId = MCRObjectID.getInstance(testId); LOGGER.debug("Checking if {} is in {}.", relatedItemId, idCollected); if (!idCollected.add(relatedItemId)) { throw new MCRPersistenceException( "Hierarchy of mods:relatedItem contains ciruit by object " + relatedItemId); } } } final Element parentElement = relatedItem.getParentElement(); if (parentElement.getName().equals("relatedItem")) { checkHierarchy(parentElement, idCollected); } } /** * Can be used in inherited classes to lock objects before processing them. The default implementation does nothing, * but calling the {@link Consumer} for each object. * @param objects the objects to lock * @param lockedObjectConsumer the consumer that should be called for each locked object */ protected void runWithLockedObject(List<MCRObjectID> objects, Consumer<MCRObjectID> lockedObjectConsumer) { objects.forEach(lockedObjectConsumer); } }
13,391
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSPagesHelper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/MCRMODSPagesHelper.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.mods; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.xpath.NodeSet; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.output.DOMOutputter; import org.mycore.common.MCRConstants; /** * Builds a mods:extent[@unit='pages'] element from text containing pages information. * For example, the input "pp. 3-4" will generate mods:start and mods:end elements. * Additionally, variants of hyphens are normalized to a unique character. * Third, incomplete end page numbers are completed, e.g. S. 3845 - 53 will result in * mods:end=3853. * * @author Frank Lützenkirchen **/ public class MCRMODSPagesHelper { private static final HyphenNormalizer HYPHEN_NORMALIZER = new HyphenNormalizer(); private static final EndPageCompleter END_PAGE_COMPLETER = new EndPageCompleter(); private static final ExtentPagesBuilder EXTENT_PAGES_BUILDER = new ExtentPagesBuilder(); public static Element buildExtentPages(String input) { String normalizedInput = input.trim(); normalizedInput = HYPHEN_NORMALIZER.normalize(normalizedInput); Element extent = EXTENT_PAGES_BUILDER.buildExtent(normalizedInput); END_PAGE_COMPLETER.completeEndPage(extent); return extent; } public static NodeSet buildExtentPagesNodeSet(String input) throws JDOMException { Element extent = buildExtentPages(input); org.w3c.dom.Element domElement = new DOMOutputter().output(extent); NodeSet nodeSet = new NodeSet(); nodeSet.addNode(domElement); return nodeSet; } } /** * Normalizes the different variants of hyphens in a given input text to a simple "minus" character. * * @author Frank Lützenkirchen **/ class HyphenNormalizer { private static final char HYPHEN_NORM = '-'; private char[] hyphenVariants = { '\u002D', '\u2010', '\u2011', '\u2012', '\u2013', '\u2015', '\u2212', '\u2E3B', '\uFE58', '\uFE63', }; String normalize(String input) { String normalizedInput = input; for (char hypenVariant : hyphenVariants) { normalizedInput = normalizedInput.replace(hypenVariant, HYPHEN_NORM); } return normalizedInput; } } /** * When start and end page are given, often only the differing prefix of the end page number is specified, e.g. * "3845 - 53" meaning end page is 3853. This class completes the value of mods:end if start and end page * are both numbers. * * @author Frank Lützenkirchen **/ class EndPageCompleter { void completeEndPage(Element extent) { String start = extent.getChildText("start", MCRConstants.MODS_NAMESPACE); String end = extent.getChildText("end", MCRConstants.MODS_NAMESPACE); if (isNumber(start) && isNumber(end) && start.length() > end.length()) { end = start.substring(0, start.length() - end.length()) + end; extent.getChild("end", MCRConstants.MODS_NAMESPACE).setText(end); } } boolean isNumber(String value) { return ((value != null) && value.matches("\\d+")); } } /** * Builds a mods:extent element containing appropriate child elements representing the same * pages information as some textual input. For example, the input "pp. 3-4" will generate mods:start and * mods:end elements. * * @author Frank Lützenkirchen **/ class ExtentPagesBuilder { private static final String OPTIONAL = "?"; private static final String ZERO_OR_MORE = "*"; private static final String ONE_OR_MORE = "+"; private static final String NUMBER = "([0-9]+)"; private static final String PAGENR = "([a-zA-Z0-9\\.]+)"; private static final String SPACE = "\\s"; private static final String SPACES = SPACE + ONE_OR_MORE; private static final String SPACES_OPTIONAL = SPACE + ZERO_OR_MORE; private static final String DOT = "\\."; private static final String HYPHEN = SPACES_OPTIONAL + "-" + SPACES_OPTIONAL; private static final String PAGENR_W_HYPHEN = "([a-zA-Z0-9-\\.]+)"; private static final String HYPHEN_SEPARATED = SPACES + "-" + SPACES; private static final String PAGE = "([sSp]{1,2}" + DOT + OPTIONAL + SPACES_OPTIONAL + ")" + OPTIONAL; private static final String PAGES = "(pages|[Ss]eiten|S\\.)"; private static final String FF = "(" + SPACES + "ff?\\.?)" + OPTIONAL; private List<PagesPattern> patterns = new ArrayList<>(); ExtentPagesBuilder() { PagesPattern startEnd = new PagesPattern(PAGE + PAGENR + HYPHEN + PAGENR + DOT + OPTIONAL); startEnd.addMapping("start", 2); startEnd.addMapping("end", 3); patterns.add(startEnd); PagesPattern startEndVariant = new PagesPattern( PAGE + PAGENR_W_HYPHEN + HYPHEN_SEPARATED + PAGENR_W_HYPHEN + DOT + OPTIONAL); startEndVariant.addMapping("start", 2); startEndVariant.addMapping("end", 3); patterns.add(startEndVariant); PagesPattern startTotal = new PagesPattern( PAGE + PAGENR + SPACES + "\\(" + NUMBER + SPACES_OPTIONAL + PAGES + "\\)"); startTotal.addMapping("start", 2); startTotal.addMapping("total", 3); patterns.add(startTotal); PagesPattern startOnly = new PagesPattern(PAGE + PAGENR + FF); startOnly.addMapping("start", 2); patterns.add(startOnly); PagesPattern totalOnly = new PagesPattern("\\(?" + PAGENR + SPACES + PAGES + OPTIONAL + "\\)?"); totalOnly.addMapping("total", 1); patterns.add(totalOnly); PagesPattern list = new PagesPattern("(.+)"); list.addMapping("list", 1); patterns.add(list); } /** * Builds a mods:extent element containing appropriate child elements representing the same * pages information as the textual input. For example, the input "3-4" will generate mods:start and * mods:end elements. * * @param input the textual pages information, e.g. "S. 3-4" or "p. 123 (9 pages)" */ Element buildExtent(String input) { Element extent = buildExtent(); for (PagesPattern pattern : patterns) { PagesMatcher matcher = pattern.matcher(input); if (matcher.matches()) { matcher.addMODSto(extent); break; } } return extent; } /** Builds a new mods:extent element to hold pages information */ private Element buildExtent() { Element extent = new Element("extent", MCRConstants.MODS_NAMESPACE); extent.setAttribute("unit", "pages"); return extent; } } /** * Represents a text pattern containing pages information, like start & end page, * or start and total number of pages as textual representation. Manages a mapping * between matching groups in pattern and the corresponding MODS elements, e.g. * mods:start and mods:end. * * @author Frank Lützenkirchen **/ class PagesPattern { private Pattern pattern; /** Mapping from MODS Element name to group number in the pattern */ private Map<String, Integer> mods2group = new LinkedHashMap<>(); PagesPattern(String regularExpression) { pattern = Pattern.compile(regularExpression); } /** * Add a mapping from MODS Element name to group number in the pattern. * * @param modsElement the name of the MODS element mapped, e.g. "start" * @param groupNumber number of the group in the regular expression pattern **/ void addMapping(String modsElement, int groupNumber) { mods2group.put(modsElement, groupNumber); } /** * Returns the mappings from MODS Element name to group number */ Set<Entry<String, Integer>> getMappings() { return mods2group.entrySet(); } /** * Returns a matcher for the given input text */ PagesMatcher matcher(String input) { return new PagesMatcher(this, pattern.matcher(input)); } } /** * Represents a matcher for a given input text containing pages information, * associated with a PagesPattern that possibly matches the text. * * @author Frank Lützenkirchen **/ class PagesMatcher { PagesPattern pattern; Matcher matcher; PagesMatcher(PagesPattern pattern, Matcher matcher) { this.pattern = pattern; this.matcher = matcher; } boolean matches() { return matcher.matches(); } /** * If matches(), adds MODS elements mapped to the matching groups in the pattern. * Note that matches() MUST be called first! * * @param extent the mods:extent element to add new MODS elements to */ void addMODSto(Element extent) { for (Entry<String, Integer> mapping : pattern.getMappings()) { int group = mapping.getValue(); String name = mapping.getKey(); Element mods = new Element(name, MCRConstants.MODS_NAMESPACE); String value = matcher.group(group); mods.setText(value); extent.addContent(mods); } } }
9,982
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSRelationshipType.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/MCRMODSRelationshipType.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.mods; /** * Represents all supported relatedItem type supported for metadata sharing and linking. * * @author Thomas Scheffler * @see MCRMODSMetadataShareAgent * @see MCRMODSLinksEventHandler * @since 2015.03 */ public enum MCRMODSRelationshipType { host, preceding, original, series, otherVersion, otherFormat, references, reviewOf, }
1,094
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSEmbargoReleaseCronjob.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/MCRMODSEmbargoReleaseCronjob.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.mods; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.common.params.ModifiableSolrParams; import org.jdom2.Element; import org.mycore.common.MCRSystemUserInformation; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mcr.cronjob.MCRCronjob; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.util.concurrent.MCRFixedUserCallable; /** * This Cronjob updates the embargo dates in the Database. */ public class MCRMODSEmbargoReleaseCronjob extends MCRCronjob { private static final Logger LOGGER = LogManager.getLogger(); @Override public String getDescription() { return "Embargo Object Updater"; } @Override public void runJob() { if (MCRConfiguration2.getString("MCR.Solr.ServerURL").isEmpty()) { return; } try { new MCRFixedUserCallable<>(() -> { LOGGER.info("Searching embargoed objects"); SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient(); String today = LocalDate.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_DATE); String query = "mods.embargo.date:[* TO " + today + "]"; LOGGER.info("Searching with query " + query); ModifiableSolrParams params = new ModifiableSolrParams(); params.set("start", 0); params.set("rows", 100); params.set("fl", "id"); params.set("q", query); solrClient.query(params) .getResults() .stream() .map(result -> (String) result.get("id")) .peek(id -> LOGGER.info("Found embargoed object " + id)) .forEach(this::releaseDocument); return null; }, MCRSystemUserInformation.getSuperUserInstance()).call(); } catch (Exception e) { LOGGER.error("Failed to search embargoed objects", e); } } private void releaseDocument(String id) { try { LOGGER.info("Releasing embargoed object {}", id); MCRObjectID objectID = MCRObjectID.getInstance(id); MCRObject object = MCRMetadataManager.retrieveMCRObject(objectID); MCRMODSWrapper modsWrapper = new MCRMODSWrapper(object); String embargoXPATH = "mods:accessCondition[@type='embargo']"; Optional<Element> element = Optional.ofNullable(modsWrapper.getElement(embargoXPATH)); if (element.isPresent()) { element.get().setAttribute("type", "expiredEmbargo"); MCRMetadataManager.update(object); } } catch (Exception e) { LOGGER.error("Failed to release embargoed object " + id, e); } } }
3,949
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSSorter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/MCRMODSSorter.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.mods; import java.util.Arrays; import java.util.List; import javax.xml.transform.Source; import javax.xml.transform.URIResolver; import org.jdom2.Element; import org.jdom2.transform.JDOMSource; import org.mycore.common.xml.MCRURIResolver; /** * Provides functionality to sort MODS elements to a predefined order. * The MODSSorter can be either used as URIResolver via * "sort:[...URI returning MODS...]" * or by invoking * MCRMODSSorter.sort( [JDOM Element with mods:mods] ); * * @author Frank Lützenkirchen */ public class MCRMODSSorter implements URIResolver { private static final String[] ORDER = { "genre", "typeofResource", "titleInfo", "nonSort", "subTitle", "title", "partNumber", "partName", "name", "namePart", "displayForm", "role", "affiliation", "originInfo", "place", "publisher", "dateIssued", "dateCreated", "dateModified", "dateValid", "dateOther", "edition", "issuance", "frequency", "relatedItem", "language", "physicalDescription", "abstract", "note", "subject", "classification", "location", "shelfLocator", "url", "accessCondition", "part", "extension", "recordInfo", }; private static final List<String> ORDER_LIST = Arrays.asList(ORDER); @Override public Source resolve(String href, String base) { String subHref = href.substring(href.indexOf(":") + 1); Element mods = MCRURIResolver.instance().resolve(subHref); MCRMODSSorter.sort(mods); return new JDOMSource(mods); } public static void sort(Element mods) { mods.sortChildren(MCRMODSSorter::compare); } private static int compare(Element e1, Element e2) { int pos1 = getPos(e1); int pos2 = getPos(e2); if (pos1 == pos2) { return e1.getName().compareTo(e2.getName()); } else { return pos1 - pos2; } } private static int getPos(Element e) { String name = e.getName(); return ORDER_LIST.contains(name) ? ORDER_LIST.indexOf(name) : ORDER_LIST.size(); } }
2,797
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSDistributeMetadataJobAction.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/MCRMODSDistributeMetadataJobAction.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.mods; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRException; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRSystemUserInformation; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.frontend.support.MCRObjectIDLockTable; import org.mycore.services.queuedjob.MCRJob; import org.mycore.services.queuedjob.MCRJobAction; public class MCRMODSDistributeMetadataJobAction extends MCRJobAction { public static final String OBJECT_ID_PARAMETER = "id"; private static final Logger LOGGER = LogManager.getLogger(); /** * The constructor of the job action with specific {@link MCRJob}. * * @param job the job holding the parameters for the action */ public MCRMODSDistributeMetadataJobAction(MCRJob job) { super(job); } public String getID() { return job.getParameter(OBJECT_ID_PARAMETER); } @Override public boolean isActivated() { return true; } @Override public String name() { return "Distribute Metadata of " + getID(); } @Override public void execute() { MCRSession session = MCRSessionMgr.getCurrentSession(); try { session.setUserInformation(MCRSystemUserInformation.getGuestInstance()); session.setUserInformation(MCRSystemUserInformation.getJanitorInstance()); MCRObjectID id = MCRObjectID.getInstance(getID()); MCRObject holder = MCRMetadataManager.retrieveMCRObject(id); MCRMODSWrapper holderWrapper = new MCRMODSWrapper(holder); MCRMODSMetadataShareAgent agent = new MCRMODSMetadataShareAgent() { @Override protected void runWithLockedObject(List<MCRObjectID> objects, Consumer<MCRObjectID> lockedObjectConsumer) { MCRMODSDistributeMetadataJobAction.this.runWithLockedObject(objects, lockedObjectConsumer); } }; agent.distributeInheritedMetadata(holderWrapper); agent.distributeLinkedMetadata(holderWrapper); } finally { session.setUserInformation(MCRSystemUserInformation.getGuestInstance()); session.setUserInformation(MCRSystemUserInformation.getSystemUserInstance()); } } public void runWithLockedObject(List<MCRObjectID> objects, Consumer<MCRObjectID> lockedObjectConsumer) { try { // wait to get the lock for the object int maxTries = 10; List<MCRObjectID> notLocked = new ArrayList<>(objects); do { LOGGER.info("Try to lock {} objects", notLocked.size()); objects.forEach(MCRObjectIDLockTable::lock); notLocked.removeIf(MCRObjectIDLockTable::isLockedByCurrentSession); if (!notLocked.isEmpty()) { LOGGER.info("Wait 1 minute for lock"); Thread.sleep(TimeUnit.MINUTES.toMillis(1)); } } while (!notLocked.isEmpty() && maxTries-- > 0); objects.forEach(lockedObjectConsumer); } catch (InterruptedException e) { throw new MCRException("Error while waiting for object lock", e); } finally { objects.stream().filter(MCRObjectIDLockTable::isLockedByCurrentSession) .forEach(MCRObjectIDLockTable::unlock); } } @Override public void rollback() { // nothing to do } }
4,556
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRExtractRelatedItemsEventHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/MCRExtractRelatedItemsEventHandler.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.mods; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import org.mycore.access.MCRAccessException; import org.mycore.common.MCRConstants; import org.mycore.common.MCRException; import org.mycore.common.MCRPersistenceException; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandlerBase; import org.mycore.datamodel.metadata.MCRMetaLinkID; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; /** * Extracts occurences of mods:relatedItem and stores them as separate MCRObjects. For mods:relatedItem/@type='host', * sets the extracted object as parent. Always, sets @xlink:href of mods:relatedItem to the extracted object's ID. * * @author Frank Lützenkirchen */ public class MCRExtractRelatedItemsEventHandler extends MCREventHandlerBase { private static final Logger LOGGER = LogManager.getLogger(MCRExtractRelatedItemsEventHandler.class); /* (non-Javadoc) * @see org.mycore.common.events.MCREventHandlerBase * #handleObjectCreated(org.mycore.common.events.MCREvent, org.mycore.datamodel.metadata.MCRObject) */ @Override protected void handleObjectCreated(final MCREvent evt, final MCRObject obj) { extractRelatedItems(obj); } /* (non-Javadoc) * @see org.mycore.common.events.MCREventHandlerBase * #handleObjectUpdated(org.mycore.common.events.MCREvent, org.mycore.datamodel.metadata.MCRObject) */ @Override protected void handleObjectUpdated(final MCREvent evt, final MCRObject obj) { extractRelatedItems(obj); } /* (non-Javadoc) * @see org.mycore.common.events.MCREventHandlerBase * #handleObjectRepaired(org.mycore.common.events.MCREvent, org.mycore.datamodel.metadata.MCRObject) */ @Override protected void handleObjectRepaired(final MCREvent evt, final MCRObject obj) { extractRelatedItems(obj); } private void extractRelatedItems(final MCRObject object) { if (!MCRMODSWrapper.isSupported(object)) { return; } Element mods = new MCRMODSWrapper(object).getMODS(); MCRObjectID oid = object.getId(); for (Element relatedItem : mods.getChildren("relatedItem", MCRConstants.MODS_NAMESPACE)) { String href = relatedItem.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE); LOGGER.info("Found related item in {}, href={}", object.getId(), href); //MCR-957: only create releated object if mycoreId MCRObjectID mcrIdCheck; try { mcrIdCheck = MCRObjectID.getInstance(href); } catch (Exception e) { //not a valid MCRObjectID -> don't create anyway continue; } //create if integer value == 0 if (mcrIdCheck.getNumberAsInteger() == 0) { //MCR-931: check for type='host' and present parent document if (!isHost(relatedItem) || object.getStructure().getParentID() == null) { MCRObjectID relatedID; try { relatedID = createRelatedObject(relatedItem, oid); } catch (MCRAccessException e) { throw new MCRException(e); } href = relatedID.toString(); LOGGER.info("Setting href of related item to {}", href); relatedItem.setAttribute("href", href, MCRConstants.XLINK_NAMESPACE); if (isHost(relatedItem)) { LOGGER.info("Setting {} as parent of {}", href, oid); object.getStructure().setParent(relatedID); } } } else if (isParentExists(relatedItem)) { MCRObjectID relatedID = MCRObjectID.getInstance(href); if (object.getStructure().getParentID() == null || !object.getStructure().getParentID().equals(relatedID)) { LOGGER.info("Setting {} as parent of {}", href, oid); object.getStructure().setParent(relatedID); insertChildElement(object, relatedID); } } } } private void insertChildElement(MCRObject object, MCRObjectID relatedID) { MCRObject newParent = MCRMetadataManager.retrieveMCRObject(relatedID); if (newParent.getStructure().getChildren().stream().map(MCRMetaLinkID::getXLinkHrefID) .noneMatch(object.getId()::equals)) { newParent.getStructure().addChild(new MCRMetaLinkID("child", object.getId(), null, object.getLabel())); MCRMetadataManager.fireUpdateEvent(newParent); } } private boolean isHost(Element relatedItem) { return "host".equals(relatedItem.getAttributeValue("type")); } private MCRObjectID createRelatedObject(Element relatedItem, MCRObjectID childID) throws MCRPersistenceException, MCRAccessException { MCRMODSWrapper wrapper = new MCRMODSWrapper(); MCRObject object = wrapper.getMCRObject(); MCRObjectID oid = MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(childID.getBase()); if (oid.equals(childID)) { oid = MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(childID.getBase()); } object.setId(oid); if (isHost(relatedItem)) { object.getStructure().addChild(new MCRMetaLinkID("child", childID, childID.toString(), childID.toString())); } Element mods = cloneRelatedItem(relatedItem); wrapper.setMODS(mods); LOGGER.info("create object {}", oid); MCRMetadataManager.create(object); return oid; } private Element cloneRelatedItem(Element relatedItem) { Element mods = relatedItem.clone(); mods.setName("mods"); mods.removeAttribute("type"); mods.removeAttribute("href", MCRConstants.XLINK_NAMESPACE); mods.removeAttribute("type", MCRConstants.XLINK_NAMESPACE); mods.removeChildren("part", MCRConstants.MODS_NAMESPACE); return mods; } /** * Checks if the given related item is if type host and contains a valid MCRObjectID from an existing object. * * @return true if @type='host' and MCRObjectID in @href contains is valid and this MCRObject exists */ private boolean isParentExists(Element relatedItem) { String href = relatedItem.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE); if (isHost(relatedItem) && href != null && !href.isEmpty()) { MCRObjectID relatedID = MCRObjectID.getInstance(href); return relatedID != null; } return false; } }
7,657
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSCommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/MCRMODSCommands.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.mods; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; 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.access.MCRRuleAccessInterface; import org.mycore.common.MCRConstants; import org.mycore.common.MCRException; import org.mycore.common.MCRPersistenceException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRPathContent; import org.mycore.common.xml.MCRXMLHelper; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetaClassification; import org.mycore.datamodel.metadata.MCRMetaIFS; import org.mycore.datamodel.metadata.MCRMetaLinkID; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.frontend.cli.MCRAbstractCommands; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; import org.mycore.mods.enrichment.MCREnricher; import org.mycore.mods.rss.MCRRSSFeedImporter; import org.xml.sax.SAXException; /** * @author Thomas Scheffler (yagee) * */ @MCRCommandGroup(name = "MODS Commands") public class MCRMODSCommands extends MCRAbstractCommands { public static final String MODS_V3_XSD_URI = "http://www.loc.gov/standards/mods/v3/mods-3-7.xsd"; private static final Logger LOGGER = LogManager.getLogger(MCRMODSCommands.class); @MCRCommand(syntax = "load all mods documents from directory {0} for project {1}", help = "Load all MODS documents as MyCoRe Objects for project {1} from directory {0}", order = 10) public static List<String> loadFromDirectory(String directory, String projectID) { File dir = new File(directory); if (!dir.isDirectory()) { throw new MCRException(String.format(Locale.ENGLISH, "File %s is not a directory.", directory)); } String[] list = dir.list(); if (list.length == 0) { LOGGER.warn("No files found in directory {}", dir); return null; } return Arrays.stream(list) .filter(file -> file.endsWith(".xml")) .map(file -> String.format(Locale.ENGLISH, "load mods document from file %s for project %s", new File(dir, file).getAbsolutePath(), projectID)) .collect(Collectors.toList()); } @MCRCommand(syntax = "load mods document from file {0} for project {1}", help = "Load MODS document {0} as MyCoRe Object for project {1}", order = 20) public static void loadFromFile(String modsFileName, String projectID) throws JDOMException, IOException, SAXException, MCRPersistenceException, MCRAccessException { File modsFile = new File(modsFileName); if (!modsFile.isFile()) { throw new MCRException(String.format(Locale.ENGLISH, "File %s is not a file.", modsFile.getAbsolutePath())); } MCRPathContent pathContent = new MCRPathContent(modsFile.toPath()); Document modsDoc = pathContent.asXML(); //force validation against MODS XSD MCRXMLHelper.validate(modsDoc, MODS_V3_XSD_URI); Element modsRoot = modsDoc.getRootElement(); if (!modsRoot.getNamespace().equals(MCRConstants.MODS_NAMESPACE)) { throw new MCRException( String.format(Locale.ENGLISH, "File %s is not a MODS document.", modsFile.getAbsolutePath())); } if (modsRoot.getName().equals("modsCollection")) { List<Element> modsElements = modsRoot.getChildren("mods", MCRConstants.MODS_NAMESPACE); for (Element mods : modsElements) { saveAsMyCoReObject(projectID, mods); } } else { saveAsMyCoReObject(projectID, modsRoot); } } @MCRCommand(syntax = "load mods document from file {0} with files from directory {1} for project {2}", help = "Load MODS document {0} as MyCoRe Object with files from direcory {1} for project {2}", order = 10) public static void loadFromFileWithFiles(String modsFileName, String fileDirName, String projectID) throws JDOMException, IOException, SAXException, MCRPersistenceException, MCRAccessException { File modsFile = new File(modsFileName); if (!modsFile.isFile()) { throw new MCRException(String.format(Locale.ENGLISH, "File %s is not a file.", modsFile.getAbsolutePath())); } File fileDir = new File(fileDirName); if (!fileDir.isDirectory()) { throw new MCRException( String.format(Locale.ENGLISH, "Directory %s is not a directory.", fileDir.getAbsolutePath())); } MCRPathContent pathContent = new MCRPathContent(modsFile.toPath()); Document modsDoc = pathContent.asXML(); //force validation against MODS XSD MCRXMLHelper.validate(modsDoc, MODS_V3_XSD_URI); Element modsRoot = modsDoc.getRootElement(); if (!modsRoot.getNamespace().equals(MCRConstants.MODS_NAMESPACE)) { throw new MCRException( String.format(Locale.ENGLISH, "File %s is not a MODS document.", modsFile.getAbsolutePath())); } if (modsRoot.getName().equals("modsCollection")) { throw new MCRException(String.format(Locale.ENGLISH, "File %s contains a mods collection witch not supported by this command.", modsFile.getAbsolutePath())); } else { createDerivate(saveAsMyCoReObject(projectID, modsRoot), fileDir); } } private static MCRObjectID saveAsMyCoReObject(String projectID, Element modsRoot) throws MCRPersistenceException, MCRAccessException { MCRObject mcrObject = MCRMODSWrapper.wrapMODSDocument(modsRoot, projectID); mcrObject.setId(MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(mcrObject.getId().getBase())); MCRConfiguration2.getString("MCR.MODS.Import.Object.State") .ifPresent(mcrObject.getService()::setState); MCRMetadataManager.create(mcrObject); return mcrObject.getId(); } @MCRCommand(syntax = "import publications from {0} RSS feed for project {1}", help = "Read RSS feed from data source {0}, convert and save new publications as MyCoRe Object for project {1}", order = 30) public static void importFromRSSFeed(String sourceSystemID, String projectID) throws Exception { MCRRSSFeedImporter.importFromFeed(sourceSystemID, projectID); } @MCRCommand(syntax = "enrich {0} with config {1}", help = "Enriches existing MODS metadata {0} with a given enrichment configuration {1}", order = 40) public static void enrichMods(String modsId, String configID) { try { MCRObject obj = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance(modsId)); Element mods = new MCRMODSWrapper(obj).getMODS(); MCREnricher enricher = new MCREnricher(configID); enricher.enrich(mods); MCRMetadataManager.update(obj); } catch (MCRException | MCRAccessException e) { LOGGER.error("Error while trying to enrich {} with configuration {}: ", modsId, configID, e); } } private static MCRDerivate createDerivate(MCRObjectID documentID, File fileDir) throws MCRPersistenceException, IOException, MCRAccessException { MCRDerivate derivate = new MCRDerivate(); derivate.setId(MCRMetadataManager.getMCRObjectIDGenerator() .getNextFreeId(documentID.getProjectId(), "derivate")); String schema = MCRConfiguration2.getString("MCR.Metadata.Config.derivate") .orElse("datamodel-derivate.xml") .replaceAll(".xml", ".xsd"); derivate.setSchema(schema); MCRMetaLinkID linkId = new MCRMetaLinkID(); linkId.setSubTag("linkmeta"); linkId.setReference(documentID, null, null); derivate.getDerivate().setLinkMeta(linkId); final Path rootPath = fileDir.toPath(); try (Stream<Path> streamRootPath = Files.list(rootPath)) { final Optional<String> firstRegularFile = streamRootPath.filter(Files::isRegularFile) .map(rootPath::relativize) .map(Path::toString) .findFirst(); MCRMetaIFS ifs = new MCRMetaIFS(); ifs.setSubTag("internal"); ifs.setSourcePath(fileDir.getAbsolutePath()); firstRegularFile.ifPresent(ifs::setMainDoc); derivate.getDerivate().setInternals(ifs); } MCRConfiguration2.getString("MCR.MODS.Import.Derivate.Categories") .map(MCRConfiguration2::splitValue) .ifPresent(s -> { s.map(MCRCategoryID::fromString) .forEach(categId -> derivate.getDerivate().getClassifications() .add(new MCRMetaClassification("classification", 0, null, categId))); }); LOGGER.debug("Creating new derivate with ID {}", derivate.getId()); MCRMetadataManager.create(derivate); setDefaultPermissions(derivate.getId()); return derivate; } protected static void setDefaultPermissions(MCRObjectID derivateID) { if (MCRConfiguration2.getBoolean("MCR.Access.AddDerivateDefaultRule").orElse(true) && MCRAccessManager.getAccessImpl() instanceof MCRRuleAccessInterface ruleAccess) { ruleAccess .getAccessPermissionsFromConfiguration() .forEach(p -> MCRAccessManager.addRule(derivateID, p, MCRAccessManager.getTrueRule(), "default derivate rule")); } } }
10,995
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSEmbargoUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/MCRMODSEmbargoUtils.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.mods; import java.io.IOException; import java.time.DateTimeException; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRCache; import org.mycore.common.MCRPersistenceException; import org.mycore.common.MCRSessionMgr; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandlerBase; import org.mycore.common.events.MCREventManager; import org.mycore.datamodel.common.MCRCreatorCache; import org.mycore.datamodel.common.MCRISO8601Date; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; /** * @author René Adler (eagle) * */ public class MCRMODSEmbargoUtils { public static final String POOLPRIVILEGE_EMBARGO = "embargo"; private static final Logger LOGGER = LogManager.getLogger(MCRMODSEmbargoUtils.class); private static final String EMPTY_VALUE = ""; private static final int CAPACITY = 10000; private static MCRCache<MCRObjectID, String> embargoCache = new MCRCache<>(CAPACITY, "MODS embargo filter cache"); static { MCREventManager.instance().addEventHandler(MCREvent.ObjectType.OBJECT, new MCREventHandlerBase() { @Override protected void handleObjectUpdated(MCREvent evt, MCRObject obj) { embargoCache.remove(obj.getId()); } }); } public static String getCachedEmbargo(final MCRObjectID objectId) { MCRCache.ModifiedHandle modifiedHandle = MCRXMLMetadataManager.instance().getLastModifiedHandle(objectId, 10, TimeUnit.MINUTES); String embargo = null; try { embargo = embargoCache.getIfUpToDate(objectId, modifiedHandle); } catch (IOException e) { LOGGER.warn("Could not determine last modified timestamp of object {}", objectId); } if (embargo != null) { return embargo == EMPTY_VALUE ? null : embargo; } try { MCRMODSWrapper modsWrapper = new MCRMODSWrapper(MCRMetadataManager.retrieveMCRObject(objectId)); embargo = modsWrapper.getElementValue("mods:accessCondition[@type='embargo']"); } catch (MCRPersistenceException e) { LOGGER.error(() -> "Could not read object " + objectId, e); } embargoCache.put(objectId, embargo != null ? embargo : EMPTY_VALUE); return embargo; } /** * Returns the embargo or <code>null</code> if none is set or is allowed to read. * * @param objectId the {@link MCRObjectID} * @return the embargo or <code>null</code> */ public static String getEmbargo(final String objectId) { return getEmbargo(MCRObjectID.getInstance(objectId)); } /** * Returns the embargo or <code>null</code> if none is set or is allowed to read. * * @param objectId the {@link MCRObjectID} * @return the embargo or <code>null</code> */ public static String getEmbargo(final MCRObjectID objectId) { String embargo = getCachedEmbargo(objectId); if (embargo != null && !embargo.isEmpty() && isAfterToday(embargo)) { return embargo; } return null; } public static String getEmbargo(final MCRObject object) { final MCRMODSWrapper modsWrapper = new MCRMODSWrapper(object); final String embargo = modsWrapper.getElementValue("mods:accessCondition[@type='embargo']"); if (embargo != null && !embargo.isEmpty() && isAfterToday(embargo)) { return embargo; } return null; } public static Optional<LocalDate> getEmbargoDate(final String objectID) { return parseEmbargo(getEmbargo(objectID)); } public static Optional<LocalDate> getEmbargoDate(final MCRObjectID object) { return parseEmbargo(getEmbargo(object)); } public static Optional<LocalDate> getEmbargoDate(final MCRObject object) { return parseEmbargo(getEmbargo(object)); } private static Optional<LocalDate> parseEmbargo(final String embargoDate) { final MCRISO8601Date isoED = new MCRISO8601Date(embargoDate); return Optional.ofNullable(LocalDate.from(isoED.getDt())); } public static boolean isAfterToday(final String embargoDate) { try { final Optional<LocalDate> ed = parseEmbargo(embargoDate); final LocalDate now = Instant.now().atZone(ZoneId.systemDefault()).toLocalDate(); final boolean bool = ed.map(ded -> ded.isAfter(now)).orElseGet(() -> false); return bool; } catch (DateTimeException ex) { return embargoDate.compareTo(MCRISO8601Date.now().getISOString()) > 0; } } public static boolean isCurrentUserCreator(final MCRObjectID objectId) { try { final String creator = MCRCreatorCache.getCreator(objectId); return MCRSessionMgr.getCurrentSession().getUserInformation().getUserID().equals(creator); } catch (ExecutionException e) { LOGGER.error("Error while getting creator information.", e); return false; } } }
6,210
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSLinksEventHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/MCRMODSLinksEventHandler.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.mods; import java.util.HashSet; import java.util.List; import org.jdom2.Element; import org.mycore.common.MCRConstants; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandlerBase; import org.mycore.common.events.MCREventManager; import org.mycore.datamodel.classifications2.MCRCategLinkReference; import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.common.MCRLinkTableManager; import org.mycore.datamodel.metadata.MCRMetaLinkID; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; /** * Eventhandler for linking MODS_OBJECTTYPE document to MyCoRe classifications. * * @author Thomas Scheffler (yagee) */ public class MCRMODSLinksEventHandler extends MCREventHandlerBase { public static final String INDEX_ALL_CHILDREN_PROPERTY_NAME = "MCR.MODS.LinksEventHandler.IndexAllChildren"; private static final boolean INDEX_ALL_CHILDREN = MCRConfiguration2.getBoolean(INDEX_ALL_CHILDREN_PROPERTY_NAME) .orElseThrow(() -> MCRConfiguration2.createConfigurationException(INDEX_ALL_CHILDREN_PROPERTY_NAME)); /* (non-Javadoc) * @see org.mycore.common.events.MCREventHandlerBase * #handleObjectCreated(org.mycore.common.events.MCREvent, org.mycore.datamodel.metadata.MCRObject) */ @Override protected void handleObjectCreated(final MCREvent evt, final MCRObject obj) { if (!MCRMODSWrapper.isSupported(obj)) { return; } MCRMODSWrapper modsWrapper = new MCRMODSWrapper(obj); final HashSet<MCRCategoryID> categories = new HashSet<>(modsWrapper.getMcrCategoryIDs()); if (!categories.isEmpty()) { final MCRCategLinkReference objectReference = new MCRCategLinkReference(obj.getId()); MCRCategLinkServiceFactory.getInstance().setLinks(objectReference, categories); } List<Element> linkingNodes = modsWrapper.getLinkedRelatedItems(); if (!linkingNodes.isEmpty()) { MCRLinkTableManager linkTableManager = MCRLinkTableManager.instance(); for (Element linkingNode : linkingNodes) { String targetID = linkingNode.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE); if (targetID == null) { continue; } String relationshipTypeRaw = linkingNode.getAttributeValue("type"); MCRMODSRelationshipType relType = MCRMODSRelationshipType.valueOf(relationshipTypeRaw); //MCR-1328 (no reference links for 'host') if (relType != MCRMODSRelationshipType.host) { linkTableManager.addReferenceLink(obj.getId(), MCRObjectID.getInstance(targetID), MCRLinkTableManager.ENTRY_TYPE_REFERENCE, relType.toString()); } } } } /* (non-Javadoc) * @see org.mycore.common.events.MCREventHandlerBase * #handleObjectUpdated(org.mycore.common.events.MCREvent, org.mycore.datamodel.metadata.MCRObject) */ @Override protected void handleObjectUpdated(final MCREvent evt, final MCRObject obj) { if (!MCRMODSWrapper.isSupported(obj)) { return; } handleObjectCreated(evt, obj); //may have to reindex children, if they inherit any information // TODO: remove this code, it is not part of this classes responsibility. if information is inherited, i.e. // because of a metadata share agent, that process should, in turn, cause a reindexing of affected objects if (INDEX_ALL_CHILDREN) { for (MCRMetaLinkID childLinkID : obj.getStructure().getChildren()) { MCRObjectID childID = childLinkID.getXLinkHrefID(); if (MCRMetadataManager.exists(childID)) { MCREvent childEvent = new MCREvent(MCREvent.ObjectType.OBJECT, MCREvent.EventType.INDEX); childEvent.put(MCREvent.OBJECT_KEY, MCRMetadataManager.retrieve(childID)); MCREventManager.instance().handleEvent(childEvent); } } } } /* (non-Javadoc) * @see org.mycore.common.events.MCREventHandlerBase * #handleObjectRepaired(org.mycore.common.events.MCREvent, org.mycore.datamodel.metadata.MCRObject) */ @Override protected void handleObjectRepaired(final MCREvent evt, final MCRObject obj) { handleObjectUpdated(evt, obj); } }
5,439
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSDateFormat.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/MCRMODSDateFormat.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.mods; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import org.mycore.datamodel.common.MCRISO8601Date; /** * Different supported MODS date formats. * @author Thomas Scheffler * @since 2015.03 * */ public enum MCRMODSDateFormat { iso8601("iso8601", null), w3cdtf_10("w3cdtf-10", "yyyy-MM-dd"), w3cdtf_19("w3cdtf-19", "yyyy-MM-dd'T'HH:mm:ss"), marc_4("marc-4", "yyyy"), iso8601_4("iso8601-4", "yyyy"), iso8601_7("iso8601-7", "yyyy-MM"), iso8601_8("iso8601-8", "yyyyMMdd"), iso8601_15("iso8601-15", "yyyyMMdd'T'HHmmss"), // Try to guess encoding from date length unknown_4("unknown-4", "yyyy"), unknown_8("unknown-8", "yyyyMMdd"), unknown_10("unknown-10", "yyyy-MM-dd"), unknown_19("unknown-19", "yyyy-MM-dd'T'HH:mm:ss"), unknown_15("unknown-15", "yyyyMMdd'T'HHmmss"); private static volatile Map<String, MCRMODSDateFormat> encodingToFormatMap; private final String encoding; private final String attributeValue; private final String dateFormat; final boolean dateOnly; static final TimeZone MODS_TIMEZONE = TimeZone.getTimeZone("UTC"); static final Locale DATE_LOCALE = Locale.ROOT; MCRMODSDateFormat(String encoding, String dateFormat) { this.encoding = encoding; this.attributeValue = encoding == "iso8601" ? encoding : encoding.split("-")[0]; this.dateFormat = dateFormat; this.dateOnly = dateFormat != null && !dateFormat.endsWith("ss"); //see above } public static MCRMODSDateFormat getFormat(String encoding) { if (encodingToFormatMap == null) { initMap(); } return encodingToFormatMap.get(encoding); } private static void initMap() { Map<String, MCRMODSDateFormat> encodingToFormatMap = new HashMap<>(); for (MCRMODSDateFormat f : values()) { encodingToFormatMap.put(f.encoding, f); } MCRMODSDateFormat.encodingToFormatMap = encodingToFormatMap; } public String getEncoding() { return encoding; } public boolean isDateOnly() { return dateOnly; } public String asEncodingAttributeValue() { return attributeValue; } public Date parseDate(String text) throws ParseException { if (this == iso8601) { MCRISO8601Date isoDate = new MCRISO8601Date(text); return isoDate.getDate(); } return getDateFormat().parse(text); } public String formatDate(Date date) { if (this == iso8601) { MCRISO8601Date isoDate = new MCRISO8601Date(); isoDate.setDate(date); return isoDate.getISOString(); } return getDateFormat().format(date); } public SimpleDateFormat getDateFormat() { SimpleDateFormat dateFormat = new SimpleDateFormat(this.dateFormat, MCRMODSDateFormat.DATE_LOCALE); dateFormat.setTimeZone(MCRMODSDateFormat.MODS_TIMEZONE); return dateFormat; } }
3,908
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSJobMetadataShareAgent.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/MCRMODSJobMetadataShareAgent.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.mods; import java.util.List; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRPersistenceException; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.services.queuedjob.MCRJob; import org.mycore.services.queuedjob.MCRJobDAO; import org.mycore.services.queuedjob.MCRJobQueueManager; import org.mycore.services.queuedjob.MCRJobStatus; public class MCRMODSJobMetadataShareAgent extends MCRMODSMetadataShareAgent { private static final Logger LOGGER = LogManager.getLogger(); @Override public void distributeMetadata(MCRObject holder) throws MCRPersistenceException { MCRJob job = new MCRJob(MCRMODSDistributeMetadataJobAction.class); job.setParameter(MCRMODSDistributeMetadataJobAction.OBJECT_ID_PARAMETER, holder.getId().toString()); Map<String, String> parameters = job.getParameters(); MCRJobDAO jobDAO = MCRJobQueueManager.getInstance().getJobDAO(); int count = jobDAO.getJobCount(MCRMODSDistributeMetadataJobAction.class, parameters, List.of(MCRJobStatus.NEW, MCRJobStatus.ERROR)); if (count > 0) { LOGGER.info("Job for " + holder.getId() + " already exists. Skipping."); return; } MCRJobQueueManager.getInstance().getJobQueue(MCRMODSDistributeMetadataJobAction.class).add(job); } }
2,157
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRHyphenNormalizer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/merger/MCRHyphenNormalizer.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.mods.merger; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Normalizes the different variants of hyphens in a given input text to the given character; defaults * to a simple "minus". * * @author Frank Lützenkirchen **/ public class MCRHyphenNormalizer { private static final char HYPHEN_MINUS = '\u002D'; private static final char SOFT_HYPHEN = '\u00AD'; private static final char ARMENIAN_HYPHEN = '\u058A'; private static final char HEBREW_PUNCTUATION_MAQAF = '\u05BE'; private static final char HYPHEN = '\u2010'; private static final char NON_BREAKING_HYPHEN = '\u2011'; private static final char FIGURE_DASH = '\u2012'; private static final char EN_DASH = '\u2013'; private static final char EM_DASH = '\u2014'; private static final char HORIZONTAL_BAR = '\u2015'; private static final char MINUS_SIGN = '\u2212'; private static final char TWO_EM_DASH = '\u2E3A'; private static final char THREE_EM_DASH = '\u2E3B'; private static final char SMALL_EM_DASH = '\uFE58'; private static final char SMALL_HYPHEN_MINUS = '\uFE63'; private static final char FULLWIDTH_HYPHEN_MINUS = '\uFF0D'; private static final char[] ALL_HYPHEN_VARIANTS = { HYPHEN_MINUS, SOFT_HYPHEN, ARMENIAN_HYPHEN, HEBREW_PUNCTUATION_MAQAF, HYPHEN, NON_BREAKING_HYPHEN, FIGURE_DASH, EN_DASH, EM_DASH, HORIZONTAL_BAR, MINUS_SIGN, TWO_EM_DASH, THREE_EM_DASH, SMALL_EM_DASH, SMALL_HYPHEN_MINUS, FULLWIDTH_HYPHEN_MINUS }; private static final String ALL_HYPHEN_VARIANTS_REGEX = new String(ALL_HYPHEN_VARIANTS) .chars() .mapToObj(variant -> Pattern.quote(Character.toString((char) variant))) .collect(Collectors.joining("", "[", "]")); private static final Pattern ALL_HYPHEN_VARIANTS_PATTERN = Pattern.compile(ALL_HYPHEN_VARIANTS_REGEX); /** * Normalizes the different variants of hyphens in a given input text to a simple "minus" character. **/ public String normalize(String input) { return normalizeHyphen(input); } /** * Normalizes the different variants of hyphens in a given input text to a simple "minus" character. **/ public static String normalizeHyphen(String input) { return normalizeHyphen(input, HYPHEN_MINUS); } /** * Normalizes the different variants of hyphens in a given input text to the given character. **/ public static String normalizeHyphen(String input, char replacement) { return ALL_HYPHEN_VARIANTS_PATTERN.matcher(input).replaceAll(Character.toString(replacement)); } }
3,376
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRExtentMerger.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/merger/MCRExtentMerger.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.mods.merger; import org.mycore.common.MCRConstants; /** * Compares and merges mods:extent elements. * * @author Frank Lützenkirchen */ public class MCRExtentMerger extends MCRMerger { @Override public boolean isProbablySameAs(MCRMerger other) { return (other instanceof MCRExtentMerger); } private boolean hasStartPage() { return element.getChild("start", MCRConstants.MODS_NAMESPACE) != null; } @Override public void mergeFrom(MCRMerger other) { if (element.getParentElement().getName().equals("physicalDescription")) { super.mergeFrom(other); } else { // parent is "mods:part" if ((!this.hasStartPage()) && ((MCRExtentMerger) other).hasStartPage()) { mergeAttributes(other); this.element.setContent(other.element.cloneContent()); } } } }
1,636
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMerger.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/merger/MCRMerger.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.mods.merger; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.jdom2.Attribute; import org.jdom2.Element; import org.jdom2.Namespace; import org.jdom2.filter.Filters; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.common.MCRConstants; import org.mycore.common.xml.MCRXMLHelper; /** * MCRMerger is the main and default implementation for comparing * and merging MODS elements that are semantically the same. * Each MODS element is wrapped by an instance of MCRMerger or one of its subclasses. * It contains methods to decide whether the two MODS elements are equal, or probably represent the information * maybe with different granularity. * If so, the text, elements and attributes are merged so that the "better" information/representation wins. * This is done recursively for all child elements, too. * * @author Frank Lützenkirchen */ public class MCRMerger { /** Holds the MODS namespace */ private static List<Namespace> NS = Collections.singletonList(MCRConstants.MODS_NAMESPACE); /** The MODS element wrapped and compared by this merger */ protected Element element; /** Sets the MODS element wrapped and compared by this merger */ public void setElement(Element element) { Objects.requireNonNull(element); this.element = element; } /** * Returns true, if the element wrapped by this merger probably represents the same information as the other. * The default implementation returns false and may be overwritten by subclasses implementing logic * for specific MODS elements. */ public boolean isProbablySameAs(MCRMerger other) { return false; } /** * Two mergers are equal if they wrap elements that are deep equals. */ @Override public boolean equals(Object obj) { if (obj instanceof MCRMerger other) { return sameElementName(other) && MCRXMLHelper.deepEqual(this.element, other.element); } else { return false; } } protected boolean sameElementName(MCRMerger other) { return this.element.getName().equals(other.element.getName()); } /** * Merges the contents of the element wrapped by the other merger into the contents of the element wrapped * by this merger. * Should only be called if this.isProbablySameAs(other). * * The default implementation copies all attributes from the other into this if they do not exist in this element. * Afterwards it recursively builds mergers for all child elements and compares and eventually merges them too. */ public void mergeFrom(MCRMerger other) { mergeAttributes(other); mergeElements(other); } /** * Copies those attributes from the other's element into this' element that do not exist in this' element. */ protected void mergeAttributes(MCRMerger other) { for (Attribute attribute : other.element.getAttributes()) { if (this.element.getAttribute(attribute.getName(), attribute.getNamespace()) == null) { this.element.setAttribute(attribute.clone()); } } } /** * Merges all child elements of this with that from other. * This is done by building MCRMerger instances for each child element and comparing them. */ protected void mergeElements(MCRMerger other) { List<MCRMerger> oldEntries = this.element.getChildren() .stream().map(child -> MCRMergerFactory.buildFrom(child)).collect(Collectors.toList()); List<MCRMerger> newEntries = other.element.getChildren() .stream().map(child -> MCRMergerFactory.buildFrom(child)).collect(Collectors.toList()); for (MCRMerger newEntry : newEntries) { MCRMerger matchingEntry = mergeIntoExistingEntries(oldEntries, newEntry); if (matchingEntry != null) { oldEntries.remove(matchingEntry); } } } /** * Given a list of MCRMergers which represent the current content, merges a new entry into it. * * @return the old entry that matched the given new entry, or null **/ private MCRMerger mergeIntoExistingEntries(List<MCRMerger> oldEntries, MCRMerger newEntry) { for (MCRMerger oldEntry : oldEntries) { // Only same MODS element type can be a match if (oldEntry.sameElementName(newEntry)) { if (oldEntry.equals(newEntry)) { return oldEntry; // found identical element } if (newEntry.isProbablySameAs(oldEntry)) { oldEntry.mergeFrom(newEntry); // found element to merge return oldEntry; } } } // No match found, add as new element element.addContent(newEntry.element.clone()); return null; } /** * Helper method to lookup child elements by XPath. * * @param xPath XPath expression relative to the element wrapped by this merger. * @return a list of elements matching the given XPath */ protected List<Element> getNodes(String xPath) { XPathExpression<Element> xPathExpr = XPathFactory.instance().compile(xPath, Filters.element(), null, NS); return xPathExpr.evaluate(element); } }
6,197
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUniqueTypeMerger.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/merger/MCRUniqueTypeMerger.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.mods.merger; /** * Merges MODS elements that must occur only once per type. * So if they have the same name and the same type attribute value, * they are regarded to represent the same information. * * @author Frank Lützenkirchen */ public class MCRUniqueTypeMerger extends MCRMerger { private String getType() { return this.element.getAttributeValue("type", ""); } @Override public boolean isProbablySameAs(MCRMerger other) { if (!sameElementName(other)) { return false; } return other instanceof MCRUniqueTypeMerger typeMerger && this.getType().equals(typeMerger.getType()); } }
1,401
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIdentifierMerger.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/merger/MCRIdentifierMerger.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.mods.merger; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.Locale; /** * Compares and merges mods:identifier elements. * Two identifiers are assumed to be the same when they are equals, neglecting any hyphens. * At merge, the identifier containing hyphens wins, because it is regarded prettier ;-) * * @author Frank Lützenkirchen */ public class MCRIdentifierMerger extends MCRMerger { private String getType() { return this.element.getAttributeValue("type", ""); } private String getSimplifiedID() { return URLDecoder.decode(this.element.getTextNormalize().toLowerCase(Locale.ENGLISH), StandardCharsets.UTF_8) .replace("-", ""); } @Override public boolean isProbablySameAs(MCRMerger other) { if (!(other instanceof MCRIdentifierMerger oid)) { return false; } return this.getType().equals(oid.getType()) && this.getSimplifiedID().equals(oid.getSimplifiedID()); } @Override public void mergeFrom(MCRMerger other) { if (!this.element.getText().contains("-") && other.element.getText().contains("-")) { this.element.setText(other.element.getText()); } } }
1,998
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUniqueMerger.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/merger/MCRUniqueMerger.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.mods.merger; /** * Merges those MODS elements that must occur only oncy at a given level. * So if the elements have the same name, they are regarded to prepresent the same information. * * @author Frank Lützenkirchen */ public class MCRUniqueMerger extends MCRMerger { @Override public boolean isProbablySameAs(MCRMerger other) { return (other.element.getName().equals(this.element.getName())); } }
1,173
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCategoryMerger.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/merger/MCRCategoryMerger.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.mods.merger; import java.util.ArrayList; import java.util.List; import org.mycore.common.config.MCRConfiguration2; 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.mods.classification.MCRClassMapper; /** * Merges MODS elements that represent a classification category. * * When those elements represent two categories A and B, * and B is a child of A in the classification tree, * B should win and be regarded the more detailed information, * while A should be ignored. * * When property * MCR.MODS.Merger.CategoryMerger.Repeatable.[ClassID]=false * is set, there can be only one category for this classification, * so the first element that occurs wins. * Default is "true", meaning the classification is repeatable. * * @author Frank Lützenkirchen */ public class MCRCategoryMerger extends MCRMerger { private static final MCRCategoryDAO DAO = MCRCategoryDAOFactory.getInstance(); private static final String CONFIG_PREFIX = "MCR.MODS.Merger.CategoryMerger.Repeatable."; @Override public boolean isProbablySameAs(MCRMerger other) { if (!(other instanceof MCRCategoryMerger cmOther)) { return false; } if (!MCRClassMapper.supportsClassification(this.element) || !MCRClassMapper.supportsClassification(cmOther.element)) { return false; } MCRCategoryID idThis = MCRClassMapper.getCategoryID(this.element); MCRCategoryID idOther = MCRClassMapper.getCategoryID(cmOther.element); if (idThis == null || idOther == null) { return false; } if (idThis.getRootID().equals(idOther.getRootID()) && !isRepeatable(idThis)) { return true; } return idThis.equals(idOther) || oneIsDescendantOfTheOther(idThis, idOther); } private boolean isRepeatable(MCRCategoryID id) { String p = CONFIG_PREFIX + id.getRootID(); return MCRConfiguration2.getBoolean(p).orElse(true); } static boolean oneIsDescendantOfTheOther(MCRCategoryID idThis, MCRCategoryID idOther) { List<MCRCategory> ancestorsAndSelfOfThis = getAncestorsAndSelf(idThis); List<MCRCategory> ancestorsAndSelfOfOther = getAncestorsAndSelf(idOther); return ancestorsAndSelfOfThis.containsAll(ancestorsAndSelfOfOther) || ancestorsAndSelfOfOther.containsAll(ancestorsAndSelfOfThis); } private static List<MCRCategory> getAncestorsAndSelf(MCRCategoryID categoryID) { List<MCRCategory> ancestorsAndSelf = new ArrayList<>(DAO.getParents(categoryID)); ancestorsAndSelf.remove(DAO.getRootCategory(categoryID, 0)); ancestorsAndSelf.add(DAO.getCategory(categoryID, 0)); return ancestorsAndSelf; } @Override public void mergeFrom(MCRMerger other) { MCRCategoryMerger cmo = (MCRCategoryMerger) other; MCRCategoryID idThis = MCRClassMapper.getCategoryID(this.element); MCRCategoryID idOther = MCRClassMapper.getCategoryID(cmo.element); if (idThis.equals(idOther)) { return; } if (getAncestorsAndSelf(idOther).containsAll(getAncestorsAndSelf(idThis))) { MCRClassMapper.assignCategory(this.element, idOther); } } }
4,211
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMergeTool.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/merger/MCRMergeTool.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.mods.merger; import org.jdom2.Element; /** * Provides a convenience method to merge one MODS element into another. * * @author Frank Lützenkirchen */ public class MCRMergeTool { /** * Merges a given MODS element with another. * * @param modsToMergeInto the MODS element that will be modified by merging data into it * @param modsToMergeFrom the MODS element that contains the data to merge from */ public static void merge(Element modsToMergeInto, Element modsToMergeFrom) { MCRMerger mBaseToMergeInto = MCRMergerFactory.buildFrom(modsToMergeInto); MCRMerger mToMergeFrom = MCRMergerFactory.buildFrom(modsToMergeFrom); mBaseToMergeInto.mergeFrom(mToMergeFrom); } }
1,480
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAbstractMerger.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/merger/MCRAbstractMerger.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.mods.merger; import org.apache.commons.text.similarity.LevenshteinDistance; import org.jdom2.Element; import org.mycore.common.MCRConstants; import org.mycore.common.config.MCRConfiguration2; /** * Compares and merges mods:abstract elements. The abstract text is normalized before comparing. * Two abstracts are regarded probably same * if their levenshtein distance is less than a configured percentage of the text length. * * MCR.MODS.Merger.AbstractMerger.MaxDistancePercent=[Maximum levenshtein distance in percent] * MCR.MODS.Merger.AbstractMerger.MaxCompareLength=[Maximum number of characters to compare from the two abstracts] * * @author Frank Lützenkirchen */ public class MCRAbstractMerger extends MCRMerger { /** Maximum Levenshtein distance to accept two abstracts as equal, in percent */ private static final int MAX_DISTANCE_PERCENT = MCRConfiguration2 .getOrThrow("MCR.MODS.Merger.AbstractMerger.MaxDistancePercent", Integer::parseInt); /** Maximum number of characters to compare from two abstracts */ private static final int MAX_COMPARE_LENGTH = MCRConfiguration2 .getOrThrow("MCR.MODS.Merger.AbstractMerger.MaxCompareLength", Integer::parseInt); private String text; public void setElement(Element element) { super.setElement(element); text = MCRTextNormalizer.normalizeText(element.getText()); text += element.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE, ""); text = text.substring(0, Math.min(text.length(), MAX_COMPARE_LENGTH)); } /** * Two abstracts are regarded probably same * if their levenshtein distance is less than a configured percentage of the text length. */ @Override public boolean isProbablySameAs(MCRMerger other) { if (!(other instanceof MCRAbstractMerger)) { return false; } String textOther = ((MCRAbstractMerger) other).text; int length = Math.min(text.length(), textOther.length()); if (length == 0) { return false; } int distance = LevenshteinDistance.getDefaultInstance().apply(text, textOther); return (distance * 100 / length) < MAX_DISTANCE_PERCENT; } }
2,976
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRNameMerger.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/merger/MCRNameMerger.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.mods.merger; import java.text.Normalizer; import java.text.Normalizer.Form; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Map; import java.util.Set; import org.jdom2.Element; import org.mycore.common.MCRConstants; /** * Compares and merges mods:name elements * * @author Frank Lützenkirchen */ public class MCRNameMerger extends MCRMerger { private String familyName; private Set<String> givenNames = new HashSet<>(); private Set<String> initials = new HashSet<>(); private Set<String> allNames = new HashSet<>(); private Map<String,Set<String>> nameIds = new HashMap<String,Set<String>>(); public void setElement(Element element) { super.setElement(element); setFromNameParts(element); if (familyName == null) { setFromDisplayForm(element); } collectNameIds(element); } private void setFromDisplayForm(Element element) { String displayForm = element.getChildTextTrim("displayForm", MCRConstants.MODS_NAMESPACE); if (displayForm != null) { setFromCombinedName(displayForm.replaceAll("\\s+", " ")); } } private void setFromNameParts(Element modsName) { for (Element namePart : modsName.getChildren("namePart", MCRConstants.MODS_NAMESPACE)) { String type = namePart.getAttributeValue("type"); String nameFragment = namePart.getText().replaceAll("\\p{Zs}+", " "); if (Objects.equals(type, "family")) { setFamilyName(nameFragment); } else if (Objects.equals(type, "given")) { addGivenNames(nameFragment); addInitials(nameFragment); allNames.addAll(initials); } else if (Objects.equals(type, "date")) { continue; } else if (Objects.equals(type, "termsOfAddress")) { continue; } else if ("personal".equals(modsName.getAttributeValue("type"))) { setFromCombinedName(nameFragment); } else { setFamilyName(nameFragment); } } } private void setFromCombinedName(String nameFragment) { if (isEmptyOrNull(nameFragment)) { return; } if (nameFragment.contains(",")) { String[] parts = nameFragment.split(","); setFamilyNameAndRest(parts[0].trim(), parts[1].trim()); } else if (nameFragment.contains(" ")) { int pos = nameFragment.lastIndexOf(' '); setFamilyNameAndRest(nameFragment.substring(pos), nameFragment.substring(0, pos)); } else { setFamilyName(nameFragment); } } private void setFamilyNameAndRest(String familyName, String rest) { setFamilyName(familyName); addGivenNames(rest); addInitials(rest); allNames.addAll(initials); } private void setFamilyName(String nameFragment) { if (isEmptyOrNull(nameFragment)) { return; } this.familyName = normalize(nameFragment); allNames.add(normalize(nameFragment)); } private void addGivenNames(String nameFragment) { if (isEmptyOrNull(nameFragment)) { return; } for (String token : nameFragment.split("\\s")) { String normalizedToken = normalize(token); if (normalizedToken.length() > 1 && !isEmptyOrNull(normalizedToken)) { givenNames.add(normalizedToken); allNames.add(normalizedToken); } } } private void addInitials(String nameFragment) { if (isEmptyOrNull(nameFragment)) { return; } for (String token : nameFragment.split("\\s")) { String normalizedToken = normalize(token); if (!isEmptyOrNull(normalizedToken)) { initials.add(normalizedToken.substring(0, 1)); } } } private boolean isEmptyOrNull(String nameFragment) { return nameFragment == null || normalize(nameFragment).isEmpty(); } private String normalize(String nameFragment) { String text = nameFragment.toLowerCase(Locale.getDefault()); text = MCRHyphenNormalizer.normalizeHyphen(text, ' '); // canonical decomposition, then remove accents text = Normalizer.normalize(text, Form.NFD).replaceAll("\\p{M}", ""); text = text.replace("ue", "u").replace("oe", "o").replace("ae", "a").replace("ß", "s").replace("ss", "s"); text = text.replaceAll("[^a-z0-9]\\s]", ""); //remove all non-alphabetic characters text = text.replaceAll("\\p{Punct}", " ").trim(); // remove all punctuation text = text.replaceAll("\\s+", " "); // normalize whitespace return text.trim(); } @Override public boolean isProbablySameAs(MCRMerger e) { if (!(e instanceof MCRNameMerger other)) { return false; } if (haveContradictingNameIds(this.nameIds, other.nameIds)) { return false; } else if (this.allNames.equals(other.allNames)) { return true; } else if (!Objects.equals(familyName, other.familyName)) { return false; } else if (initials.isEmpty() && other.initials.isEmpty()) { return true; // same family name, no given name, no initals, then assumed same } else if (!haveAtLeastOneCommon(this.initials, other.initials)) { return false; } else if (this.givenNames.isEmpty() || other.givenNames.isEmpty()) { return true; } else { return haveAtLeastOneCommon(this.givenNames, other.givenNames); } } private boolean haveAtLeastOneCommon(Set<String> a, Set<String> b) { Set<String> intersection = new HashSet<>(a); intersection.retainAll(b); return !intersection.isEmpty(); } private boolean haveContradictingNameIds(Map<String, Set<String>> a, Map<String, Set<String>> b) { Set<String> intersection = null; boolean foundContradictingNameIds = false; for (String type : a.keySet()) { intersection = new HashSet<>(a.get(type)); if(b.get(type) != null) { intersection.retainAll(b.get(type)); if(!intersection.isEmpty()) { return false; } else { foundContradictingNameIds = true; } } } return foundContradictingNameIds; } private void collectNameIds(Element modsName) { for (Element nameId : modsName.getChildren("nameIdentifier", MCRConstants.MODS_NAMESPACE)) { String type = nameId.getAttributeValue("type"); String id = nameId.getText(); Set<String> ids = null; if(nameIds.containsKey(type)) { ids = nameIds.get(type); } else { ids = new HashSet<String>(); } ids.add(id); nameIds.put(type, ids); } } public String toString() { StringBuilder sb = new StringBuilder(familyName); sb.append('|'); for (String givenName : givenNames) { sb.append(givenName).append(','); } if (!givenNames.isEmpty()) { sb.setLength(sb.length() - 1); } sb.append('|'); for (String initial : initials) { sb.append(initial).append(','); } if (!initials.isEmpty()) { sb.setLength(sb.length() - 1); } return sb.toString(); } @Override public void mergeFrom(MCRMerger other) { super.mergeFrom(other); // if there is family name after merge, prefer that and remove untyped name part if (!getNodes("mods:namePart[@type='family']").isEmpty()) { List<Element> namePartsWithoutType = getNodes("mods:namePart[not(@type)]"); if (!namePartsWithoutType.isEmpty()) { namePartsWithoutType.get(0).detach(); } } } }
8,956
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTitleInfoMerger.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/merger/MCRTitleInfoMerger.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.mods.merger; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jdom2.Element; import org.mycore.common.MCRConstants; /** * Compares and merges mods:titleInfo elements. * The normalized combined text of mods:nonSort, mods:title and mods:subTitle is compared. * Two titles are probably same if they are identical or one is prefix of the other. * When merging, the title that has a subtitle or the longer one wins. * * @author Frank Lützenkirchen */ public class MCRTitleInfoMerger extends MCRMerger { private String originalText; private String normalizedText; public void setElement(Element element) { super.setElement(element); originalText = Stream.of(textOf("nonSort"), textOf("title"), textOf("subTitle")) .filter(s -> !s.isEmpty()).collect(Collectors.joining(" ")); normalizedText = MCRTextNormalizer.normalizeText(originalText); } private String getType() { return this.element.getAttributeValue("type", ""); } @Override public boolean isProbablySameAs(MCRMerger other) { if (!(other instanceof MCRTitleInfoMerger otherTitle)) { return false; } if (!this.getType().equals(((MCRTitleInfoMerger) other).getType())) { return false; } if (normalizedText.equals(otherTitle.normalizedText)) { return true; } return normalizedText.startsWith(otherTitle.normalizedText) || otherTitle.normalizedText.startsWith(normalizedText); } public void mergeFrom(MCRMerger other) { mergeAttributes(other); MCRTitleInfoMerger otherTitle = (MCRTitleInfoMerger) other; boolean weHaveSubTitleOtherHasNot = !textOf("subTitle").isEmpty() && otherTitle.textOf("subTitle").isEmpty(); boolean otherHasSubTitleAndWeNot = textOf("subTitle").isEmpty() && !otherTitle.textOf("subTitle").isEmpty(); boolean otherTitleIsLonger = otherTitle.originalText.length() > this.originalText.length(); if (!weHaveSubTitleOtherHasNot && (otherHasSubTitleAndWeNot || otherTitleIsLonger)) { this.element.setContent(other.element.cloneContent()); } } private String textOf(String childName) { String text = element.getChildText(childName, MCRConstants.MODS_NAMESPACE); return text == null ? "" : text.trim(); } }
3,159
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTextNormalizer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/merger/MCRTextNormalizer.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.mods.merger; import java.text.Normalizer; import java.text.Normalizer.Form; import java.util.Locale; import org.apache.commons.lang3.StringUtils; import org.mycore.common.xml.MCRXMLFunctions; /** * Normalizes text to be fault-tolerant when matching for duplicates. * Accents, umlauts, case are normalized. Punctuation and non-alphabetic/non-digit characters are removed. * * @author Frank Lützenkirchen */ public class MCRTextNormalizer { private static final char LATIN_SMALL_LETTER_SHARP_S = '\u00DF'; private static final char LATIN_SMALL_LIGATURE_FF = '\uFB00'; private static final char LATIN_SMALL_LIGATURE_FFI = '\uFB03'; private static final char LATIN_SMALL_LIGATURE_FFL = '\uFB04'; private static final char LATIN_SMALL_LIGATURE_FI = '\uFB01'; private static final char LATIN_SMALL_LIGATURE_FL = '\uFB02'; private static final char LATIN_SMALL_LIGATURE_IJ = '\u0133'; private static final char LATIN_SMALL_LIGATURE_ST = '\uFB06'; private static final char LATIN_SMALL_LIGATURE_LONG_ST = '\uFB05'; /** * Normalizes text to be fault-tolerant when matching for duplicates. * Accents, umlauts, case are normalized. Punctuation and non-alphabetic/non-digit characters are removed. **/ public String normalize(String text) { return normalizeText(text); } /** * Normalizes text to be fault-tolerant when matching for duplicates. * Accents, umlauts, case are normalized. Punctuation and non-alphabetic/non-digit characters are removed. **/ public static String normalizeText(String text) { String normalizedText = text; if(MCRXMLFunctions.isHtml(normalizedText)) { normalizedText = MCRXMLFunctions.stripHtml(normalizedText); } // make lowercase normalizedText = normalizedText.toLowerCase(Locale.getDefault()); // replace all hyphen-like characters with a single space normalizedText = MCRHyphenNormalizer.normalizeHyphen(normalizedText, ' '); // canonical decomposition normalizedText = Normalizer.normalize(normalizedText, Form.NFD); // strip accents normalizedText = StringUtils.stripAccents(normalizedText); // replace sharp s and double s with normal s normalizedText = normalizedText.replace(Character.toString(LATIN_SMALL_LETTER_SHARP_S), "s"); normalizedText = normalizedText.replace("ss", "s"); // decompose ligatures normalizedText = normalizedText.replace(Character.toString(LATIN_SMALL_LIGATURE_FF), "ff"); normalizedText = normalizedText.replace(Character.toString(LATIN_SMALL_LIGATURE_FFI), "ffi"); normalizedText = normalizedText.replace(Character.toString(LATIN_SMALL_LIGATURE_FFL), "ffl"); normalizedText = normalizedText.replace(Character.toString(LATIN_SMALL_LIGATURE_FI), "fi"); normalizedText = normalizedText.replace(Character.toString(LATIN_SMALL_LIGATURE_FL), "fl"); normalizedText = normalizedText.replace(Character.toString(LATIN_SMALL_LIGATURE_IJ), "ij"); normalizedText = normalizedText.replace(Character.toString(LATIN_SMALL_LIGATURE_ST), "st"); normalizedText = normalizedText.replace(Character.toString(LATIN_SMALL_LIGATURE_LONG_ST), "st"); // remove all non-alphabetic/non-digit characters normalizedText = normalizedText.replaceAll("[^\\p{Alpha}\\p{Digit}\\p{Space}]", " "); // replace all sequences of space-like characters with a single space normalizedText = normalizedText.replaceAll("\\p{Space}+", " "); // remove leading and trailing spaces normalizedText = normalizedText.trim(); return normalizedText; } }
4,486
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMergerFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/merger/MCRMergerFactory.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.mods.merger; import org.jdom2.Element; import org.mycore.common.config.MCRConfiguration2; /** * Builds appropriate MCRMerger instances for a given MODS XML element. * Since MODS elements need to be compared and merged differently, the factory returns * different merger implementations for different element types. * * MCR.MODS.Merger.default=[Default class to merge MODS, typically MCRMerger] * MCR.MODS.Merger.[elementName]=[Specific implementation by element name] * * @author Frank Lützenkirchen */ public class MCRMergerFactory { /** * Returns an MCRMerger instance usable for merging MODS elements with the given name */ private static MCRMerger getEntryInstance(String name) { String prefix = "MCR.MODS.Merger."; String defaultClass = MCRConfiguration2.getStringOrThrow(prefix + "default"); return MCRConfiguration2.<MCRMerger>getInstanceOf(prefix + name) .orElseGet(() -> MCRConfiguration2.instantiateClass(defaultClass)); } /** * Returns an MCRMerger instance usable to merge the given MODS element. */ public static MCRMerger buildFrom(Element element) { String name = element.getName(); MCRMerger entry = getEntryInstance(name); entry.setElement(element); return entry; } }
2,057
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRelatedItemMerger.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/merger/MCRRelatedItemMerger.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.mods.merger; /** * Compares and merges mods:relatedItem elements. * Two related items are only probably same * if they are of type "host", since there can only be one host per publication. * * @author Frank Lützenkirchen */ public class MCRRelatedItemMerger extends MCRMerger { @Override public boolean isProbablySameAs(MCRMerger other) { return other instanceof MCRRelatedItemMerger relatedItemMerger && isRelatedItemTypeHost() && relatedItemMerger.isRelatedItemTypeHost(); } private boolean isRelatedItemTypeHost() { return "host".equals(element.getAttributeValue("type")); } }
1,396
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDataSource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/enrichment/MCRDataSource.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.mods.enrichment; import java.util.ArrayList; import java.util.List; /** * A data source is able to return publication data in MODS format * for a given publication identifier. A data source may support more than * one identifier, e.g. DOI and PubMed ID for PubMed as a data source: * * MCR.MODS.EnrichmentResolver.DataSource.PubMed.IdentifierTypes=doi pubmed * * For each supported identifier type, the data source has a resolver URI * that returns MODS data for that identifier type. * * Depending on the global configuration property * MCR.MODS.EnrichmentResolver.DefaultStopOnFirstResult=true|false * a data source will stop retrieving data after any first identifier * returned valid data, or will continue to retrieve data for all identifiers * it is configured for. * * This global configuration can be overwritten per data source, e.g. * MCR.MODS.EnrichmentResolver.DataSource.ZDB.StopOnFirstResult=false * * @see MCRIdentifierResolver * * @author Frank Lützenkirchen */ class MCRDataSource { private String sourceID; private boolean stopOnFirstResult = true; private List<MCRIdentifierResolver> resolvers = new ArrayList<>(); MCRDataSource(String sourceID, boolean stopOnFirstResult) { this.sourceID = sourceID; this.stopOnFirstResult = stopOnFirstResult; } boolean shouldStopOnFirstResult() { return stopOnFirstResult; } void addResolver(MCRIdentifierResolver resolver) { resolvers.add(resolver); } /** Returns all resolvers to get publication data for a given identifier */ List<MCRIdentifierResolver> getResolvers() { return resolvers; } String getID() { return sourceID; } public String toString() { return "data source " + sourceID; } }
2,560
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDataSourceCall.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/enrichment/MCRDataSourceCall.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.mods.enrichment; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; /** * Used to request publication data from a given data source, * trying the identifiers supported by this data source one by one. * * Depending on the configuration properties * MCR.MODS.EnrichmentResolver.DefaultStopOnFirstResult=true|false * and * MCR.MODS.EnrichmentResolver.DataSource.[ID].StopOnFirstResult=true|false * the data source will stop trying to resolve publication data after * the first successful call with a given identifier and skip others, * or will try to retrieve data for all given identifiers. * * @see MCRDataSource * * @author Frank Lützenkirchen */ class MCRDataSourceCall implements Callable<Boolean> { private static final Logger LOGGER = LogManager.getLogger(MCRDataSourceCall.class); private MCRDataSource ds; private MCRIdentifierPool idPool; private List<Element> results = new ArrayList<>(); private boolean gotResults = false; MCRDataSourceCall(MCRDataSource ds, MCRIdentifierPool idPool) { this.ds = ds; this.idPool = idPool; } /** * Used to request publication data from a given data source, * trying the identifiers supported by this data source one by one. * * @return true, if the data source returned valid publication data */ public Boolean call() { if (!isFinished()) { loop: for (MCRIdentifierResolver idResolver : ds.getResolvers()) { for (MCRIdentifier id : idPool.getCurrentIdentifiersOfType(idResolver.getType())) { if (isFinished()) { break loop; } LOGGER.debug(ds + " with " + id + " starting call..."); Element result = idResolver.resolve(id.getValue()); if (result != null) { gotResults = true; results.add(result); idPool.addIdentifiersFrom(result); } LOGGER.info(ds + " with " + id + " returned " + (result != null ? "" : "no ") + "valid data"); } } } return wasSuccessful(); } boolean wasSuccessful() { return gotResults; } private boolean isFinished() { return ds.shouldStopOnFirstResult() && wasSuccessful(); } List<Element> getResults() { return results; } void clearResults() { results.clear(); } }
3,423
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIdentifierResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/enrichment/MCRIdentifierResolver.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.mods.enrichment; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.MessageFormat; import java.util.Locale; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.Element; import org.mycore.common.xml.MCRURIResolver; import org.mycore.common.xml.MCRXMLHelper; import org.mycore.mods.MCRMODSCommands; import org.xml.sax.SAXException; /** * Returns publication data in MODS format for a given identifier. * Each resolver belongs to a certain data source, e.g. the data source * "PubMed" may have two resolves to get publication data by DOI or PubMed artice ID. * * The resolver will use an URI to get the publication data. * MCR.MODS.EnrichmentResolver.DataSource.[SourceID].[TypeID].URI=[URI] * * This is typically a HTTP URL followed by a XSL stylesheet to transform the * source format to MODS, e.g. * MCR.MODS.EnrichmentResolver.DataSource.DataCite.doi.URI=xslStyle:datacite2mods:https://data.datacite.org/application/vnd.datacite.datacite+xml/{0} * * Within the URI, the pattern {0} will be replaced by the given identifier value, * optionally the pattern {1} will be replaced by the value uri-encoded as http request parameter * * @author Frank Lützenkirchen */ class MCRIdentifierResolver { private static final Logger LOGGER = LogManager.getLogger(MCRIdentifierResolver.class); private MCRDataSource ds; private MCRIdentifierType idType; private String uriPattern; MCRIdentifierResolver(MCRDataSource ds, MCRIdentifierType idType, String uriPattern) { this.ds = ds; this.idType = idType; this.uriPattern = uriPattern; } MCRIdentifierType getType() { return idType; } /** * Tries to resolve publication data for the given identifier. * * @param identifier the identifier's value, e.g. a DOI or ISBN * @return the publication data in MODS format, or null if the data source did not return data for this identifier */ Element resolve(String identifier) { Object[] params = new Object[] { identifier, URLEncoder.encode(identifier, StandardCharsets.UTF_8) }; String uri = new MessageFormat(uriPattern, Locale.ROOT).format(params); Element resolved = null; try { resolved = MCRURIResolver.instance().resolve(uri); } catch (Exception ex) { LOGGER.warn("Exception resolving " + uri, ex); return null; } // Normalize various error/not found cases if (resolved == null || !"mods".equals(resolved.getName()) || resolved.getChildren().isEmpty()) { LOGGER.warn(ds + " returned none or empty MODS for " + idType + " " + identifier); return null; } try { ensureIsValidMODS(resolved); return resolved; } catch (Exception ex) { LOGGER.warn(ds + " returned invalid MODS for " + identifier + ": " + ex.getMessage(), ex); return null; } } void ensureIsValidMODS(Element mods) throws SAXException, IOException { MCRXMLHelper.validate(new Document().addContent(mods.detach()), MCRMODSCommands.MODS_V3_XSD_URI); } }
4,034
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCREnricher.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/enrichment/MCREnricher.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.mods.enrichment; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.StringTokenizer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import org.jdom2.filter.Filters; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.common.MCRConstants; import org.mycore.common.config.MCRConfiguration2; import org.mycore.mods.MCRMODSSorter; import org.mycore.mods.merger.MCRMergeTool; import org.mycore.util.concurrent.MCRTransactionableCallable; /** * Enriches a given MODS publication * by retrieving publication data from external data sources * and merging that data into the existing data. * * There may be different configurations for the enrichment process. * Each configuration has a unique ID and determines * the selection of data sources to query and the order and priority of merging. * * MCR.MODS.EnrichmentResolver.DataSources.[ConfigID]=[DataSourceID] [DataSourceID] [DataSourceID]... * e.g. * MCR.MODS.EnrichmentResolver.DataSources.import=(Scopus PubMed IEEE CrossRef DataCite) OADOI (LOBID GBV SWB) ZDB * * All data sources that support one of the identifiers present in the publication are queried. * * Depending on the configuration properties * MCR.MODS.EnrichmentResolver.DefaultStopOnFirstResult=true|false * and * MCR.MODS.EnrichmentResolver.DataSource.[ID].StopOnFirstResult=true|false * the data source will stop trying to resolve publication data after * the first successful call with a given identifier and skip others, * or will try to retrieve data for all given identifiers. * * Should a data source return new, additional identifiers, * other data sources that support these identifiers will be tried again. * * The enrichment takes place on each publication level, * that means also the host (e.g. journal or book the article is published in) * and series level is enriched with external data. * * The order of the data source IDs in configuration determines the order of merging the publication data. * If some data sources are grouped using braces, merging is skipped after the first successful data source. * For example, when * * MCR.MODS.EnrichmentResolver.DataSources.sample=A (B C) D * * all four data sources are queried until all returned data or all identifiers have been tried. * Afterwards, the data returned from A is merged into the original data. * Next, if B returned data, the data of B is merged and the data of C will be ignored. * If B did not return data and C returned data, the data of C is merged. * At the end, the data of D is merged. * So building groups of data sources with braces can be used to express data source priority. * * @see MCRDataSource * * @author Frank Lützenkirchen */ public class MCREnricher { private static final Logger LOGGER = LogManager.getLogger(MCREnricher.class); private static final String XPATH_HOST_SERIES = "mods:relatedItem[@type='host' or @type='series']"; private static final String DELIMITERS = " ()"; private XPathExpression<Element> xPath2FindNestedObjects; private String dsConfig; private MCRIdentifierPool idPool = new MCRIdentifierPool(); private Map<String, MCRDataSourceCall> id2call; private MCREnrichmentDebugger debugger = new MCRNoOpEnrichmentDebugger(); public MCREnricher(String configID) { xPath2FindNestedObjects = XPathFactory.instance().compile(XPATH_HOST_SERIES, Filters.element(), null, MCRConstants.getStandardNamespaces()); dsConfig = MCRConfiguration2.getStringOrThrow("MCR.MODS.EnrichmentResolver.DataSources." + configID); } public void setDebugger(MCREnrichmentDebugger debugger) { this.debugger = debugger; } public synchronized void enrich(Element publication) { debugger.debugPublication("before", publication); id2call = prepareDataSourceCalls(); idPool.addIdentifiersFrom(publication); while (idPool.hasNewIdentifiers()) { debugger.startIteration(); debugger.debugNewIdentifiers(idPool.getNewIdentifiers()); idPool.prepareNextIteration(); resolveExternalData(); mergeNewIdentifiers(publication); mergeExternalData(publication); MCRMODSSorter.sort(publication); debugger.endIteration(); } for (Element nestedObject : xPath2FindNestedObjects.evaluate(publication)) { enrich(nestedObject); } } private void mergeNewIdentifiers(Element publication) { idPool.getNewIdentifiers().forEach(id -> id.mergeInto(publication)); } private Map<String, MCRDataSourceCall> prepareDataSourceCalls() { id2call = new HashMap<>(); for (StringTokenizer st = new StringTokenizer(dsConfig, DELIMITERS, false); st.hasMoreTokens();) { String dataSourceID = st.nextToken(); MCRDataSource dataSource = MCRDataSourceFactory.instance().getDataSource(dataSourceID); MCRDataSourceCall call = new MCRDataSourceCall(dataSource, idPool); id2call.put(dataSourceID, call); } return id2call; } private void resolveExternalData() { Collection<MCRTransactionableCallable<Boolean>> calls = id2call.values() .stream() .map(MCRTransactionableCallable::new) .collect(Collectors.toList()); ExecutorService executor = Executors.newFixedThreadPool(calls.size()); try { executor.invokeAll(calls); } catch (InterruptedException ex) { LOGGER.warn(ex); } finally { executor.shutdown(); } } private void mergeExternalData(Element publication) { boolean withinGroup = false; for (StringTokenizer st = new StringTokenizer(dsConfig, DELIMITERS, true); st.hasMoreTokens();) { String token = st.nextToken(DELIMITERS).trim(); if (token.isEmpty()) { continue; } else if (Objects.equals(token, "(")) { withinGroup = true; } else if (Objects.equals(token, ")")) { withinGroup = false; } else { MCRDataSourceCall call = id2call.get(token); if (call.wasSuccessful()) { call.getResults().forEach(result -> { LOGGER.info("merging data from " + token); merge(publication, result); debugger.debugResolved(token, result); debugger.debugPublication("afterMerge", publication); }); call.clearResults(); if (withinGroup) { st.nextToken(")"); // skip forward to end of group withinGroup = false; } } } } } static void merge(Element publication, Element toMergeWith) { if (publication.getName().equals("relatedItem")) { // resolved is always mods:mods, transform to mods:relatedItem to be mergeable toMergeWith.setName("relatedItem"); toMergeWith.setAttribute(publication.getAttribute("type").clone()); } MCRMergeTool.merge(publication, toMergeWith); } }
8,321
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCREnrichmentDebugger.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/enrichment/MCREnrichmentDebugger.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.mods.enrichment; import java.util.Set; import org.jdom2.Element; /** * Allows debugging enrichment resolving steps. * * @see MCREnricher#setDebugger(MCREnrichmentDebugger) * * @author Frank Lützenkirchen */ public interface MCREnrichmentDebugger { void startIteration(); void endIteration(); void debugPublication(String label, Element publication); void debugNewIdentifiers(Set<MCRIdentifier> ids); void debugResolved(String token, Element result); }
1,235
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIdentifierPool.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/enrichment/MCRIdentifierPool.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.mods.enrichment; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; /** * Tracks all identifiers found in a given publication. * Each resolving and merge step may add new identifiers * returned by data sources. For example, * the publication may initially only have a PubMed ID, * but after resolving that ID the data source may have returned * the DOI of the publication. So we keep a list to distinguish * newly found identifiers from already known and resolved identifiers. * * @author Frank Lützenkirchen */ class MCRIdentifierPool { private static final Logger LOGGER = LogManager.getLogger(); /** Set of already known identifiers resolved in the last round */ private Set<MCRIdentifier> oldIdentifiers = new HashSet<>(); /** Set of currently processed identifiers */ private Set<MCRIdentifier> currentIdentifiers = new HashSet<>(); /** Set of new identifiers returned with data from external sources in the current resolving round */ private Set<MCRIdentifier> newIdentifiers = new HashSet<>(); /** Add all new identifiers that can be found in the given MODS object */ synchronized void addIdentifiersFrom(Element object) { for (MCRIdentifierType type : MCRIdentifierTypeFactory.instance().getTypes()) { newIdentifiers.addAll(type.getIdentifiers(object)); } newIdentifiers.removeAll(currentIdentifiers); newIdentifiers.removeAll(oldIdentifiers); } /** Remember all currently known identifiers, mark them as "old" **/ void prepareNextIteration() { currentIdentifiers.clear(); currentIdentifiers.addAll(newIdentifiers); oldIdentifiers.addAll(newIdentifiers); newIdentifiers.clear(); } boolean hasNewIdentifiers() { for (MCRIdentifier id : newIdentifiers) { LOGGER.info("new identifier " + id); } return !newIdentifiers.isEmpty(); } Set<MCRIdentifier> getNewIdentifiers() { return newIdentifiers; } List<MCRIdentifier> getCurrentIdentifiersOfType(MCRIdentifierType type) { return currentIdentifiers.stream().filter(id -> id.getType().equals(type)).collect(Collectors.toList()); } }
3,125
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDataSourceFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/enrichment/MCRDataSourceFactory.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.mods.enrichment; import org.mycore.common.MCRCache; import org.mycore.common.config.MCRConfiguration2; /** * Builds and caches all data sources as configured in mycore.properties. * * For each data source, the types of identifiers must be configured: * MCR.MODS.EnrichmentResolver.DataSource.[ID].IdentifierTypes=[TYPE] [TYPE] [TYPE] * e.g. * MCR.MODS.EnrichmentResolver.DataSource.PubMed.IdentifierTypes=doi pubmed * * Per data source, for each identifier type, there must be a pattern configured * that defines the URI to get the data for this type of identifier * * @see MCRIdentifierResolver * * As a global parameter, or per data source, it can be configured whether * the data source will stop after the first successful call, or retrieve all data * for all identifiers. * * @see MCRDataSource * * @author Frank Lützenkirchen */ class MCRDataSourceFactory { private static final String CONFIG_PREFIX = "MCR.MODS.EnrichmentResolver."; private static MCRDataSourceFactory INSTANCE = new MCRDataSourceFactory(); private MCRCache<String, MCRDataSource> dataSources = new MCRCache<>(30, "data sources"); private Boolean defaultStopOnFirstResult; static MCRDataSourceFactory instance() { return INSTANCE; } private MCRDataSourceFactory() { String cfgProperty = CONFIG_PREFIX + "DefaultStopOnFirstResult"; defaultStopOnFirstResult = MCRConfiguration2.getBoolean(cfgProperty).orElse(Boolean.TRUE); } private MCRDataSource buildDataSource(String sourceID) { String configPrefix = CONFIG_PREFIX + "DataSource." + sourceID + "."; String modeProperty = configPrefix + "StopOnFirstResult"; boolean stopOnFirstResult = MCRConfiguration2.getBoolean(modeProperty).orElse(defaultStopOnFirstResult); MCRDataSource dataSource = new MCRDataSource(sourceID, stopOnFirstResult); String typesProperty = configPrefix + "IdentifierTypes"; String[] identifierTypes = MCRConfiguration2.getStringOrThrow(typesProperty).split("\\s"); for (String typeID : identifierTypes) { String property = configPrefix + typeID + ".URI"; String uri = MCRConfiguration2.getStringOrThrow(property); MCRIdentifierType idType = MCRIdentifierTypeFactory.instance().getType(typeID); MCRIdentifierResolver resolver = new MCRIdentifierResolver(dataSource, idType, uri); dataSource.addResolver(resolver); } return dataSource; } MCRDataSource getDataSource(String sourceID) { MCRDataSource dataSource = dataSources.get(sourceID); if (dataSource == null) { dataSource = buildDataSource(sourceID); dataSources.put(sourceID, dataSource); } return dataSource; } }
3,556
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRNoOpEnrichmentDebugger.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/enrichment/MCRNoOpEnrichmentDebugger.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.mods.enrichment; import java.util.Set; import org.jdom2.Element; /** * Default debugger for enrichment process. Does nothing. * * @see MCREnricher#setDebugger(MCREnrichmentDebugger) * * @author Frank Lützenkirchen */ public class MCRNoOpEnrichmentDebugger implements MCREnrichmentDebugger { public void startIteration() { // Do nothing here } public void endIteration() { // Do nothing here } public void debugPublication(String label, Element publication) { // Do nothing here } public void debugNewIdentifiers(Set<MCRIdentifier> ids) { // Do nothing here } public void debugResolved(String token, Element result) { // Do nothing here } }
1,483
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIdentifierType.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/enrichment/MCRIdentifierType.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.mods.enrichment; import java.util.List; import java.util.stream.Collectors; import org.jdom2.Element; import org.jdom2.filter.Filters; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.common.MCRConstants; /** * Represents a type of publication identifier, like DOI or ISBN. * Each type has a corresponding XPath expression * used to locate or build identifiers of this type within MODS. * * If the corresponding XPath representation is * mods:identifier[@type='TYPE'], no explicit configuration is needed. * * Otherwise, the XPath must be configured, e.g. * MCR.MODS.EnrichmentResolver.IdentifierType.shelfmark=mods:location/mods:shelfLocator * * @author Frank Lützenkirchen */ public class MCRIdentifierType { private String typeID; private String xPath; private XPathExpression<Element> xPathExpr; MCRIdentifierType(String typeID, String xPath) { this.typeID = typeID; this.xPath = xPath; this.xPathExpr = XPathFactory.instance().compile(xPath, Filters.element(), null, MCRConstants.getStandardNamespaces()); } public String getTypeID() { return typeID; } public String getXPath() { return xPath; } /** Returns all identifiers of this type found in the given MODS element. */ List<MCRIdentifier> getIdentifiers(Element mods) { return xPathExpr.evaluate(mods).stream() .map(e -> new MCRIdentifier(this, e.getTextTrim())) .collect(Collectors.toList()); } @Override public String toString() { return "identifier type " + typeID; } }
2,400
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIdentifierTypeFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/enrichment/MCRIdentifierTypeFactory.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.mods.enrichment; import java.util.Collection; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.mycore.common.config.MCRConfiguration2; /** * Builds identifiers types as configured in mycore.properties. * * If the corresponding XPath representation is * mods:identifier[@type='TYPE'], no explicit configuration is needed. * * Otherwise, the XPath must be configured, e.g. * MCR.MODS.EnrichmentResolver.IdentifierType.shelfmark=mods:location/mods:shelfLocator * * @author Frank Lützenkirchen */ class MCRIdentifierTypeFactory { private static String DEFAULT_XPATH = "mods:identifier[@type=\"%s\"]"; private static MCRIdentifierTypeFactory INSTANCE = new MCRIdentifierTypeFactory(); private Map<String, MCRIdentifierType> id2type = new HashMap<>(); static MCRIdentifierTypeFactory instance() { return INSTANCE; } private MCRIdentifierTypeFactory() { } private MCRIdentifierType buildIdentifierType(String typeID) { String configProperty = "MCR.MODS.EnrichmentResolver.IdentifierType." + typeID; String defaultXPath = String.format(Locale.ROOT, DEFAULT_XPATH, typeID); String xPath = MCRConfiguration2.getString(configProperty).orElse(defaultXPath); return new MCRIdentifierType(typeID, xPath); } /** Returns the identifier type with the given ID, e.g. DOI or ISBN */ MCRIdentifierType getType(String typeID) { MCRIdentifierType type = id2type.get(typeID); if (type == null) { type = buildIdentifierType(typeID); id2type.put(typeID, type); } return type; } /** Returns all identifier types used or configured so far */ Collection<MCRIdentifierType> getTypes() { return id2type.values(); } }
2,554
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIdentifier.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/enrichment/MCRIdentifier.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.mods.enrichment; import org.jaxen.JaxenException; import org.jdom2.Element; import org.mycore.common.MCRException; import org.mycore.common.xml.MCRNodeBuilder; /** * Represents a publication's identifier like DOI or ISBN * * @author Frank Lützenkirchen */ public class MCRIdentifier { private MCRIdentifierType type; private String value; MCRIdentifier(MCRIdentifierType type, String value) { this.type = type; this.value = value; } public MCRIdentifierType getType() { return type; } public String getValue() { return value; } @Override public boolean equals(Object other) { return (other instanceof MCRIdentifier && this.toString().equals(other.toString())); } @Override public int hashCode() { return toString().hashCode(); } @Override public String toString() { return type.getTypeID() + " " + value; } /** * Builds the XML representation of this identifier within MODS. */ void mergeInto(Element publication) { Element container = new Element(publication.getName(), publication.getNamespace()); try { new MCRNodeBuilder().buildElement(type.getXPath(), value, container); } catch (JaxenException ex) { throw new MCRException(ex); } MCREnricher.merge(publication, container); } }
2,155
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRToXMLEnrichmentDebugger.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/enrichment/MCRToXMLEnrichmentDebugger.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.mods.enrichment; import java.util.Set; import org.jdom2.Element; /** * Allows debugging enrichment resolving steps. * Writes debug output to an XML element. * Run enrich() on the resolver, * afterwards call getDebugXML() on this debugger. * * @see MCREnricher#setDebugger(MCREnrichmentDebugger) * @see MCRToXMLEnrichmentDebugger#getDebugXML() * * @author Frank Lützenkirchen */ public class MCRToXMLEnrichmentDebugger implements MCREnrichmentDebugger { Element debugElement = new Element("debugEnrichment"); public void startIteration() { Element enrichmentIteration = new Element("enrichmentIteration"); debugElement.addContent(enrichmentIteration); debugElement = enrichmentIteration; } public void endIteration() { debugElement = debugElement.getParentElement(); } public void debugPublication(String label, Element publication) { debugElement.addContent(new Element(label).addContent(publication.clone())); } public void debugNewIdentifiers(Set<MCRIdentifier> ids) { Element e = new Element("newIdentifiersFound"); ids.forEach(id -> id.mergeInto(e)); debugElement.addContent(e); } public void debugResolved(String dataSourceID, Element result) { Element resolved = new Element("resolved").setAttribute("from", dataSourceID); debugElement.addContent(resolved); resolved.addContent(result.clone()); } public Element getDebugXML() { return debugElement; } }
2,277
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCREnrichmentResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/enrichment/MCREnrichmentResolver.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.mods.enrichment; import javax.xml.transform.Source; import javax.xml.transform.URIResolver; import org.jdom2.Element; import org.jdom2.transform.JDOMSource; import org.mycore.common.xml.MCRURIResolver; /** * Retrieves a publication as MODS XML from a given URI and * enriches publication data using external data sources. * * There may be different configurations for the enrichment process. * Syntax: * enrich:[ConfigID]:[URIReturningExistingMODS] * * To start with just an identifier, use the "buildxml" resolver, e.g. * enrich:import:buildxml:_rootName_=mods:mods&amp;mods:identifier=10.123/456&amp;mods:identifier/@type=doi * This first builds an empty MODS document with just a DOI identifier, * then enriches it using the "import" configuration of MCREnricher. * * For further details, * @see MCREnricher * * @author Frank Lützenkirchen */ public class MCREnrichmentResolver implements URIResolver { @Override public Source resolve(String href, String base) { href = href.substring(href.indexOf(":") + 1); String configID = href.substring(0, href.indexOf(':')); href = href.substring(href.indexOf(":") + 1); Element mods = MCRURIResolver.instance().resolve(href); enrichPublication(mods, configID); return new JDOMSource(mods); } public void enrichPublication(Element mods, String configID) { MCREnricher enricher = new MCREnricher(configID); enricher.enrich(mods); } }
2,231
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSPURLMetadataService.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/identifier/MCRMODSPURLMetadataService.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.mods.identifier; public class MCRMODSPURLMetadataService extends MCRAbstractMODSMetadataService { @Override protected String getIdentifierType() { return "purl"; } }
933
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRURLIdentifierDetector.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/identifier/MCRURLIdentifierDetector.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.mods.identifier; import java.net.URI; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; public class MCRURLIdentifierDetector implements MCRIdentifierDetector<URI> { private Set<MCRIdentifierDetector<URI>> normalizers = new HashSet<>(); public MCRURLIdentifierDetector(Collection<MCRIdentifierDetector<URI>> normalizers) { this.normalizers.addAll(normalizers); } public MCRURLIdentifierDetector() { } public void addDetector(MCRIdentifierDetector<URI> identifierDetector) { normalizers.add(identifierDetector); } public void removeDetector(MCRIdentifierDetector<URI> identifierDetector) { normalizers.remove(identifierDetector); } @Override public Optional<Map.Entry<String, String>> detect(URI resolvable) { return this.normalizers.stream() .map(detector -> detector.detect(resolvable)) .filter(Optional::isPresent) .map(Optional::get) .findFirst(); } }
1,815
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAbstractMODSMetadataService.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/identifier/MCRAbstractMODSMetadataService.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.mods.identifier; import java.util.Optional; import org.jdom2.Element; import org.mycore.common.MCRConstants; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.mods.MCRMODSWrapper; import org.mycore.pi.MCRPIManager; import org.mycore.pi.MCRPIMetadataService; import org.mycore.pi.MCRPersistentIdentifier; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; /** * Base class for all ModsMetadataServices. Basically in mods just the type is different, which will be resolved from * {@link #getIdentifierType()}. * <p> * This MetadataService has two parameters: * <dl> * <dt>Prefix</dt> * <dd>Will be passed to starts-with() as seconds parameter when the PI is read from the mods document. * So it ensures that only the right pi is read. E.g. if only DOI which start with the prefix 10.5072</dd> * <dt>Type</dt> * <dd>The type will be used in the mods:identifier@type attribute and it will be used to resolve the parser. * See: {@link MCRPIManager#getParserForType}</dd> * </dl> */ public class MCRAbstractMODSMetadataService extends MCRPIMetadataService<MCRPersistentIdentifier> { public static final String PREFIX_PROPERTY_KEY = "Prefix"; @Override public void insertIdentifier(MCRPersistentIdentifier identifier, MCRBase base, String additional) throws MCRPersistentIdentifierException { MCRObject object = checkObject(base); MCRMODSWrapper wrapper = new MCRMODSWrapper(object); Element identifierElement = wrapper.getElement(getXPath()); final String type = getIdentifierType(); if (identifierElement != null) { throw new MCRPersistentIdentifierException( type + " with prefix " + getProperties().get(PREFIX_PROPERTY_KEY) + " already exist!"); } identifierElement = new Element("identifier", MCRConstants.MODS_NAMESPACE); identifierElement.setAttribute("type", type); identifierElement.setText(identifier.asString()); wrapper.addElement(identifierElement); } protected MCRObject checkObject(MCRBase base) throws MCRPersistentIdentifierException { if (base instanceof MCRObject object) { return object; } throw new MCRPersistentIdentifierException(getClass().getName() + " does only support MyCoReObjects!"); } @Override public void removeIdentifier(MCRPersistentIdentifier identifier, MCRBase obj, String additional) { // not supported } @Override public Optional<MCRPersistentIdentifier> getIdentifier(MCRBase base, String additional) throws MCRPersistentIdentifierException { MCRObject object = checkObject(base); MCRMODSWrapper wrapper = new MCRMODSWrapper(object); final String xPath = getXPath(); Element element = wrapper.getElement(xPath); if (element == null) { return Optional.empty(); } String text = element.getTextNormalize(); return MCRPIManager.getInstance().getParserForType(getIdentifierType()) .parse(text) .map(MCRPersistentIdentifier.class::cast); } protected String getIdentifierType() { return getProperties().get("Type"); } protected String getXPath() { StringBuilder xPathBuilder = new StringBuilder(); xPathBuilder.append("mods:identifier[@type='").append(getIdentifierType()).append('\''); if (getProperties().containsKey(PREFIX_PROPERTY_KEY)) { String[] prefixes = getProperties().get(PREFIX_PROPERTY_KEY).split(","); if (prefixes.length != 0) { xPathBuilder.append(" and (starts-with(text(), '").append(prefixes[0]).append("')"); for (int i = 1; i < prefixes.length; i++) { xPathBuilder.append(" or starts-with(text(), '").append(prefixes[i]).append("')"); } xPathBuilder.append(')'); } } xPathBuilder.append(']'); return xPathBuilder.toString(); } }
4,842
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIdentifierDetector.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/identifier/MCRIdentifierDetector.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.mods.identifier; import java.util.Map; import java.util.Optional; /** * Identifies identifiers in specific sources. E.g. T=URL could Detect the <b>GND <i>118948032</i></b> in a URL like <a href="http://d-nb.info/gnd/118948032">http://d-nb.info/gnd/118948032</a>. */ public interface MCRIdentifierDetector<T> { /** * @param resolvable some thing that can be resolved to a unique identifier * @return a {@link java.util.Map.Entry} with the identifier type as key and the identifier as value. * The Optional can be empty if no identifier can be detected or if a error occurs. */ Optional<Map.Entry<String, String>> detect(T resolvable); }
1,414
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSDOIMetadataService.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/identifier/MCRMODSDOIMetadataService.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.mods.identifier; public class MCRMODSDOIMetadataService extends MCRAbstractMODSMetadataService { @Override protected String getIdentifierType() { return "doi"; } }
931
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRGBVURLDetector.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/identifier/MCRGBVURLDetector.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.mods.identifier; import java.net.URI; import java.util.AbstractMap; import java.util.Map; import java.util.Optional; import java.util.regex.Pattern; /** * This Detector normalizes <a href="http://uri.gbv.de/document/gvk:ppn:834532662">http://uri.gbv.de/document/gvk:ppn:834532662</a> to URI <a href="gvk:ppn:834532662">gvk:ppn:834532662</a>. * <p> * TODO: maybe detect other identifier then ppn */ public class MCRGBVURLDetector implements MCRIdentifierDetector<URI> { public static final String GBV_PREFIX = "uri.gbv.de/document/"; public static final String GVK_PREFIX = "gso.gbv.de/DB=2.1/PPNSET?PPN="; @Override public Optional<Map.Entry<String, String>> detect(URI resolvable) { String urlString = resolvable.toString(); // case http://uri.gbv.de/document/ if (urlString.contains(GBV_PREFIX)) { String[] strings = urlString.split(GBV_PREFIX, 2); if (strings.length == 2) { String ppnIdentifier = strings[1]; String[] ppnValues = ppnIdentifier.split(":"); // format is $catalog:ppn:$ppn if (ppnValues.length == 3 && ppnValues[1].equals("ppn")) { return Optional.of(new AbstractMap.SimpleEntry<>("ppn", ppnIdentifier)); } } } if (urlString.contains(GVK_PREFIX)) { String[] strings = urlString.split(Pattern.quote(GVK_PREFIX), 2); if (strings.length == 2) { String gvkPPN = strings[1]; return Optional.of(new AbstractMap.SimpleEntry<>("ppn", "gvk:ppn:" + gvkPPN)); } } return Optional.empty(); } }
2,422
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSURNMetadataService.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/identifier/MCRMODSURNMetadataService.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.mods.identifier; public class MCRMODSURNMetadataService extends MCRAbstractMODSMetadataService { @Override protected String getIdentifierType() { return "urn"; } }
932
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRModsItemDataProvider.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/csl/MCRModsItemDataProvider.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.mods.csl; import static org.mycore.common.MCRConstants.MODS_NAMESPACE; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; 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.common.config.MCRConfiguration2; import org.mycore.common.content.MCRContent; import org.mycore.csl.MCRItemDataProvider; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.mods.MCRMODSWrapper; import org.mycore.mods.classification.MCRClassMapper; import de.undercouch.citeproc.csl.CSLDateBuilder; import de.undercouch.citeproc.csl.CSLItemData; import de.undercouch.citeproc.csl.CSLItemDataBuilder; import de.undercouch.citeproc.csl.CSLName; import de.undercouch.citeproc.csl.CSLNameBuilder; import de.undercouch.citeproc.csl.CSLType; import de.undercouch.citeproc.helper.json.JsonBuilder; import de.undercouch.citeproc.helper.json.StringJsonBuilderFactory; public class MCRModsItemDataProvider extends MCRItemDataProvider { private static final Logger LOGGER = LogManager.getLogger(); private static final String NON_DROPPING_PARTICLE = "nonDroppingParticle"; private static final String DROPPING_PARTICLE = "droppingParticle"; public static final String USABLE_TITLE_XPATH = "mods:titleInfo[not(@altFormat) and (not(@xlink:type)" + " or @xlink:type='simple')]"; public static final String SHORT_TITLE_XPATH = "mods:titleInfo[not(@altFormat) and (not(@xlink:type)" + " or @xlink:type='simple') and @type='abbreviated']"; public static final String MODS_RELATED_ITEM_XPATH = "mods:relatedItem/"; public static final String MODS_ORIGIN_INFO_PUBLICATION = "mods:originInfo[@eventType='publication' or not" + "(@eventType)]"; public static final String NONE_TYPE = "none"; public static final String URN_RESOLVER_LINK = "https://nbn-resolving.org/"; private static final Set<String> KNOWN_UNMAPPED_PERSON_ROLES = MCRConfiguration2 .getString("MCR.CSL.KnownUnmappedPersonRoles") .stream() .flatMap(str -> Stream.of(str.split(","))) .collect(Collectors.toUnmodifiableSet()); private MCRMODSWrapper wrapper; private String id; private final Set<String> nonDroppingParticles = MCRConfiguration2.getString("MCR.CSL.NonDroppingParticles") .stream() .flatMap(str -> Stream.of(str.split(","))) .collect(Collectors.toSet()); private final Set<String> droppingParticles = MCRConfiguration2.getString("MCR.CSL.DroppingParticles") .stream() .flatMap(str -> Stream.of(str.split(","))) .collect(Collectors.toSet()); private static Stream<String> getModsElementTextStream(Element element, String elementName) { return element.getChildren(elementName, MODS_NAMESPACE) .stream() .map(Element::getTextNormalize); } @Override public CSLItemData retrieveItem(String id) { final CSLItemDataBuilder idb = new CSLItemDataBuilder().id(id); processMyCoReId(id, idb); processURL(id, idb); processGenre(idb); processTitles(idb); processLanguage(idb); processNames(idb); processIdentifier(idb); processPublicationData(idb); processAbstract(idb); processModsPart(idb); processSubject(idb); CSLItemData build = idb.build(); if (LOGGER.isDebugEnabled()) { JsonBuilder jsonBuilder = new StringJsonBuilderFactory().createJsonBuilder(); String str = (String) build.toJson(jsonBuilder); LOGGER.debug("Created json object: {}", str); } return build; } private void processMyCoReId(String id, CSLItemDataBuilder idb) { idb.citationKey(id); } private void processSubject(CSLItemDataBuilder idb) { final String keyword = wrapper.getElements("mods:subject/mods:topic") .stream() .map(Element::getTextNormalize) .collect(Collectors.joining(", ")); if (keyword.length() > 0) { idb.keyword(keyword); } } protected void processLanguage(CSLItemDataBuilder idb) { Optional.ofNullable( wrapper.getElement("mods:language/mods:languageTerm[@authority='rfc5646' or @authority='rfc4646']")) .or(() -> Optional.ofNullable(wrapper.getElement(MODS_RELATED_ITEM_XPATH + "mods:language/mods:languageTerm[@authority='rfc5646' or @authority='rfc4646']"))) .ifPresent(el -> idb.language(el.getTextNormalize())); } protected void processURL(String id, CSLItemDataBuilder idb) { // use 1. urn 2. mods:location/mods:url 3. receive if there is a fulltext 4. url of parent Optional.ofNullable(wrapper.getElement("mods:identifier[@type='urn']")) .map(Element::getTextNormalize) .map((urn) -> URN_RESOLVER_LINK + urn) .or(() -> Optional.ofNullable(wrapper.getElement("mods:location/mods:url")) .map(Element::getTextNormalize)) .or(() -> Optional.of(MCRFrontendUtil.getBaseURL() + "receive/" + id) .filter(url -> this.wrapper.getMCRObject().getStructure().getDerivates().size() > 0)) .or(() -> Optional.ofNullable(wrapper.getElement("mods:relatedItem[@type='host']/mods:location/mods:url")) .map(Element::getTextNormalize)) .ifPresent(idb::URL); } protected void processModsPart(CSLItemDataBuilder idb) { String issueVolumeXP = "mods:relatedItem/mods:part[count(mods:detail[@type='issue' or @type='volume'" + " or @type='article_number'])>0]"; final Optional<Element> parentPartOpt = Optional.ofNullable(wrapper.getElement(issueVolumeXP)) .or(() -> Optional.ofNullable(wrapper.getElement(".//" + issueVolumeXP))); parentPartOpt.ifPresent((modsPartElement) -> { final List<Element> detailElements = modsPartElement.getChildren("detail", MODS_NAMESPACE); for (Element detailElement : detailElements) { final String type = detailElement.getAttributeValue("type"); final Element num = detailElement.getChild("number", MODS_NAMESPACE); if (num != null) { Consumer<String> strFN = null; Consumer<Integer> intFn = null; switch (type) { case "issue" -> { strFN = idb::issue; intFn = idb::issue; } case "volume" -> { strFN = idb::volume; intFn = idb::volume; } case "article_number" -> { intFn = idb::number; strFN = idb::number; } default -> LOGGER.warn("Unknown type " + type + " in mods:detail in " + this.id); } try { if (intFn != null) { intFn.accept(Integer.parseInt(num.getTextNormalize())); } } catch (NumberFormatException nfe) { /* if(strFN!=null){ java compiler: always true :O */ strFN.accept(num.getTextNormalize()); //} } } } }); final Element modsExtentElement = wrapper .getElement("mods:relatedItem[@type='host']/mods:part/mods:extent[@unit='pages']"); if (modsExtentElement != null) { final String start = modsExtentElement.getChildTextNormalize("start", MODS_NAMESPACE); final String end = modsExtentElement.getChildTextNormalize("end", MODS_NAMESPACE); final String list = modsExtentElement.getChildTextNormalize("list", MODS_NAMESPACE); final String total = modsExtentElement.getChildTextNormalize("total", MODS_NAMESPACE); if (list != null) { idb.page(list); } else if (start != null && end != null && start.matches("\\d+") && end.matches("\\d+")) { idb.page(Integer.parseInt(start) , Integer.parseInt(end)); } else if (start != null && end != null) { idb.page(start + "-" + end); } else if (start != null && total != null) { idb.page(start); try { final int startI = Integer.parseInt(start); final int totalI = Integer.parseInt(total); idb.page(startI, (totalI - startI)); } catch (NumberFormatException e) { idb.page(start); } idb.numberOfPages(total); } else if (start != null) { idb.page(start); } else if (end != null) { idb.page(end); } } } protected void processGenre(CSLItemDataBuilder idb) { final List<Element> elements = wrapper.getElements("mods:genre"); final Set<String> genres = elements.stream() .map(this::getGenreStringFromElement) .filter(Objects::nonNull) .collect(Collectors.toSet()); final List<Element> parentElements = wrapper.getElements("mods:relatedItem[@type='host']/mods:genre"); final Set<String> parentGenres = parentElements.stream() .map(this::getGenreStringFromElement) .filter(Objects::nonNull) .collect(Collectors.toSet()); if (genres.contains("article")) { if (parentGenres.contains("journal")) { idb.type(CSLType.ARTICLE_JOURNAL); } else if (parentGenres.contains("newspaper")) { idb.type(CSLType.ARTICLE_NEWSPAPER); } else { idb.type(CSLType.ARTICLE); } } else if (genres.contains("book") || genres.contains("proceedings") || genres.contains("collection") || genres.contains("festschrift") || genres.contains("lexicon") || genres.contains("monograph") || genres.contains("lecture")) { idb.type(CSLType.BOOK); } else if (genres.contains("interview")) { idb.type(CSLType.INTERVIEW); } else if (genres.contains("research_data")) { idb.type(CSLType.DATASET); } else if (genres.contains("patent")) { idb.type(CSLType.PATENT); } else if (genres.contains("chapter") || genres.contains("contribution")) { idb.type(CSLType.CHAPTER); } else if (genres.contains("entry")) { idb.type(CSLType.ENTRY_ENCYCLOPEDIA); } else if (genres.contains("preface")) { idb.type(CSLType.ARTICLE); } else if (genres.contains("speech") || genres.contains("poster")) { idb.type(CSLType.SPEECH); } else if (genres.contains("video")) { idb.type(CSLType.MOTION_PICTURE); } else if (genres.contains("broadcasting")) { idb.type(CSLType.BROADCAST); } else if (genres.contains("picture")) { idb.type(CSLType.GRAPHIC); } else if (genres.contains("review")) { idb.type(CSLType.REVIEW); if (parentGenres.contains("book")) { idb.type(CSLType.REVIEW_BOOK); } } else if (genres.contains("thesis") || genres.contains("exam") || genres.contains("dissertation") || genres.contains("habilitation") || genres.contains("diploma_thesis") || genres.contains("master_thesis") || genres.contains("bachelor_thesis") || genres.contains("student_research_project") || genres.contains("magister_thesis")) { idb.type(CSLType.THESIS); } else if (genres.contains("report") || genres.contains("research_results") || genres.contains("in_house") || genres.contains("press_release") || genres.contains("declaration")) { idb.type(CSLType.REPORT); /* } else if (genres.contains("teaching_material") || genres.contains("lecture_resource") || genres.contains("course_resources")) { // TODO: find right mapping } else if (genres.contains("series")) { // TODO: find right mapping } else if (genres.contains("journal")) { // TODO: find right mapping } else if (genres.contains("newspaper")) { // TODO: find right mapping */ } else { idb.type(CSLType.ARTICLE); } } protected String getGenreStringFromElement(Element genre) { if (genre.getAttributeValue("authorityURI") != null) { MCRCategoryID categoryID = MCRClassMapper.getCategoryID(genre); if (categoryID == null) { return null; } return categoryID.getId(); } else { return genre.getText(); } } protected void processAbstract(CSLItemDataBuilder idb) { Optional.ofNullable(wrapper.getElement("mods:abstract[not(@altFormat)]")) .map(Element::getTextNormalize) .ifPresent(idb::abstrct); } protected void processPublicationData(CSLItemDataBuilder idb) { Optional.ofNullable(wrapper.getElement(MODS_ORIGIN_INFO_PUBLICATION + "/mods:place/mods:placeTerm")) .or(() -> Optional.ofNullable(wrapper.getElement(MODS_RELATED_ITEM_XPATH + MODS_ORIGIN_INFO_PUBLICATION + "/mods:place/mods:placeTerm"))) .ifPresent(el -> idb.publisherPlace(el.getTextNormalize())); Optional.ofNullable(wrapper.getElement(MODS_ORIGIN_INFO_PUBLICATION + "/mods:publisher")) .or(() -> Optional.ofNullable(wrapper.getElement(MODS_RELATED_ITEM_XPATH + MODS_ORIGIN_INFO_PUBLICATION + "/mods:publisher"))) .ifPresent(el -> idb.publisher(el.getTextNormalize())); Optional.ofNullable(wrapper.getElement(MODS_ORIGIN_INFO_PUBLICATION + "/mods:edition")) .or(() -> Optional.ofNullable(wrapper.getElement(MODS_RELATED_ITEM_XPATH + MODS_ORIGIN_INFO_PUBLICATION + "/mods:edition"))) .ifPresent(el -> idb.edition(el.getTextNormalize())); Optional.ofNullable(wrapper.getElement(MODS_ORIGIN_INFO_PUBLICATION + "/mods:dateIssued")) .or(() -> Optional.ofNullable(wrapper.getElement(MODS_RELATED_ITEM_XPATH + MODS_ORIGIN_INFO_PUBLICATION + "/mods:dateIssued"))) .ifPresent(el -> idb.issued(new CSLDateBuilder().raw(el.getTextNormalize()).build())); } protected void processIdentifier(CSLItemDataBuilder idb) { final List<Element> parentIdentifiers = wrapper.getElements("mods:relatedItem[@type='host']/mods:identifier"); parentIdentifiers.forEach(parentIdentifier -> applyIdentifier(idb, parentIdentifier, true)); final List<Element> identifiers = wrapper.getElements("mods:identifier"); identifiers.forEach(identifierElement -> applyIdentifier(idb, identifierElement, false)); } private void applyIdentifier(CSLItemDataBuilder idb, Element identifierElement, boolean parent) { final String type = identifierElement.getAttributeValue("type"); final String identifier = identifierElement.getTextNormalize(); if(type == null){ LOGGER.info("Type is null for identifier {}", identifier); return; } switch (type) { case "doi" -> idb.DOI(identifier); case "isbn" -> idb.ISBN(identifier); case "issn" -> idb.ISSN(identifier); case "pmid" -> { if (!parent) { idb.PMID(identifier); } } case "pmcid" -> { if (!parent) { idb.PMCID(identifier); } } } } protected void processTitles(CSLItemDataBuilder idb) { final Element titleInfoElement = wrapper.getElement(USABLE_TITLE_XPATH); if (titleInfoElement != null) { idb.titleShort(buildShortTitle(titleInfoElement)); idb.title(buildTitle(titleInfoElement)); } final Element titleInfoShortElement = wrapper.getElement(SHORT_TITLE_XPATH); if (titleInfoShortElement != null) { idb.titleShort(buildShortTitle(titleInfoShortElement)); } Optional.ofNullable(wrapper.getElement("mods:relatedItem[@type='host']/" + USABLE_TITLE_XPATH)) .ifPresent((titleInfo) -> { idb.containerTitleShort(buildShortTitle(titleInfo)); idb.containerTitle(buildTitle(titleInfo)); }); Optional.ofNullable(wrapper.getElement("mods:relatedItem[@type='host']/" + SHORT_TITLE_XPATH)) .ifPresent((titleInfo) -> idb.containerTitleShort(buildShortTitle(titleInfo))); wrapper.getElements(".//mods:relatedItem[@type='series' or (@type='host' and " + "mods:genre[@type='intern'] = 'series')]/" + USABLE_TITLE_XPATH).stream() .findFirst().ifPresent((relatedItem) -> idb.collectionTitle(buildTitle(relatedItem))); } protected void processNames(CSLItemDataBuilder idb) { final List<Element> modsNameElements = wrapper.getElements("mods:name"); HashMap<String, List<CSLName>> roleNameMap = new HashMap<>(); for (Element modsName : modsNameElements) { final CSLName cslName = buildName(modsName); if (isNameEmpty(cslName)) { continue; } fillRoleMap(roleNameMap, modsName, cslName); } roleNameMap.forEach((role, list) -> { final CSLName[] cslNames = list.toArray(list.toArray(new CSLName[0])); switch (role) { case "aut", "inv" -> idb.author(cslNames); case "col" -> idb.collectionEditor(cslNames); case "edt" -> idb.editor(cslNames); case "fmd" -> idb.director(cslNames); case "ivr" -> idb.interviewer(cslNames); case "ive" -> idb.author(cslNames); case "ill" -> idb.illustrator(cslNames); case "trl" -> idb.translator(cslNames); case "cmp" -> idb.composer(cslNames); case "conference-name", "pup" -> idb .event(Stream.of(cslNames).map(CSLName::getLiteral).collect(Collectors.joining(", "))); default -> { if (KNOWN_UNMAPPED_PERSON_ROLES.contains(role)) { LOGGER.trace("Unmapped person role " + role + " in " + this.id); } else { LOGGER.warn("Unknown person role " + role + " in " + this.id); } } } }); HashMap<String, List<CSLName>> parentRoleMap = new HashMap<>(); final List<Element> parentModsNameElements = wrapper.getElements("mods:relatedItem/mods:name"); for (Element modsName : parentModsNameElements) { final CSLName cslName = buildName(modsName); if (isNameEmpty(cslName)) { continue; } fillRoleMap(parentRoleMap, modsName, cslName); } parentRoleMap.forEach((role, list) -> { final CSLName[] cslNames = list.toArray(list.toArray(new CSLName[0])); switch (role) { case "aut" -> idb.containerAuthor(cslNames); case "edt" -> idb.collectionEditor(cslNames); default -> { } // we dont care } }); } private void fillRoleMap(HashMap<String, List<CSLName>> roleNameMap, Element modsName, CSLName cslName) { final Element roleElement = modsName.getChild("role", MODS_NAMESPACE); if (roleElement != null) { final List<Element> roleTerms = roleElement.getChildren("roleTerm", MODS_NAMESPACE); for (Element roleTermElement : roleTerms) { final String role = roleTermElement.getTextNormalize(); roleNameMap.computeIfAbsent(role, s -> new ArrayList<>()).add(cslName); } } else { String nameType = modsName.getAttributeValue("type"); if (Objects.equals(nameType, "conference")) { roleNameMap.computeIfAbsent("conference-name", s -> new ArrayList<>()).add(cslName); } } } private CSLName buildName(Element modsName) { final CSLNameBuilder nameBuilder = new CSLNameBuilder(); String nameType = modsName.getAttributeValue("type"); final boolean isInstitution = Objects.equals(nameType, "corporate") || Objects.equals(nameType, "conference"); nameBuilder.isInstitution(isInstitution); if (!isInstitution) { //todo: maybe better mapping here HashMap<String, List<String>> typeContentsMap = new HashMap<>(); modsName.getChildren("namePart", MODS_NAMESPACE).forEach(namePart -> { final String type = namePart.getAttributeValue("type"); final String content = namePart.getTextNormalize(); if ((Objects.equals(type, "family") || Objects.equals(type, "given")) && nonDroppingParticles.contains(content)) { typeContentsMap.computeIfAbsent(NON_DROPPING_PARTICLE, t -> new ArrayList<>()) .add(content); } else if ((Objects.equals(type, "family") || Objects.equals(type, "given")) && droppingParticles.contains(content)) { typeContentsMap.computeIfAbsent(NON_DROPPING_PARTICLE, t -> new ArrayList<>()) .add(content); } else { typeContentsMap.computeIfAbsent(Optional.ofNullable(type).orElse(NONE_TYPE), t -> new ArrayList<>()) .add(content); } }); if (typeContentsMap.containsKey("family")) { nameBuilder.family(String.join(" ", typeContentsMap.get("family"))); } if (typeContentsMap.containsKey("given")) { nameBuilder.given(String.join(" ", typeContentsMap.get("given"))); } if (typeContentsMap.containsKey(NON_DROPPING_PARTICLE)) { nameBuilder.nonDroppingParticle(String.join(" ", typeContentsMap.get(NON_DROPPING_PARTICLE))); } if (typeContentsMap.containsKey(DROPPING_PARTICLE)) { nameBuilder.droppingParticle(String.join(" ", typeContentsMap.get(DROPPING_PARTICLE))); } if (typeContentsMap.containsKey(NONE_TYPE)) { nameBuilder.literal(String.join(" ", typeContentsMap.get(NONE_TYPE))); } Element displayForm = modsName.getChild("displayForm", MODS_NAMESPACE); if (typeContentsMap.isEmpty() && displayForm != null) { LOGGER.warn("The displayForm ({}) is used, because no mods name elements are present in doc {}!", displayForm.getTextNormalize(), this.id); nameBuilder.literal(displayForm.getTextNormalize()); } } else { String lit = Optional.ofNullable(modsName.getChildTextNormalize("displayForm", MODS_NAMESPACE)) .orElse(modsName.getChildren("namePart", MODS_NAMESPACE).stream().map(Element::getTextNormalize) .collect(Collectors.joining(" "))); if (!lit.isBlank()) { nameBuilder.literal(lit); } } return nameBuilder.build(); } protected boolean isNameEmpty(CSLName cslName) { Predicate<String> isNullOrEmpty = (p) -> p == null || p.isEmpty(); return isNullOrEmpty.test(cslName.getFamily()) && isNullOrEmpty.test(cslName.getGiven()) && isNullOrEmpty.test(cslName.getDroppingParticle()) && isNullOrEmpty.test(cslName.getNonDroppingParticle()) && isNullOrEmpty.test(cslName.getSuffix()) && isNullOrEmpty.test(cslName.getLiteral()); } protected String buildShortTitle(Element titleInfoElement) { return titleInfoElement.getChild("title", MODS_NAMESPACE).getText(); } protected String buildTitle(Element titleInfoElement) { StringBuilder titleBuilder = new StringBuilder(); titleBuilder.append(Stream.of("nonSort", "title") .flatMap(n -> getModsElementTextStream(titleInfoElement, n)) .collect(Collectors.joining(" "))); final String subTitle = getModsElementTextStream(titleInfoElement, "subTitle").collect(Collectors.joining(" ")); if (subTitle.length() > 0) { titleBuilder.append(": ").append(subTitle); } titleBuilder.append(Stream.of("partNumber", "partName") .flatMap(n -> getModsElementTextStream(titleInfoElement, n)) .collect(Collectors.joining(","))); return titleBuilder.toString(); } @Override public Collection<String> getIds() { return List.of(id); } @Override public void addContent(MCRContent content) throws IOException, JDOMException { final Document document = content.asXML(); addContent(document); } protected void addContent(Document document) { final MCRObject object = new MCRObject(document); wrapper = new MCRMODSWrapper(object); this.id = object.getId().toString(); } @Override public void reset() { this.id = null; this.wrapper = null; } }
27,110
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRListModsItemDataProvider.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/csl/MCRListModsItemDataProvider.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.mods.csl; import java.io.IOException; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.mycore.common.MCRCache; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.csl.MCRItemDataProvider; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.xml.sax.SAXException; import de.undercouch.citeproc.csl.CSLItemData; /** * Does the same as @{@link MCRModsItemDataProvider} but you can provide multiple objects */ public class MCRListModsItemDataProvider extends MCRItemDataProvider { protected static MCRCache<String, CSLItemData> cslCache = new MCRCache<>(2000, "CSL Mods Data"); private LinkedHashMap<String, CSLItemData> store = new LinkedHashMap<>(); @Override public void addContent(MCRContent content) throws IOException, JDOMException, SAXException { Document document = content.asXML(); List<Element> objects = document.getRootElement().getChildren("mycoreobject"); for (Element object : objects) { Element copy = object.clone().detach(); String objectID = copy.getAttributeValue("ID"); MCRObjectID mcrObjectID = MCRObjectID.getInstance(objectID); CSLItemData itemData = cslCache.getIfUpToDate(objectID, MCRXMLMetadataManager.instance() .getLastModified(mcrObjectID)); if (itemData == null) { MCRModsItemDataProvider midp = new MCRModsItemDataProvider(); midp.addContent(new MCRJDOMContent(copy)); itemData = midp.retrieveItem(objectID); cslCache.put(objectID, itemData); } store.put(objectID, itemData); } } @Override public void reset() { this.store.clear(); } @Override public CSLItemData retrieveItem(String s) { return this.store.get(s); } @Override public Collection<String> getIds() { return new LinkedHashSet<>(this.store.keySet()); } }
2,971
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRField2XPathTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/bibtex/MCRField2XPathTransformer.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.mods.bibtex; import org.jdom2.Element; import bibtex.dom.BibtexAbstractValue; import bibtex.dom.BibtexString; /** * Generic implementation that transforms a single BibTeX field to a given MODS structure expressed as XPath . * * @author Frank Lützenkirchen */ class MCRField2XPathTransformer extends MCRFieldTransformer { protected String xPath; MCRField2XPathTransformer(String field, String xPath) { super(field); this.xPath = xPath; } void buildField(BibtexAbstractValue value, Element parent) { String content = ((BibtexString) value).getContent(); content = normalizeValue(content); buildElement(xPath, content, parent); } }
1,446
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRBibTeX2MODSTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/bibtex/MCRBibTeX2MODSTransformer.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.mods.bibtex; import java.io.IOException; import java.io.StringReader; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jdom2.Element; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.content.transformer.MCRContentTransformer; import bibtex.dom.BibtexFile; import bibtex.parser.BibtexMultipleFieldValuesPolicy; import bibtex.parser.BibtexParser; import bibtex.parser.ParseException; /** * Transforms BibTeX source code to JDOM MODS elements. * Output is a mods:modsCollection. * * @author Frank Lützenkirchen */ public class MCRBibTeX2MODSTransformer extends MCRContentTransformer { private static final Pattern MISSING_KEYS_PATTERN = Pattern .compile("(@[a-zA-Z0-9]+\\s*\\{)(\\s*[a-zA-Z0-9]+\\s*\\=)"); @Override public MCRJDOMContent transform(MCRContent source) throws IOException { String input = source.asString(); input = fixMissingEntryKeys(input); BibtexFile bibtexFile = parse(input); Element collection = new MCRBibTeXFileTransformer().transform(bibtexFile); return new MCRJDOMContent(collection); } private String fixMissingEntryKeys(String input) { StringBuilder sb = new StringBuilder(); int i = 0; Matcher m = MISSING_KEYS_PATTERN.matcher(input); while (m.find()) { String entryKey = "key" + (++i); m.appendReplacement(sb, m.group(1) + entryKey + ", " + m.group(2)); } m.appendTail(sb); return sb.toString(); } private BibtexFile parse(String input) throws IOException { BibtexFile bibtexFile = new BibtexFile(); BibtexParser parser = new BibtexParser(false); parser.setMultipleFieldValuesPolicy(BibtexMultipleFieldValuesPolicy.KEEP_ALL); try { parser.parse(bibtexFile, new StringReader(input)); } catch (ParseException ex) { MCRMessageLogger.logMessage(ex.toString()); } return bibtexFile; } }
2,806
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMoveToRelatedItemIfExists.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/bibtex/MCRMoveToRelatedItemIfExists.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.mods.bibtex; import org.jdom2.Element; import org.jdom2.filter.Filters; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.common.MCRConstants; import bibtex.dom.BibtexEntry; /** * Some bibTeX fields must be moved "up" to the mods:relatedItem if a given XPath condition matches, * e.g. "here is a host". * * @author Frank Lützenkirchen */ class MCRMoveToRelatedItemIfExists extends MCRFieldTransformer { private String xPathOfRelatedItem; private MCRFieldTransformer wrappedTransformer; MCRMoveToRelatedItemIfExists(String xPathOfRelatedItem, MCRFieldTransformer wrappedTransformer) { super(wrappedTransformer.field); this.xPathOfRelatedItem = xPathOfRelatedItem; this.wrappedTransformer = wrappedTransformer; } @Override void transformField(BibtexEntry entry, Element parent) { Element target = getRelatedItemIfExists(parent); wrappedTransformer.transformField(entry, target); } Element getRelatedItemIfExists(Element parent) { XPathExpression<Element> xPath = XPathFactory.instance().compile(xPathOfRelatedItem, Filters.element(), null, MCRConstants.getStandardNamespaces()); Element fixedParent = xPath.evaluateFirst(parent); return fixedParent != null ? fixedParent : parent; } }
2,100
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMessageLogger.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/bibtex/MCRMessageLogger.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.mods.bibtex; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Comment; import org.jdom2.Element; /** * Helper class to log messages during transformation and add those messages as comment nodes in the resulting MODS XML. * * @author Frank Lützenkirchen */ class MCRMessageLogger { private static final Logger LOGGER = LogManager.getLogger(MCRMessageLogger.class); static void logMessage(String message) { LOGGER.warn(message); } static void logMessage(String message, Element parent) { logMessage(message); parent.addContent(new Comment(message)); } }
1,404
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z