Search in sources :

Example 66 with Document

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

the class MCREditorOutValidator method setDefaultObjectACLs.

/**
 * The method add a default ACL-block.
 *
 * @param service
 * @throws IOException
 * @throws JDOMException
 */
private void setDefaultObjectACLs(org.jdom2.Element service) throws JDOMException, IOException {
    if (!MCRConfiguration.instance().getBoolean("MCR.Access.AddObjectDefaultRule", true)) {
        LOGGER.info("Adding object default acl rule is disabled.");
        return;
    }
    String resourcetype = "/editor_default_acls_" + id.getTypeId() + ".xml";
    String resourcebase = "/editor_default_acls_" + id.getBase() + ".xml";
    // Read stylesheet and add user
    InputStream aclxml = MCREditorOutValidator.class.getResourceAsStream(resourcebase);
    if (aclxml == null) {
        aclxml = MCREditorOutValidator.class.getResourceAsStream(resourcetype);
        if (aclxml == null) {
            LOGGER.warn("Can't find default object ACL file {} or {}", resourcebase.substring(1), resourcetype.substring(1));
            // fallback
            String resource = "/editor_default_acls.xml";
            aclxml = MCREditorOutValidator.class.getResourceAsStream(resource);
            if (aclxml == null) {
                return;
            }
        }
    }
    Document xml = SAX_BUILDER.build(aclxml);
    Element acls = xml.getRootElement().getChild("servacls");
    if (acls == null) {
        return;
    }
    for (Element acl : acls.getChildren()) {
        Element condition = acl.getChild("condition");
        if (condition == null) {
            continue;
        }
        Element rootbool = condition.getChild("boolean");
        if (rootbool == null) {
            continue;
        }
        for (Element orbool : rootbool.getChildren("boolean")) {
            for (Element firstcond : orbool.getChildren("condition")) {
                if (firstcond == null) {
                    continue;
                }
                String value = firstcond.getAttributeValue("value");
                if (value == null) {
                    continue;
                }
                if (value.equals("$CurrentUser")) {
                    String thisuser = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID();
                    firstcond.setAttribute("value", thisuser);
                    continue;
                }
                if (value.equals("$CurrentGroup")) {
                    throw new MCRException("The parameter $CurrentGroup in default ACLs is no more supported since MyCoRe 2014.06 because it is not supported in Servlet API 3.0");
                }
                int i = value.indexOf("$CurrentIP");
                if (i != -1) {
                    String thisip = MCRSessionMgr.getCurrentSession().getCurrentIP();
                    firstcond.setAttribute("value", value.substring(0, i) + thisip + value.substring(i + 10, value.length()));
                }
            }
        }
    }
    service.addContent(acls.detach());
}
Also used : MCRException(org.mycore.common.MCRException) InputStream(java.io.InputStream) Element(org.jdom2.Element) Document(org.jdom2.Document)

Example 67 with Document

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

the class MCRStoreBrowserRequest method buildResponseXML.

/**
 * Builds the xml output to be rendered as response
 */
Document buildResponseXML() throws Exception {
    File dir = getRequestedDirectory();
    String[] children = dir.list();
    Element xml = new Element("storeBrowser");
    if (children != null)
        for (String child : children) {
            xml.addContent(buildXML(child));
        }
    return new Document(xml);
}
Also used : Element(org.jdom2.Element) Document(org.jdom2.Document) File(java.io.File)

Example 68 with Document

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

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

the class MCRRestAPIObjectsHelper method listDerivateContentAsXML.

private static Document listDerivateContentAsXML(MCRDerivate derObj, String path, int depth, UriInfo info) throws IOException {
    Document doc = new Document();
    MCRPath root = MCRPath.getPath(derObj.getId().toString(), "/");
    root = MCRPath.toMCRPath(root.resolve(path));
    if (depth == -1) {
        depth = Integer.MAX_VALUE;
    }
    if (root != null) {
        Element eContents = new Element("contents");
        eContents.setAttribute("mycoreobject", derObj.getOwnerID().toString());
        eContents.setAttribute("mycorederivate", derObj.getId().toString());
        doc.addContent(eContents);
        if (!path.endsWith("/")) {
            path += "/";
        }
        MCRPath p = MCRPath.getPath(derObj.getId().toString(), path);
        if (p != null && Files.exists(p)) {
            Element eRoot = MCRPathXML.getDirectoryXML(p).getRootElement();
            eContents.addContent(eRoot.detach());
            createXMLForSubdirectories(p, eRoot, 1, depth);
        }
        // add href Attributes
        String baseURL = MCRJerseyUtil.getBaseURL(info) + MCRConfiguration.instance().getString("MCR.RestAPI.v1.Files.URL.path");
        baseURL = baseURL.replace("${mcrid}", derObj.getOwnerID().toString()).replace("${derid}", derObj.getId().toString());
        XPathExpression<Element> xp = XPathFactory.instance().compile(".//child[@type='file']", Filters.element());
        for (Element e : xp.evaluate(eContents)) {
            String uri = e.getChildText("uri");
            if (uri != null) {
                int pos = uri.lastIndexOf(":/");
                String subPath = uri.substring(pos + 2);
                while (subPath.startsWith("/")) {
                    subPath = path.substring(1);
                }
                e.setAttribute("href", baseURL + subPath);
            }
        }
    }
    return doc;
}
Also used : Element(org.jdom2.Element) Document(org.jdom2.Document) MCRPath(org.mycore.datamodel.niofs.MCRPath)

Example 70 with Document

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

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