Example usage for org.jdom2.output XMLOutputter XMLOutputter

List of usage examples for org.jdom2.output XMLOutputter XMLOutputter

Introduction

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

Prototype

public XMLOutputter(XMLOutputProcessor processor) 

Source Link

Document

This will create an XMLOutputter with the specified XMLOutputProcessor.

Usage

From source file:org.mycore.frontend.editor.MCREditorSubmission.java

License:Open Source License

private void validate(MCRRequestParameters parms, Element editor) {
    LOGGER.info("Validating editor input... ");

    for (Enumeration e = parms.getParameterNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();

        if (!name.startsWith("_sortnr-")) {
            continue;
        }/*  w ww .  ja  v a  2s  .  c o m*/

        name = name.substring(8);

        String ID = parms.getParameter("_id@" + name);

        if (ID == null || ID.trim().length() == 0) {
            continue;
        }

        String[] values = { "" };

        if (parms.getParameterValues(name) != null) {
            values = parms.getParameterValues(name);
        }

        Element component = MCREditorDefReader.findElementByID(ID, editor);

        if (component == null) {
            continue;
        }

        List conditions = component.getChildren("condition");

        if (conditions == null) {
            continue;
        }

        // Skip variables with values equal to autofill text
        String attrib = component.getAttributeValue("autofill");
        String elem = component.getChildTextTrim("autofill");
        String autofill = null;

        if (attrib != null && attrib.trim().length() > 0) {
            autofill = attrib.trim();
        } else if (attrib != null && attrib.trim().length() > 0) {
            autofill = elem.trim();
        }

        if (values[0].trim().equals(autofill)) {
            values[0] = "";
        }

        for (Object condition1 : conditions) {
            Element condition = (Element) condition1;

            boolean ok = true;
            for (int j = 0; j < values.length && ok; j++) {
                String nname = j == 0 ? name : name + "[" + (j + 1) + "]";
                ok = checkCondition(condition, nname, values[j]);

                if (!ok) {
                    String sortNr = parms.getParameter("_sortnr-" + name);
                    failed.put(sortNr, condition);

                    if (LOGGER.isDebugEnabled()) {
                        String cond = new XMLOutputter(Format.getCompactFormat()).outputString(condition);
                        LOGGER.debug("Validation condition failed:");
                        LOGGER.debug(nname + " = \"" + values[j] + "\"");
                        LOGGER.debug(cond);
                    }
                }
            }
        }
    }

    for (Enumeration e = parms.getParameterNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();

        if (!name.startsWith("_cond-")) {
            continue;
        }

        String path = name.substring(6);
        String[] ids = parms.getParameterValues(name);

        if (ids != null) {
            for (String id : ids) {
                Element condition = MCREditorDefReader.findElementByID(id, editor);

                if (condition == null) {
                    continue;
                }

                String field1 = condition.getAttributeValue("field1", "");
                String field2 = condition.getAttributeValue("field2", "");

                if (!field1.isEmpty() || !field2.isEmpty()) {
                    String pathA = path + ((!field1.isEmpty() && !field1.equals(".")) ? "/" + field1 : "");
                    String pathB = path + ((!field2.isEmpty() && !field2.equals(".")) ? "/" + field2 : "");

                    String valueA = parms.getParameter(pathA);
                    String valueB = parms.getParameter(pathB);

                    String sortNrA = parms.getParameter("_sortnr-" + pathA);
                    String sortNrB = parms.getParameter("_sortnr-" + pathB);

                    boolean pairValuesAlreadyInvalid = (failed.containsKey(sortNrA)
                            || failed.containsKey(sortNrB));

                    if (!pairValuesAlreadyInvalid) {
                        MCRValidator validator = MCRValidatorBuilder.buildPredefinedCombinedPairValidator();
                        setValidatorProperties(validator, condition);
                        if (!validator.isValid(valueA, valueB)) {
                            failed.put(sortNrA, condition);
                            failed.put(sortNrB, condition);
                        }
                    }
                } else {
                    XPathExpression<Element> xpath = XPathFactory.instance().compile(path, Filters.element(),
                            null, getNamespaceMap().values());
                    Element current = xpath.evaluateFirst(getXML());
                    if (current == null) {
                        LOGGER.debug("Could not validate, because no element found at xpath " + path);
                        continue;
                    }

                    MCRValidator validator = MCRValidatorBuilder.buildPredefinedCombinedElementValidator();
                    setValidatorProperties(validator, condition);
                    if (!validator.isValid(current)) {
                        String sortNr = parms.getParameter("_sortnr-" + path);
                        failed.put(sortNr, condition);
                    }
                }
            }
        }
    }
}

From source file:org.mycore.oai.MCROAIObjectManager.java

License:Open Source License

protected Element getURI(String uri) {
    Element e = MCRURIResolver.instance().resolve(uri).detach();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("get " + uri);
        XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
        LOGGER.debug(out.outputString(e));
    }//w  w w .j  a v  a  2s  .c  o m
    return e;
}

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

License:Open Source License

/**
 *
 * @param info - a Jersey Context Object for URI
 *     Possible values are: json | xml (required)
 *//*from  w ww.j a va2  s .  c o m*/
@GET
@Path("/")
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8" })
public Response listClassifications(@Context UriInfo info,
        @QueryParam("format") @DefaultValue("json") String format) {
    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").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").build();
        } catch (IOException e) {
            //toDo
        }
    }
    return Response.status(Status.BAD_REQUEST).build();
}

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

License:Open Source License

/**
 * Output xml/*w w  w  .j a va2  s.c o 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.MCRRestAPIMessages.java

License:Open Source License

/**
 * returns a single messages entry./*  www  . j av a  2 s. com*/
 * 
 * @param info - a Jersey Context Object for URI
 * @param format 
 *     Possible values are: props (default) | json | xml (required)
 */
@GET
@Path("/{value}")
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8",
        MediaType.TEXT_PLAIN + ";charset=UTF-8" })
public Response getMessage(@Context UriInfo info, @PathParam("value") String key,
        @QueryParam("lang") @DefaultValue("de") String lang,
        @QueryParam("format") @DefaultValue("text") String format) {

    Locale locale = Locale.forLanguageTag(lang);
    String result = MCRTranslation.translate(key, locale);
    try {
        if (FORMAT_PROPERTY.equals(format)) {
            return Response.ok(key + "=" + result).type("text/plain; charset=ISO-8859-1").build();
        }
        if (FORMAT_XML.equals(format)) {
            Document doc = new Document();
            Element root = new Element("entry");
            root.setAttribute("key", key);
            root.setText(result);
            doc.addContent(root);
            StringWriter sw = new StringWriter();
            XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
            outputter.output(doc, sw);
            return Response.ok(sw.toString()).type("application/xml; charset=UTF-8").build();
        }
        if (FORMAT_JSON.equals(format)) {
            StringWriter sw = new StringWriter();
            JsonWriter writer = new JsonWriter(sw);
            writer.setIndent("    ");
            writer.beginObject();
            writer.name(key);
            writer.value(result);
            writer.endObject();
            writer.close();
            return Response.ok(sw.toString()).type("application/json; charset=UTF-8").build();
        }
        //text only
        return Response.ok(result).type("text/plain; charset=UTF-8").build();
    } catch (IOException e) {
        //toDo
    }
    return Response.status(Status.BAD_REQUEST).build();
}

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

License:Open Source License

public static Response showMCRObject(String pathParamId, String queryParamStyle, UriInfo info) {
    try {/*  w  w  w .  j av  a 2 s  .co  m*/
        MCRObject mcrObj = retrieveMCRObject(pathParamId);
        Document doc = mcrObj.createXML();
        Element eStructure = doc.getRootElement().getChild("structure");
        if (queryParamStyle != null && !MCRRestAPIObjects.STYLE_DERIVATEDETAILS.equals(queryParamStyle)) {
            throw new MCRRestAPIException(MCRRestAPIError.create(Response.Status.BAD_REQUEST,
                    "The value of parameter {style} is not allowed.",
                    "Allowed values for {style} parameter are: " + MCRRestAPIObjects.STYLE_DERIVATEDETAILS));
        }

        if (MCRRestAPIObjects.STYLE_DERIVATEDETAILS.equals(queryParamStyle) && eStructure != null) {
            Element eDerObjects = eStructure.getChild("derobjects");
            if (eDerObjects != null) {
                for (Element eDer : (List<Element>) eDerObjects.getChildren("derobject")) {
                    String derID = eDer.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE);
                    try {
                        MCRDerivate der = MCRMetadataManager
                                .retrieveMCRDerivate(MCRObjectID.getInstance(derID));
                        eDer.addContent(der.createXML().getRootElement().detach());

                        //<mycorederivate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:noNamespaceSchemaLocation="datamodel-derivate.xsd" ID="cpr_derivate_00003760" label="display_image" version="1.3">
                        //  <derivate display="true">

                        eDer = eDer.getChild("mycorederivate").getChild("derivate");
                        eDer.addContent(listDerivateContent(mcrObj,
                                MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(derID)), info));
                    } catch (MCRException e) {
                        eDer.addContent(new Comment("Error: Derivate not found."));
                    } catch (IOException e) {
                        eDer.addContent(
                                new Comment("Error: Derivate content could not be listed: " + e.getMessage()));
                    }
                }
            }
        }

        StringWriter sw = new StringWriter();
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        try {
            outputter.output(doc, sw);
        } catch (IOException e) {
            throw new MCRRestAPIException(MCRRestAPIError.create(Response.Status.INTERNAL_SERVER_ERROR,
                    "Unable to retrieve MyCoRe object", e.getMessage()));
        }
        return Response.ok(sw.toString()).type("application/xml").build();
    }

    catch (MCRRestAPIException rae) {
        return rae.getError().createHttpResponse();
    }

}