Example usage for javax.xml.stream XMLStreamWriter flush

List of usage examples for javax.xml.stream XMLStreamWriter flush

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamWriter flush.

Prototype

public void flush() throws XMLStreamException;

Source Link

Document

Write any cached data to the underlying output mechanism.

Usage

From source file:org.deegree.services.sos.SOSController.java

private void doGetObservation(GetObservation observationReq, HttpResponseBuffer response)
        throws XMLStreamException, IOException, OWSException {
    XMLStreamWriter xmlWriter = response.getXMLWriter();
    LOG.debug("offering: {}", observationReq.getOffering());
    if (sosService.hasOffering(observationReq.getOffering())) {
        validateGetObservation(observationReq);

        Offering offering = sosService.getOffering(observationReq.getOffering());
        Observation observation = getObservationResult(offering, observationReq);

        writeObservationResult(xmlWriter, observation, observationReq);

    } else {/*  w  ww.  j a  v a2  s .com*/
        throw new OWSException("the offering " + observationReq.getOffering() + " is invalid",
                OWSException.INVALID_PARAMETER_VALUE, "offering");
    }
    xmlWriter.flush();
}

From source file:org.deegree.services.sos.SOSController.java

private void doGetCapabilities(GetCapabilities capabilitiesReq, DeegreeServicesMetadataType serviceMetadata,
        HttpResponseBuffer response)/*from w  ww  . j  av  a2 s.  co m*/
        throws XMLStreamException, IOException, OWSException, ObservationDatastoreException {
    negotiateVersion(capabilitiesReq); // throws OWS Exception, if version is not supported
    XMLStreamWriter xmlWriter = response.getXMLWriter();
    Set<Sections> sections = getSections(capabilitiesReq);
    ObservationStoreManager storeMgr = workspace.getSubsystemManager(ObservationStoreManager.class);
    Capabilities100XMLAdapter.export(sections, sosService.getAllOfferings(), serviceMetadata, identification,
            xmlWriter, storeMgr);
    xmlWriter.flush();
}

From source file:org.deegree.services.wcs.WCSController.java

private void doDescribeCoverage(DescribeCoverage describeReq, HttpResponseBuffer response)
        throws IOException, XMLStreamException, OWSException {
    response.setContentType("text/xml");
    XMLStreamWriter xmlWriter = getXMLStreamWriter(response.getWriter());
    List<WCSCoverage> coverages = new LinkedList<WCSCoverage>();
    if (describeReq.getCoverages().size() == 0) { // return all
        coverages = wcsService.getAllCoverages();
    } else {//from ww  w . j a  v  a 2  s  .c  om
        for (String reqCoverage : describeReq.getCoverages()) {
            if (wcsService.hasCoverage(reqCoverage)) {
                coverages.add(wcsService.getCoverage(reqCoverage));
            } else {
                throw new OWSException("Unknown coverage " + reqCoverage, COVERAGE_NOT_DEFINED, "coverage");
            }
        }
    }
    CoverageDescription100XMLAdapter.export(xmlWriter, coverages, UPDATE_SEQUENCE);
    xmlWriter.flush();
}

From source file:org.deegree.services.wcs.WCSController.java

private void doGetCapabilities(GetCapabilities request, HttpServletRequest requestWrapper,
        HttpResponseBuffer response) throws IOException, XMLStreamException, OWSException {

    Set<Sections> sections = getSections(request);

    Version negotiateVersion = negotiateVersion(request);
    // if update sequence is given and matches the given update sequence an error should occur
    // http://cite.opengeospatial.org/OGCTestData/wcs/1.0.0/specs/03-065r6.html#7.2.1_Key-value_pair_encoding
    if (negotiateVersion.equals(VERSION_100)) {
        String updateSeq = request.getUpdateSequence();
        int requestedUS = UPDATE_SEQUENCE - 1;
        try {//from w  ww .  j  a v  a  2s .  c o m
            requestedUS = Integer.parseInt(updateSeq);
        } catch (NumberFormatException e) {
            // nothing to do, just ignore it.
        }
        if (requestedUS == UPDATE_SEQUENCE) {
            throw new OWSException("Update sequence may not be equal than server's current update sequence.",
                    WCSConstants.ExeptionCode_1_0_0.CurrentUpdateSequence.name());
        } else if (requestedUS > UPDATE_SEQUENCE) {
            throw new OWSException("Update sequence may not be higher than server's current update sequence.",
                    WCSConstants.ExeptionCode_1_0_0.InvalidUpdateSequence.name());
        }
    }

    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    factory.setProperty(IS_REPAIRING_NAMESPACES, true);

    response.setContentType("text/xml");
    XMLStreamWriter xmlWriter = getXMLStreamWriter(response.getWriter());
    if (negotiateVersion.equals(VERSION_100)) {
        Capabilities100XMLAdapter.export(xmlWriter, request, identification, provider, allowedOperations,
                sections, wcsService.getAllCoverages(), mainMetadataConf, mainControllerConf, xmlWriter,
                UPDATE_SEQUENCE);
    } else {
        // the 1.1.0
    }
    xmlWriter.writeEndDocument();
    xmlWriter.flush();
}

From source file:org.deegree.services.wfs.WebFeatureService.java

private void doGetCapabilities(GetCapabilities request, HttpResponseBuffer response)
        throws XMLStreamException, IOException, OWSException {

    LOG.debug("doGetCapabilities: " + request);
    Version negotiatedVersion = negotiateVersion(request);

    // cope with the 'All' section specifier
    Set<String> sections = request.getSections();
    Set<String> sectionsUC = new HashSet<String>();
    for (String section : sections) {
        if (section.equalsIgnoreCase("ALL")) {
            sectionsUC = null;//from   ww  w .  j av  a 2  s  .  c  o  m
            break;
        }
        sectionsUC.add(section.toUpperCase());
    }
    // never empty (only null)
    if (sectionsUC != null && sectionsUC.size() == 0) {
        sectionsUC = null;
    }
    final Collection<FeatureType> sortedFts = getFeatureTypesToExport();

    XMLStreamWriter xmlWriter = getXMLResponseWriter(response, "text/xml", null);
    GetCapabilitiesHandler adapter = new GetCapabilitiesHandler(this, service, negotiatedVersion, xmlWriter,
            sortedFts, sectionsUC, enableTransactions, queryCRS, mdProvider);
    adapter.export();
    xmlWriter.flush();
}

From source file:org.deegree.services.wps.WPService.java

private void doDescribeProcess(DescribeProcessRequest request, HttpResponseBuffer response)
        throws OWSException {

    LOG.trace("doDescribeProcess invoked, request: " + request);

    // check that all requested processes exist (and resolve special value 'ALL')
    List<WPSProcess> processes = new ArrayList<WPSProcess>();
    for (CodeType identifier : request.getIdentifiers()) {
        LOG.debug("Looking up process '" + identifier + "'");
        if (ALL_PROCESSES_IDENTIFIER.equals(identifier)) {
            processes.addAll(processManager.getProcesses().values());
            break;
        }//from   www .  j a  va  2 s.  com
        WPSProcess process = processManager.getProcess(identifier);
        if (process != null) {
            processes.add(process);
        } else {
            throw new OWSException("InvalidParameterValue: Identifier\nNo process with id " + identifier
                    + " is registered in the WPS.", OWSException.INVALID_PARAMETER_VALUE);
        }
    }

    try {
        response.setContentType("text/xml; charset=UTF-8");
        XMLStreamWriter xmlWriter = response.getXMLWriter();

        Map<ProcessDefinition, String> processDefToWSDLUrl = new HashMap<ProcessDefinition, String>();
        for (WPSProcess process : processes) {
            ProcessDefinition processDef = process.getDescription();
            CodeType processId = new CodeType(processDef.getIdentifier().getValue(),
                    processDef.getIdentifier().getCodeSpace());
            // TODO WSDL
            // if ( processIdToWSDL.containsKey( processId ) ) {
            // String wsdlURL = OGCFrontController.getHttpGetURL()
            // + "service=WPS&version=1.0.0&request=GetWPSWSDL&identifier=" + processId.getCode();
            // processDefToWSDLUrl.put( processDef, wsdlURL );
            // }
        }

        DescribeProcessResponseXMLAdapter.export100(xmlWriter, processes, processDefToWSDLUrl);
        xmlWriter.flush();
    } catch (XMLStreamException e) {
        e.printStackTrace();
        LOG.error("Internal error: " + e.getMessage());
        throw new OWSException("Error occured while creating response for DescribeProcess operation",
                NO_APPLICABLE_CODE);
    } catch (IOException e) {
        throw new OWSException("Error occured while creating response for DescribeProcess operation",
                NO_APPLICABLE_CODE);
    } catch (Exception e) {
        e.printStackTrace();
        LOG.error("Internal error: " + e.getMessage());
    }

    LOG.trace("doDescribeProcess finished");
}

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 . ja  v  a  2s.  c om

    // 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.eclipse.koneki.protocols.omadm.client.basic.DMBasicSession.java

private void writeMessage(final OutputStream out) throws XMLStreamException {
    final XMLStreamWriter writer = this.dmClient.createXMLStreamWriter(out, ENCODING);
    writer.writeStartDocument(ENCODING, "1.0"); //$NON-NLS-1$
    // CHECKSTYLE:OFF (imbricated blocks)
    {//w  w  w .j  av  a  2 s. com
        writer.writeStartElement("SyncML"); //$NON-NLS-1$
        writer.writeAttribute("xmlns", "SYNCML:SYNCML1.2"); //$NON-NLS-1$//$NON-NLS-2$
        {
            writer.writeStartElement("SyncHdr"); //$NON-NLS-1$
            {
                writer.writeStartElement("VerDTD"); //$NON-NLS-1$
                writer.writeCharacters("1.2"); //$NON-NLS-1$
                writer.writeEndElement();
                writer.writeStartElement("VerProto"); //$NON-NLS-1$
                writer.writeCharacters("DM/1.2"); //$NON-NLS-1$
                writer.writeEndElement();
                writer.writeStartElement("SessionID"); //$NON-NLS-1$
                writer.writeCharacters(this.sessionId);
                writer.writeEndElement();
                writer.writeStartElement("MsgID"); //$NON-NLS-1$
                writer.writeCharacters(String.valueOf(this.idGenerator.nextMsgID()));
                writer.writeEndElement();
                writer.writeStartElement("Target"); //$NON-NLS-1$
                {
                    writer.writeStartElement("LocURI"); //$NON-NLS-1$
                    writer.writeCharacters(this.server.toString());
                    writer.writeEndElement();
                }
                writer.writeEndElement();
                writer.writeStartElement("Source"); //$NON-NLS-1$
                {
                    writer.writeStartElement("LocURI"); //$NON-NLS-1$
                    writer.writeCharacters(this.client.toString());
                    writer.writeEndElement();
                }
                writer.writeEndElement();

                /*
                 * Add basic authentication
                 */
                writer.writeStartElement("Cred"); //$NON-NLS-1$
                {
                    writer.writeStartElement("Meta"); //$NON-NLS-1$
                    {
                        writer.writeStartElement("Format"); //$NON-NLS-1$
                        writer.writeAttribute("xmlns", "syncml:metinf"); //$NON-NLS-1$ //$NON-NLS-2$
                        writer.writeCharacters("b64"); //$NON-NLS-1$
                        writer.writeEndElement();

                        writer.writeStartElement("Type"); //$NON-NLS-1$
                        writer.writeAttribute("xmlns", "syncml:metinf"); //$NON-NLS-1$ //$NON-NLS-2$
                        writer.writeCharacters("syncml:auth-basic"); //$NON-NLS-1$
                        writer.writeEndElement();
                    }
                    writer.writeEndElement();

                    writer.writeStartElement("Data"); //$NON-NLS-1$
                    writer.writeCharacters(userAuth);
                    writer.writeEndElement();

                }
                writer.writeEndElement();
                /*
                 * End authentication
                 */
            }
            writer.writeEndElement();
            writer.writeStartElement("SyncBody"); //$NON-NLS-1$
            {
                writeStatus(writer);
                if (!this.isClientAuthenticated) {
                    writeAlert(writer, "1201"); //$NON-NLS-1$
                    writeGenericAlert(writer, this.genericAlerts);
                    writeReplace(writer, this.devInfoNodes);
                }

                writer.writeStartElement("Final"); //$NON-NLS-1$
                writer.writeEndElement();
            }
            writer.writeEndElement();
        }
        writer.writeEndElement();
    }
    // CHECKSTYLE:ON
    writer.writeEndDocument();
    writer.flush();
    writer.close();
}

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

/**
 * Write JNLP xml file to browser./*from  www .j  a v a2 s .  c om*/
 *
 * @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());
    }

}

From source file:org.exoplatform.services.jcr.ext.artifact.ArtifactManagingServiceImpl.java

protected File createSingleMetadata(String groupId, String artifactId, String version)
        throws FileNotFoundException {
    File temp = null;//from   www  .  jav a2s. co  m
    try {
        String filename = getUniqueFilename("maven-metadata.xml");
        temp = File.createTempFile(filename, null);

        OutputStream os = new FileOutputStream(temp);
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = factory.createXMLStreamWriter(os);
        try {
            writer.writeStartDocument("UTF-8", "1.0");
            writer.writeStartElement("metadata");

            writer.writeStartElement("groupId");
            writer.writeCharacters(groupId);
            writer.writeEndElement();

            writer.writeStartElement("artifactId");
            writer.writeCharacters(artifactId);
            writer.writeEndElement();

            writer.writeStartElement("version");
            writer.writeCharacters(version);
            writer.writeEndElement();

            writer.writeEndElement();
            writer.writeEndDocument();
        } finally {
            writer.flush();
            writer.close();
            os.close();
        }
    } catch (XMLStreamException e) {
        LOG.error("Error on creating metadata - XML", e);
    } catch (IOException e) {
        LOG.error("Error on creating metadata - FILE", e);
    }
    return (temp != null && temp.exists()) ? temp : null;
}