Search in sources :

Example 21 with MCRCategory

use of org.mycore.datamodel.classifications2.MCRCategory in project mycore by MyCoRe-Org.

the class MCRClassificationMappingEventHandlerTest method loadCategory.

private void loadCategory(String categoryFileName) throws URISyntaxException, JDOMException, IOException {
    ClassLoader classLoader = getClass().getClassLoader();
    SAXBuilder saxBuilder = new SAXBuilder();
    MCRCategory category = MCRXMLTransformer.getCategory(saxBuilder.build(classLoader.getResourceAsStream(TEST_DIRECTORY + categoryFileName)));
    getDAO().addCategory(null, category);
}
Also used : MCRCategory(org.mycore.datamodel.classifications2.MCRCategory) SAXBuilder(org.jdom2.input.SAXBuilder)

Example 22 with MCRCategory

use of org.mycore.datamodel.classifications2.MCRCategory in project mycore by MyCoRe-Org.

the class MCRClassMapper method getAuthority.

private static String getAuthority(String rootID) {
    long classLastModified = Math.max(0, DAO.getLastModified(rootID));
    String auth = authCache.getIfUpToDate(rootID, classLastModified);
    if (auth == null) {
        MCRCategory rootCategory = DAO.getRootCategory(MCRCategoryID.rootID(rootID), 0);
        auth = rootCategory.getLabel("x-auth").map(MCRLabel::getText).orElse("");
        authCache.put(rootID, auth, classLastModified);
    }
    return auth.isEmpty() ? null : auth;
}
Also used : MCRCategory(org.mycore.datamodel.classifications2.MCRCategory) MCRLabel(org.mycore.datamodel.classifications2.MCRLabel)

Example 23 with MCRCategory

use of org.mycore.datamodel.classifications2.MCRCategory in project mycore by MyCoRe-Org.

the class MCRClassMapper method getAuthorityURI.

private static String getAuthorityURI(String rootID) {
    long classLastModified = Math.max(0, DAO.getLastModified(rootID));
    String authURI = authURICache.getIfUpToDate(rootID, classLastModified);
    if (authURI == null) {
        MCRCategory rootCategory = DAO.getRootCategory(MCRCategoryID.rootID(rootID), 0);
        authURI = MCRAuthorityWithURI.getAuthorityURI(rootCategory);
        authURICache.put(rootID, authURI, classLastModified);
    }
    return authURI;
}
Also used : MCRCategory(org.mycore.datamodel.classifications2.MCRCategory)

Example 24 with MCRCategory

use of org.mycore.datamodel.classifications2.MCRCategory 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 25 with MCRCategory

use of org.mycore.datamodel.classifications2.MCRCategory 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)

Aggregations

MCRCategory (org.mycore.datamodel.classifications2.MCRCategory)87 MCRCategoryID (org.mycore.datamodel.classifications2.MCRCategoryID)36 Test (org.junit.Test)24 MCRLabel (org.mycore.datamodel.classifications2.MCRLabel)17 MCRCategoryDAO (org.mycore.datamodel.classifications2.MCRCategoryDAO)10 ArrayList (java.util.ArrayList)9 Document (org.jdom2.Document)9 Element (org.jdom2.Element)8 MCRException (org.mycore.common.MCRException)8 IOException (java.io.IOException)6 EntityManager (javax.persistence.EntityManager)6 URI (java.net.URI)5 Collection (java.util.Collection)5 HashMap (java.util.HashMap)5 LogManager (org.apache.logging.log4j.LogManager)5 Logger (org.apache.logging.log4j.Logger)5 MCRCommand (org.mycore.frontend.cli.annotation.MCRCommand)5 HashSet (java.util.HashSet)4 LinkedList (java.util.LinkedList)4 List (java.util.List)4