Search in sources :

Example 66 with Format

use of org.jdom2.output.Format 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 67 with Format

use of org.jdom2.output.Format 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 68 with Format

use of org.jdom2.output.Format in project mycore by MyCoRe-Org.

the class MCRRestAPIClassifications method writeChildrenAsJSONCBTree.

/**
 * output children in JSON format used as input for Dijit Checkbox Tree
 *
 * @param eParent - the parent xml element
 * @param writer - the JSON writer
 * @param lang - the language to be filtered or null if all languages should be displayed
 *
 * @throws IOException
 */
private static void writeChildrenAsJSONCBTree(Element eParent, JsonWriter writer, String lang, boolean checked) throws IOException {
    writer.beginArray();
    for (Element e : eParent.getChildren("category")) {
        writer.beginObject();
        writer.name("ID").value(e.getAttributeValue("ID"));
        for (Element eLabel : e.getChildren("label")) {
            if (lang == null || lang.equals(eLabel.getAttributeValue("lang", Namespace.XML_NAMESPACE))) {
                writer.name("text").value(eLabel.getAttributeValue("text"));
            }
        }
        writer.name("checked").value(checked);
        if (e.getChildren("category").size() > 0) {
            writer.name("children");
            writeChildrenAsJSONCBTree(e, writer, lang, checked);
        }
        writer.endObject();
    }
    writer.endArray();
}
Also used : Element(org.jdom2.Element)

Example 69 with Format

use of org.jdom2.output.Format in project mycore by MyCoRe-Org.

the class MCRRestAPIMessages method getMessage.

/**
 * returns a single messages entry.
 *
 * @param info - the injected Jersey context object for URI
 * @param request - the injected HTTPServletRequest object
 * @param key - the message key
 * @param lang - the language
 * @param format
 *     Possible values are: props (default) | json | xml (required)
 * @return a Jersey Response Object
 * @throws MCRRestAPIException
 */
@GET
@Path("/{value}")
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8", MediaType.TEXT_PLAIN + ";charset=UTF-8" })
public Response getMessage(@Context UriInfo info, @Context HttpServletRequest request, @PathParam("value") String key, @QueryParam("lang") @DefaultValue("de") String lang, @QueryParam("format") @DefaultValue("text") String format) throws MCRRestAPIException {
    MCRRestAPIUtil.checkRestAPIAccess(request, MCRRestAPIACLPermission.READ, "/v1/messages");
    Locale locale = Locale.forLanguageTag(lang);
    String result = MCRTranslation.translate(key, locale);
    String authHeader = MCRJSONWebTokenUtil.createJWTAuthorizationHeader(MCRJSONWebTokenUtil.retrieveAuthenticationToken(request));
    try {
        if (FORMAT_PROPERTY.equals(format)) {
            return Response.ok(key + "=" + result).type("text/plain; charset=ISO-8859-1").header(HEADER_NAME_AUTHORIZATION, authHeader).build();
        }
        if (FORMAT_XML.equals(format)) {
            Document doc = new Document();
            Element root = new Element("entry");
            root.setAttribute("key", key);
            root.setText(result);
            doc.addContent(root);
            StringWriter sw = new StringWriter();
            XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
            outputter.output(doc, sw);
            return Response.ok(sw.toString()).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, authHeader).build();
        }
        if (FORMAT_JSON.equals(format)) {
            StringWriter sw = new StringWriter();
            JsonWriter writer = new JsonWriter(sw);
            writer.setIndent("    ");
            writer.beginObject();
            writer.name(key);
            writer.value(result);
            writer.endObject();
            writer.close();
            return Response.ok(sw.toString()).type("application/json; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, authHeader).build();
        }
        // text only
        return Response.ok(result).type("text/plain; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, authHeader).build();
    } catch (IOException e) {
    // toDo
    }
    return Response.status(Status.BAD_REQUEST).build();
}
Also used : Locale(java.util.Locale) XMLOutputter(org.jdom2.output.XMLOutputter) StringWriter(java.io.StringWriter) Element(org.jdom2.Element) IOException(java.io.IOException) Document(org.jdom2.Document) JsonWriter(com.google.gson.stream.JsonWriter) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

Element (org.jdom2.Element)56 Document (org.jdom2.Document)20 XMLOutputter (org.jdom2.output.XMLOutputter)19 IOException (java.io.IOException)15 StringWriter (java.io.StringWriter)9 Attribute (org.jdom2.Attribute)9 Format (org.jdom2.output.Format)7 File (java.io.File)5 ArrayList (java.util.ArrayList)5 MCRRestAPIError (org.mycore.restapi.v1.errors.MCRRestAPIError)5 MCRRestAPIException (org.mycore.restapi.v1.errors.MCRRestAPIException)5 JsonWriter (com.google.gson.stream.JsonWriter)4 Date (java.util.Date)4 SAXBuilder (org.jdom2.input.SAXBuilder)4 SimpleDateFormat (java.text.SimpleDateFormat)3 JDOMException (org.jdom2.JDOMException)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 MalformedURLException (java.net.MalformedURLException)2 List (java.util.List)2 JComponent (javax.swing.JComponent)2