org.jdom2.output.XMLOutputter Java Examples

The following examples show how to use org.jdom2.output.XMLOutputter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NcepHtmlScraper.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void writeTableAXml(String name, String source, String filename, List<Stuff> stuff) throws IOException {
  org.jdom2.Element rootElem = new org.jdom2.Element("tableA");
  org.jdom2.Document doc = new org.jdom2.Document(rootElem);
  rootElem.addContent(new org.jdom2.Element("title").setText(name));
  rootElem.addContent(new org.jdom2.Element("source").setText(source));

  for (Stuff p : stuff) {
    org.jdom2.Element paramElem = new org.jdom2.Element("parameter");
    paramElem.setAttribute("code", Integer.toString(p.no));
    paramElem.addContent(new org.jdom2.Element("description").setText(p.desc));
    rootElem.addContent(paramElem);
  }

  XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
  String x = fmt.outputString(doc);

  try (FileOutputStream fout = new FileOutputStream(dirOut + filename)) {
    fout.write(x.getBytes(StandardCharsets.UTF_8));
  }

  if (show)
    System.out.printf("%s%n", x);
}
 
Example #2
Source File: JnlpLauncher.java    From weasis-pacs-connector with Eclipse Public License 2.0 6 votes vote down vote up
protected String buildJnlpResponse(JnlpTemplate launcher) throws ServletErrorException {

        launcher.rootElt.setAttribute(JNLP_TAG_ATT_CODEBASE,
            ServletUtil.getFirstParameter(launcher.parameterMap.get(WeasisConfig.PARAM_CODEBASE)));
        launcher.rootElt.removeAttribute(JNLP_TAG_ATT_HREF); // this tag has not to be used inside dynamic JNLP

        handleRequestPropertyParameter(launcher);
        handleRequestArgumentParameter(launcher);

        filterRequestParameterMarker(launcher);

        String outputStr = null;
        try {
            Format format = Format.getPrettyFormat();
            // Converts native encodings to ASCII with escaped Unicode like (ô è é...),
            // necessary for jnlp
            format.setEncoding("US-ASCII");
            outputStr = new XMLOutputter(format).outputString(launcher.rootElt);
        } catch (Exception e) {
            throw new ServletErrorException(HttpServletResponse.SC_NOT_MODIFIED, "Can't build Jnlp launcher ", e);
        }

        return outputStr;
    }
 
Example #3
Source File: MCREditorOutValidator.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * tries to generate a valid MCRObject as JDOM Document.
 *
 * @return MCRObject
 */
public Document generateValidMyCoReObject() throws JDOMException, SAXParseException, IOException {
    MCRObject obj;
    // load the JDOM object
    XPathFactory.instance()
        .compile("/mycoreobject/*/*/*/@editor.output", Filters.attribute())
        .evaluate(input)
        .forEach(Attribute::detach);
    try {
        byte[] xml = new MCRJDOMContent(input).asByteArray();
        obj = new MCRObject(xml, true);
    } catch (SAXParseException e) {
        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        LOGGER.warn("Failure while parsing document:\n{}", xout.outputString(input));
        throw e;
    }
    Date curTime = new Date();
    obj.getService().setDate("modifydate", curTime);

    // return the XML tree
    input = obj.createXML();
    return input;
}
 
Example #4
Source File: WSIFInvoker.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static HashMap invokeMethod(String wsdlLocation,
                                   String portName, String operationName,
                                   Element inputDataDoc,
                                   AuthenticationConfig authconfig) {
    System.out.println("XMLOutputter = " + new XMLOutputter(Format.getPrettyFormat()).outputString(inputDataDoc));
    System.out.println("wsdl location = " + wsdlLocation);
    System.out.println("port name = " + portName);
    System.out.println("operation name = " + operationName);

    List<String> argsV = new ArrayList<String>();
    for (Element element : inputDataDoc.getChildren()) {
        argsV.add(element.getText());
    }
    String[] args = new String[argsV.size()];
    argsV.toArray(args);
    return invokeMethod(
            wsdlLocation, operationName,
            null, null,
            portName, null,
            args, 0,
            authconfig);
}
 
Example #5
Source File: MCROAIDataProvider.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void doGetPost(MCRServletJob job) throws Exception {
    HttpServletRequest request = job.getRequest();
    // get base url
    if (this.myBaseURL == null) {
        this.myBaseURL = MCRFrontendUtil.getBaseURL() + request.getServletPath().substring(1);
    }
    logRequest(request);
    // create new oai request
    OAIRequest oaiRequest = new OAIRequest(fixParameterMap(request.getParameterMap()));
    // create new oai provider
    OAIProvider oaiProvider = oaiAdapterServiceLoader
        .findFirst()
        .orElseThrow(() -> new ServletException("No implementation of " + OAIProvider.class + " found."));
    oaiProvider.setAdapter(getOAIAdapter());
    // handle request
    OAIResponse oaiResponse = oaiProvider.handleRequest(oaiRequest);
    // build response
    Element xmlRespone = oaiResponse.toXML();
    // fire
    job.getResponse().setContentType("text/xml; charset=UTF-8");
    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat(), OAI_XML_OUTPUT_PROCESSOR);
    xout.output(addXSLStyle(new Document(xmlRespone)), job.getResponse().getOutputStream());
}
 
Example #6
Source File: UnifyDoc.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static void unifyAllProjects(boolean local) {
	try {

		WorkspaceManager ws = new WorkspaceManager(".", local);
 		HashMap<String, File> hmFiles = local ? ws.getAllDocFilesLocal() : ws.getAllDocFiles();			

		Document doc = mergeFiles(hmFiles);

		System.out.println("" + hmFiles);

		XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
		sortie.output(doc, new FileOutputStream(Constants.DOCGAMA_GLOBAL_FILE));
	} catch (Exception ex) {
		ex.printStackTrace();
	}
}
 
Example #7
Source File: UnifyDoc.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static void unify(boolean local) {
	try {

		WorkspaceManager ws = new WorkspaceManager(".",local);
		HashMap<String, File> hmFiles = ws.getProductDocFiles();

		Document doc = mergeFiles(hmFiles);

		System.out.println("" + hmFiles);

		XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
		sortie.output(doc, new FileOutputStream(Constants.DOCGAMA_GLOBAL_FILE));
	} catch (Exception ex) {
		ex.printStackTrace();
	}
}
 
Example #8
Source File: MCRRestAPIClassifications.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Output xml
 * @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();
}
 
Example #9
Source File: Database.java    From CardinalPGM with MIT License 6 votes vote down vote up
public boolean save(File file) {
    XMLOutputter out = new XMLOutputter();
    out.setFormat(Format.getPrettyFormat());
    try {
        if (file.createNewFile()) {
            Cardinal.getInstance().getLogger().info("Database file not found, creating...");
            out.output(document, new FileWriter(file));
            return true;
        } else {
            out.output(document, new FileWriter(file));
            return true;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}
 
Example #10
Source File: JDOMUtil.java    From emissary with Apache License 2.0 6 votes vote down vote up
/**
 * Get a string from a JDOM Document
 *
 * @param jdom the jdom document
 * @return String value in UTF-8
 */
public static String toString(final Document jdom) {
    final XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    // outputter.setOmitDeclaration(false);
    // outputter.setEncoding("utf-8");
    // outputter.setOmitEncoding(false);
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        outputter.output(jdom, os);
        return os.toString();
    } catch (IOException iox) {
        logger.error("ByteArrayOutputStream exception", iox);
        return null;
    } finally {
        try {
            os.close();
        } catch (IOException ignore) {
            // empty exception block
        }
    }
}
 
Example #11
Source File: MCRMetaISO8601DateTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void createXML() {
    MCRMetaISO8601Date ts = new MCRMetaISO8601Date("servdate", "createdate", 0);
    String timeString = "1997-07-16T19:20:30.452300+01:00";
    ts.setDate(timeString);
    assertNotNull("Date is null", ts.getDate());
    Element export = ts.createXML();
    if (LOGGER.isDebugEnabled()) {
        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        StringWriter sw = new StringWriter();
        try {
            xout.output(export, sw);
            LOGGER.debug(sw.toString());
        } catch (IOException e) {
            LOGGER.warn("Failure printing xml result", e);
        }
    }
}
 
Example #12
Source File: MCRAccessCommands.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This method invokes MCRUserMgr.getAllPrivileges() and retrieves a
 * ArrayList of all privileges stored in the persistent datastore.
 */
@MCRCommand(syntax = "list all permissions", help = "List all permission entries.", order = 20)
public static void listAllPermissions() throws MCRException {
    MCRAccessInterface accessImpl = MCRAccessManager.getAccessImpl();
    Collection<String> permissions = accessImpl.getPermissions();
    boolean noPermissionsDefined = true;
    for (String permission : permissions) {
        noPermissionsDefined = false;
        String description = accessImpl.getRuleDescription(permission);
        if (description.equals("")) {
            description = "No description";
        }
        Element rule = accessImpl.getRule(permission);
        LOGGER.info("       {}", permission);
        LOGGER.info("           {}", description);
        if (rule != null) {
            XMLOutputter o = new XMLOutputter();
            LOGGER.info("           {}", o.outputString(rule));
        }
    }
    if (noPermissionsDefined) {
        LOGGER.warn("No permissions defined");
    }
    LOGGER.info("");
}
 
Example #13
Source File: FileBasedCollection.java    From rome with Apache License 2.0 6 votes vote down vote up
private void updateFeedDocument(final Feed f) throws AtomException {
    try {
        synchronized (FileStore.getFileStore()) {
            final WireFeedOutput wireFeedOutput = new WireFeedOutput();
            final Document feedDoc = wireFeedOutput.outputJDom(f);
            final XMLOutputter outputter = new XMLOutputter();
            // outputter.setFormat(Format.getPrettyFormat());
            final OutputStream fos = FileStore.getFileStore().getFileOutputStream(getFeedPath());
            outputter.output(feedDoc, new OutputStreamWriter(fos, "UTF-8"));
        }
    } catch (final FeedException fex) {
        throw new AtomException(fex);
    } catch (final IOException ex) {
        throw new AtomException(ex);
    }
}
 
Example #14
Source File: ItemTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void toXML() throws Exception {
    JAXBContext jc = JAXBContext.newInstance(MCRNavigationItem.class);
    Marshaller m = jc.createMarshaller();
    JDOMResult JDOMResult = new JDOMResult();
    m.marshal(this.item, JDOMResult);
    Element itemElement = JDOMResult.getDocument().getRootElement();

    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
    out.output(itemElement, System.out);

    assertEquals("template_mysample", itemElement.getAttributeValue("template"));
    assertEquals("bold", itemElement.getAttributeValue("style"));
    assertEquals("_self", itemElement.getAttributeValue("target"));
    assertEquals("intern", itemElement.getAttributeValue("type"));
    assertEquals("true", itemElement.getAttributeValue("constrainPopUp"));
    assertEquals("false", itemElement.getAttributeValue("replaceMenu"));
    assertEquals("item.test.key", itemElement.getAttributeValue("i18nKey"));

    Element label1 = itemElement.getChildren().get(0);
    Element label2 = itemElement.getChildren().get(1);

    assertEquals("Deutschland", label1.getValue());
    assertEquals("England", label2.getValue());
}
 
Example #15
Source File: CdmrFeatureDataset.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static org.jdom2.Document getCapabilities(String endpoint) throws IOException {
  org.jdom2.Document doc;
  try (InputStream in = CdmRemote.sendQuery(null, endpoint, "req=capabilities")) {
    SAXBuilder builder = new SAXBuilder();
    doc = builder.build(in); // LOOK closes in when done ??

  } catch (Throwable t) {
    throw new IOException(t);
  }

  if (showXML) {
    System.out.printf("*** endpoint = %s %n", endpoint);
    XMLOutputter xmlOut = new XMLOutputter();
    System.out.printf("*** CdmrFeatureDataset/showParsedXML = %n %s %n", xmlOut.outputString(doc));
  }

  return doc;
}
 
Example #16
Source File: MCRCategoryDAOImplTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@After
@Override
public void tearDown() throws Exception {
    try {
        startNewTransaction();
        MCRCategoryImpl rootNode = getRootCategoryFromSession();
        MCRCategoryImpl rootNode2 = (MCRCategoryImpl) DAO.getCategory(category.getId(), -1);
        if (rootNode != null) {
            try {
                checkLeftRightLevelValue(rootNode, 0, 0);
                checkLeftRightLevelValue(rootNode2, 0, 0);
            } catch (AssertionError e) {
                LogManager.getLogger().error("Error while checking left, right an level values in database.");
                new XMLOutputter(Format.getPrettyFormat())
                    .output(MCRCategoryTransformer.getMetaDataDocument(rootNode, false), System.out);
                printCategoryTable();
                throw e;
            }
        }
    } finally {
        super.tearDown();
    }
}
 
Example #17
Source File: CodeTableGen.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static public void prettyPrint() throws IOException {
  org.jdom2.Document doc;
  try {
    SAXBuilder builder = new SAXBuilder();
    doc = builder.build("C:/docs/bufr/wmo/Code-FlagTables-11-2007.xml");

    Format pretty = Format.getPrettyFormat();
    String sep = pretty.getLineSeparator();
    String ind = pretty.getIndent();
    String mine = "\r\n";
    pretty.setLineSeparator(mine);

    // wierd - cant pretty print ??!!
    XMLOutputter fmt = new XMLOutputter(pretty);
    Writer pw = new FileWriter("C:/docs/bufr/wmo/wordNice.txt");
    fmt.output(doc, pw);

  } catch (JDOMException e) {
    throw new IOException(e.getMessage());
  }

}
 
Example #18
Source File: CodeTableGen.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static public void passTwo() throws IOException {
  org.jdom2.Document tdoc;
  try {
    SAXBuilder builder = new SAXBuilder();
    tdoc = builder.build(trans1);

    org.jdom2.Document ndoc = new org.jdom2.Document();
    Element nroot = new Element("ndoc");
    ndoc.setRootElement(nroot);

    transform2(tdoc.getRootElement(), nroot);

    XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
    Writer pw = new FileWriter(trans2);
    fmt.output(ndoc, pw);
    pw = new PrintWriter(System.out);
    fmt.output(ndoc, pw);

  } catch (JDOMException e) {
    throw new IOException(e.getMessage());
  }
}
 
Example #19
Source File: NcepHtmlScraper.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void writeTable2Xml(String name, String source, String filename, List<Param> params) throws IOException {
  org.jdom2.Element rootElem = new org.jdom2.Element("parameterMap");
  org.jdom2.Document doc = new org.jdom2.Document(rootElem);
  rootElem.addContent(new org.jdom2.Element("title").setText(name));
  rootElem.addContent(new org.jdom2.Element("source").setText(source));

  for (Param p : params) {
    org.jdom2.Element paramElem = new org.jdom2.Element("parameter");
    paramElem.setAttribute("code", Integer.toString(p.pnum));
    paramElem.addContent(new org.jdom2.Element("shortName").setText(p.name));
    paramElem.addContent(new org.jdom2.Element("description").setText(p.desc));
    paramElem.addContent(new org.jdom2.Element("units").setText(p.unit));
    rootElem.addContent(paramElem);
  }

  XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
  String x = fmt.outputString(doc);

  try (FileOutputStream fout = new FileOutputStream(dirOut + filename)) {
    fout.write(x.getBytes(StandardCharsets.UTF_8));
  }

  if (show)
    System.out.printf("%s%n", x);
}
 
Example #20
Source File: NcepHtmlScraper.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void writeCodeTableXml(String filename, String title, String source, String tableName, List<Code> stuff)
    throws IOException {
  org.jdom2.Element rootElem = new org.jdom2.Element("codeTable");
  org.jdom2.Document doc = new org.jdom2.Document(rootElem);
  rootElem.addContent(new org.jdom2.Element("table").setText(tableName));
  rootElem.addContent(new org.jdom2.Element("title").setText(title));
  rootElem.addContent(new org.jdom2.Element("source").setText(source));

  for (Code p : stuff) {
    org.jdom2.Element paramElem = new org.jdom2.Element("parameter");
    paramElem.setAttribute("code", Integer.toString(p.no));
    paramElem.addContent(new org.jdom2.Element("description").setText(p.desc));
    rootElem.addContent(paramElem);
  }

  XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
  String x = fmt.outputString(doc);

  try (FileOutputStream fout = new FileOutputStream(dirOut + filename + ".xml")) {
    fout.write(x.getBytes(StandardCharsets.UTF_8));
  }

  if (show)
    System.out.printf("%s%n", x);
}
 
Example #21
Source File: MCRWCMSDefaultSectionProvider.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the content of an element as string. The element itself
 * is ignored.
 * 
 * @param e the element to get the content from
 * @return the content as string
 */
protected String getContent(Element e) throws IOException {
    XMLOutputter out = new XMLOutputter();
    StringWriter writer = new StringWriter();
    for (Content child : e.getContent()) {
        if (child instanceof Element) {
            out.output((Element) child, writer);
        } else if (child instanceof Text) {
            Text t = (Text) child;
            String trimmedText = t.getTextTrim();
            if (!"".equals(trimmedText)) {
                Text newText = new Text(trimmedText);
                out.output(newText, writer);
            }
        }
    }
    return writer.toString();
}
 
Example #22
Source File: MCRUserAttributeMapperTest.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testUserCreate() throws Exception {
    Map<String, Object> attributes = new HashMap<>();
    attributes.put("eduPersonPrincipalName", mcrUser.getUserName() + "@" + realmId);
    attributes.put("displayName", mcrUser.getRealName());
    attributes.put("mail", mcrUser.getEMailAddress());
    attributes.put("eduPersonAffiliation", roles);

    MCRUserInformation userInfo = new MCRShibbolethUserInformation(mcrUser.getUserName(), realmId, attributes);

    MCRTransientUser user = new MCRTransientUser(userInfo);

    assertEquals(mcrUser.getUserName(), user.getUserName());
    assertEquals(mcrUser.getRealName(), user.getRealName());
    assertTrue(user.isUserInRole("editor"));

    Map<String, String> extraAttribs = new HashMap<>();
    extraAttribs.put("attrib1", "test123");
    extraAttribs.put("attrib2", "test321");
    extraAttribs.entrySet().forEach(e -> user.setUserAttribute(e.getKey(), e.getValue()));

    MCRUserManager.createUser(user);

    startNewTransaction();

    MCRUser storedUser = MCRUserManager.getUser(user.getUserName(), realmId);

    assertEquals(mcrUser.getEMailAddress(), storedUser.getEMailAddress());

    assertEquals(extraAttribs.get("attrib1"), storedUser.getUserAttribute("attrib1"));
    assertEquals(extraAttribs.get("attrib2"), storedUser.getUserAttribute("attrib2"));

    Document exportableXML = MCRUserTransformer.buildExportableXML(storedUser);
    new XMLOutputter(Format.getPrettyFormat()).output(exportableXML, System.out);
}
 
Example #23
Source File: MCRQLSearchServlet.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void doGetPost(MCRServletJob job) throws IOException, ServletException, TransformerException, SAXException {
    HttpServletRequest request = job.getRequest();
    HttpServletResponse response = job.getResponse();
    String searchString = getReqParameter(request, "search", null);
    String queryString = getReqParameter(request, "query", null);

    Document input = (Document) request.getAttribute("MCRXEditorSubmission");
    MCRQuery query;

    if (input != null) {
        //xeditor input
        query = MCRQLSearchUtils.buildFormQuery(input.getRootElement());
    } else {
        if (queryString != null) {
            query = MCRQLSearchUtils.buildComplexQuery(queryString);
        } else if (searchString != null) {
            query = MCRQLSearchUtils.buildDefaultQuery(searchString, defaultSearchField);
        } else {
            query = MCRQLSearchUtils.buildNameValueQuery(request);
        }

        input = MCRQLSearchUtils.setQueryOptions(query, request);
    }

    // Show incoming query document
    if (LOGGER.isDebugEnabled()) {
        XMLOutputter out = new XMLOutputter(org.jdom2.output.Format.getPrettyFormat());
        LOGGER.debug(out.outputString(input));
    }

    boolean doNotRedirect = "false".equals(getReqParameter(request, "redirect", null));

    if (doNotRedirect) {
        showResults(request, response, query, input);
    } else {
        sendRedirect(request, response, query, input);
    }
}
 
Example #24
Source File: CategoryFeedsFragment.java    From SimpleNews with Apache License 2.0 5 votes vote down vote up
private void shareOpml(Opml opml) {
    String finalMessage = null;
    try {
        finalMessage = new XMLOutputter().outputString(new OPML20Generator().generate(opml));
    } catch (FeedException e) {
        e.printStackTrace();
    }
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/xml");
    shareIntent.putExtra(Intent.EXTRA_TEXT,
            finalMessage);
    startActivity(shareIntent);
}
 
Example #25
Source File: MCRAccessCommands.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This method just export the permissions to a file
 * 
 * @param filename
 *            the file written to
 */
@MCRCommand(syntax = "export all permissions to file {0}",
    help = "Export all permissions from the Access Control System to the file {0}.",
    order = 50)
public static void exportAllPermissionsToFile(String filename) throws Exception {
    MCRAccessInterface accessImpl = MCRAccessManager.getAccessImpl();

    Element mcrpermissions = new Element("mcrpermissions");
    mcrpermissions.addNamespaceDeclaration(XSI_NAMESPACE);
    mcrpermissions.addNamespaceDeclaration(XLINK_NAMESPACE);
    mcrpermissions.setAttribute("noNamespaceSchemaLocation", "MCRPermissions.xsd", XSI_NAMESPACE);
    Document doc = new Document(mcrpermissions);
    Collection<String> permissions = accessImpl.getPermissions();
    for (String permission : permissions) {
        Element mcrpermission = new Element("mcrpermission");
        mcrpermission.setAttribute("name", permission);
        String ruleDescription = accessImpl.getRuleDescription(permission);
        if (!ruleDescription.equals("")) {
            mcrpermission.setAttribute("ruledescription", ruleDescription);
        }
        Element rule = accessImpl.getRule(permission);
        mcrpermission.addContent(rule);
        mcrpermissions.addContent(mcrpermission);
    }
    File file = new File(filename);
    if (file.exists()) {
        LOGGER.warn("File {} yet exists, overwrite.", filename);
    }
    FileOutputStream fos = new FileOutputStream(file);
    LOGGER.info("Writing to file {} ...", filename);
    String mcrEncoding = MCRConfiguration2.getString("MCR.Metadata.DefaultEncoding").orElse(DEFAULT_ENCODING);
    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setEncoding(mcrEncoding));
    out.output(doc, fos);
}
 
Example #26
Source File: XmlLogFileHandler.java    From orcas with Apache License 2.0 5 votes vote down vote up
private String getXmlString( Element pElement )
{
  try
  {
    StringWriter lStringWriter = new StringWriter();
    new XMLOutputter( Format.getPrettyFormat() ).output( pElement, lStringWriter );

    return lStringWriter.getBuffer().toString();
  }
  catch( IOException e )
  {
    throw new RuntimeException( e );
  }
}
 
Example #27
Source File: MCRMetsIIIFPresentationImpl.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public MCRIIIFManifest getManifest(String id) {
    try {
        Document metsDocument = getMets(id);
        LOGGER.info(new XMLOutputter(Format.getPrettyFormat()).outputString(metsDocument));
        return getConverter(id, metsDocument).convert();
    } catch (IOException | JDOMException | SAXException e) {
        throw new MCRException(e);
    }
}
 
Example #28
Source File: DatasetTrackerInMem.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public boolean trackDataset(long catId, Dataset dataset, Callback callback) {
  if (callback != null)
    callback.hasDataset(dataset);

  if (dataset.getRestrictAccess() != null) {
    if (callback != null)
      callback.hasRestriction(dataset);
    else
      putResourceControl(dataset);
  }

  // dont track ncml for DatasetScan or FeatureCollectionRef
  if (dataset instanceof DatasetScan)
    return false;
  if (dataset instanceof FeatureCollectionRef)
    return false;

  if (dataset.getNcmlElement() != null) {
    if (callback != null)
      callback.hasNcml(dataset);
    // want the string representation
    Element ncmlElem = dataset.getNcmlElement();
    XMLOutputter xmlOut = new XMLOutputter();
    String ncml = xmlOut.outputString(ncmlElem);
    System.out.printf("%s%n", ncml);
    ncmlDatasetHash.put(dataset.getUrlPath(), ncml);
  }
  return true;
}
 
Example #29
Source File: NcepHtmlScraper.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void writeTable3Xml(String name, String source, String filename, List<VertCoordType> stuff)
    throws IOException {
  org.jdom2.Element rootElem = new org.jdom2.Element("table3");
  org.jdom2.Document doc = new org.jdom2.Document(rootElem);
  rootElem.addContent(new org.jdom2.Element("title").setText(name));
  rootElem.addContent(new org.jdom2.Element("source").setText(source));

  for (VertCoordType p : stuff) {
    org.jdom2.Element paramElem = new org.jdom2.Element("parameter");
    paramElem.setAttribute("code", Integer.toString(p.getCode()));
    paramElem.addContent(new org.jdom2.Element("description").setText(p.getDesc()));
    paramElem.addContent(new org.jdom2.Element("abbrev").setText(p.getAbbrev()));
    String units = p.getUnits();
    if (units == null)
      units = handcodedUnits(p.getCode());
    if (units != null)
      paramElem.addContent(new org.jdom2.Element("units").setText(units));
    if (p.getDatum() != null)
      paramElem.addContent(new org.jdom2.Element("datum").setText(p.getDatum()));
    if (p.isPositiveUp())
      paramElem.addContent(new org.jdom2.Element("isPositiveUp").setText("true"));
    if (p.isLayer())
      paramElem.addContent(new org.jdom2.Element("isLayer").setText("true"));
    rootElem.addContent(paramElem);
  }

  XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
  String x = fmt.outputString(doc);

  try (FileOutputStream fout = new FileOutputStream(dirOut + filename)) {
    fout.write(x.getBytes(StandardCharsets.UTF_8));
  }

  if (show)
    System.out.printf("%s%n", x);
}
 
Example #30
Source File: XmlBuilder.java    From iaf with Apache License 2.0 5 votes vote down vote up
public String toXML(boolean xmlHeader) {
	Document document = new Document(element.detach());
	XMLOutputter xmlOutputter = new XMLOutputter();
	xmlOutputter.setFormat(
			Format.getPrettyFormat().setOmitDeclaration(!xmlHeader));
	return xmlOutputter.outputString(document);
}