Search in sources :

Example 21 with Format

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

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

the class MCRRestAPIClassifications method listClassifications.

/**
 * lists all available classifications as XML or JSON
 *
 * @param info - the URIInfo object
 * @param request - the HTTPServletRequest object
 * @param format - the output format ('xml' or 'json)
 * @return a Jersey Response Object
 * @throws MCRRestAPIException
 */
@GET
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8" })
public Response listClassifications(@Context UriInfo info, @Context HttpServletRequest request, @QueryParam("format") @DefaultValue("json") String format) throws MCRRestAPIException {
    MCRRestAPIUtil.checkRestAPIAccess(request, MCRRestAPIACLPermission.READ, "/v1/classifications");
    String authHeader = MCRJSONWebTokenUtil.createJWTAuthorizationHeader(MCRJSONWebTokenUtil.retrieveAuthenticationToken(request));
    if (FORMAT_XML.equals(format)) {
        StringWriter sw = new StringWriter();
        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        Document docOut = new Document();
        Element eRoot = new Element("mycoreclassifications");
        docOut.setRootElement(eRoot);
        for (MCRCategory cat : DAO.getRootCategories()) {
            eRoot.addContent(new Element("mycoreclass").setAttribute("ID", cat.getId().getRootID()).setAttribute("href", info.getAbsolutePathBuilder().path(cat.getId().getRootID()).build().toString()));
        }
        try {
            xout.output(docOut, sw);
            return Response.ok(sw.toString()).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, authHeader).build();
        } catch (IOException e) {
        // ToDo
        }
    }
    if (FORMAT_JSON.equals(format)) {
        StringWriter sw = new StringWriter();
        try {
            JsonWriter writer = new JsonWriter(sw);
            writer.setIndent("    ");
            writer.beginObject();
            writer.name("mycoreclass");
            writer.beginArray();
            for (MCRCategory cat : DAO.getRootCategories()) {
                writer.beginObject();
                writer.name("ID").value(cat.getId().getRootID());
                writer.name("href").value(info.getAbsolutePathBuilder().path(cat.getId().getRootID()).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) {
        // toDo
        }
    }
    return Response.status(Status.BAD_REQUEST).build();
}
Also used : XMLOutputter(org.jdom2.output.XMLOutputter) MCRCategory(org.mycore.datamodel.classifications2.MCRCategory) StringWriter(java.io.StringWriter) Element(org.jdom2.Element) IOException(java.io.IOException) Document(org.jdom2.Document) JsonWriter(com.google.gson.stream.JsonWriter) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 23 with Format

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

the class MCRRestAPIClassifications method writeChildrenAsJSON.

/**
 * output categories in JSON format
 * @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 writeChildrenAsJSON(Element eParent, JsonWriter writer, String lang) throws IOException {
    if (eParent.getChildren("category").size() == 0)
        return;
    writer.name("categories");
    writer.beginArray();
    for (Element e : eParent.getChildren("category")) {
        writer.beginObject();
        writer.name("ID").value(e.getAttributeValue("ID"));
        writer.name("labels").beginArray();
        for (Element eLabel : e.getChildren("label")) {
            if (lang == null || lang.equals(eLabel.getAttributeValue("lang", Namespace.XML_NAMESPACE))) {
                writer.beginObject();
                writer.name("lang").value(eLabel.getAttributeValue("lang", Namespace.XML_NAMESPACE));
                writer.name("text").value(eLabel.getAttributeValue("text"));
                if (eLabel.getAttributeValue("description") != null) {
                    writer.name("description").value(eLabel.getAttributeValue("description"));
                }
                writer.endObject();
            }
        }
        writer.endArray();
        if (e.getChildren("category").size() > 0) {
            writeChildrenAsJSON(e, writer, lang);
        }
        writer.endObject();
    }
    writer.endArray();
}
Also used : Element(org.jdom2.Element)

Example 24 with Format

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

the class MCRRestAPIClassifications method showObject.

/**
 *  returns a single classification object
 *
 * @param classID - the classfication id
 * @param format
 *   Possible values are: json | xml (required)
 * @param filter
 * 	 a ';'-separated list of ':'-separated key-value pairs, possible keys are:
 *      - lang - the language of the returned labels, if ommited all labels in all languages will be returned
 *      - root - an id for a category which will be used as root
 *      - nonempty - hide empty categories
 * @param style
 * 	a ';'-separated list of values, possible keys are:
 *   	- 'checkboxtree' - create a json syntax which can be used as input for a dojo checkboxtree;
 *      - 'checked'   - (together with 'checkboxtree') all checkboxed will be checked
 *      - 'jstree' - create a json syntax which can be used as input for a jsTree
 *      - 'opened' - (together with 'jstree') - all nodes will be opened
 *      - 'disabled' - (together with 'jstree') - all nodes will be disabled
 *      - 'selected' - (together with 'jstree') - all nodes will be selected
 * @param request - the HTTPServletRequestObject
 * @param callback - used in JSONP to wrap json result into a Javascript function named by callback parameter
 * @return a Jersey Response object
 * @throws MCRRestAPIException
 */
@GET
// @Path("/id/{value}{format:(\\.[^/]+?)?}")  -> working, but returns empty string instead of default value
@Path("/{classID}")
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8" })
public Response showObject(@Context HttpServletRequest request, @PathParam("classID") String classID, @QueryParam("format") @DefaultValue("xml") String format, @QueryParam("filter") @DefaultValue("") String filter, @QueryParam("style") @DefaultValue("") String style, @QueryParam("callback") @DefaultValue("") String callback) throws MCRRestAPIException {
    MCRRestAPIUtil.checkRestAPIAccess(request, MCRRestAPIACLPermission.READ, "/v1/classifications");
    String rootCateg = null;
    String lang = null;
    boolean filterNonEmpty = false;
    boolean filterNoChildren = false;
    for (String f : filter.split(";")) {
        if (f.startsWith("root:")) {
            rootCateg = f.substring(5);
        }
        if (f.startsWith("lang:")) {
            lang = f.substring(5);
        }
        if (f.startsWith("nonempty")) {
            filterNonEmpty = true;
        }
        if (f.startsWith("nochildren")) {
            filterNoChildren = true;
        }
    }
    if (format == null || classID == null) {
        return Response.serverError().status(Status.BAD_REQUEST).build();
    // TODO response.sendError(HttpServletResponse.SC_NOT_FOUND,
    // "Please specify parameters format and classid.");
    }
    try {
        MCRCategory cl = DAO.getCategory(MCRCategoryID.rootID(classID), -1);
        if (cl == null) {
            throw new MCRRestAPIException(Response.Status.BAD_REQUEST, new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "Classification not found.", "There is no classification with the given ID."));
        }
        Document docClass = MCRCategoryTransformer.getMetaDataDocument(cl, false);
        Element eRoot = docClass.getRootElement();
        if (rootCateg != null) {
            XPathExpression<Element> xpe = XPathFactory.instance().compile("//category[@ID='" + rootCateg + "']", Filters.element());
            Element e = xpe.evaluateFirst(docClass);
            if (e != null) {
                eRoot = e;
            } else {
                throw new MCRRestAPIException(Response.Status.BAD_REQUEST, new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "Category not found.", "The classfication does not contain a category with the given ID."));
            }
        }
        if (filterNonEmpty) {
            Element eFilter = eRoot;
            if (eFilter.getName().equals("mycoreclass")) {
                eFilter = eFilter.getChild("categories");
            }
            filterNonEmpty(docClass.getRootElement().getAttributeValue("ID"), eFilter);
        }
        if (filterNoChildren) {
            eRoot.removeChildren("category");
        }
        String authHeader = MCRJSONWebTokenUtil.createJWTAuthorizationHeader(MCRJSONWebTokenUtil.retrieveAuthenticationToken(request));
        if (FORMAT_JSON.equals(format)) {
            String json = writeJSON(eRoot, lang, style);
            // eventually: allow Cross Site Requests: .header("Access-Control-Allow-Origin", "*")
            if (callback.length() > 0) {
                return Response.ok(callback + "(" + json + ")").type("application/javascript; charset=UTF-8").build();
            } else {
                return Response.ok(json).type("application/json; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, authHeader).build();
            }
        }
        if (FORMAT_XML.equals(format)) {
            String xml = writeXML(eRoot, lang);
            return Response.ok(xml).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, authHeader).build();
        }
    } catch (Exception e) {
        LogManager.getLogger(this.getClass()).error("Error outputting classification", e);
    // TODO response.sendError(HttpServletResponse.SC_NOT_FOUND, "Error outputting classification");
    }
    return null;
}
Also used : MCRCategory(org.mycore.datamodel.classifications2.MCRCategory) MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) Element(org.jdom2.Element) MCRRestAPIError(org.mycore.restapi.v1.errors.MCRRestAPIError) Document(org.jdom2.Document) SolrServerException(org.apache.solr.client.solrj.SolrServerException) IOException(java.io.IOException) MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 25 with Format

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

the class MCRRestAPIClassifications method writeChildrenAsJSONJSTree.

/**
 * output children in JSON format used as input for a jsTree
 *
 * @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
 * @param opened - true, if all leaf nodes should be displayed
 * @param disabled - true, if all nodes should be disabled
 * @param selected - true, if all node should be selected
 *
 * @throws IOException
 */
private static void writeChildrenAsJSONJSTree(Element eParent, JsonWriter writer, String lang, boolean opened, boolean disabled, boolean selected) 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"));
            }
        }
        if (opened || disabled || selected) {
            writer.name("state");
            writer.beginObject();
            if (opened) {
                writer.name("opened").value(true);
            }
            if (disabled) {
                writer.name("disabled").value(true);
            }
            if (selected) {
                writer.name("selected").value(true);
            }
            writer.endObject();
        }
        if (e.getChildren("category").size() > 0) {
            writer.name("children");
            writeChildrenAsJSONJSTree(e, writer, lang, opened, disabled, selected);
        }
        writer.endObject();
    }
    writer.endArray();
}
Also used : Element(org.jdom2.Element)

Aggregations

Element (org.jdom2.Element)57 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