Search in sources :

Example 11 with MCRRestAPIException

use of org.mycore.restapi.v1.errors.MCRRestAPIException 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 12 with MCRRestAPIException

use of org.mycore.restapi.v1.errors.MCRRestAPIException in project mycore by MyCoRe-Org.

the class MCRRestAPIObjectsHelper method retrieveMCRObject.

private static MCRObject retrieveMCRObject(String idString) throws MCRRestAPIException {
    // the default value for the key
    String key = "mcr";
    if (idString.contains(":")) {
        int pos = idString.indexOf(":");
        key = idString.substring(0, pos);
        idString = idString.substring(pos + 1);
        if (!key.equals("mcr")) {
            try {
                idString = URLDecoder.decode(idString, "UTF-8");
            } catch (UnsupportedEncodingException e) {
            // will not happen
            }
        // ToDo - Shall we restrict the key set with a property?
        // throw new MCRRestAPIException(MCRRestAPIError.create(Response.Status.BAD_REQUEST,
        // "The ID is not valid.", "The prefix is unkown. Only 'mcr' is allowed."));
        }
    }
    if (key.equals("mcr")) {
        MCRObjectID mcrID = null;
        try {
            mcrID = MCRObjectID.getInstance(idString);
        } catch (Exception e) {
            throw new MCRRestAPIException(Response.Status.BAD_REQUEST, new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_ID, "The MyCoRe ID '" + idString + "' is not valid. - Did you use the proper format: '{project}_{type}_{number}'?", e.getMessage()));
        }
        if (!MCRMetadataManager.exists(mcrID)) {
            throw new MCRRestAPIException(Response.Status.NOT_FOUND, new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "There is no object with the given MyCoRe ID '" + idString + "'.", null));
        }
        return MCRMetadataManager.retrieveMCRObject(mcrID);
    } else {
        SolrClient solrClient = MCRSolrClientFactory.getSolrClient();
        SolrQuery query = new SolrQuery();
        query.setQuery(key + ":" + idString);
        try {
            QueryResponse response = solrClient.query(query);
            SolrDocumentList solrResults = response.getResults();
            if (solrResults.getNumFound() == 1) {
                String id = solrResults.get(0).getFieldValue("returnId").toString();
                return retrieveMCRObject(id);
            } else {
                if (solrResults.getNumFound() == 0) {
                    throw new MCRRestAPIException(Response.Status.NOT_FOUND, new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "There is no object with the given ID '" + key + ":" + idString + "'.", null));
                } else {
                    throw new MCRRestAPIException(Response.Status.NOT_FOUND, new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "The ID is not unique. There are " + solrResults.getNumFound() + " objecst fore the given ID '" + key + ":" + idString + "'.", null));
                }
            }
        } catch (SolrServerException | IOException e) {
            LOGGER.error(e);
            throw new MCRRestAPIException(Response.Status.BAD_REQUEST, new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, "Internal server error.", e.getMessage()));
        }
    }
}
Also used : MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) SolrServerException(org.apache.solr.client.solrj.SolrServerException) MCRRestAPIError(org.mycore.restapi.v1.errors.MCRRestAPIError) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SolrDocumentList(org.apache.solr.common.SolrDocumentList) IOException(java.io.IOException) SolrServerException(org.apache.solr.client.solrj.SolrServerException) JDOMException(org.jdom2.JDOMException) ParseException(java.text.ParseException) MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MCRException(org.mycore.common.MCRException) IOException(java.io.IOException) SolrQuery(org.apache.solr.client.solrj.SolrQuery) SolrClient(org.apache.solr.client.solrj.SolrClient) QueryResponse(org.apache.solr.client.solrj.response.QueryResponse) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID)

Example 13 with MCRRestAPIException

use of org.mycore.restapi.v1.errors.MCRRestAPIException 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 14 with MCRRestAPIException

use of org.mycore.restapi.v1.errors.MCRRestAPIException in project mycore by MyCoRe-Org.

the class MCRRestAPIObjectsHelper method showMCRDerivate.

public static Response showMCRDerivate(String pathParamMcrID, String pathParamDerID, UriInfo info, HttpServletRequest request) throws MCRRestAPIException {
    MCRObject mcrObj = retrieveMCRObject(pathParamMcrID);
    MCRDerivate derObj = retrieveMCRDerivate(mcrObj, pathParamDerID);
    try {
        Document doc = derObj.createXML();
        Document docContent = listDerivateContentAsXML(derObj, "/", -1, info);
        if (docContent != null && docContent.hasRootElement()) {
            doc.getRootElement().addContent(docContent.getRootElement().detach());
        }
        StringWriter sw = new StringWriter();
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        outputter.output(doc, sw);
        String authHeader = MCRJSONWebTokenUtil.createJWTAuthorizationHeader(MCRJSONWebTokenUtil.retrieveAuthenticationToken(request));
        return Response.ok(sw.toString()).type("application/xml").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()));
    }
// return MCRRestAPIError.create(Response.Status.INTERNAL_SERVER_ERROR, "Unexepected program flow termination.",
// "Please contact a developer!").createHttpResponse();
}
Also used : XMLOutputter(org.jdom2.output.XMLOutputter) MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) MCRObject(org.mycore.datamodel.metadata.MCRObject) StringWriter(java.io.StringWriter) MCRRestAPIError(org.mycore.restapi.v1.errors.MCRRestAPIError) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) IOException(java.io.IOException) Document(org.jdom2.Document)

Example 15 with MCRRestAPIException

use of org.mycore.restapi.v1.errors.MCRRestAPIException 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)

Aggregations

MCRRestAPIException (org.mycore.restapi.v1.errors.MCRRestAPIException)16 MCRRestAPIError (org.mycore.restapi.v1.errors.MCRRestAPIError)14 IOException (java.io.IOException)11 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)8 Document (org.jdom2.Document)7 XMLOutputter (org.jdom2.output.XMLOutputter)6 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)6 SignedJWT (com.nimbusds.jwt.SignedJWT)5 StringWriter (java.io.StringWriter)5 MCRUserInformation (org.mycore.common.MCRUserInformation)5 MCRObject (org.mycore.datamodel.metadata.MCRObject)5 Date (java.util.Date)4 Element (org.jdom2.Element)4 MCRSession (org.mycore.common.MCRSession)4 ArrayList (java.util.ArrayList)3 MCRAccessException (org.mycore.access.MCRAccessException)3 MCRPersistenceException (org.mycore.common.MCRPersistenceException)3 MCRMetaLinkID (org.mycore.datamodel.metadata.MCRMetaLinkID)3 JsonWriter (com.google.gson.stream.JsonWriter)2 ParseException (java.text.ParseException)2