Search in sources :

Example 71 with Document

use of com.google.cloud.documentai.v1beta2.Document 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 72 with Document

use of com.google.cloud.documentai.v1beta2.Document 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 73 with Document

use of com.google.cloud.documentai.v1beta2.Document in project mycore by MyCoRe-Org.

the class MCREditorSubmissionTest method testSubmitSelectOptions.

@Test
public void testSubmitSelectOptions() throws JaxenException, JDOMException, IOException {
    String template = "document[category='a'][category[2]='b'][category[3]='c']";
    MCREditorSession session = new MCREditorSession();
    session.setEditedXML(new Document(new MCRNodeBuilder().buildElement(template, null, null)));
    session.getSubmission().mark2checkResubmission(new MCRBinding("/document/category", true, session.getRootBinding()));
    session.getSubmission().emptyNotResubmittedNodes();
    List<Element> categories = session.getEditedXML().getRootElement().getChildren("category");
    assertEquals(3, categories.size());
    assertEquals("", categories.get(0).getText());
    assertEquals("", categories.get(1).getText());
    assertEquals("", categories.get(2).getText());
    session.getSubmission().mark2checkResubmission(new MCRBinding("/document/category", true, session.getRootBinding()));
    Map<String, String[]> submittedValues = new HashMap<>();
    submittedValues.put("/document/category", new String[] { "c", "d" });
    session.getSubmission().setSubmittedValues(submittedValues);
    session.getSubmission().emptyNotResubmittedNodes();
    categories = session.getEditedXML().getRootElement().getChildren("category");
    assertEquals(3, categories.size());
    assertEquals("c", categories.get(0).getText());
    assertEquals("d", categories.get(1).getText());
    assertEquals("", categories.get(2).getText());
    session.getSubmission().mark2checkResubmission(new MCRBinding("/document/category", true, session.getRootBinding()));
    submittedValues.clear();
    submittedValues.put("/document/category", new String[] { "a", "b", "c", "d" });
    session.getSubmission().setSubmittedValues(submittedValues);
    session.getSubmission().emptyNotResubmittedNodes();
    categories = session.getEditedXML().getRootElement().getChildren("category");
    assertEquals(4, categories.size());
    assertEquals("a", categories.get(0).getText());
    assertEquals("b", categories.get(1).getText());
    assertEquals("c", categories.get(2).getText());
    assertEquals("d", categories.get(3).getText());
}
Also used : MCRNodeBuilder(org.mycore.common.xml.MCRNodeBuilder) HashMap(java.util.HashMap) Element(org.jdom2.Element) Document(org.jdom2.Document) Test(org.junit.Test)

Example 74 with Document

use of com.google.cloud.documentai.v1beta2.Document in project mycore by MyCoRe-Org.

the class MCRDOIRegistrationService method transformToDatacite.

protected Document transformToDatacite(MCRDigitalObjectIdentifier doi, MCRBase mcrBase) throws MCRPersistentIdentifierException {
    MCRObjectID id = mcrBase.getId();
    MCRBaseContent content = new MCRBaseContent(mcrBase);
    try {
        MCRContent transform = MCRContentTransformerFactory.getTransformer(this.transformer).transform(content);
        Document dataciteDocument = transform.asXML();
        insertDOI(dataciteDocument, doi);
        Schema dataciteSchema = loadDataciteSchema();
        try {
            dataciteSchema.newValidator().validate(new JDOMSource(dataciteDocument));
        } catch (SAXException e) {
            String translatedInformation = MCRTranslation.translate(TRANSLATE_PREFIX + ERR_CODE_1_2);
            throw new MCRPersistentIdentifierException("The document " + id + " does not generate well formed Datacite!", translatedInformation, ERR_CODE_1_2, e);
        }
        return dataciteDocument;
    } catch (IOException | JDOMException | SAXException e) {
        throw new MCRPersistentIdentifierException("Could not transform the content of " + id + " with the transformer " + transformer, e);
    }
}
Also used : Schema(javax.xml.validation.Schema) MCRBaseContent(org.mycore.common.content.MCRBaseContent) JDOMSource(org.jdom2.transform.JDOMSource) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) IOException(java.io.IOException) Document(org.jdom2.Document) MCRPersistentIdentifierException(org.mycore.pi.exceptions.MCRPersistentIdentifierException) JDOMException(org.jdom2.JDOMException) MCRContent(org.mycore.common.content.MCRContent) SAXException(org.xml.sax.SAXException)

Example 75 with Document

use of com.google.cloud.documentai.v1beta2.Document in project mycore by MyCoRe-Org.

the class MCRDOIRegistrationService method registerJob.

@Override
public void registerJob(Map<String, String> parameters) throws MCRPersistentIdentifierException {
    MCRDigitalObjectIdentifier doi = getDOIFromJob(parameters);
    String idString = parameters.get(CONTEXT_OBJ);
    MCRObjectID objectID = MCRObjectID.getInstance(idString);
    this.validateJobUserRights(objectID);
    MCRObject object = MCRMetadataManager.retrieveMCRObject(objectID);
    MCRObject mcrBase = MCRMetadataManager.retrieveMCRObject(objectID);
    Document dataciteDocument = transformToDatacite(doi, mcrBase);
    MCRDataciteClient dataciteClient = getDataciteClient();
    dataciteClient.storeMetadata(dataciteDocument);
    URI registeredURI;
    try {
        registeredURI = getRegisteredURI(object);
        dataciteClient.mintDOI(doi, registeredURI);
    } catch (URISyntaxException e) {
        throw new MCRException("Base-URL seems to be invalid!", e);
    }
    List<Map.Entry<String, URI>> entryList = getMediaList((MCRObject) object);
    dataciteClient.setMediaList(doi, entryList);
    this.updateRegistrationDate(objectID, "", new Date());
}
Also used : MCRException(org.mycore.common.MCRException) MCRObject(org.mycore.datamodel.metadata.MCRObject) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) URISyntaxException(java.net.URISyntaxException) Document(org.jdom2.Document) URI(java.net.URI) Date(java.util.Date)

Aggregations

Document (org.jdom2.Document)559 Element (org.jdom2.Element)330 Test (org.junit.Test)170 SAXBuilder (org.jdom2.input.SAXBuilder)160 IOException (java.io.IOException)146 JDOMException (org.jdom2.JDOMException)94 File (java.io.File)84 XMLOutputter (org.jdom2.output.XMLOutputter)80 MCRJDOMContent (org.mycore.common.content.MCRJDOMContent)48 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)34 ArrayList (java.util.ArrayList)33 HashMap (java.util.HashMap)32 MCRNodeBuilder (org.mycore.common.xml.MCRNodeBuilder)31 MCRContent (org.mycore.common.content.MCRContent)30 MCRObject (org.mycore.datamodel.metadata.MCRObject)30 MCRException (org.mycore.common.MCRException)28 InputStream (java.io.InputStream)27 StringReader (java.io.StringReader)26 Path (java.nio.file.Path)26 URL (java.net.URL)24