Search in sources :

Example 11 with MCRPersistenceException

use of org.mycore.common.MCRPersistenceException in project mycore by MyCoRe-Org.

the class MCRURNGranularRESTRegistrationService method registerURN.

private MCRDNBURN registerURN(MCRDerivate deriv, String filePath) {
    MCRObjectID derivID = deriv.getId();
    Function<String, Integer> countCreatedPI = s -> MCRPersistentIdentifierManager.getInstance().getCreatedIdentifiers(derivID, getType(), getRegistrationServiceID()).size();
    int seed = Optional.of(filePath).filter(p -> !"".equals(p)).map(countCreatedPI).map(count -> count + 1).orElse(1);
    MCRDNBURN derivURN = Optional.ofNullable(deriv.getDerivate()).map(MCRObjectDerivate::getURN).flatMap(new MCRDNBURNParser()::parse).orElseGet(() -> createNewURN(deriv));
    String setID = derivID.getNumberAsString();
    GranularURNGenerator granularURNGen = new GranularURNGenerator(seed, derivURN, setID);
    Function<MCRPath, Supplier<String>> generateURN = p -> granularURNGen.getURNSupplier();
    derivateFileStream.apply(deriv).filter(notInIgnoreList().and(matchFile(filePath))).sorted().collect(Collectors.toMap(generateURN, p -> p, (m1, m2) -> m1, LinkedHashMap::new)).forEach(createFileMetadata(deriv).andThen(persistURN(deriv)));
    try {
        MCRMetadataManager.update(deriv);
    } catch (MCRPersistenceException | MCRAccessException e) {
        LOGGER.error("Error while updating derivate {}", derivID, e);
    }
    EntityTransaction transaction = MCREntityManagerProvider.getCurrentEntityManager().getTransaction();
    if (!transaction.isActive()) {
        transaction.begin();
    }
    transaction.commit();
    return derivURN;
}
Also used : MCRBase(org.mycore.datamodel.metadata.MCRBase) Arrays(java.util.Arrays) Date(java.util.Date) Function(java.util.function.Function) Supplier(java.util.function.Supplier) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) ArrayList(java.util.ArrayList) MCRDNBURN(org.mycore.pi.urn.MCRDNBURN) LinkedHashMap(java.util.LinkedHashMap) MCRPI(org.mycore.pi.backend.MCRPI) Locale(java.util.Locale) BiConsumer(java.util.function.BiConsumer) MCRAccessException(org.mycore.access.MCRAccessException) Path(java.nio.file.Path) MCRMetadataManager(org.mycore.datamodel.metadata.MCRMetadataManager) MCRObjectDerivate(org.mycore.datamodel.metadata.MCRObjectDerivate) MCRPersistentIdentifierException(org.mycore.pi.exceptions.MCRPersistentIdentifierException) Files(java.nio.file.Files) Predicate(java.util.function.Predicate) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRPersistenceException(org.mycore.common.MCRPersistenceException) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) MCREntityManagerProvider(org.mycore.backend.jpa.MCREntityManagerProvider) MCRPIRegistrationService(org.mycore.pi.MCRPIRegistrationService) List(java.util.List) Stream(java.util.stream.Stream) Logger(org.apache.logging.log4j.Logger) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) EntityTransaction(javax.persistence.EntityTransaction) Optional(java.util.Optional) MCRPersistentIdentifierManager(org.mycore.pi.MCRPersistentIdentifierManager) Pattern(java.util.regex.Pattern) MCRActiveLinkException(org.mycore.datamodel.common.MCRActiveLinkException) MCRDNBURNParser(org.mycore.pi.urn.MCRDNBURNParser) LogManager(org.apache.logging.log4j.LogManager) EntityTransaction(javax.persistence.EntityTransaction) MCRDNBURN(org.mycore.pi.urn.MCRDNBURN) MCRAccessException(org.mycore.access.MCRAccessException) MCRObjectDerivate(org.mycore.datamodel.metadata.MCRObjectDerivate) MCRDNBURNParser(org.mycore.pi.urn.MCRDNBURNParser) LinkedHashMap(java.util.LinkedHashMap) Supplier(java.util.function.Supplier) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRPersistenceException(org.mycore.common.MCRPersistenceException)

Example 12 with MCRPersistenceException

use of org.mycore.common.MCRPersistenceException in project mycore by MyCoRe-Org.

the class MCRAVExtRealHelix method init.

@Override
public void init(MCRFile file) throws MCRPersistenceException {
    super.init(file);
    MCRConfiguration config = MCRConfiguration.instance();
    String prefix = "MCR.IFS.AVExtender." + file.getStoreID() + ".";
    baseMetadata = config.getString(prefix + "ViewSourceBaseURL");
    try {
        String data = getMetadata(baseMetadata + file.getStorageID());
        String sSize = getBetween("File Size:</strong>", "Bytes", data, "0");
        String sBitRate = getBetween("Bit Rate:</strong>", "Kbps", data, "0.0");
        String sFrameRate = getBetween("Frame Rate: </strong>", "fps", data, "0.0");
        String sDuration = getBetween("Duration:</strong>", "<br>", data, "0:0.0");
        String sType = getBetween("Stream:</strong>", "<br>", data, "");
        bitRate = Math.round(1024 * Float.valueOf(sBitRate));
        StringTokenizer st1 = new StringTokenizer(sFrameRate, " ,");
        while (st1.hasMoreTokens()) {
            double value = Double.valueOf(st1.nextToken());
            frameRate = Math.max(frameRate, value);
        }
        hasVideo = frameRate > 0;
        StringTokenizer st2 = new StringTokenizer(sDuration, ":.");
        durationMinutes = Integer.parseInt(st2.nextToken());
        durationSeconds = Integer.parseInt(st2.nextToken());
        if (Integer.parseInt(st2.nextToken()) > 499) {
            durationSeconds += 1;
            if (durationSeconds > 59) {
                durationMinutes += 1;
                durationSeconds = 0;
            }
        }
        StringTokenizer st3 = new StringTokenizer(sSize, ",");
        StringBuilder sb = new StringBuilder();
        while (st3.hasMoreTokens()) {
            sb.append(st3.nextToken());
        }
        size = Long.parseLong(sb.toString());
        durationHours = durationMinutes / 60;
        durationMinutes = durationMinutes - durationHours * 60;
        if (sType.contains("MPEG Layer 3")) {
            contentTypeID = "mp3";
            hasVideo = false;
        } else if (sType.contains("3GPP")) {
            contentTypeID = "3gp";
            hasVideo = true;
        } else if (sType.contains("MPEG4")) {
            contentTypeID = "mpeg4";
            hasVideo = true;
        } else if (sType.contains("MPEG")) {
            contentTypeID = "mpegvid";
            hasVideo = true;
        } else if (sType.contains("RealVideo")) {
            contentTypeID = "realvid";
        } else if (sType.contains("RealAudio")) {
            contentTypeID = "realaud";
        } else if (sType.contains("Wave File")) {
            contentTypeID = "wav";
            hasVideo = false;
        } else // should be one of "wma" "wmv" "asf"
        {
            contentTypeID = file.getContentTypeID();
            hasVideo = !contentTypeID.equals("wma");
        }
        if (" wma wmv asf asx ".contains(" " + contentTypeID + " ")) {
            basePlayerStarter = config.getString(prefix + "AsxGenBaseURL");
            playerDownloadURL = config.getString(prefix + "MediaPlayerURL");
        } else {
            basePlayerStarter = config.getString(prefix + "RamGenBaseURL");
            playerDownloadURL = config.getString(prefix + "RealPlayerURL");
        }
        URLConnection con = getConnection(basePlayerStarter + file.getStorageID());
        playerStarterCT = con.getContentType();
    } catch (Exception exc) {
        String msg = "Error parsing metadata from Real Server ViewSource: " + file.getStorageID();
        LOGGER.warn(msg, exc);
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) MCRConfiguration(org.mycore.common.config.MCRConfiguration) URLConnection(java.net.URLConnection) MCRPersistenceException(org.mycore.common.MCRPersistenceException) IOException(java.io.IOException)

Example 13 with MCRPersistenceException

use of org.mycore.common.MCRPersistenceException in project mycore by MyCoRe-Org.

the class MCRAudioVideoExtender method getMetadata.

/**
 * Helper method that connects to the given URL and returns the response as
 * a String
 *
 * @param url
 *            the URL to connect to
 * @return the response content as a String
 */
protected String getMetadata(String url) throws MCRPersistenceException {
    try {
        URLConnection connection = getConnection(url);
        connection.setConnectTimeout(getConnectTimeout());
        String contentType = connection.getContentType();
        // defined by RFC 2616 (sec 3.7.1)
        Charset charset = StandardCharsets.ISO_8859_1;
        if (contentType != null) {
            MediaType mediaType = MediaType.parse(contentType);
            mediaType.charset().or(StandardCharsets.ISO_8859_1);
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
        forwardData(connection, out);
        return new String(out.toByteArray(), charset);
    } catch (IOException exc) {
        String msg = "Could not get metadata from Audio/Video Store URL: " + url;
        throw new MCRPersistenceException(msg, exc);
    }
}
Also used : Charset(java.nio.charset.Charset) MediaType(com.google.common.net.MediaType) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) MCRPersistenceException(org.mycore.common.MCRPersistenceException) URLConnection(java.net.URLConnection)

Example 14 with MCRPersistenceException

use of org.mycore.common.MCRPersistenceException in project mycore by MyCoRe-Org.

the class MCRUpdateDerivateServlet method updateDerivateXML.

/**
 * Updates derivate xml in the persistence backend
 * @param editorSubmission
 *  MyCoRe derivate as XML
 * @return
 *  MCRObjectID of the MyCoRe object
 * @throws SAXParseException
 * @throws MCRAccessException
 */
private MCRObjectID updateDerivateXML(Document editorSubmission) throws SAXParseException, IOException, MCRAccessException {
    MCRObjectID objectID;
    Element root = editorSubmission.getRootElement();
    root.setAttribute("noNamespaceSchemaLocation", "datamodel-derivate.xsd", XSI_NAMESPACE);
    root.addNamespaceDeclaration(XLINK_NAMESPACE);
    root.addNamespaceDeclaration(XSI_NAMESPACE);
    byte[] xml = new MCRJDOMContent(editorSubmission).asByteArray();
    MCRDerivate der = new MCRDerivate(xml, true);
    MCRObjectID derivateID = der.getId();
    // store entry of derivate xlink:title in object
    objectID = der.getDerivate().getMetaLink().getXLinkHrefID();
    MCRObject obj = MCRMetadataManager.retrieveMCRObject(objectID);
    MCRObjectStructure structure = obj.getStructure();
    MCRMetaLinkID linkID = structure.getDerivateLink(derivateID);
    linkID.setXLinkTitle(der.getLabel());
    try {
        MCRMetadataManager.update(obj);
        MCRMetadataManager.update(der);
    } catch (MCRPersistenceException | MCRAccessException e) {
        throw new MCRPersistenceException("Can't store label of derivate " + derivateID + " in derivate list of object " + objectID + ".", e);
    }
    return objectID;
}
Also used : MCRObjectStructure(org.mycore.datamodel.metadata.MCRObjectStructure) MCRObject(org.mycore.datamodel.metadata.MCRObject) Element(org.jdom2.Element) MCRJDOMContent(org.mycore.common.content.MCRJDOMContent) MCRAccessException(org.mycore.access.MCRAccessException) MCRMetaLinkID(org.mycore.datamodel.metadata.MCRMetaLinkID) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRPersistenceException(org.mycore.common.MCRPersistenceException)

Example 15 with MCRPersistenceException

use of org.mycore.common.MCRPersistenceException in project mycore by MyCoRe-Org.

the class MCRDFGLinkServlet method getOrderNumber.

private static int getOrderNumber(Document metsDoc, String fileHref) {
    int orderNumber = -1;
    String fileID = null;
    try {
        Mets mets = new Mets(metsDoc);
        List<FileGrp> fileGroups = mets.getFileSec().getFileGroups();
        for (FileGrp fileGrp : fileGroups) {
            List<File> fileList = fileGrp.getFileList();
            for (File file : fileList) {
                FLocat fLocat = file.getFLocat();
                if (fLocat.getHref().equals(MCRXMLFunctions.encodeURIPath(fileHref)))
                    fileID = file.getId();
            }
        }
        if (fileID != null) {
            PhysicalStructMap structMap = (PhysicalStructMap) mets.getStructMap(PhysicalStructMap.TYPE);
            PhysicalDiv rootDiv = structMap.getDivContainer();
            List<PhysicalSubDiv> children = rootDiv.getChildren();
            for (int index = 0; index < children.size(); index++) {
                PhysicalSubDiv physicalSubDiv = children.get(index);
                List<Fptr> fptrList = physicalSubDiv.getChildren();
                for (Fptr fptr : fptrList) {
                    if (fptr.getFileId().equals(fileID))
                        orderNumber = index + 1;
                }
            }
        }
    } catch (Exception e) {
        throw new MCRPersistenceException("could not parse mets.xml", e);
    }
    return orderNumber;
}
Also used : PhysicalStructMap(org.mycore.mets.model.struct.PhysicalStructMap) FileGrp(org.mycore.mets.model.files.FileGrp) Fptr(org.mycore.mets.model.struct.Fptr) PhysicalDiv(org.mycore.mets.model.struct.PhysicalDiv) MCRPersistenceException(org.mycore.common.MCRPersistenceException) PhysicalSubDiv(org.mycore.mets.model.struct.PhysicalSubDiv) Mets(org.mycore.mets.model.Mets) FLocat(org.mycore.mets.model.files.FLocat) File(org.mycore.mets.model.files.File) MCRPersistenceException(org.mycore.common.MCRPersistenceException)

Aggregations

MCRPersistenceException (org.mycore.common.MCRPersistenceException)36 IOException (java.io.IOException)18 MCRAccessException (org.mycore.access.MCRAccessException)13 JDOMException (org.jdom2.JDOMException)9 MCRActiveLinkException (org.mycore.datamodel.common.MCRActiveLinkException)8 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)8 MCRPath (org.mycore.datamodel.niofs.MCRPath)8 MCRException (org.mycore.common.MCRException)7 SAXException (org.xml.sax.SAXException)6 File (java.io.File)5 PersistenceException (javax.persistence.PersistenceException)5 Path (java.nio.file.Path)4 UncheckedIOException (java.io.UncheckedIOException)3 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)3 Date (java.util.Date)3 EntityManager (javax.persistence.EntityManager)3 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)3 MCRMetaLinkID (org.mycore.datamodel.metadata.MCRMetaLinkID)3 SignedJWT (com.nimbusds.jwt.SignedJWT)2 PrintWriter (java.io.PrintWriter)2