Search in sources :

Example 51 with Filter

use of org.jdom2.filter.Filter 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)

Example 52 with Filter

use of org.jdom2.filter.Filter in project mycore by MyCoRe-Org.

the class MCRRestAPIClassifications method writeXML.

/**
 * Output xml
 * @param eRoot - the root element
 * @param lang - the language which should be filtered or null for no filter
 * @return a string representation of the XML
 * @throws IOException
 */
private static String writeXML(Element eRoot, String lang) throws IOException {
    StringWriter sw = new StringWriter();
    if (lang != null) {
        // <label xml:lang="en" text="part" />
        XPathExpression<Element> xpE = XPathFactory.instance().compile("//label[@xml:lang!='" + lang + "']", Filters.element(), null, Namespace.XML_NAMESPACE);
        for (Element e : xpE.evaluate(eRoot)) {
            e.getParentElement().removeContent(e);
        }
    }
    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
    Document docOut = new Document(eRoot.detach());
    xout.output(docOut, sw);
    return sw.toString();
}
Also used : XMLOutputter(org.jdom2.output.XMLOutputter) StringWriter(java.io.StringWriter) Element(org.jdom2.Element) Document(org.jdom2.Document)

Example 53 with Filter

use of org.jdom2.filter.Filter in project qpp-conversion-tool by CMSgov.

the class ValidationApiAcceptance method verifyDetail.

private void verifyDetail(Detail detail) {
    String xPath = detail.getPath();
    Filter filter = xPath.contains("@") ? Filters.attribute() : Filters.element();
    try {
        Object found = evaluateXpath(detail.getPath(), filter);
        if (filter.equals(Filters.attribute())) {
            Attribute attribute = (Attribute) found;
            assertThat(attribute.getIntValue()).isEqualTo(CANNED_VALUE);
            assertThat(detail.getMessage()).startsWith(ValidationServiceImpl.SV_LABEL);
        } else {
            assertThat(found).isNotNull();
        }
    } catch (XmlException | DataConversionException ex) {
        fail("This xpath could not be found: " + detail.getPath(), ex);
    }
}
Also used : Filter(org.jdom2.filter.Filter) Attribute(org.jdom2.Attribute) XmlException(gov.cms.qpp.conversion.xml.XmlException) DataConversionException(org.jdom2.DataConversionException)

Aggregations

Element (org.jdom2.Element)43 Document (org.jdom2.Document)24 List (java.util.List)22 IOException (java.io.IOException)20 ArrayList (java.util.ArrayList)19 LogManager (org.apache.logging.log4j.LogManager)17 Logger (org.apache.logging.log4j.Logger)17 JDOMException (org.jdom2.JDOMException)17 Collectors (java.util.stream.Collectors)16 File (java.io.File)11 MCRException (org.mycore.common.MCRException)11 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)11 Collections (java.util.Collections)10 MCRObject (org.mycore.datamodel.metadata.MCRObject)10 Map (java.util.Map)9 MCRAccessException (org.mycore.access.MCRAccessException)9 MCRConstants (org.mycore.common.MCRConstants)9 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)9 MCRMetadataManager (org.mycore.datamodel.metadata.MCRMetadataManager)9 Files (java.nio.file.Files)8