Search in sources :

Example 16 with Filter

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

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

the class MCRURNObjectXPathMetadataManager method removeIdentifier.

@Override
public void removeIdentifier(MCRDNBURN identifier, MCRBase obj, String additional) {
    String xpath = getProperties().get("Xpath");
    Document xml = obj.createXML();
    XPathFactory xPathFactory = XPathFactory.instance();
    XPathExpression<Element> xp = xPathFactory.compile(xpath, Filters.element());
    List<Element> elements = xp.evaluate(xml);
    elements.stream().filter(element -> element.getTextTrim().equals(identifier.asString())).forEach(Element::detach);
}
Also used : MCRBase(org.mycore.datamodel.metadata.MCRBase) MCRMetadataManager(org.mycore.datamodel.metadata.MCRMetadataManager) MCRPersistentIdentifierException(org.mycore.pi.exceptions.MCRPersistentIdentifierException) XPathFactory(org.jdom2.xpath.XPathFactory) MCRPersistentIdentifier(org.mycore.pi.MCRPersistentIdentifier) MCRException(org.mycore.common.MCRException) Text(org.jdom2.Text) XPathExpression(org.jdom2.xpath.XPathExpression) Document(org.jdom2.Document) List(java.util.List) MCRObject(org.mycore.datamodel.metadata.MCRObject) Optional(java.util.Optional) MCRPersistentIdentifierMetadataManager(org.mycore.pi.MCRPersistentIdentifierMetadataManager) Filters(org.jdom2.filter.Filters) MCRNodeBuilder(org.mycore.common.xml.MCRNodeBuilder) Element(org.jdom2.Element) XPathFactory(org.jdom2.xpath.XPathFactory) Element(org.jdom2.Element) Document(org.jdom2.Document)

Example 18 with Filter

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

the class MCRIdentifierXSLUtils method getPIServiceInformation.

/**
 * Gets all available services which are configured.
 * e.g.
 *   <ul>
 *     <li>&lt;service id="service1" inscribed="false" permission="true" type="urn" /&gt;</li>
 *     <li>&lt;service id="service2" inscribed="true" permission="false" type="doi" /&gt;</li>
 *   </ul>
 *
 * @param objectID the object
 * @return a Nodelist
 * @throws JDOMException
 */
public static NodeList getPIServiceInformation(String objectID) throws JDOMException {
    Element e = new Element("list");
    MCRBase obj = MCRMetadataManager.retrieve(MCRObjectID.getInstance(objectID));
    MCRConfiguration.instance().getPropertiesMap("MCR.PI.Registration.").keySet().stream().map(s -> s.substring("MCR.PI.Registration.".length())).filter(id -> !id.contains(".")).map((serviceID) -> MCRPIRegistrationServiceManager.getInstance().getRegistrationService(serviceID)).map((rs -> {
        Element service = new Element("service");
        service.setAttribute("id", rs.getRegistrationServiceID());
        // Check if the inscriber of this service can read a PI
        try {
            if (rs.getMetadataManager().getIdentifier(obj, "").isPresent()) {
                service.setAttribute("inscribed", "true");
            } else {
                service.setAttribute("inscribed", "false");
            }
        } catch (MCRPersistentIdentifierException e1) {
            LOGGER.warn("Error happened while try to read PI from object: {}", objectID, e1);
            service.setAttribute("inscribed", "false");
        }
        // rights
        String permission = "register-" + rs.getRegistrationServiceID();
        Boolean canRegister = MCRAccessManager.checkPermission(objectID, "writedb") && MCRAccessManager.checkPermission(obj.getId(), permission);
        service.setAttribute("permission", canRegister.toString().toLowerCase(Locale.ROOT));
        // add the type
        service.setAttribute("type", rs.getType());
        return service;
    })).forEach(e::addContent);
    return new DOMOutputter().output(e).getElementsByTagName("service");
}
Also used : MCRBase(org.mycore.datamodel.metadata.MCRBase) MCRMetadataManager(org.mycore.datamodel.metadata.MCRMetadataManager) NodeList(org.w3c.dom.NodeList) DOMOutputter(org.jdom2.output.DOMOutputter) MCRPersistentIdentifierException(org.mycore.pi.exceptions.MCRPersistentIdentifierException) MCRConfiguration(org.mycore.common.config.MCRConfiguration) MCRPersistentIdentifier(org.mycore.pi.MCRPersistentIdentifier) MCRAccessManager(org.mycore.access.MCRAccessManager) MCRPIRegistrationService(org.mycore.pi.MCRPIRegistrationService) Logger(org.apache.logging.log4j.Logger) JDOMException(org.jdom2.JDOMException) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) Locale(java.util.Locale) MCRPersistentIdentifierManager(org.mycore.pi.MCRPersistentIdentifierManager) LogManager(org.apache.logging.log4j.LogManager) MCRPIRegistrationServiceManager(org.mycore.pi.MCRPIRegistrationServiceManager) Element(org.jdom2.Element) DOMOutputter(org.jdom2.output.DOMOutputter) MCRBase(org.mycore.datamodel.metadata.MCRBase) MCRPIRegistrationService(org.mycore.pi.MCRPIRegistrationService) Locale(java.util.Locale) Element(org.jdom2.Element) MCRBase(org.mycore.datamodel.metadata.MCRBase) MCRPersistentIdentifierException(org.mycore.pi.exceptions.MCRPersistentIdentifierException)

Example 19 with Filter

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

the class MCRAttributeValueFilter method filter.

public Element filter(Object arg0) {
    Element e = super.filter(arg0);
    if (e == null) {
        return null;
    }
    String value = e.getAttributeValue(attrKey, ns);
    return (value != null && value.equals(attrValue)) ? e : null;
}
Also used : Element(org.jdom2.Element)

Example 20 with Filter

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

the class MCRErrorServlet method generateErrorPage.

protected void generateErrorPage(HttpServletRequest request, HttpServletResponse response, String msg, Throwable ex, Integer statusCode, Class<? extends Throwable> exceptionType, String requestURI, String servletName) throws IOException, TransformerException, SAXException {
    boolean exceptionThrown = ex != null;
    LOGGER.log(exceptionThrown ? Level.ERROR : Level.WARN, MessageFormat.format("{0}: Error {1} occured. The following message was given: {2}", requestURI, statusCode, msg), ex);
    String style = MCRFrontendUtil.getProperty(request, "XSL.Style").filter("xml"::equals).orElse("default");
    request.setAttribute("XSL.Style", style);
    Document errorDoc = buildErrorPage(msg, statusCode, requestURI, exceptionType, servletName, ex);
    final String requestAttr = "MCRErrorServlet.generateErrorPage";
    if (!response.isCommitted() && request.getAttribute(requestAttr) == null) {
        if (statusCode != null) {
            response.setStatus(statusCode);
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        request.setAttribute(requestAttr, msg);
        boolean currentSessionActive = MCRSessionMgr.hasCurrentSession();
        boolean sessionFromRequest = setCurrentSession(request);
        MCRSession session = null;
        try {
            session = MCRSessionMgr.getCurrentSession();
            boolean openTransaction = session.isTransactionActive();
            if (!openTransaction) {
                session.beginTransaction();
            }
            try {
                setWebAppBaseURL(session, request);
                LAYOUT_SERVICE.doLayout(request, response, new MCRJDOMContent(errorDoc));
            } finally {
                if (!openTransaction)
                    session.commitTransaction();
            }
        } finally {
            if (exceptionThrown || !currentSessionActive) {
                MCRSessionMgr.releaseCurrentSession();
            }
            if (!sessionFromRequest) {
                // new session created for transaction
                session.close();
            }
        }
    } else {
        if (request.getAttribute(requestAttr) != null) {
            LOGGER.warn("Could not send error page. Generating error page failed. The original message:\n{}", request.getAttribute(requestAttr));
        } else {
            LOGGER.warn("Could not send error page. Response allready commited. The following message was given:\n{}", msg);
        }
    }
}
Also used : MCRSession(org.mycore.common.MCRSession) MCRJDOMContent(org.mycore.common.content.MCRJDOMContent) Document(org.jdom2.Document)

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