List of usage examples for org.jdom2.output Format getPrettyFormat
public static Format getPrettyFormat()
From source file:org.mycore.restapi.v1.MCRRestAPIClassifications.java
License:Open Source License
/** * Output xml//from w w w . ja v a2 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./*w ww . ja v a 2s .c o m*/ * * @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 ww . ja va2s .c o 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(); } }
From source file:org.mycore.restapi.v1.utils.MCRRestAPIObjectsHelper.java
License:Open Source License
public static Response showMCRDerivate(String pathParamMcrID, String pathParamDerID, UriInfo info) throws IOException { try {/*from w w w. java 2 s .co m*/ MCRObject mcrObj = retrieveMCRObject(pathParamMcrID); MCRDerivate derObj = retrieveMCRDerivate(mcrObj, pathParamDerID); Document doc = derObj.createXML(); doc.getRootElement().addContent(listDerivateContent(mcrObj, derObj, info)); StringWriter sw = new StringWriter(); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); outputter.output(doc, sw); return Response.ok(sw.toString()).type("application/xml").build(); } catch (MCRRestAPIException e) { return e.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
/** * @see MCRRestAPIObjects#listObjects(UriInfo, String, String, String) *///from w ww. j a v a 2 s. co 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) *//*from w w w . java 2 s. c o m*/ 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 a2 s.c o 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.user2.login.MCRLDAPClient.java
License:Open Source License
public static void main(String[] args) throws Exception { String userName = args[0];// w w w. j a va 2s . co m String realmID = args[1]; MCRUser user = MCRUserManager.getUser(userName, realmID); if (user == null) { user = new MCRUser(userName, realmID); } LOGGER.info("\n" + new XMLOutputter(Format.getPrettyFormat()) .outputString(MCRUserTransformer.buildExportableSafeXML(user))); MCRLDAPClient.instance().updateUserProperties(user); LOGGER.info("\n" + new XMLOutputter(Format.getPrettyFormat()) .outputString(MCRUserTransformer.buildExportableSafeXML(user))); }
From source file:org.mycore.user2.MCRUserCommands.java
License:Open Source License
/** * Exports a single role to the specified directory. * @throws FileNotFoundException if target directory does not exist *//*from w w w. j av a 2s . co m*/ @MCRCommand(syntax = "export role {0} to directory {1}", help = "Export the role {0} to the directory {1}. The filename will be {0}.xml") public static void exportRole(String roleID, String directory) throws FileNotFoundException, IOException { MCRRole mcrRole = MCRRoleManager.getRole(roleID); File targetFile = new File(directory, roleID + ".xml"); try (FileOutputStream fout = new FileOutputStream(targetFile)) { XMLOutputter xout = new XMLOutputter( Format.getPrettyFormat().setEncoding(MCRConstants.DEFAULT_ENCODING)); xout.output(MCRRoleTransformer.buildExportableXML(mcrRole), fout); } }
From source file:org.mycore.user2.MCRUserCommands.java
License:Open Source License
/** * This method just saves a JDOM document to a file automatically closes {@link OutputStream}. * * @param mcrUser//from ww w .j a v a 2 s . c om * the JDOM XML document to be printed * @param outFile * a FileOutputStream object for the output * @throws IOException * if output file can not be closed */ private static void saveToXMLFile(MCRUser mcrUser, FileOutputStream outFile) throws MCRException, IOException { // Create the output XMLOutputter outputter = new XMLOutputter( Format.getPrettyFormat().setEncoding(MCRConstants.DEFAULT_ENCODING)); try { outputter.output(MCRUserTransformer.buildExportableXML(mcrUser), outFile); } catch (Exception e) { throw new MCRException("Error while save XML to file: " + e.getMessage()); } finally { outFile.close(); } }