Search in sources :

Example 91 with MCRPath

use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.

the class MCRMETSServlet method getLastModified.

/*
     * (non-Javadoc)
     * 
     * @see
     * org.mycore.frontend.servlets.MCRServlet#getLastModified(javax.servlet
     * .http.HttpServletRequest)
     */
@Override
protected long getLastModified(HttpServletRequest request) {
    String ownerID = getOwnerID(request.getPathInfo());
    MCRSession session = MCRSessionMgr.getCurrentSession();
    MCRPath metsPath = MCRPath.getPath(ownerID, "/mets.xml");
    try {
        session.beginTransaction();
        try {
            if (Files.exists(metsPath)) {
                return Files.getLastModifiedTime(metsPath).toMillis();
            } else if (Files.isDirectory(metsPath.getParent())) {
                return Files.getLastModifiedTime(metsPath.getParent()).toMillis();
            }
        } catch (IOException e) {
            LOGGER.warn("Error while retrieving last modified information from {}", metsPath, e);
        }
        return -1L;
    } finally {
        session.commitTransaction();
        MCRSessionMgr.releaseCurrentSession();
        // just created session for db transaction
        session.close();
    }
}
Also used : MCRSession(org.mycore.common.MCRSession) IOException(java.io.IOException) MCRPath(org.mycore.datamodel.niofs.MCRPath)

Example 92 with MCRPath

use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.

the class MCRRestAPIObjectsHelper method createXMLForSubdirectories.

private static void createXMLForSubdirectories(MCRPath mcrPath, Element currentElement, int currentDepth, int maxDepth) {
    if (currentDepth < maxDepth) {
        XPathExpression<Element> xp = XPathFactory.instance().compile("./children/child[@type='directory']", Filters.element());
        for (Element e : xp.evaluate(currentElement)) {
            String name = e.getChildTextNormalize("name");
            try {
                MCRPath pChild = (MCRPath) mcrPath.resolve(name);
                Document doc = MCRPathXML.getDirectoryXML(pChild);
                Element eChildren = doc.getRootElement().getChild("children");
                if (eChildren != null) {
                    e.addContent(eChildren.detach());
                    createXMLForSubdirectories(pChild, e, currentDepth + 1, maxDepth);
                }
            } catch (IOException ex) {
            // ignore
            }
        }
    }
}
Also used : Element(org.jdom2.Element) IOException(java.io.IOException) MCRPath(org.mycore.datamodel.niofs.MCRPath) Document(org.jdom2.Document)

Example 93 with MCRPath

use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.

the class MCRRestAPIObjectsHelper method listContents.

/**
 * lists derivate content (file listing)
 * @param info - the Jersey UriInfo Object
 * @param request - the HTTPServletRequest object
 * @param mcrObjID - the MyCoRe Object ID
 * @param mcrDerID - the MyCoRe Derivate ID
 * @param format - the output format ('xml'|'json')
 * @param path - the sub path of a directory inside the derivate
 * @param depth - the level of subdirectories to be returned
 * @return a Jersey Response object
 * @throws MCRRestAPIException
 */
public static Response listContents(UriInfo info, HttpServletRequest httpRequest, Request request, String mcrObjID, String mcrDerID, String format, String path, int depth) throws MCRRestAPIException {
    if (!format.equals(MCRRestAPIObjects.FORMAT_JSON) && !format.equals(MCRRestAPIObjects.FORMAT_XML)) {
        throw new MCRRestAPIException(Response.Status.BAD_REQUEST, new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER, "The syntax of format parameter is wrong.", "Allowed values for format are 'json' or 'xml'."));
    }
    MCRObject mcrObj = retrieveMCRObject(mcrObjID);
    MCRDerivate derObj = retrieveMCRDerivate(mcrObj, mcrDerID);
    String authHeader = MCRJSONWebTokenUtil.createJWTAuthorizationHeader(MCRJSONWebTokenUtil.retrieveAuthenticationToken(httpRequest));
    try {
        MCRPath root = MCRPath.getPath(derObj.getId().toString(), "/");
        BasicFileAttributes readAttributes = Files.readAttributes(root, BasicFileAttributes.class);
        Date lastModified = new Date(readAttributes.lastModifiedTime().toMillis());
        ResponseBuilder responseBuilder = request.evaluatePreconditions(lastModified);
        if (responseBuilder != null) {
            return responseBuilder.header(HEADER_NAME_AUTHORIZATION, authHeader).build();
        }
        switch(format) {
            case MCRRestAPIObjects.FORMAT_XML:
                Document docOut = listDerivateContentAsXML(derObj, path, depth, info);
                try (StringWriter sw = new StringWriter()) {
                    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
                    xout.output(docOut, sw);
                    return response(sw.toString(), "application/xml", lastModified, authHeader);
                } catch (IOException e) {
                    throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, GENERAL_ERROR_MSG, e.getMessage()));
                }
            case MCRRestAPIObjects.FORMAT_JSON:
                if (MCRRestAPIObjects.FORMAT_JSON.equals(format)) {
                    String result = listDerivateContentAsJson(derObj, path, depth, info);
                    return response(result, "application/json", lastModified, authHeader);
                }
            default:
                throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, "Unexepected program flow termination.", "Please contact a developer!"));
        }
    } catch (IOException e) {
        throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, "Unexepected program flow termination.", e.getMessage()));
    }
}
Also used : XMLOutputter(org.jdom2.output.XMLOutputter) MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) MCRRestAPIError(org.mycore.restapi.v1.errors.MCRRestAPIError) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) IOException(java.io.IOException) Document(org.jdom2.Document) Date(java.util.Date) MCRObjectIDDate(org.mycore.datamodel.common.MCRObjectIDDate) MCRObject(org.mycore.datamodel.metadata.MCRObject) StringWriter(java.io.StringWriter) MCRPath(org.mycore.datamodel.niofs.MCRPath) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 94 with MCRPath

use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.

the class MCRRestAPIObjectsHelper method listDerivateContentAsJson.

private static String listDerivateContentAsJson(MCRDerivate derObj, String path, int depth, UriInfo info) throws IOException {
    StringWriter sw = new StringWriter();
    MCRPath root = MCRPath.getPath(derObj.getId().toString(), "/");
    root = MCRPath.toMCRPath(root.resolve(path));
    if (depth == -1) {
        depth = Integer.MAX_VALUE;
    }
    if (root != null) {
        JsonWriter writer = new JsonWriter(sw);
        Files.walkFileTree(root, EnumSet.noneOf(FileVisitOption.class), depth, new MCRJSONFileVisitor(writer, derObj.getOwnerID(), derObj.getId(), info));
        writer.close();
    }
    return sw.toString();
}
Also used : StringWriter(java.io.StringWriter) FileVisitOption(java.nio.file.FileVisitOption) MCRPath(org.mycore.datamodel.niofs.MCRPath) JsonWriter(com.google.gson.stream.JsonWriter)

Example 95 with MCRPath

use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.

the class MCRURNGranularRESTRegistrationServiceTest method fullRegister.

@Test
public void fullRegister() throws Exception {
    new MockContentTypes();
    new MockFrontendUtil();
    new MockFiles();
    new MockAccessManager();
    new MockObjectDerivate();
    new MockDerivate();
    MockMetadataManager mockMetadataManager = new MockMetadataManager();
    MCRDerivate derivate = new MCRDerivate();
    MCRObjectID mcrObjectID = MCRPIUtils.getNextFreeID();
    derivate.setId(mcrObjectID);
    mockMetadataManager.put(mcrObjectID, derivate);
    Function<MCRDerivate, Stream<MCRPath>> foo = deriv -> IntStream.iterate(0, i -> i + 1).mapToObj(i -> "/foo/" + UUID.randomUUID() + "_" + String.format(Locale.getDefault(), "%02d", i)).map(f -> MCRPath.getPath(derivate.getId().toString(), f)).limit(numOfDerivFiles);
    String serviceID = "TestService";
    MCRURNGranularRESTRegistrationService testService = new MCRURNGranularRESTRegistrationService(serviceID, foo);
    testService.register(derivate, "", true);
    timerTask();
    List<MCRPIRegistrationInfo> registeredURNs = MCREntityManagerProvider.getEntityManagerFactory().createEntityManager().createNamedQuery("Get.PI.Created", MCRPIRegistrationInfo.class).setParameter("mcrId", mcrObjectID.toString()).setParameter("type", MCRDNBURN.TYPE).setParameter("service", serviceID).getResultList();
    Assert.assertEquals("Wrong number of registered URNs: ", numOfDerivFiles + 1, registeredURNs.size());
}
Also used : IntStream(java.util.stream.IntStream) Date(java.util.Date) MCRUUIDURNGenerator(org.mycore.pi.urn.MCRUUIDURNGenerator) Function(java.util.function.Function) MCRException(org.mycore.common.MCRException) TreeSet(java.util.TreeSet) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) MCRAccessManager(org.mycore.access.MCRAccessManager) MCRDNBURN(org.mycore.pi.urn.MCRDNBURN) LinkOption(java.nio.file.LinkOption) Locale(java.util.Locale) MCRMetaIFS(org.mycore.datamodel.metadata.MCRMetaIFS) Map(java.util.Map) After(org.junit.After) Mock(mockit.Mock) MCRFileMetadata(org.mycore.datamodel.metadata.MCRFileMetadata) Path(java.nio.file.Path) MCRObjectDerivate(org.mycore.datamodel.metadata.MCRObjectDerivate) MockUp(mockit.MockUp) MCRContentTypes(org.mycore.datamodel.niofs.MCRContentTypes) Files(java.nio.file.Files) MCRPath(org.mycore.datamodel.niofs.MCRPath) IOException(java.io.IOException) Test(org.junit.Test) MCRPIRegistrationInfo(org.mycore.pi.MCRPIRegistrationInfo) UUID(java.util.UUID) MCRFrontendUtil(org.mycore.frontend.MCRFrontendUtil) TimeUnit(java.util.concurrent.TimeUnit) MCREntityManagerProvider(org.mycore.backend.jpa.MCREntityManagerProvider) List(java.util.List) Stream(java.util.stream.Stream) MCRStoreTestCase(org.mycore.common.MCRStoreTestCase) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MockMetadataManager(org.mycore.pi.MockMetadataManager) MCRPIUtils(org.mycore.pi.MCRPIUtils) Assert(org.junit.Assert) MCRPIRegistrationInfo(org.mycore.pi.MCRPIRegistrationInfo) MockMetadataManager(org.mycore.pi.MockMetadataManager) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) IntStream(java.util.stream.IntStream) Stream(java.util.stream.Stream) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) Test(org.junit.Test)

Aggregations

MCRPath (org.mycore.datamodel.niofs.MCRPath)96 IOException (java.io.IOException)49 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)26 Path (java.nio.file.Path)25 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)22 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)22 Document (org.jdom2.Document)15 JDOMException (org.jdom2.JDOMException)15 MCRPersistenceException (org.mycore.common.MCRPersistenceException)14 MCRException (org.mycore.common.MCRException)13 MCRDirectory (org.mycore.datamodel.ifs.MCRDirectory)13 MCRAccessException (org.mycore.access.MCRAccessException)12 Files (java.nio.file.Files)11 Collectors (java.util.stream.Collectors)11 LogManager (org.apache.logging.log4j.LogManager)11 Logger (org.apache.logging.log4j.Logger)11 FileVisitResult (java.nio.file.FileVisitResult)10 NoSuchFileException (java.nio.file.NoSuchFileException)10 Date (java.util.Date)10 List (java.util.List)10