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.betaconceptframework.astroboa.model.jaxb.AstroboaMarshaller.java

@Override
public void marshal(Object arg0, Writer arg1) throws JAXBException {
    if (outputTypeIsJSON()) {

        XMLStreamWriter jsonXmlStreamWriter = null;
        try {//  w w  w  .jav a2 s  . com

            jsonXmlStreamWriter = CmsEntitySerialization.Context.createJsonXmlStreamWriter(arg1, true,
                    BooleanUtils.isTrue((Boolean) marshaller.getProperty(Marshaller.JAXB_FORMATTED_OUTPUT)));

            marshal(arg0, jsonXmlStreamWriter);
        } catch (Exception e) {
            try {
                if (jsonXmlStreamWriter != null) {
                    jsonXmlStreamWriter.flush();
                    logger.error("JSON Export so far {}", arg1);
                }
            } catch (Exception e1) {
                //Ignore it
            }
            throw new JAXBException(e);
        }
    } else {
        marshaller.marshal(arg0, arg1);
    }

}

From source file:org.chorusbdd.chorus.tools.webagent.jettyhandler.XmlStreamingHandler.java

@Override
protected final void doHandle(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    try {/*from w w w  .ja  va 2 s  .c o m*/
        XMLStreamWriter writer = XmlUtils.getIndentingXmlStreamWriter(response.getWriter());
        doHandle(target, baseRequest, request, response, writer);
        writer.flush();
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); //client may not see if content already sent
        log.error("Failed while streaming XML", e);
    }
}

From source file:org.codice.ddf.security.interceptor.AnonymousInterceptor.java

@Override
public void handleMessage(SoapMessage message) throws Fault {

    if (anonymousAccessDenied) {
        LOGGER.debug("AnonymousAccess not enabled - no message checking performed.");
        return;//from w w w  .ja  v a  2 s .  co m
    }

    if (message != null) {
        SoapVersion version = message.getVersion();
        SOAPMessage soapMessage = getSOAPMessage(message);
        SOAPFactory soapFactory = null;
        SOAPElement securityHeader = null;

        //Check if security header exists; if not, execute AnonymousInterceptor logic
        String actor = (String) getOption(WSHandlerConstants.ACTOR);
        if (actor == null) {
            actor = (String) message.getContextualProperty(SecurityConstants.ACTOR);
        }

        Element existingSecurityHeader = null;
        try {
            LOGGER.debug("Checking for security header.");
            existingSecurityHeader = WSSecurityUtil.getSecurityHeader(soapMessage.getSOAPPart(), actor);
        } catch (WSSecurityException e1) {
            LOGGER.debug("Issue with getting security header", e1);
        }
        if (existingSecurityHeader == null) {
            LOGGER.debug("Current request has no security header, continuing with AnonymousInterceptor");

            AssertionInfoMap assertionInfoMap = message.get(AssertionInfoMap.class);

            // if there is a policy we need to follow or we are ignoring policies, prepare the SOAP message
            if ((assertionInfoMap != null) || overrideEndpointPolicies) {
                RequestData reqData = new CXFRequestData();

                WSSConfig config = (WSSConfig) message.getContextualProperty(WSSConfig.class.getName());
                WSSecurityEngine engine = null;
                if (config != null) {
                    engine = new WSSecurityEngine();
                    engine.setWssConfig(config);
                }
                if (engine == null) {
                    engine = new WSSecurityEngine();
                    config = engine.getWssConfig();
                }

                reqData.setWssConfig(config);

                try {
                    soapFactory = SOAPFactory.newInstance();
                } catch (SOAPException e) {
                    LOGGER.error("Could not create a SOAPFactory.", e);
                    return; // can't add anything if we can't create it
                }
                if (soapFactory != null) {
                    //Create security header
                    try {
                        securityHeader = soapFactory.createElement(WSConstants.WSSE_LN, WSConstants.WSSE_PREFIX,
                                WSConstants.WSSE_NS);
                        securityHeader.addAttribute(
                                new QName(WSConstants.URI_SOAP11_ENV, WSConstants.ATTR_MUST_UNDERSTAND), "1");
                    } catch (SOAPException e) {
                        LOGGER.error("Unable to create security header for anonymous user.", e);
                        return; // can't create the security - just return
                    }
                }
            }

            EffectivePolicy effectivePolicy = message.get(EffectivePolicy.class);
            Exchange exchange = message.getExchange();
            BindingOperationInfo bindingOperationInfo = exchange.getBindingOperationInfo();
            Endpoint endpoint = exchange.get(Endpoint.class);
            if (null == endpoint) {
                return;
            }
            EndpointInfo endpointInfo = endpoint.getEndpointInfo();

            Bus bus = exchange.get(Bus.class);
            PolicyEngine policyEngine = bus.getExtension(PolicyEngine.class);

            if (effectivePolicy == null) {
                if (policyEngine != null) {
                    if (MessageUtils.isRequestor(message)) {
                        effectivePolicy = policyEngine.getEffectiveClientResponsePolicy(endpointInfo,
                                bindingOperationInfo, message);
                    } else {
                        effectivePolicy = policyEngine.getEffectiveServerRequestPolicy(endpointInfo,
                                bindingOperationInfo, message);
                    }
                }
            }

            //Auto analyze endpoint policies

            //Token Assertions
            String tokenAssertion = null;
            String tokenType = null;

            //Security Binding Assertions
            boolean layoutLax = false;
            boolean layoutStrict = false;
            boolean layoutLaxTimestampFirst = false;
            boolean layoutLaxTimestampLast = false;
            boolean requireClientCert = false;
            QName secBindingAssertion = null;

            //Supporting Token Assertions
            QName supportingTokenAssertion = null;
            boolean policyRequirementsSupported = false;

            // if there is a policy, try to follow it as closely as possible
            if (effectivePolicy != null) {
                Policy policy = effectivePolicy.getPolicy();
                if (policy != null) {
                    AssertionInfoMap infoMap = new AssertionInfoMap(policy);
                    Set<Map.Entry<QName, Collection<AssertionInfo>>> entries = infoMap.entrySet();
                    for (Map.Entry<QName, Collection<AssertionInfo>> entry : entries) {
                        Collection<AssertionInfo> assetInfoList = entry.getValue();
                        for (AssertionInfo info : assetInfoList) {
                            LOGGER.debug("Assertion Name: {}", info.getAssertion().getName().getLocalPart());
                            QName qName = info.getAssertion().getName();
                            StringWriter out = new StringWriter();
                            XMLStreamWriter writer = null;
                            try {
                                writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
                            } catch (XMLStreamException e) {
                                LOGGER.debug("Error with XMLStreamWriter", e);
                            } catch (FactoryConfigurationError e) {
                                LOGGER.debug("Error with FactoryConfiguration", e);
                            }
                            try {
                                if (writer != null) {
                                    info.getAssertion().serialize(writer);
                                    writer.flush();
                                }
                            } catch (XMLStreamException e) {
                                LOGGER.debug("Error with XMLStream", e);
                            } finally {
                                if (writer != null) {
                                    try {
                                        writer.close();
                                    } catch (XMLStreamException ignore) {
                                        //ignore
                                    }
                                }
                            }
                            LOGGER.trace("Assertion XML: {}", out.toString());
                            String xml = out.toString();

                            // TODO DDF-1205 complete support for dynamic policy handling
                            if (qName.equals(SP12Constants.TRANSPORT_BINDING)) {
                                secBindingAssertion = qName;
                            } else if (qName.equals(SP12Constants.INCLUDE_TIMESTAMP)) {
                                createIncludeTimestamp(soapFactory, securityHeader);
                            } else if (qName.equals(SP12Constants.LAYOUT)) {
                                String xpathLax = "/Layout/Policy/Lax";
                                String xpathStrict = "/Layout/Policy/Strict";
                                String xpathLaxTimestampFirst = "/Layout/Policy/LaxTimestampFirst";
                                String xpathLaxTimestampLast = "/Layout/Policy/LaxTimestampLast";

                            } else if (qName.equals(SP12Constants.TRANSPORT_TOKEN)) {

                            } else if (qName.equals(SP12Constants.HTTPS_TOKEN)) {
                                String xpath = "/HttpsToken/Policy/RequireClientCertificate";

                            } else if (qName.equals(SP12Constants.SIGNED_SUPPORTING_TOKENS)) {
                                String xpath = "/SignedSupportingTokens/Policy//IssuedToken/RequestSecurityTokenTemplate/TokenType";
                                tokenType = retrieveXmlValue(xml, xpath);
                                supportingTokenAssertion = qName;

                            } else if (qName.equals(SP12Constants.SUPPORTING_TOKENS)) {
                                String xpath = "/SupportingTokens/Policy//IssuedToken/RequestSecurityTokenTemplate/TokenType";
                                tokenType = retrieveXmlValue(xml, xpath);
                                supportingTokenAssertion = qName;

                            } else if (qName.equals(
                                    org.apache.cxf.ws.addressing.policy.MetadataConstants.ADDRESSING_ASSERTION_QNAME)) {
                                createAddressing(message, soapMessage, soapFactory);

                            } else if (qName.equals(SP12Constants.TRUST_13)) {

                            } else if (qName.equals(SP12Constants.ISSUED_TOKEN)) {
                                //Check Token Assertion
                                String xpath = "/IssuedToken/@IncludeToken";
                                tokenAssertion = retrieveXmlValue(xml, xpath);

                            } else if (qName.equals(SP12Constants.WSS11)) {

                            }
                        }
                    }

                    //Check security and token policies
                    if (tokenAssertion != null && tokenType != null
                            && tokenAssertion.trim().equals(SP12Constants.INCLUDE_ALWAYS_TO_RECIPIENT)
                            && tokenType.trim().equals(TOKEN_SAML20)) {
                        policyRequirementsSupported = true;
                    } else {
                        LOGGER.warn(
                                "AnonymousInterceptor does not support the policies presented by the endpoint.");
                    }

                } else {
                    if (overrideEndpointPolicies) {
                        LOGGER.debug(
                                "WS Policy is null, override is true - an anonymous assertion will be generated");
                    } else {
                        LOGGER.warn(
                                "WS Policy is null, override flag is false - no anonymous assertion will be generated.");
                    }
                }
            } else {
                if (overrideEndpointPolicies) {
                    LOGGER.debug(
                            "Effective WS Policy is null, override is true - an anonymous assertion will be generated");
                } else {
                    LOGGER.warn(
                            "Effective WS Policy is null, override flag is false - no anonymous assertion will be generated.");
                }
            }

            if (policyRequirementsSupported || overrideEndpointPolicies) {
                LOGGER.debug("Creating anonymous security token.");
                if (soapFactory != null) {
                    HttpServletRequest request = (HttpServletRequest) message
                            .get(AbstractHTTPDestination.HTTP_REQUEST);
                    createSecurityToken(version, soapFactory, securityHeader, request.getRemoteAddr());
                    try {
                        // Add security header to SOAP message
                        soapMessage.getSOAPHeader().addChildElement(securityHeader);
                    } catch (SOAPException e) {
                        LOGGER.error("Issue when adding security header to SOAP message:" + e.getMessage());
                    }
                } else {
                    LOGGER.debug("Security Header was null so not creating a SAML Assertion");
                }
            }
        } else {
            LOGGER.debug("SOAP message contains security header, no action taken by the AnonymousInterceptor.");
        }
        if (LOGGER.isTraceEnabled()) {
            try {
                LOGGER.trace("SOAP request after anonymous interceptor: {}",
                        SecurityLogger.getFormattedXml(soapMessage.getSOAPHeader().getParentNode()));
            } catch (SOAPException e) {
                //ignore
            }
        }
    } else {
        LOGGER.error("Incoming SOAP message is null - anonymous interceptor makes no sense.");
    }
}

From source file:org.corpus_tools.salt.util.internal.persistence.SaltXML10Writer.java

/**
 * Writes a Salt project to the file given by {@link #getPath()}.
 * /* www . j  a v a 2 s  . c  om*/
 * @param project
 *            the Salt project to be written
 */
public void writeSaltProject(SaltProject project) {
    XMLStreamWriter xml = null;
    try (OutputStream output = new FileOutputStream(path)) {
        xml = xmlFactory.createXMLStreamWriter(output, "UTF-8");
        xml.writeStartDocument("1.0");
        if (isPrettyPrint) {
            xml.writeCharacters("\n");
        }
        writeSaltProject(xml, project);

        xml.writeEndDocument();

    } catch (XMLStreamException | IOException e) {
        throw new SaltResourceException("Cannot store salt project to file '" + getLocationStr() + "'. ", e);
    } finally {
        if (xml != null) {
            try {
                xml.flush();
                xml.close();
            } catch (XMLStreamException e) {
                throw new SaltResourceException("Cannot store salt project to file '" + getLocationStr()
                        + "', because the opened stream is not closable. ", e);
            }
        }
    }
}

From source file:org.corpus_tools.salt.util.internal.persistence.SaltXML10Writer.java

/**
 * Writes a corpus graph to the xml stream
 * /*from   www. j  av a 2  s.c  o m*/
 * @param graph
 *            the corpus graph to be written
 * @param embedded
 *            determines whether this corpus graph is part of a saltProject
 * @param xml
 *            xml stream to write corpus graph to, if the passed one is
 *            null, a new one will be created
 */
public void writeCorpusGraph(XMLStreamWriter xml, SCorpusGraph graph, boolean embedded) {
    try {
        if (!embedded) {
            xml.writeStartDocument("1.0");
            if (isPrettyPrint) {
                xml.writeCharacters("\n");
                xml.writeStartElement(NS_SALTCOMMON, TAG_SCORPUSGRAPH, NS_VALUE_SALTCOMMON);
                xml.writeNamespace(NS_SCORPUSSTRUCTURE, NS_VALUE_SCORPUSSTRUCTURE);
                xml.writeNamespace(NS_XMI, NS_VALUE_XMI);
                xml.writeNamespace(NS_XSI, NS_VALUE_XSI);
                xml.writeNamespace(NS_SALTCORE, NS_VALUE_SALTCORE);
                xml.writeNamespace(NS_SALTCOMMON, NS_VALUE_SALTCOMMON);
                xml.writeAttribute(NS_VALUE_XMI, ATT_XMI_VERSION, "2.0");
            }
        } else {
            xml.writeStartElement(TAG_SCORPUSGRAPH);
        }

        // write all labels
        if (graph.getLabels() != null) {
            Iterator<Label> labelIt = graph.getLabels().iterator();
            while (labelIt.hasNext()) {
                if (isPrettyPrint) {
                    xml.writeCharacters("\n");
                    xml.writeCharacters("\t");
                }
                writeLabel(xml, labelIt.next());
            }
        }
        // stores the position of a single node in the list of nodes to
        // refer them in a relation
        Map<SNode, Integer> nodePositions = new HashMap<>();

        // write all nodes
        if (graph.getNodes() != null) {
            Iterator<SNode> nodeIt = graph.getNodes().iterator();
            Integer position = 0;
            while (nodeIt.hasNext()) {
                SNode node = nodeIt.next();
                writeNode(xml, node, null);
                nodePositions.put(node, position);
                position++;
            }
        }

        // write all relations
        if (graph.getRelations() != null) {
            Iterator<SRelation<SNode, SNode>> relIt = graph.getRelations().iterator();
            while (relIt.hasNext()) {
                SRelation<SNode, SNode> rel = relIt.next();
                writeRelation(xml, rel, nodePositions, null);
            }
        }
        if (isPrettyPrint) {
            xml.writeCharacters("\n");
            xml.writeCharacters("\t");
        }
        xml.writeEndElement();
    } catch (XMLStreamException e) {
        throw new SaltResourceException(
                "Cannot store salt project to file '" + getLocationStr() + "'. " + e.getMessage(), e);
    } finally {
        if (!embedded) {
            if (xml != null) {
                try {
                    xml.flush();
                    xml.close();
                } catch (XMLStreamException e) {
                    throw new SaltResourceException("Cannot store salt project to file '" + getLocationStr()
                            + "', because the opened stream is not closable. ", e);
                }
            }
        }
    }
}

From source file:org.corpus_tools.salt.util.internal.persistence.SaltXML10Writer.java

/**
 * Writes a document graph to the file given by {@link #getPath()}.
 * //w  ww .j a  va  2s  .  c o m
 * @param graph
 */
public void writeDocumentGraph(SDocumentGraph graph) {
    XMLStreamWriter xml = null;
    try (OutputStream output = new FileOutputStream(path)) {
        xml = xmlFactory.createXMLStreamWriter(output, "UTF-8");

        xml.writeStartDocument("1.0");
        if (isPrettyPrint) {
            xml.writeCharacters("\n");
        }

        writeDocumentGraph(xml, graph);

        xml.writeEndDocument();
    } catch (XMLStreamException | IOException e) {
        throw new SaltResourceException("Cannot store document graph to file '" + getLocationStr() + "'. ", e);
    } finally {
        if (xml != null) {
            try {
                xml.flush();
                xml.close();
            } catch (XMLStreamException e) {
                throw new SaltResourceException("Cannot store document graph to file '" + getLocationStr()
                        + "', because the opened stream is not closable. ", e);
            }
        }
    }
}

From source file:org.corpus_tools.salt.util.VisJsVisualizer.java

private void writeHTML(File outputFolder) throws XMLStreamException, IOException {

    int nodeDist = 0;
    int sprLength = 0;
    double sprConstant = 0.0;

    try (OutputStream os = new FileOutputStream(new File(outputFolder, HTML_FILE));
            FileOutputStream fos = new FileOutputStream(tmpFile)) {
        XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        XMLStreamWriter xmlWriter = outputFactory.createXMLStreamWriter(os, "UTF-8");

        setNodeWriter(os);/*from   w  ww .  j  a  v  a  2s.  c  o  m*/
        setEdgeWriter(fos);

        xmlWriter.writeStartDocument("UTF-8", "1.0");
        xmlWriter.writeCharacters(NEWLINE);
        xmlWriter.writeStartElement(TAG_HTML);
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeStartElement(TAG_HEAD);
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeStartElement(TAG_TITLE);
        xmlWriter.writeCharacters("Salt Document Tree");
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeStartElement(TAG_STYLE);
        xmlWriter.writeAttribute(ATT_TYPE, "text/css");
        xmlWriter.writeCharacters(NEWLINE);
        xmlWriter.writeCharacters("body {" + NEWLINE + "font: 10pt sans;" + NEWLINE + "}" + NEWLINE
                + "#mynetwork {" + NEWLINE + "height: 90%;" + NEWLINE + "width: 90%;" + NEWLINE
                + "border: 1px solid lightgray; " + NEWLINE + "text-align: center;" + NEWLINE + "}" + NEWLINE
                + "#loadingBar {" + NEWLINE + "position:absolute;" + NEWLINE + "top:0px;" + NEWLINE
                + "left:0px;" + NEWLINE + "width: 0px;" + NEWLINE + "height: 0px;" + NEWLINE
                + "background-color:rgba(200,200,200,0.8);" + NEWLINE + "-webkit-transition: all 0.5s ease;"
                + NEWLINE + "-moz-transition: all 0.5s ease;" + NEWLINE + "-ms-transition: all 0.5s ease;"
                + NEWLINE + "-o-transition: all 0.5s ease;" + NEWLINE + "transition: all 0.5s ease;" + NEWLINE
                + "opacity:1;" + NEWLINE + "}" + NEWLINE + "#wrapper {" + NEWLINE + "position:absolute;"
                + NEWLINE + "width: 1200px;" + NEWLINE + "height: 90%;" + NEWLINE + "}" + NEWLINE + "#text {"
                + NEWLINE + "position:absolute;" + NEWLINE + "top:8px;" + NEWLINE + "left:530px;" + NEWLINE
                + "width:30px;" + NEWLINE + "height:50px;" + NEWLINE + "margin:auto auto auto auto;" + NEWLINE
                + "font-size:16px;" + NEWLINE + "color: #000000;" + NEWLINE + "}" + NEWLINE
                + "div.outerBorder {" + NEWLINE + "position:relative;" + NEWLINE + "top:400px;" + NEWLINE
                + "width:600px;" + NEWLINE + "height:44px;" + NEWLINE + "margin:auto auto auto auto;" + NEWLINE
                + "border:8px solid rgba(0,0,0,0.1);" + NEWLINE
                + "background: rgb(252,252,252); /* Old browsers */" + NEWLINE
                + "background: -moz-linear-gradient(top,  rgba(252,252,252,1) 0%, rgba(237,237,237,1) 100%); /* FF3.6+ */"
                + NEWLINE
                + "background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(252,252,252,1)), color-stop(100%,rgba(237,237,237,1))); /* Chrome,Safari4+ */"
                + NEWLINE
                + "background: -webkit-linear-gradient(top,  rgba(252,252,252,1) 0%,rgba(237,237,237,1) 100%); /* Chrome10+,Safari5.1+ */"
                + NEWLINE
                + "background: -o-linear-gradient(top,  rgba(252,252,252,1) 0%,rgba(237,237,237,1) 100%); /* Opera 11.10+ */"
                + NEWLINE
                + "background: -ms-linear-gradient(top,  rgba(252,252,252,1) 0%,rgba(237,237,237,1) 100%); /* IE10+ */"
                + NEWLINE
                + "background: linear-gradient(to bottom,  rgba(252,252,252,1) 0%,rgba(237,237,237,1) 100%); /* W3C */"
                + NEWLINE
                + "filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#ededed',GradientType=0 ); /* IE6-9 */"
                + NEWLINE + "border-radius:72px;" + NEWLINE + "box-shadow: 0px 0px 10px rgba(0,0,0,0.2);"
                + NEWLINE + "}" + NEWLINE + "#border {" + NEWLINE + "position:absolute;" + NEWLINE + "top:10px;"
                + NEWLINE + "left:10px;" + NEWLINE + "width:500px;" + NEWLINE + "height:23px;" + NEWLINE
                + "margin:auto auto auto auto;" + NEWLINE + "box-shadow: 0px 0px 4px rgba(0,0,0,0.2);" + NEWLINE
                + "border-radius:10px;" + NEWLINE + "}" + NEWLINE + "#bar {" + NEWLINE + "position:absolute;"
                + NEWLINE + "top:0px;" + NEWLINE + "left:0px;" + NEWLINE + "width:20px;" + NEWLINE
                + "height:20px;" + NEWLINE + "margin:auto auto auto auto;" + NEWLINE + "border-radius:6px;"
                + NEWLINE + "border:1px solid rgba(30,30,30,0.05);" + NEWLINE
                + "background: rgb(0, 173, 246); /* Old browsers */" + NEWLINE
                + "box-shadow: 2px 0px 4px rgba(0,0,0,0.4);" + NEWLINE + "}" + NEWLINE);
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeStartElement(TAG_SCRIPT);
        xmlWriter.writeAttribute(ATT_SRC, VIS_JS_SRC);
        xmlWriter.writeAttribute(ATT_TYPE, "text/javascript");
        xmlWriter.writeCharacters(NEWLINE);
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeStartElement(TAG_SCRIPT);
        xmlWriter.writeAttribute(ATT_SRC, JQUERY_SRC);
        xmlWriter.writeAttribute(ATT_TYPE, "text/javascript");
        xmlWriter.writeCharacters(NEWLINE);
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeEmptyElement(TAG_LINK);
        xmlWriter.writeAttribute(ATT_HREF, VIS_CSS_SRC);
        xmlWriter.writeAttribute(ATT_REL, "stylesheet");
        xmlWriter.writeAttribute(ATT_TYPE, "text/css");
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeStartElement(TAG_SCRIPT);
        xmlWriter.writeAttribute(ATT_TYPE, "text/javascript");
        xmlWriter.writeCharacters(NEWLINE + "function frameSize() {" + NEWLINE
                + "$(document).ready(function() {" + NEWLINE + "function elementResize() {" + NEWLINE
                + "var browserWidth = $(window).width()*0.98;" + NEWLINE
                + "document.getElementById('mynetwork').style.width = browserWidth;" + NEWLINE + "}" + NEWLINE
                + "elementResize();" + NEWLINE + "$(window).bind(\"resize\", function(){" + NEWLINE
                + "elementResize();" + NEWLINE + "});" + NEWLINE + "});" + NEWLINE + "}" + NEWLINE);
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeStartElement(TAG_SCRIPT);
        xmlWriter.writeAttribute(ATT_TYPE, "text/javascript");
        xmlWriter.writeCharacters(NEWLINE + "function start(){" + NEWLINE + "loadSaltObjectAndDraw();" + NEWLINE
                + "frameSize();" + NEWLINE + "}" + NEWLINE + "var nodesJson = [];" + NEWLINE
                + "var edgesJson = [];" + NEWLINE + "var network = null;" + NEWLINE
                + "function loadSaltObjectAndDraw() {" + NEWLINE + "var nodesJson = " + NEWLINE);
        xmlWriter.flush();

        try {
            buildJSON();
        } catch (SaltParameterException e) {
            throw new SaltParameterException(e.getMessage());
        } catch (SaltException e) {
            throw new SaltException(e.getMessage());
        }

        if (nNodes < 20) {
            nodeDist = 120;
            sprConstant = 1.2;
            sprLength = 120;
        } else if (nNodes >= 20 && nNodes < 100) {
            nodeDist = 150;
            sprConstant = 1.1;
            sprLength = 160;
        } else if (nNodes >= 100 && nNodes < 400) {
            nodeDist = 180;
            sprConstant = 0.9;
            sprLength = 180;
        } else if (nNodes >= 400 && nNodes < 800) {
            nodeDist = 200;
            sprConstant = 0.6;
            sprLength = 200;
        } else {
            nodeDist = 250;
            sprConstant = 0.3;
            sprLength = 230;
        }
        ;

        // write nodes as array
        nodeWriter.flush();

        xmlWriter.writeCharacters(";" + NEWLINE);
        xmlWriter.writeCharacters("var edgesJson = " + NEWLINE);
        xmlWriter.flush();

        // write edges as array to tmp file
        edgeWriter.flush();

        // copy edges from tmp file
        ByteStreams.copy(new FileInputStream(tmpFile), os);

        xmlWriter.writeCharacters(";" + NEWLINE);

        xmlWriter.writeCharacters("var nodeDist =" + nodeDist + ";" + NEWLINE);

        xmlWriter.writeCharacters("draw(nodesJson, edgesJson, nodeDist);" + NEWLINE + "}" + NEWLINE
                + "var directionInput = document.getElementById(\"direction\");" + NEWLINE
                + "function destroy() {" + NEWLINE + "if (network !== null) {" + NEWLINE + "network.destroy();"
                + NEWLINE + "network = null;" + NEWLINE + "}" + NEWLINE + "}" + NEWLINE + NEWLINE
                + "function draw(nodesJson, edgesJson, nodeDist) {" + NEWLINE + "destroy();" + NEWLINE
                + "var connectionCount = [];" + NEWLINE + "var nodes = [];" + NEWLINE + "var edges = [];"
                + NEWLINE + NEWLINE + "nodes = new vis.DataSet(nodesJson);" + NEWLINE
                + "edges = new vis.DataSet(edgesJson);" + NEWLINE
                + "var container = document.getElementById('mynetwork');" + NEWLINE + "var data = {" + NEWLINE
                + "nodes: nodes," + NEWLINE + "edges: edges" + NEWLINE + "};" + NEWLINE + "var options = {"
                + NEWLINE + "nodes:{" + NEWLINE + "shape: \"box\"" + NEWLINE + "}," + NEWLINE + "edges: {"
                + NEWLINE + "smooth: true," + NEWLINE + "arrows: {" + NEWLINE + "to: {" + NEWLINE
                + "enabled: true" + NEWLINE + "}" + NEWLINE + "}" + NEWLINE + "}," + NEWLINE + "interaction: {"
                + NEWLINE + "navigationButtons: true," + NEWLINE + "keyboard: true" + NEWLINE + "}," + NEWLINE
                + "layout: {" + NEWLINE + "hierarchical:{" + NEWLINE + "direction: directionInput.value"
                + NEWLINE + "}" + NEWLINE + "}," + NEWLINE + "physics: {" + NEWLINE + "hierarchicalRepulsion: {"
                + NEWLINE + "centralGravity: 0.8," + NEWLINE + "springLength: " + sprLength + "," + NEWLINE
                + "springConstant: " + sprConstant + "," + NEWLINE + "nodeDistance: nodeDist," + NEWLINE
                + "damping: 0.04" + NEWLINE + "}," + NEWLINE + "maxVelocity: 50," + NEWLINE + "minVelocity: 1,"
                + NEWLINE + "solver: 'hierarchicalRepulsion'," + NEWLINE + "timestep: 0.5," + NEWLINE
                + "stabilization: {" + NEWLINE + "iterations: 1000" + NEWLINE + "}" + NEWLINE + "}" + NEWLINE
                + "}" + NEWLINE + ";" + NEWLINE + "network = new vis.Network(container, data, options);"
                + NEWLINE);

        if (withPhysics == true) {
            xmlWriter.writeCharacters("network.on(\"stabilizationProgress\", function(params) {" + NEWLINE
                    + "var maxWidth = 496;" + NEWLINE + "var minWidth = 20;" + NEWLINE
                    + "var widthFactor = params.iterations/params.total;" + NEWLINE
                    + "var width = Math.max(minWidth,maxWidth * widthFactor);" + NEWLINE
                    + "document.getElementById('loadingBar').style.opacity = 1;" + NEWLINE
                    + "document.getElementById('bar').style.width = width + 'px';" + NEWLINE
                    + "document.getElementById('text').innerHTML = Math.round(widthFactor*100) + '%';" + NEWLINE
                    + "});" + NEWLINE + "network.on(\"stabilizationIterationsDone\", function() {" + NEWLINE
                    + "document.getElementById('text').innerHTML = '100%';" + NEWLINE
                    + "document.getElementById('bar').style.width = '496px';" + NEWLINE
                    + "document.getElementById('loadingBar').style.opacity = 0;" + NEWLINE + "});" + NEWLINE);
        }

        xmlWriter.writeCharacters("}" + NEWLINE);
        // script
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters(NEWLINE);

        // head
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeStartElement(TAG_BODY);
        xmlWriter.writeAttribute("onload", "start();");
        xmlWriter.writeCharacters(NEWLINE);

        if (withPhysics == true) {
            xmlWriter.writeStartElement(TAG_DIV);
            xmlWriter.writeAttribute(ATT_ID, "wrapper");
            xmlWriter.writeCharacters(NEWLINE);

            xmlWriter.writeStartElement(TAG_DIV);
            xmlWriter.writeAttribute(ATT_ID, "loadingBar");
            xmlWriter.writeCharacters(NEWLINE);

            xmlWriter.writeStartElement(TAG_DIV);
            xmlWriter.writeAttribute(ATT_CLASS, "outerBorder");
            xmlWriter.writeCharacters(NEWLINE);

            xmlWriter.writeStartElement(TAG_DIV);
            xmlWriter.writeAttribute(ATT_ID, "text");
            xmlWriter.writeCharacters("0%");
            xmlWriter.writeEndElement();
            xmlWriter.writeCharacters(NEWLINE);

            xmlWriter.writeStartElement(TAG_DIV);
            xmlWriter.writeAttribute(ATT_ID, "border");
            xmlWriter.writeCharacters(NEWLINE);

            xmlWriter.writeStartElement(TAG_DIV);
            xmlWriter.writeAttribute(ATT_ID, "bar");
            xmlWriter.writeCharacters(NEWLINE);
            xmlWriter.writeEndElement();
            xmlWriter.writeCharacters(NEWLINE);

            xmlWriter.writeEndElement();
            xmlWriter.writeCharacters(NEWLINE);
            xmlWriter.writeEndElement();
            xmlWriter.writeCharacters(NEWLINE);
            xmlWriter.writeEndElement();
            xmlWriter.writeCharacters(NEWLINE);
        }

        xmlWriter.writeStartElement(TAG_H2);
        xmlWriter.writeCharacters("Dokument-Id: " + docId);
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeStartElement(TAG_DIV);
        xmlWriter.writeAttribute(ATT_STYLE, TEXT_STYLE);
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeStartElement("p");

        xmlWriter.writeEmptyElement(TAG_INPUT);
        xmlWriter.writeAttribute(ATT_TYPE, "button");
        xmlWriter.writeAttribute(ATT_ID, "btn-UD");
        xmlWriter.writeAttribute(ATT_VALUE, "Up-Down");
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeEmptyElement(TAG_INPUT);
        xmlWriter.writeAttribute(ATT_TYPE, "button");
        xmlWriter.writeAttribute(ATT_ID, "btn-DU");
        xmlWriter.writeAttribute(ATT_VALUE, "Down-Up");
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeEmptyElement(TAG_INPUT);
        xmlWriter.writeAttribute(ATT_TYPE, "hidden");
        // TODO check the apostrophes
        xmlWriter.writeAttribute(ATT_ID, "direction");
        xmlWriter.writeAttribute(ATT_VALUE, "UD");
        xmlWriter.writeCharacters(NEWLINE);

        // p
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeStartElement(TAG_DIV);
        xmlWriter.writeAttribute(ATT_ID, "mynetwork");
        xmlWriter.writeCharacters(NEWLINE);
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeStartElement(TAG_P);
        xmlWriter.writeAttribute(ATT_ID, "selection");
        xmlWriter.writeCharacters(NEWLINE);
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeStartElement(TAG_SCRIPT);
        xmlWriter.writeAttribute(ATT_LANG, "JavaScript");
        xmlWriter.writeCharacters(NEWLINE);
        xmlWriter.writeCharacters("var directionInput = document.getElementById(\"direction\");" + NEWLINE
                + "var btnUD = document.getElementById(\"btn-UD\");" + NEWLINE + "btnUD.onclick = function() {"
                + NEWLINE + "directionInput.value = \"UD\";" + NEWLINE + "start();" + NEWLINE + "};" + NEWLINE
                + "var btnDU = document.getElementById(\"btn-DU\");" + NEWLINE + "btnDU.onclick = function() {"
                + NEWLINE + "directionInput.value = \"DU\";" + NEWLINE + "start();" + NEWLINE + "};" + NEWLINE);
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters(NEWLINE);

        // div wrapper
        if (withPhysics == true) {
            xmlWriter.writeEndElement();
            xmlWriter.writeCharacters(NEWLINE);
        }

        // body
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters(NEWLINE);

        // html
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters(NEWLINE);

        xmlWriter.writeEndDocument();
        xmlWriter.flush();
        xmlWriter.close();
        nodeWriter.close();
        edgeWriter.close();
    }

}

From source file:org.deegree.gml.geometry.GML3GeometryWriterTest.java

private void assertAIXMReexport(String srcFileName, String expectedFileName)
        throws XMLParsingException, ClassCastException, ClassNotFoundException, InstantiationException,
        IllegalAccessException, XMLStreamException, FactoryConfigurationError, IOException, UnknownCRSException,
        TransformationException {//from   w w  w . jav  a2 s. co  m

    String aixmNs = "http://www.aixm.aero/schema/5.1";
    Geometry geom = readAIXMGeometry(srcFileName);

    XMLMemoryStreamWriter memoryWriter = new XMLMemoryStreamWriter();
    XMLStreamWriter xmlWriter = new IndentingXMLStreamWriter(memoryWriter.getXMLStreamWriter());
    GMLStreamWriter exporter = createGMLStreamWriter(GML_32, xmlWriter);
    Map<String, String> nsBindings = new HashMap<String, String>();
    nsBindings.put("aixm", aixmNs);
    exporter.setNamespaceBindings(nsBindings);
    exporter.write(geom);
    xmlWriter.flush();

    byte[] expected = IOUtils.toByteArray(
            GML3GeometryWriterTest.class.getResourceAsStream("../aixm/geometry/" + expectedFileName));
    String s = new String(expected, "UTF-8");
    Assert.assertEquals(s, memoryWriter.toString());
}

From source file:org.deegree.services.csw.CSWController.java

/**
 * Exports the correct recognized request.
 * //from  w w  w  . j  a  v  a2s.  co  m
 * @param getCapabilitiesRequest
 * @param requestWrapper
 * @param response
 * @throws XMLStreamException
 * @throws IOException
 * @throws OWSException
 */
private void doGetCapabilities(GetCapabilities getCapabilitiesRequest, HttpResponseBuffer response,
        boolean isSoap) throws XMLStreamException, IOException, OWSException {
    Set<Sections> sections = getSections(getCapabilitiesRequest);
    Version negotiatedVersion = null;
    if (getCapabilitiesRequest.getAcceptVersions() == null) {
        negotiatedVersion = new Version(2, 0, 2);
    } else {
        negotiatedVersion = negotiateVersion(getCapabilitiesRequest);
    }
    response.setContentType(profile.getAcceptFormat(getCapabilitiesRequest));
    XMLStreamWriter xmlWriter = getXMLResponseWriter(response, null);
    CapabilitiesHandler gce = profile.getCapabilitiesHandler(xmlWriter, mainMetadataConf, mainControllerConf,
            sections, mainMetadataConf.getServiceIdentification(), negotiatedVersion, enableTransactions,
            enableInspireExtensions, mainMetadataConf.getServiceProvider(), extendedCapabilities);
    gce.export();
    xmlWriter.flush();

}

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

private void doGetFeatureOfInterest(GetFeatureOfInterest foi, HttpResponseBuffer response)
        throws IOException, XMLStreamException {
    XMLStreamWriter xmlWriter = response.getXMLWriter();

    List<String> foiIDs = Arrays.asList(foi.getFoiID());

    xmlWriter.writeStartElement(SA_PREFIX, "SamplingFeatureCollection", SA_NS);
    xmlWriter.writeNamespace(SA_PREFIX, SA_NS);
    xmlWriter.writeNamespace(XSI_PREFIX, XSINS);
    xmlWriter.writeNamespace(XLINK_PREFIX, XLNNS);
    xmlWriter.writeNamespace(GML_PREFIX, GMLNS);

    xmlWriter.writeAttribute(XSI_PREFIX, XSINS, "schemaLocation",
            "http://www.opengis.net/sampling/1.0 http://schemas.opengis.net/sampling/1.0.0/sampling.xsd");

    // TODO a url should be specified in the xlink:href of sampledFeature
    xmlWriter.writeEmptyElement(SA_PREFIX, "sampledFeature", SA_NS);

    for (Offering offering : sosService.getAllOfferings()) {
        for (Procedure procedure : offering.getProcedures()) {
            if (foiIDs.contains(procedure.getFeatureOfInterestHref())) {
                Geometry procGeometry = procedure.getLocation();
                if (procGeometry instanceof Point) { // TODO check if the procedure can have some other geometries
                    // and if so,
                    // handle them

                    xmlWriter.writeStartElement(SA_PREFIX, "member", SA_NS);

                    xmlWriter.writeStartElement(SA_PREFIX, "SamplingPoint", SA_NS);
                    xmlWriter.writeStartElement(GML_PREFIX, "name", GMLNS);
                    xmlWriter.writeCharacters(procedure.getFeatureOfInterestHref());
                    // TODO if the GetFeatureOfInterest does not provide a foi but a location instead, search
                    // for all
                    // sensors
                    // inside that BBOX
                    xmlWriter.writeEndElement();

                    // TODO a url should be specified in the xlink:href of sampledFeature
                    xmlWriter.writeEmptyElement(SA_PREFIX, "sampledFeature", SA_NS);

                    xmlWriter.writeStartElement(SA_PREFIX, "position", SA_NS);
                    // exporting a gml:Point TODO use GML encoder
                    xmlWriter.writeStartElement(GML_PREFIX, "Point", GMLNS);
                    // have the last part of the foiID as the Point id attribute
                    String[] foiParts = procedure.getFeatureOfInterestHref().split(":");
                    xmlWriter.writeAttribute(GML_PREFIX, GMLNS, "id", foiParts[foiParts.length - 1]);

                    xmlWriter.writeStartElement(GML_PREFIX, "pos", GMLNS);
                    ICRS foiCRS = null;/*  w  w  w.j  a  v  a  2  s.c  om*/
                    foiCRS = procGeometry.getCoordinateSystem();
                    xmlWriter.writeAttribute("srsName", foiCRS.getCode().toString());

                    Point p = (Point) procGeometry;
                    xmlWriter.writeCharacters(p.get0() + " " + p.get1());
                    xmlWriter.writeEndElement(); // gml:pos
                    xmlWriter.writeEndElement(); // gml:Point
                    xmlWriter.writeEndElement(); // gml:position
                    xmlWriter.writeEndElement(); // sa:SamplingPoint
                    xmlWriter.writeEndElement(); // sa:member
                }
            }
        }
    }

    xmlWriter.writeEndElement(); // sa:SamplingFeatureCollection
    xmlWriter.writeEndDocument();
    xmlWriter.flush();
}