Example usage for javax.xml.stream XMLOutputFactory newInstance

List of usage examples for javax.xml.stream XMLOutputFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.stream XMLOutputFactory newInstance.

Prototype

public static XMLOutputFactory newInstance() throws FactoryConfigurationError 

Source Link

Document

Creates a new instance of the factory in exactly the same manner as the #newFactory() method.

Usage

From source file:org.deegree.tools.alkis.BackReferenceFixer.java

public static void main(String[] args) {
    Options opts = initOptions();/* w  w w  .  j  a  v  a2 s.c o m*/
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        CommandLine line = new PosixParser().parse(opts, args);
        String input = line.getOptionValue('i');
        String output = line.getOptionValue('o');
        String schema = line.getOptionValue('s');
        fis = new FileInputStream(input);
        fos = new FileOutputStream(output);
        XMLInputFactory xifac = XMLInputFactory.newInstance();
        XMLOutputFactory xofac = XMLOutputFactory.newInstance();
        XMLStreamReader xreader = xifac.createXMLStreamReader(input, fis);
        IndentingXMLStreamWriter xwriter = new IndentingXMLStreamWriter(xofac.createXMLStreamWriter(fos));
        GMLStreamReader reader = GMLInputFactory.createGMLStreamReader(GMLVersion.GML_32, xreader);

        AppSchema appSchema = new GMLAppSchemaReader(null, null, schema).extractAppSchema();
        reader.setApplicationSchema(appSchema);

        GMLStreamWriter writer = GMLOutputFactory.createGMLStreamWriter(GMLVersion.GML_32, xwriter);
        XlinkedObjectsHandler handler = new XlinkedObjectsHandler(true, null, new GmlXlinkOptions());
        writer.setReferenceResolveStrategy(handler);

        QName prop = new QName(ns601, "dientZurDarstellungVon");

        Map<String, List<String>> refs = new HashMap<String, List<String>>();
        Map<String, List<String>> types = new HashMap<String, List<String>>();
        Map<String, String> bindings = null;

        for (Feature f : reader.readFeatureCollectionStream()) {
            if (bindings == null) {
                bindings = f.getType().getSchema().getNamespaceBindings();
            }
            for (Property p : f.getProperties(prop)) {
                FeatureReference ref = (FeatureReference) p.getValue();
                List<String> list = refs.get(ref.getId());
                if (list == null) {
                    list = new ArrayList<String>();
                    refs.put(ref.getId(), list);
                }
                list.add(f.getId());
                list = types.get(ref.getId());
                if (list == null) {
                    list = new ArrayList<String>();
                    types.put(ref.getId(), list);
                }
                list.add("inversZu_dientZurDarstellungVon_" + f.getType().getName().getLocalPart());
            }
        }

        QName[] inversePropNames = new QName[] {
                new QName(ns601, "inversZu_dientZurDarstellungVon_AP_Darstellung"),
                new QName(ns601, "inversZu_dientZurDarstellungVon_AP_LTO"),
                new QName(ns601, "inversZu_dientZurDarstellungVon_AP_PTO"),
                new QName(ns601, "inversZu_dientZurDarstellungVon_AP_FPO"),
                new QName(ns601, "inversZu_dientZurDarstellungVon_AP_KPO_3D"),
                new QName(ns601, "inversZu_dientZurDarstellungVon_AP_LPO"),
                new QName(ns601, "inversZu_dientZurDarstellungVon_AP_PPO") };

        reader.close();
        fis.close();
        writer.setNamespaceBindings(bindings);

        fis = new FileInputStream(input);
        xreader = xifac.createXMLStreamReader(input, fis);
        reader = GMLInputFactory.createGMLStreamReader(GMLVersion.GML_32, xreader);
        reader.setApplicationSchema(appSchema);

        if (bindings != null) {
            for (Map.Entry<String, String> e : bindings.entrySet()) {
                if (!e.getKey().isEmpty()) {
                    xwriter.setPrefix(e.getValue(), e.getKey());
                }
            }
        }
        xwriter.writeStartDocument();
        xwriter.setPrefix("gml", "http://www.opengis.net/gml/3.2");
        xwriter.writeStartElement("http://www.opengis.net/gml/3.2", "FeatureCollection");
        xwriter.writeNamespace("gml", "http://www.opengis.net/gml/3.2");

        GmlDocumentIdContext ctx = new GmlDocumentIdContext(GMLVersion.GML_32);

        for (Feature f : reader.readFeatureCollectionStream()) {
            if (refs.containsKey(f.getId())) {
                List<Property> props = new ArrayList<Property>(f.getProperties());
                ListIterator<Property> iter = props.listIterator();
                String name = iter.next().getName().getLocalPart();
                while (name.equals("lebenszeitintervall") || name.equals("modellart") || name.equals("anlass")
                        || name.equals("zeigtAufExternes") || name.equals("istTeilVon")
                        || name.equals("identifier")) {
                    if (iter.hasNext()) {
                        name = iter.next().getName().getLocalPart();
                    } else {
                        break;
                    }
                }
                if (iter.hasPrevious()) {
                    iter.previous();
                }
                for (QName propName : inversePropNames) {
                    Iterator<String> idIter = refs.get(f.getId()).iterator();
                    Iterator<String> typeIter = types.get(f.getId()).iterator();
                    while (idIter.hasNext()) {
                        String id = idIter.next();
                        if (typeIter.next().equals(propName.getLocalPart())) {
                            PropertyType pt = f.getType().getPropertyDeclaration(propName);
                            Property p = new GenericProperty(pt, new FeatureReference(ctx, "#" + id, null));
                            iter.add(p);
                        }
                    }
                }
                f.setProperties(props);

            }
            xwriter.writeStartElement("http://www.opengis.net/gml/3.2", "featureMember");
            writer.write(f);
            xwriter.writeEndElement();
        }

        xwriter.writeEndElement();
        xwriter.close();
    } catch (Throwable e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(fos);
    }
}

From source file:org.deegree.tools.crs.XMLCoordinateTransform.java

private static void doTransform(CommandLine line) throws IllegalArgumentException, TransformationException,
        UnknownCRSException, IOException, XMLStreamException, FactoryConfigurationError {

    // TODO source srs should actually override all srsName attributes in document, not just be the default
    ICRS sourceCRS = null;/*from   w w w  .jav a 2  s. c o m*/
    String sourceCRSId = line.getOptionValue(OPT_S_SRS);
    if (sourceCRSId != null) {
        sourceCRS = CRSManager.lookup(sourceCRSId);
    }

    String targetCRSId = line.getOptionValue(OPT_T_SRS);
    ICRS targetCRS = CRSManager.lookup(targetCRSId);

    String transId = line.getOptionValue(OPT_TRANSFORMATION);
    List<Transformation> trans = null;
    if (transId != null) {
        Transformation t = CRSManager.getTransformation(null, transId);
        if (t != null) {
            trans = Collections.singletonList(CRSManager.getTransformation(null, transId));
        } else {
            throw new IllegalArgumentException(
                    "Specified transformation id '" + transId + "' does not exist in CRS database.");
        }
    }

    GMLVersion gmlVersion = GMLVersion.GML_31;
    String gmlVersionString = line.getOptionValue(OPT_GML_VERSION);
    if (gmlVersionString != null) {
        gmlVersion = GMLVersion.valueOf(gmlVersionString);
    }

    String i = line.getOptionValue(OPT_INPUT);
    File inputFile = new File(i);
    if (!inputFile.exists()) {
        throw new IllegalArgumentException("Input file '" + inputFile + "' does not exist.");
    }
    XMLStreamReader xmlReader = XMLInputFactory.newInstance()
            .createXMLStreamReader(new FileInputStream(inputFile));

    String o = line.getOptionValue(OPT_OUTPUT);
    XMLStreamWriter xmlWriter = null;
    if (o != null) {
        File outputFile = new File(o);
        xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(outputFile),
                "UTF-8");
    } else {
        xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out, "UTF-8");
    }

    xmlWriter = new IndentingXMLStreamWriter(xmlWriter, "    ");
    xmlWriter.writeStartDocument("UTF-8", "1.0");
    XMLTransformer transformer = new XMLTransformer(targetCRS);
    transformer.transform(xmlReader, xmlWriter, sourceCRS, gmlVersion, false, trans);
    xmlWriter.close();
}

From source file:org.deegree.tools.services.wms.FeatureTypesToLayerTree.java

/**
 * @param args//from ww  w . java  2  s. co m
 */
public static void main(String[] args) {
    Options options = initOptions();

    // for the moment, using the CLI API there is no way to respond to a help argument; see
    // https://issues.apache.org/jira/browse/CLI-179
    if (args.length == 0 || (args.length > 0 && (args[0].contains("help") || args[0].contains("?")))) {
        CommandUtils.printHelp(options, FeatureTypesToLayerTree.class.getSimpleName(), null, null);
    }

    XMLStreamWriter out = null;
    try {
        CommandLine line = new PosixParser().parse(options, args);

        String storeFile = line.getOptionValue("f");
        String nm = new File(storeFile).getName();
        String storeId = nm.substring(0, nm.length() - 4);

        FileOutputStream os = new FileOutputStream(line.getOptionValue("o"));
        XMLOutputFactory fac = XMLOutputFactory.newInstance();
        out = new IndentingXMLStreamWriter(fac.createXMLStreamWriter(os));
        out.setDefaultNamespace(ns);

        Workspace ws = new DefaultWorkspace(new File("nix"));
        ws.initAll();
        DefaultResourceIdentifier<FeatureStore> identifier = new DefaultResourceIdentifier<FeatureStore>(
                FeatureStoreProvider.class, "unknown");
        ws.add(new DefaultResourceLocation<FeatureStore>(new File(storeFile), identifier));
        ws.prepare(identifier);
        FeatureStore store = ws.init(identifier, null);

        AppSchema schema = store.getSchema();

        // prepare document
        out.writeStartDocument();
        out.writeStartElement(ns, "deegreeWMS");
        out.writeDefaultNamespace(ns);
        out.writeAttribute("configVersion", "0.5.0");
        out.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        out.writeAttribute("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation",
                "http://www.deegree.org/services/wms http://schemas.deegree.org/wms/0.5.0/wms_configuration.xsd");
        out.writeStartElement(ns, "ServiceConfiguration");

        HashSet<FeatureType> visited = new HashSet<FeatureType>();

        if (schema.getRootFeatureTypes().length == 1) {
            writeLayer(visited, out, schema.getRootFeatureTypes()[0], storeId);
        } else {
            out.writeCharacters("\n");
            out.writeStartElement(ns, "UnrequestableLayer");
            XMLAdapter.writeElement(out, ns, "Title", "Root Layer");
            for (FeatureType ft : schema.getRootFeatureTypes()) {
                writeLayer(visited, out, ft, storeId);
            }
            out.writeEndElement();
            out.writeCharacters("\n");
        }

        out.writeEndElement();
        out.writeEndElement();
        out.writeEndDocument();
    } catch (ParseException exp) {
        System.err.println(Messages.getMessage("TOOL_COMMANDLINE_ERROR", exp.getMessage()));
        CommandUtils.printHelp(options, FeatureTypesToLayerTree.class.getSimpleName(), null, null);
    } catch (ResourceInitException e) {
        LOG.info("The feature store could not be loaded: '{}'", e.getLocalizedMessage());
        LOG.trace("Stack trace:", e);
    } catch (FileNotFoundException e) {
        LOG.info("A file could not be found: '{}'", e.getLocalizedMessage());
        LOG.trace("Stack trace:", e);
    } catch (XMLStreamException e) {
        LOG.info("The XML output could not be written: '{}'", e.getLocalizedMessage());
        LOG.trace("Stack trace:", e);
    } catch (FactoryConfigurationError e) {
        LOG.info("The XML system could not be initialized: '{}'", e.getLocalizedMessage());
        LOG.trace("Stack trace:", e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (XMLStreamException e) {
                LOG.trace("Stack trace:", e);
            }
        }
    }

}

From source file:org.dita.dost.module.GenMapAndTopicListModule.java

private void writeExportAnchors() throws DITAOTException {
    if (INDEX_TYPE_ECLIPSEHELP.equals(transtype)) {
        // Output plugin id
        final File pluginIdFile = new File(job.tempDir, FILE_NAME_PLUGIN_XML);
        final DelayConrefUtils delayConrefUtils = new DelayConrefUtils();
        delayConrefUtils.writeMapToXML(exportAnchorsFilter.getPluginMap(), pluginIdFile);

        XMLStreamWriter export = null;
        try (OutputStream exportStream = new FileOutputStream(new File(job.tempDir, FILE_NAME_EXPORT_XML))) {
            export = XMLOutputFactory.newInstance().createXMLStreamWriter(exportStream, "UTF-8");
            export.writeStartDocument();
            export.writeStartElement("stub");
            for (final ExportAnchor e : exportAnchorsFilter.getExportAnchors()) {
                export.writeStartElement("file");
                export.writeAttribute("name",
                        tempFileNameScheme.generateTempFileName(toFile(e.file).toURI()).toString());
                for (final String t : sort(e.topicids)) {
                    export.writeStartElement("topicid");
                    export.writeAttribute("name", t);
                    export.writeEndElement();
                }//from w  w  w .  j  a  va  2 s .  c  om
                for (final String i : sort(e.ids)) {
                    export.writeStartElement("id");
                    export.writeAttribute("name", i);
                    export.writeEndElement();
                }
                for (final String k : sort(e.keys)) {
                    export.writeStartElement("keyref");
                    export.writeAttribute("name", k);
                    export.writeEndElement();
                }
                export.writeEndElement();
            }
            export.writeEndElement();
            export.writeEndDocument();
        } catch (final IOException e) {
            throw new DITAOTException("Failed to write export anchor file: " + e.getMessage(), e);
        } catch (final XMLStreamException e) {
            throw new DITAOTException("Failed to serialize export anchor file: " + e.getMessage(), e);
        } finally {
            if (export != null) {
                try {
                    export.close();
                } catch (final XMLStreamException e) {
                    logger.error("Failed to close export anchor file: " + e.getMessage(), e);
                }
            }
        }
    }
}

From source file:org.dita.dost.reader.ChunkMapReader.java

/**
 * Create the new topic stump./*from  w  ww. jav  a2  s  . c  o  m*/
 */
private void createTopicStump(final File newFile) {
    OutputStream newFileWriter = null;
    try {
        newFileWriter = new FileOutputStream(newFile);
        final XMLStreamWriter o = XMLOutputFactory.newInstance().createXMLStreamWriter(newFileWriter, UTF8);
        o.writeStartDocument();
        o.writeProcessingInstruction(PI_WORKDIR_TARGET,
                UNIX_SEPARATOR + newFile.getParentFile().getAbsolutePath());
        o.writeProcessingInstruction(PI_WORKDIR_TARGET_URI, newFile.getParentFile().toURI().toString());
        o.writeStartElement(ELEMENT_NAME_DITA);
        o.writeEndElement();
        o.writeEndDocument();
        o.close();
        newFileWriter.flush();
    } catch (final RuntimeException e) {
        throw e;
    } catch (final Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            if (newFileWriter != null) {
                newFileWriter.close();
            }
        } catch (final Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:org.dkpro.core.io.xces.XcesBasicXmlWriter.java

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    OutputStream docOS = null;/*from ww w  . j av a2s .com*/
    try {
        docOS = getOutputStream(aJCas, filenameSuffix);
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        XMLEventWriter xmlEventWriter = new IndentingXMLEventWriter(
                xmlOutputFactory.createXMLEventWriter(docOS));
        JAXBContext context = JAXBContext.newInstance(XcesBodyBasic.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        XMLEventFactory xmlef = XMLEventFactory.newInstance();
        xmlEventWriter.add(xmlef.createStartDocument());
        // Begin cesDoc
        xmlEventWriter.add(xmlef.createStartElement("", "", "cesDoc"));
        // Begin and End cesHeader
        xmlEventWriter.add(xmlef.createStartElement("", "", "cesHeader"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "cesHeader"));

        // Begin text and body
        xmlEventWriter.add(xmlef.createStartElement("", "", "text"));
        // xmlEventWriter.add(xmlef.createStartElement("", "", "body"));

        // Begin body of all the paragraphs            
        Collection<Paragraph> parasInCas = JCasUtil.select(aJCas, Paragraph.class);
        XcesBodyBasic xb = convertToXcesBasicPara(parasInCas);
        marshaller.marshal(new JAXBElement<XcesBodyBasic>(new QName("body"), XcesBodyBasic.class, xb),
                xmlEventWriter);
        // End body of all the paragraphs
        // xmlEventWriter.add(xmlef.createEndElement("", "", "body"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "text"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "cesDoc"));
        xmlEventWriter.add(xmlef.createEndDocument());
    } catch (Exception e) {
        throw new AnalysisEngineProcessException(e);
    } finally {
        closeQuietly(docOS);
    }

}

From source file:org.dkpro.core.io.xces.XcesXmlWriter.java

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    OutputStream docOS = null;/* ww w  .j  a v a2s. c om*/
    try {
        docOS = getOutputStream(aJCas, filenameSuffix);
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        XMLEventWriter xmlEventWriter = new IndentingXMLEventWriter(
                xmlOutputFactory.createXMLEventWriter(docOS));
        JAXBContext context = JAXBContext.newInstance(XcesBody.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        XMLEventFactory xmlef = XMLEventFactory.newInstance();
        xmlEventWriter.add(xmlef.createStartDocument());
        // Begin cesDoc
        xmlEventWriter.add(xmlef.createStartElement("", "", "cesDoc"));
        // Begin and End cesHeader
        xmlEventWriter.add(xmlef.createStartElement("", "", "cesHeader"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "cesHeader"));

        // Begin text and body
        xmlEventWriter.add(xmlef.createStartElement("", "", "text"));
        // xmlEventWriter.add(xmlef.createStartElement("", "", "body"));

        // Begin body of all the paragraphs            
        Collection<Paragraph> parasInCas = JCasUtil.select(aJCas, Paragraph.class);
        XcesBody xb = convertToXcesPara(parasInCas);
        marshaller.marshal(new JAXBElement<XcesBody>(new QName("body"), XcesBody.class, xb), xmlEventWriter);
        // End body of all the paragraphs
        // xmlEventWriter.add(xmlef.createEndElement("", "", "body"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "text"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "cesDoc"));
        xmlEventWriter.add(xmlef.createEndDocument());
    } catch (Exception e) {
        throw new AnalysisEngineProcessException(e);
    } finally {
        closeQuietly(docOS);
    }

}

From source file:org.eclipse.gyrex.logback.config.internal.LogbackConfigGenerator.java

public File generateConfig() {
    // get state location
    if (!parentFolder.isDirectory() && !parentFolder.mkdirs()) {
        throw new IllegalStateException(
                String.format("Unable to create configs directory (%s).", parentFolder));
    }/*w  w w . j a  v a  2s .c  o m*/

    // save file
    final File configFile = new File(parentFolder,
            String.format("logback.%s.xml", DateFormatUtils.format(lastModified, "yyyyMMdd-HHmmssSSS")));
    OutputStream outputStream = null;
    XMLStreamWriter xmlStreamWriter = null;
    try {
        outputStream = new BufferedOutputStream(FileUtils.openOutputStream(configFile));
        final XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        xmlStreamWriter = outputFactory.createXMLStreamWriter(outputStream, CharEncoding.UTF_8);
        // try to format the output
        try {
            final Class<?> clazz = getClass().getClassLoader()
                    .loadClass("com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter");
            xmlStreamWriter = (XMLStreamWriter) clazz.getConstructor(XMLStreamWriter.class)
                    .newInstance(xmlStreamWriter);
        } catch (final Exception e) {
            // ignore
        }
        config.toXml(xmlStreamWriter);
        xmlStreamWriter.flush();
    } catch (final IOException e) {
        throw new IllegalStateException(
                String.format("Unable to create config file (%s).", ExceptionUtils.getRootCauseMessage(e)), e);
    } catch (final XMLStreamException e) {
        throw new IllegalStateException(
                String.format("Error writing config (%s).", ExceptionUtils.getRootCauseMessage(e)), e);
    } finally {
        if (null != xmlStreamWriter) {
            try {
                xmlStreamWriter.close();
            } catch (final Exception e) {
                // ignore
            }
        }
        IOUtils.closeQuietly(outputStream);
    }

    // cleanup directory
    removeOldFiles(parentFolder);

    return configFile;
}

From source file:org.emonocot.job.io.StaxEventItemWriter.java

/**
 * Helper method for opening output source at given file position.
 * @param position Set the position//w w w  . j a v  a 2 s  .c om
 * @param restarted Is this execution being restarted
 */
private void open(final long position, final boolean restarted) {

    File file;
    FileOutputStream os = null;

    try {
        file = resource.getFile();
        FileUtils.setUpOutputFile(file, restarted, overwriteOutput);
        Assert.state(resource.exists(), "Output resource must exist");
        os = new FileOutputStream(file, true);
        channel = os.getChannel();
        setPosition(position);
    } catch (IOException ioe) {
        throw new DataAccessResourceFailureException("Unable to write to file resource: [" + resource + "]",
                ioe);
    }

    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();

    if (outputFactory.isPropertySupported("com.ctc.wstx.automaticEndElements")) {
        // If the current XMLOutputFactory implementation is supplied by
        // Woodstox >= 3.2.9 we want to disable its
        // automatic end element feature (see:
        // http://jira.codehaus.org/browse/WSTX-165) per
        // http://jira.springframework.org/browse/BATCH-761.
        outputFactory.setProperty("com.ctc.wstx.automaticEndElements", Boolean.FALSE);
    }

    try {
        if (transactional) {
            bufferedWriter = new TransactionAwareBufferedWriter(new OutputStreamWriter(os, encoding),
                    new Runnable() {
                        public void run() {
                            closeStream();
                        }
                    });
        } else {
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, encoding));
        }
        delegateEventWriter = outputFactory.createXMLEventWriter(bufferedWriter);
        eventWriter = new NoStartEndDocumentStreamWriter(delegateEventWriter);
        if (!restarted) {
            startDocument(delegateEventWriter);
        }
    } catch (XMLStreamException xse) {
        throw new DataAccessResourceFailureException("Unable to write to file resource: [" + resource + "]",
                xse);
    } catch (UnsupportedEncodingException e) {
        throw new DataAccessResourceFailureException(
                "Unable to write to file resource: [" + resource + "] with encoding=[" + encoding + "]", e);
    }

}

From source file:org.exist.webstart.JnlpWriter.java

/**
 * Write JNLP xml file to browser.//from  w w  w  .  ja v a 2  s.  c  o m
 *
 * @param response Object for writing to end user.
 * @throws java.io.IOException
 */
void writeJnlpXML(JnlpJarFiles jnlpFiles, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    logger.debug("Writing JNLP file");

    // Format URL: "http://host:8080/CONTEXT/webstart/exist.jnlp"
    final String currentUrl = request.getRequestURL().toString();

    // Find BaseUrl http://host:8080/CONTEXT
    final int webstartPos = currentUrl.indexOf("/webstart");
    final String existBaseUrl = currentUrl.substring(0, webstartPos);

    // Find codeBase for jarfiles http://host:8080/CONTEXT/webstart/
    final String codeBase = existBaseUrl + "/webstart/";

    // Perfom sanity checks
    int counter = 0;
    for (final File jar : jnlpFiles.getAllWebstartJars()) {
        counter++; // debugging
        if (jar == null || !jar.exists()) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Missing Jar file! (" + counter + ")");
            return;
        }
    }

    // Find URL to connect to with client
    final String startUrl = existBaseUrl.replaceFirst("http:", "xmldb:exist:")
            .replaceFirst("https:", "xmldb:exist:").replaceAll("-", "%2D") + "/xmlrpc";

    //        response.setDateHeader("Last-Modified", mainJar.lastModified());
    response.setContentType("application/x-java-jnlp-file");
    try {
        final XMLStreamWriter writer = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(response.getOutputStream());

        writer.writeStartDocument();
        writer.writeStartElement("jnlp");
        writer.writeAttribute("spec", "1.0+");
        writer.writeAttribute("codebase", codeBase);
        writer.writeAttribute("href", "exist.jnlp");

        writer.writeStartElement("information");

        writer.writeStartElement("title");
        writer.writeCharacters("eXist XML-DB client");
        writer.writeEndElement();

        writer.writeStartElement("vendor");
        writer.writeCharacters("exist-db.org");
        writer.writeEndElement();

        writer.writeStartElement("homepage");
        writer.writeAttribute("href", "http://exist-db.org");
        writer.writeEndElement();

        writer.writeStartElement("description");
        writer.writeCharacters("Integrated command-line and gui client, "
                + "entirely based on the XML:DB API and provides commands "
                + "for most database related tasks, like creating and "
                + "removing collections, user management, batch-loading " + "XML data or querying.");
        writer.writeEndElement();

        writer.writeStartElement("description");
        writer.writeAttribute("kind", "short");
        writer.writeCharacters("eXist XML-DB client");
        writer.writeEndElement();

        writer.writeStartElement("description");
        writer.writeAttribute("kind", "tooltip");
        writer.writeCharacters("eXist XML-DB client");
        writer.writeEndElement();

        writer.writeStartElement("icon");
        writer.writeAttribute("href", "jnlp_logo.jpg");
        writer.writeEndElement();

        writer.writeStartElement("icon");
        writer.writeAttribute("href", "jnlp_icon_128x128.gif");
        writer.writeAttribute("width", "128");
        writer.writeAttribute("height", "128");
        writer.writeEndElement();

        writer.writeStartElement("icon");
        writer.writeAttribute("href", "jnlp_icon_64x64.gif");
        writer.writeAttribute("width", "64");
        writer.writeAttribute("height", "64");
        writer.writeEndElement();

        writer.writeStartElement("icon");
        writer.writeAttribute("href", "jnlp_icon_32x32.gif");
        writer.writeAttribute("width", "32");
        writer.writeAttribute("height", "32");
        writer.writeEndElement();

        writer.writeEndElement(); // information

        writer.writeStartElement("security");
        writer.writeEmptyElement("all-permissions");
        writer.writeEndElement();

        // ----------

        writer.writeStartElement("resources");

        writer.writeStartElement("property");
        writer.writeAttribute("name", "jnlp.packEnabled");
        writer.writeAttribute("value", "true");
        writer.writeEndElement();

        writer.writeStartElement("j2se");
        writer.writeAttribute("version", "1.6+");
        writer.writeEndElement();

        for (final File jar : jnlpFiles.getAllWebstartJars()) {
            writer.writeStartElement("jar");
            writer.writeAttribute("href", jar.getName());
            writer.writeAttribute("size", "" + jar.length());
            writer.writeEndElement();
        }

        writer.writeEndElement(); // resources

        writer.writeStartElement("application-desc");
        writer.writeAttribute("main-class", "org.exist.client.InteractiveClient");

        writer.writeStartElement("argument");
        writer.writeCharacters("-ouri=" + startUrl);
        writer.writeEndElement();

        writer.writeStartElement("argument");
        writer.writeCharacters("--no-embedded-mode");
        writer.writeEndElement();

        if (request.isSecure()) {
            writer.writeStartElement("argument");
            writer.writeCharacters("--use-ssl");
            writer.writeEndElement();
        }

        writer.writeEndElement(); // application-desc

        writer.writeEndElement(); // jnlp

        writer.writeEndDocument();

        writer.flush();
        writer.close();

    } catch (final Throwable ex) {
        logger.error(ex);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }

}