Search in sources :

Example 1 with MCRObjectIDDate

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

the class MCRRestAPIObjectsHelper method listObjects.

/**
 * returns a list of objects
 * @param info - the injected Jersey URIInfo object
 *
 * @param format - the output format ('xml'|'json')
 * @param filter - a filter criteria
 * @param sort - the sort criteria
 *
 * @return a Jersey response object
 * @throws MCRRestAPIException
 *
 * @see org.mycore.restapi.v1.MCRRestAPIObjects#listObjects(UriInfo, HttpServletRequest, String, String, String)
 */
public static Response listObjects(UriInfo info, HttpServletRequest request, String format, String filter, String sort) throws MCRRestAPIException {
    List<MCRRestAPIError> errors = new ArrayList<>();
    // analyze sort
    MCRRestAPISortObject sortObj = null;
    try {
        sortObj = createSortObject(sort);
    } catch (MCRRestAPIException rae) {
        errors.addAll(rae.getErrors());
    }
    if (format.equals(MCRRestAPIObjects.FORMAT_JSON) || format.equals(MCRRestAPIObjects.FORMAT_XML)) {
    // ok
    } else {
        errors.add(new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER, "The parameter 'format' is wrong.", "Allowed values for format are 'json' or 'xml'."));
    }
    // analyze filter
    List<String> projectIDs = new ArrayList<>();
    List<String> typeIDs = new ArrayList<>();
    String lastModifiedBefore = null;
    String lastModifiedAfter = null;
    if (filter != null) {
        for (String s : filter.split(";")) {
            if (s.startsWith("project:")) {
                projectIDs.add(s.substring(8));
                continue;
            }
            if (s.startsWith("type:")) {
                typeIDs.add(s.substring(5));
                continue;
            }
            if (s.startsWith("lastModifiedBefore:")) {
                if (!validateDateInput(s.substring(19))) {
                    errors.add(new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER, "The parameter 'filter' is wrong.", "The value of lastModifiedBefore could not be parsed. Please use UTC syntax: yyyy-MM-dd'T'HH:mm:ss'Z'."));
                    continue;
                }
                if (lastModifiedBefore == null) {
                    lastModifiedBefore = s.substring(19);
                } else if (s.substring(19).compareTo(lastModifiedBefore) < 0) {
                    lastModifiedBefore = s.substring(19);
                }
                continue;
            }
            if (s.startsWith("lastModifiedAfter:")) {
                if (!validateDateInput(s.substring(18))) {
                    errors.add(new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER, "The parameter 'filter' is wrong.", "The value of lastModifiedAfter could not be parsed. Please use UTC syntax: yyyy-MM-dd'T'HH:mm:ss'Z'."));
                    continue;
                }
                if (lastModifiedAfter == null) {
                    lastModifiedAfter = s.substring(18);
                } else if (s.substring(18).compareTo(lastModifiedAfter) > 0) {
                    lastModifiedAfter = s.substring(18);
                }
                continue;
            }
            errors.add(new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER, "The parameter 'filter' is wrong.", "The syntax of the filter '" + s + "'could not be parsed. The syntax should be [filterName]:[value]. Allowed filterNames are 'project', 'type', 'lastModifiedBefore' and 'lastModifiedAfter'."));
        }
    }
    if (errors.size() > 0) {
        throw new MCRRestAPIException(Status.BAD_REQUEST, errors);
    }
    // Parameters are validated - continue to retrieve data
    // retrieve MCRIDs by Type and Project ID
    Set<String> mcrIDs = new HashSet<>();
    if (projectIDs.isEmpty()) {
        if (typeIDs.isEmpty()) {
            mcrIDs = MCRXMLMetadataManager.instance().listIDs().stream().filter(id -> !id.contains("_derivate_")).collect(Collectors.toSet());
        } else {
            for (String t : typeIDs) {
                mcrIDs.addAll(MCRXMLMetadataManager.instance().listIDsOfType(t));
            }
        }
    } else {
        if (typeIDs.isEmpty()) {
            for (String id : MCRXMLMetadataManager.instance().listIDs()) {
                String[] split = id.split("_");
                if (!split[1].equals("derivate") && projectIDs.contains(split[0])) {
                    mcrIDs.add(id);
                }
            }
        } else {
            for (String p : projectIDs) {
                for (String t : typeIDs) {
                    mcrIDs.addAll(MCRXMLMetadataManager.instance().listIDsForBase(p + "_" + t));
                }
            }
        }
    }
    // Filter by modifiedBefore and modifiedAfter
    List<String> l = new ArrayList<>();
    l.addAll(mcrIDs);
    List<MCRObjectIDDate> objIdDates = new ArrayList<>();
    try {
        objIdDates = MCRXMLMetadataManager.instance().retrieveObjectDates(l);
    } catch (IOException e) {
    // TODO
    }
    if (lastModifiedAfter != null || lastModifiedBefore != null) {
        List<MCRObjectIDDate> testObjIdDates = objIdDates;
        objIdDates = new ArrayList<>();
        for (MCRObjectIDDate oid : testObjIdDates) {
            String test = SDF_UTC.format(oid.getLastModified());
            if (lastModifiedAfter != null && test.compareTo(lastModifiedAfter) < 0)
                continue;
            if (lastModifiedBefore != null && lastModifiedBefore.compareTo(test.substring(0, lastModifiedBefore.length())) < 0)
                continue;
            objIdDates.add(oid);
        }
    }
    // sort if necessary
    if (sortObj != null) {
        objIdDates.sort(new MCRRestAPISortObjectComparator(sortObj));
    }
    String authHeader = MCRJSONWebTokenUtil.createJWTAuthorizationHeader(MCRJSONWebTokenUtil.retrieveAuthenticationToken(request));
    // output as XML
    if (MCRRestAPIObjects.FORMAT_XML.equals(format)) {
        Element eMcrobjects = new Element("mycoreobjects");
        Document docOut = new Document(eMcrobjects);
        eMcrobjects.setAttribute("numFound", Integer.toString(objIdDates.size()));
        for (MCRObjectIDDate oid : objIdDates) {
            Element eMcrObject = new Element("mycoreobject");
            eMcrObject.setAttribute("ID", oid.getId());
            eMcrObject.setAttribute("lastModified", SDF_UTC.format(oid.getLastModified()));
            eMcrObject.setAttribute("href", info.getAbsolutePathBuilder().path(oid.getId()).build().toString());
            eMcrobjects.addContent(eMcrObject);
        }
        try {
            StringWriter sw = new StringWriter();
            XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
            xout.output(docOut, sw);
            return Response.ok(sw.toString()).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, authHeader).build();
        } catch (IOException e) {
            throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, GENERAL_ERROR_MSG, e.getMessage()));
        }
    }
    // output as JSON
    if (MCRRestAPIObjects.FORMAT_JSON.equals(format)) {
        StringWriter sw = new StringWriter();
        try {
            JsonWriter writer = new JsonWriter(sw);
            writer.setIndent("    ");
            writer.beginObject();
            writer.name("numFound").value(objIdDates.size());
            writer.name("mycoreobjects");
            writer.beginArray();
            for (MCRObjectIDDate oid : objIdDates) {
                writer.beginObject();
                writer.name("ID").value(oid.getId());
                writer.name("lastModified").value(SDF_UTC.format(oid.getLastModified()));
                writer.name("href").value(info.getAbsolutePathBuilder().path(oid.getId()).build().toString());
                writer.endObject();
            }
            writer.endArray();
            writer.endObject();
            writer.close();
            return Response.ok(sw.toString()).type("application/json; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, authHeader).build();
        } catch (IOException e) {
            throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, GENERAL_ERROR_MSG, e.getMessage()));
        }
    }
    throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, "A problem in programm flow", null));
}
Also used : XMLOutputter(org.jdom2.output.XMLOutputter) MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) MCRObjectIDDate(org.mycore.datamodel.common.MCRObjectIDDate) Element(org.jdom2.Element) MCRRestAPIError(org.mycore.restapi.v1.errors.MCRRestAPIError) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.jdom2.Document) JsonWriter(com.google.gson.stream.JsonWriter) StringWriter(java.io.StringWriter) HashSet(java.util.HashSet)

Example 2 with MCRObjectIDDate

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

the class MCRGoogleSitemapCommon method buildPartSitemap.

/**
 * The method call the database and build the sitemap_google.xml JDOM document.
 *
 * @param number
 *            number of this file - '1' = sitemap_google.xml - '&gt; 1' sitemap_google_xxx.xml
 * @return The sitemap.xml as JDOM document
 */
protected final Document buildPartSitemap(int number) throws Exception {
    LOGGER.debug("Build Google URL sitemap list number {}", Integer.toString(number));
    // build document frame
    Element urlset = new Element("urlset", ns);
    urlset.addNamespaceDeclaration(XSI_NAMESPACE);
    urlset.setAttribute("schemaLocation", SITEMAP_SCHEMA, XSI_NAMESPACE);
    Document jdom = new Document(urlset);
    // build over all types
    int start = numberOfURLs * (number);
    int stop = numberOfURLs * (number + 1);
    if (stop > objidlist.size())
        stop = objidlist.size();
    LOGGER.debug("Build Google URL in range from {} to {}.", Integer.toString(start), Integer.toString(stop - 1));
    for (int i = start; i < stop; i++) {
        MCRObjectIDDate objectIDDate = objidlist.get(i);
        urlset.addContent(buildURLElement(objectIDDate));
    }
    return jdom;
}
Also used : MCRObjectIDDate(org.mycore.datamodel.common.MCRObjectIDDate) Element(org.jdom2.Element) Document(org.jdom2.Document)

Example 3 with MCRObjectIDDate

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

the class MCRGoogleSitemapCommon method buildSingleSitemap.

/**
 * The method build the sitemap_google.xml JDOM document over all items.
 *
 * @return The sitemap_google.xml as JDOM document
 */
protected final Document buildSingleSitemap() throws Exception {
    LOGGER.debug("Build Google URL sitemap_google.xml for whole items.");
    // build document frame
    Element urlset = new Element("urlset", ns);
    urlset.addNamespaceDeclaration(XSI_NAMESPACE);
    urlset.setAttribute("noNamespaceSchemaLocation", SITEMAP_SCHEMA, XSI_NAMESPACE);
    Document jdom = new Document(urlset);
    // build over all types
    for (MCRObjectIDDate objectIDDate : objidlist) {
        urlset.addContent(buildURLElement(objectIDDate));
    }
    return jdom;
}
Also used : MCRObjectIDDate(org.mycore.datamodel.common.MCRObjectIDDate) Element(org.jdom2.Element) Document(org.jdom2.Document)

Example 4 with MCRObjectIDDate

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

the class MCRRestAPIObjectsHelper method listDerivates.

/**
 * returns a list of derivate objects
 * @param info - the injected Jersey URIInfo object
 *
 * @param mcrObjID - the MyCoRe Object ID
 * @param format - the output format ('xml'|'json')
 * @param sort - the sort criteria
 *
 * @return a Jersey response object
 * @throws MCRRestAPIException
 *
 * @see org.mycore.restapi.v1.MCRRestAPIObjects#listDerivates(UriInfo, HttpServletRequest, String, String, String)
 */
public static Response listDerivates(UriInfo info, HttpServletRequest request, String mcrObjID, String format, String sort) throws MCRRestAPIException {
    List<MCRRestAPIError> errors = new ArrayList<>();
    MCRRestAPISortObject sortObj = null;
    try {
        sortObj = createSortObject(sort);
    } catch (MCRRestAPIException rae) {
        errors.addAll(rae.getErrors());
    }
    if (format.equals(MCRRestAPIObjects.FORMAT_JSON) || format.equals(MCRRestAPIObjects.FORMAT_XML)) {
    // ok
    } else {
        errors.add(new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER, "The Parameter format is wrong.", "Allowed values for format are 'json' or 'xml'."));
    }
    if (errors.size() > 0) {
        throw new MCRRestAPIException(Status.BAD_REQUEST, errors);
    }
    // Parameters are checked - continue to retrieve data
    List<MCRObjectIDDate> objIdDates = retrieveMCRObject(mcrObjID).getStructure().getDerivates().stream().map(MCRMetaLinkID::getXLinkHrefID).filter(MCRMetadataManager::exists).map(id -> new MCRObjectIDDate() {

        long lastModified;

        {
            try {
                lastModified = MCRXMLMetadataManager.instance().getLastModified(id);
            } catch (IOException e) {
                lastModified = 0;
                LOGGER.error("Exception while getting last modified of {}", id, e);
            }
        }

        @Override
        public String getId() {
            return id.toString();
        }

        @Override
        public Date getLastModified() {
            return new Date(lastModified);
        }
    }).sorted(new MCRRestAPISortObjectComparator(sortObj)::compare).collect(Collectors.toList());
    String authHeader = MCRJSONWebTokenUtil.createJWTAuthorizationHeader(MCRJSONWebTokenUtil.retrieveAuthenticationToken(request));
    // output as XML
    if (MCRRestAPIObjects.FORMAT_XML.equals(format)) {
        Element eDerObjects = new Element("derobjects");
        Document docOut = new Document(eDerObjects);
        eDerObjects.setAttribute("numFound", Integer.toString(objIdDates.size()));
        for (MCRObjectIDDate oid : objIdDates) {
            Element eDerObject = new Element("derobject");
            eDerObject.setAttribute("ID", oid.getId());
            MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(oid.getId()));
            String mcrID = der.getDerivate().getMetaLink().getXLinkHref();
            eDerObject.setAttribute("metadata", mcrID);
            if (der.getLabel() != null) {
                eDerObject.setAttribute("label", der.getLabel());
            }
            eDerObject.setAttribute("lastModified", SDF_UTC.format(oid.getLastModified()));
            eDerObject.setAttribute("href", info.getAbsolutePathBuilder().path(oid.getId()).build().toString());
            eDerObjects.addContent(eDerObject);
        }
        try {
            StringWriter sw = new StringWriter();
            XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
            xout.output(docOut, sw);
            return Response.ok(sw.toString()).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, authHeader).build();
        } catch (IOException e) {
            throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, GENERAL_ERROR_MSG, e.getMessage()));
        }
    }
    // output as JSON
    if (MCRRestAPIObjects.FORMAT_JSON.equals(format)) {
        StringWriter sw = new StringWriter();
        try {
            JsonWriter writer = new JsonWriter(sw);
            writer.setIndent("    ");
            writer.beginObject();
            writer.name("numFound").value(objIdDates.size());
            writer.name("mycoreobjects");
            writer.beginArray();
            for (MCRObjectIDDate oid : objIdDates) {
                writer.beginObject();
                writer.name("ID").value(oid.getId());
                MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(oid.getId()));
                String mcrID = der.getDerivate().getMetaLink().getXLinkHref();
                writer.name("metadata").value(mcrID);
                if (der.getLabel() != null) {
                    writer.name("label").value(der.getLabel());
                }
                writer.name("lastModified").value(SDF_UTC.format(oid.getLastModified()));
                writer.name("href").value(info.getAbsolutePathBuilder().path(oid.getId()).build().toString());
                writer.endObject();
            }
            writer.endArray();
            writer.endObject();
            writer.close();
            return Response.ok(sw.toString()).type("application/json; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, authHeader).build();
        } catch (IOException e) {
            throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, GENERAL_ERROR_MSG, e.getMessage()));
        }
    }
    throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, "Unexepected program flow termination.", "Please contact a developer!"));
}
Also used : XMLOutputter(org.jdom2.output.XMLOutputter) MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) MCRObjectIDDate(org.mycore.datamodel.common.MCRObjectIDDate) Element(org.jdom2.Element) MCRRestAPIError(org.mycore.restapi.v1.errors.MCRRestAPIError) ArrayList(java.util.ArrayList) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) IOException(java.io.IOException) Document(org.jdom2.Document) JsonWriter(com.google.gson.stream.JsonWriter) Date(java.util.Date) MCRObjectIDDate(org.mycore.datamodel.common.MCRObjectIDDate) StringWriter(java.io.StringWriter) MCRMetaLinkID(org.mycore.datamodel.metadata.MCRMetaLinkID)

Aggregations

Document (org.jdom2.Document)4 Element (org.jdom2.Element)4 MCRObjectIDDate (org.mycore.datamodel.common.MCRObjectIDDate)4 JsonWriter (com.google.gson.stream.JsonWriter)2 IOException (java.io.IOException)2 StringWriter (java.io.StringWriter)2 ArrayList (java.util.ArrayList)2 XMLOutputter (org.jdom2.output.XMLOutputter)2 MCRRestAPIError (org.mycore.restapi.v1.errors.MCRRestAPIError)2 MCRRestAPIException (org.mycore.restapi.v1.errors.MCRRestAPIException)2 Date (java.util.Date)1 HashSet (java.util.HashSet)1 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)1 MCRMetaLinkID (org.mycore.datamodel.metadata.MCRMetaLinkID)1