Example usage for org.jdom2 Document Document

List of usage examples for org.jdom2 Document Document

Introduction

In this page you can find the example usage for org.jdom2 Document Document.

Prototype

public Document(List<? extends Content> content) 

Source Link

Document

This will create a new Document, with the supplied list of content, and a DocType declaration only if the content contains a DocType instance.

Usage

From source file:org.mycore.restapi.v1.MCRRestAPIClassifications.java

License:Open Source License

/**
 * Output xml//  www . j a va  2  s. co m
 * @param eRoot - the root element
 * @param lang - the language which should be filtered or null for no filter
 * @return a string representation of the XML
 * @throws IOException
 */
private static String writeXML(Element eRoot, String lang) throws IOException {
    StringWriter sw = new StringWriter();
    if (lang != null) {
        // <label xml:lang="en" text="part" />
        XPathExpression<Element> xpE = XPathFactory.instance().compile("//label[@xml:lang!='" + lang + "']",
                Filters.element(), null, Namespace.XML_NAMESPACE);
        for (Element e : xpE.evaluate(eRoot)) {
            e.getParentElement().removeContent(e);
        }
    }
    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
    Document docOut = new Document(eRoot.detach());
    xout.output(docOut, sw);
    return sw.toString();
}

From source file:org.mycore.restapi.v1.utils.MCRRestAPIObjectsHelper.java

License:Open Source License

/**
 * @see MCRRestAPIObjects#listObjects(UriInfo, String, String, String)
 *//*from   w  ww. j  av a 2  s .c o  m*/
public static Response listObjects(UriInfo info, String format, String filter, String sort) {
    //analyze sort
    MCRRestAPIError error = MCRRestAPIError.create(Response.Status.BAD_REQUEST,
            "The syntax of one or more query parameters is wrong.", null);

    MCRRestAPISortObject sortObj = null;
    try {
        sortObj = createSortObject(sort);
    } catch (MCRRestAPIException rae) {
        for (MCRRestAPIFieldError fe : rae.getError().getFieldErrors()) {
            error.addFieldError(fe);
        }
    }

    //analyze format

    if (format.equals(MCRRestAPIObjects.FORMAT_JSON) || format.equals(MCRRestAPIObjects.FORMAT_XML)) {
        //ok
    } else {
        error.addFieldError(
                MCRRestAPIFieldError.create("format", "Allowed values for format are 'json' or 'xml'."));
    }

    //analyze filter
    List<String> projectIDs = new ArrayList<String>();
    List<String> typeIDs = new ArrayList<String>();
    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))) {
                    error.addFieldError(MCRRestAPIFieldError.create("filter",
                            "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))) {
                    error.addFieldError(MCRRestAPIFieldError.create("filter",
                            "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;
            }

            error.addFieldError(MCRRestAPIFieldError.create("filter", "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 (error.getFieldErrors().size() > 0) {
        return error.createHttpResponse();
    }

    //Parameters are checked - continue tor retrieve data

    //retrieve MCRIDs by Type and Project ID
    Set<String> mcrIDs = new HashSet<String>();
    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<String>();
    l.addAll(mcrIDs);
    List<MCRObjectIDDate> objIdDates = new ArrayList<MCRObjectIDDate>();
    try {
        objIdDates = MCRXMLMetadataManager.instance().retrieveObjectDates(l);
    } catch (IOException e) {
        //TODO
    }
    if (lastModifiedAfter != null || lastModifiedBefore != null) {
        List<MCRObjectIDDate> testObjIdDates = objIdDates;
        objIdDates = new ArrayList<MCRObjectIDDate>();
        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) {
        Collections.sort(objIdDates, new MCRRestAPISortObjectComparator(sortObj));
    }

    //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").build();
        } catch (IOException e) {
            return MCRRestAPIError.create(Response.Status.INTERNAL_SERVER_ERROR,
                    "A problem occurred while fetching the data", e.getMessage()).createHttpResponse();
        }
    }

    //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").build();
        } catch (IOException e) {
            return MCRRestAPIError.create(Response.Status.INTERNAL_SERVER_ERROR,
                    "A problem occurred while fetching the data", e.getMessage()).createHttpResponse();
        }
    }
    return MCRRestAPIError.create(Response.Status.INTERNAL_SERVER_ERROR, "A problem in programm flow", null)
            .createHttpResponse();
}

From source file:org.mycore.restapi.v1.utils.MCRRestAPIObjectsHelper.java

License:Open Source License

/**
 * @see MCRRestAPIObjects#listDerivates(UriInfo, String, String, String)
 *///ww  w.jav  a 2 s.c  om
public static Response listDerivates(UriInfo info, String mcrIDString, String format, String sort) {
    //analyze sort
    try {
        MCRRestAPIError error = MCRRestAPIError.create(Response.Status.BAD_REQUEST,
                "The syntax of one or more query parameters is wrong.", null);

        MCRRestAPISortObject sortObj = null;
        try {
            sortObj = createSortObject(sort);
        } catch (MCRRestAPIException rae) {
            for (MCRRestAPIFieldError fe : rae.getError().getFieldErrors()) {
                error.addFieldError(fe);
            }
        }

        //analyze format

        if (format.equals(MCRRestAPIObjects.FORMAT_JSON) || format.equals(MCRRestAPIObjects.FORMAT_XML)) {
            //ok
        } else {
            error.addFieldError(
                    MCRRestAPIFieldError.create("format", "Allowed values for format are 'json' or 'xml'."));
        }

        if (error.getFieldErrors().size() > 0) {
            throw new MCRRestAPIException(error);
        }

        //Parameters are checked - continue to retrieve data

        List<MCRObjectIDDate> objIdDates = retrieveMCRObject(mcrIDString).getStructure().getDerivates().stream()
                .map(MCRMetaLinkID::getXLinkHrefID).filter(MCRMetadataManager::exists).map(id -> {
                    return 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());

        //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").build();
            } catch (IOException e) {
                return MCRRestAPIError
                        .create(Response.Status.INTERNAL_SERVER_ERROR,
                                "A problem occurred while fetching the data", e.getMessage())
                        .createHttpResponse();
            }
        }

        //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").build();
            } catch (IOException e) {
                throw new MCRRestAPIException(MCRRestAPIError.create(Response.Status.INTERNAL_SERVER_ERROR,
                        "A problem occurred while fetching the data", e.getMessage()));
            }
        }
    } catch (MCRRestAPIException rae) {
        return rae.getError().createHttpResponse();
    }

    return MCRRestAPIError.create(Response.Status.INTERNAL_SERVER_ERROR,
            "Unexepected program flow termination.", "Please contact a developer!").createHttpResponse();
}

From source file:org.mycore.restapi.v1.utils.MCRRestAPIObjectsHelper.java

License:Open Source License

public static Response listContents(Request request, String mcrIDString, String derIDString, String format,
        String path, int depth, UriInfo info) throws IOException {
    try {// www  .j  a  v  a  2 s. co  m

        if (!format.equals(MCRRestAPIObjects.FORMAT_JSON) && !format.equals(MCRRestAPIObjects.FORMAT_XML)) {
            MCRRestAPIError error = MCRRestAPIError.create(Response.Status.BAD_REQUEST,
                    "The syntax of one or more query parameters is wrong.", null);
            error.addFieldError(
                    MCRRestAPIFieldError.create("format", "Allowed values for format are 'json' or 'xml'."));
            throw new MCRRestAPIException(error);
        }
        //TODO: parsing jdom documents is really necessary?
        MCRObject mcrObj = retrieveMCRObject(mcrIDString);
        MCRDerivate derObj = retrieveMCRDerivate(mcrObj, derIDString);

        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.build();
        }
        switch (format) {
        case MCRRestAPIObjects.FORMAT_XML:
            Document docOut = new Document(listDerivateContent(mcrObj, derObj, path, info));
            try (StringWriter sw = new StringWriter()) {
                XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
                xout.output(docOut, sw);
                return response(sw.toString(), "application/xml", lastModified);
            } catch (IOException e) {
                return MCRRestAPIError
                        .create(Response.Status.INTERNAL_SERVER_ERROR,
                                "A problem occurred while fetching the data", e.getMessage())
                        .createHttpResponse();
            }
        case MCRRestAPIObjects.FORMAT_JSON:
            if (MCRRestAPIObjects.FORMAT_JSON.equals(format)) {
                String result = listDerivateContentAsJson(derObj, path, depth, info);
                return response(result, "application/json", lastModified);
            }
        default:
            return MCRRestAPIError.create(Response.Status.INTERNAL_SERVER_ERROR,
                    "Unexepected program flow termination.", "Please contact a developer!")
                    .createHttpResponse();
        }
    } catch (MCRRestAPIException rae) {
        return rae.getError().createHttpResponse();
    }
}

From source file:org.mycore.services.fieldquery.MCRQuery.java

License:Open Source License

/**
 * Builds a XML representation of the query
 * /*from www.j  a v a  2s .  c o  m*/
 * @return a XML document containing all query parameters
 */
public synchronized Document buildXML() {
    if (doc == null) {
        Element query = new Element("query");
        query.setAttribute("maxResults", String.valueOf(maxResults));

        if (sortBy != null && sortBy.size() > 0) {
            Element sortByElem = new Element("sortBy");
            query.addContent(sortByElem);
            for (MCRSortBy sb : sortBy) {
                Element ref = new Element("field");
                ref.setAttribute("name", sb.getFieldName());
                ref.setAttribute("order", sb.getSortOrder() ? "ascending" : "descending");
                sortByElem.addContent(ref);
            }
        }

        Element conditions = new Element("conditions");
        query.addContent(conditions);
        conditions.setAttribute("format", "xml");
        conditions.addContent(cond.toXML());
        doc = new Document(query);
    }
    return doc;
}

From source file:org.mycore.solr.index.document.MCRSolrTransformerInputDocumentFactory.java

License:Open Source License

private Document getMergedDocument(Map<MCRObjectID, MCRContent> contentMap)
        throws IOException, SAXException, JDOMException {
    Element rootElement = new Element("add");
    Document doc = new Document(rootElement);
    for (Map.Entry<MCRObjectID, MCRContent> entry : contentMap.entrySet()) {
        rootElement.addContent(entry.getValue().asXML().detachRootElement());
    }//from   ww  w.  j a  v a  2 s .  c  o m
    return doc;
}

From source file:org.mycore.user2.MCRRoleServlet.java

License:Open Source License

private void chooseRoleRoot(HttpServletRequest request) {
    Element rootElement = getRootElement(request);
    rootElement.addContent(getRoleElements());
    request.setAttribute(LAYOUT_ELEMENT_KEY, new Document(rootElement));
}

From source file:org.mycore.user2.MCRRoleServlet.java

License:Open Source License

private static void chooseCategory(HttpServletRequest request) {
    MCRCategoryID categoryID;//ww w.java  2  s .com
    String categID = getProperty(request, "categID");
    if (categID != null) {
        categoryID = MCRCategoryID.fromString(categID);
    } else {
        String rootID = getProperty(request, "classID");
        categoryID = (rootID == null) ? MCRUser2Constants.ROLE_CLASSID : MCRCategoryID.rootID(rootID);
    }
    Element rootElement = getRootElement(request);
    rootElement.setAttribute("classID", categoryID.getRootID());
    if (!categoryID.isRootID()) {
        rootElement.setAttribute("categID", categoryID.getID());
    }
    request.setAttribute(LAYOUT_ELEMENT_KEY, new Document(rootElement));
}

From source file:org.mycore.user2.MCRUserResolver.java

License:Open Source License

@Deprecated
public static Document getAllUsers() throws MCRAccessException {
    LOGGER.warn(//from  w  ww .  j  a v  a  2 s.c  om
            "Please fix https://sourceforge.net/tracker/?func=detail&aid=3497583&group_id=92005&atid=599192");
    if (!MCRAccessManager.checkPermission("modify-user")
            && !MCRAccessManager.checkPermission("modify-contact")) {
        throw MCRAccessException.missingPrivilege("List all users.", "modify-user", "modify-contact");
    }
    List<MCRUser> users = MCRUserManager.listUsers(null, null, null);
    // Loop over all assignable group IDs
    Element root = new org.jdom2.Element("items");
    for (MCRUser user : users) {
        Element item = new Element("item");
        StringBuilder label = new StringBuilder(user.getUserID());
        item.setAttribute("value", label.toString());
        if (user.getRealName() != null && user.getRealName().length() > 0) {
            label.append(" (").append(user.getRealName()).append(')');
        }
        item.setAttribute("label", label.toString());
        root.addContent(item);
    }
    return new Document(root);
}

From source file:org.openkennel.model.filemngr.XMLFileHandler.java

License:Open Source License

/**
 * Creates a XMLFileHandler to handle specific XML files.
 * Aswell the root element specified by parameter root is set.
 * /* www  . j  a v  a  2 s  .c om*/
 * @param root
 */
public XMLFileHandler(String root) {
    docBuilder = new SAXBuilder();
    xmlRoot = new Element(root);
    xmlFile = new Document(xmlRoot);
}