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.asimba.wa.integrationtest.saml2.model.Response.java

/**
 * Build response based on current state.<br/>
 * Only do Base64-encoding of the XML-document -- no deflating whatsoever may be done.
 * //from   ww w.ja  v a2 s  . co m
 * @return
 * @throws XMLStreamException 
 */
public String getResponse(int format) throws XMLStreamException {
    _logger.info("For ID: " + getId());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    StringWriter sw = new StringWriter();

    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    XMLStreamWriter writer = null;

    // ugly but effective:
    if (format == base64) {
        writer = factory.createXMLStreamWriter(baos);
    } else {
        writer = factory.createXMLStreamWriter(sw);
    }

    writer.writeStartElement("saml2p", "Response", "urn:oasis:names:tc:SAML:2.0:protocol");
    writer.writeNamespace("saml2p", "urn:oasis:names:tc:SAML:2.0:protocol");
    writer.writeNamespace("xs", "http://www.w3.org/2001/XMLSchema");

    writer.writeAttribute("Destination", _destination);
    writer.writeAttribute("ID", _id);
    writer.writeAttribute("InResponseTo", _inResponseTo);
    writer.writeAttribute("IssueInstant", _issueInstant);
    writer.writeAttribute("Version", "2.0");

    writeIssuer(writer);

    writeStatus(writer);

    _assertion.writeAssertion(writer);

    writer.writeEndElement(); // SAML2

    writer.flush();

    if (format == base64) {
        byte[] bain = baos.toByteArray();
        byte[] encoded = Base64.encodeBase64(bain, false);
        String result = new String(encoded, Charset.forName("UTF-8"));

        return result;
    } else {
        return sw.toString();
    }
}

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 ww  w  .  java  2s.  c  om*/
    }

    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.pepper.core.PepperJobImpl.java

/**
 * {@inheritDoc PepperJob#save(URI)}/* ww  w. j  av a2 s . c  om*/
 */
@Override
public URI save(URI uri) {
    if (uri == null) {
        throw new PepperException(
                "Cannot save Pepper job '" + getId() + "', because the passed uri is empty. ");
    }
    File file = null;
    if (PepperUtil.FILE_ENDING_PEPPER.equals(uri.fileExtension())) {
        // passed uri already points to a Pepper file
        file = new File(uri.toFileString());
    } else {
        // uri points to a directory
        String directory = uri.toFileString();
        if (!directory.endsWith("/")) {
            directory = directory + "/";
        }
        file = new File(directory + getId() + "." + PepperUtil.FILE_ENDING_PEPPER);
    }
    // create parent directory of file
    if (!file.getParentFile().exists()) {
        if (!file.getParentFile().mkdirs()) {
            if (!file.getParentFile().canWrite()) {
                throw new PepperModuleXMLResourceException(
                        "Cannot create folder '" + file.getParentFile().getAbsolutePath()
                                + "' to store Pepper workflow file, because of an access permission. ");
            } else {
                throw new PepperModuleXMLResourceException("Cannot create folder '"
                        + file.getParentFile().getAbsolutePath() + "' to store Pepper workflow file. ");
            }
        }
        ;
    }

    XMLOutputFactory xof = XMLOutputFactory.newInstance();
    XMLStreamWriter xml;

    try {
        xml = new XMLStreamWriter(xof.createXMLStreamWriter(new FileWriter(file.getAbsolutePath())));
        xml.setPrettyPrint(true);
        xml.writeStartDocument();
        // <pepper>
        xml.writeStartElement(WorkflowDescriptionReader.TAG_PEPEPR_JOB);
        if (getId() != null) {
            xml.writeAttribute(WorkflowDescriptionReader.ATT_ID, getId());
        }
        xml.writeAttribute(WorkflowDescriptionReader.ATT_VERSION, "1.0");
        // <customization> ???
        List<StepDesc> importers = new ArrayList<>();
        List<StepDesc> manipulators = new ArrayList<>();
        List<StepDesc> exporters = new ArrayList<>();
        for (StepDesc step : getStepDescs()) {
            if (MODULE_TYPE.IMPORTER.equals(step.getModuleType())) {
                importers.add(step);
            } else if (MODULE_TYPE.MANIPULATOR.equals(step.getModuleType())) {
                manipulators.add(step);
            } else if (MODULE_TYPE.EXPORTER.equals(step.getModuleType())) {
                exporters.add(step);
            }
        }

        // <importer>
        for (StepDesc step : importers) {
            xml.writeStartElement(WorkflowDescriptionReader.TAG_IMPORTER);
            save_module(xml, step);
            xml.writeEndElement();
        }
        // <manipulator>
        for (StepDesc step : manipulators) {
            xml.writeStartElement(WorkflowDescriptionReader.TAG_MANIPULATOR);
            save_module(xml, step);
            xml.writeEndElement();
        }
        // <exporter>
        for (StepDesc step : exporters) {
            xml.writeStartElement(WorkflowDescriptionReader.TAG_EXPORTER);
            save_module(xml, step);
            xml.writeEndElement();
        }
        xml.writeEndElement();
        xml.writeEndDocument();
        xml.flush();
    } catch (XMLStreamException | IOException e) {
        throw new PepperException("Cannot store Pepper job '" + getId() + "' because of a nested exception. ",
                e);
    }
    return (URI.createFileURI(file.getAbsolutePath()));
}

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 av  a 2 s.  c om*/
        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.commons.xml.stax.FilteringXMLStreamWriterTest.java

private XMLStreamWriter getWriter(List<String> paths, OutputStream stream) throws Exception {
    XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(stream);
    writer = new IndentingXMLStreamWriter(writer);
    List<XPath> xpaths = new ArrayList<XPath>();
    for (String s : paths) {
        xpaths.add(new XPath(s, nsBindings));
    }/*ww  w .j ava  2s .c o  m*/
    writer = new FilteringXMLStreamWriter(writer, xpaths);
    return writer;
}

From source file:org.deegree.console.datastore.feature.MappingWizardSQL.java

public String generateConfig() {

    try {//from   w  w  w  . j a  v a  2  s  . c  o  m
        ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
        Workspace ws = ((WorkspaceBean) ctx.getApplicationMap().get("workspace")).getActiveWorkspace()
                .getNewWorkspace();

        CRSRef storageCrs = CRSManager.getCRSRef(this.storageCrs);
        boolean createBlobMapping = storageMode.equals("hybrid") || storageMode.equals("blob");
        boolean createRelationalMapping = storageMode.equals("hybrid") || storageMode.equals("relational");
        GeometryStorageParams geometryParams = new GeometryStorageParams(storageCrs, storageSrid, DIM_2);
        AppSchemaMapper mapper = new AppSchemaMapper(appSchema, createBlobMapping, createRelationalMapping,
                geometryParams, Math.min(tableNameLength, columnNameLength), true, false);
        mappedSchema = mapper.getMappedSchema();
        SQLFeatureStoreConfigWriter configWriter = new SQLFeatureStoreConfigWriter(mappedSchema);
        File tmpConfigFile = File.createTempFile("fsconfig", ".xml");
        FileOutputStream fos = new FileOutputStream(tmpConfigFile);
        XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(fos);
        xmlWriter = new IndentingXMLStreamWriter(xmlWriter);

        List<String> schemaUrls = new ArrayList<String>(selectedAppSchemaFiles.length);
        for (String schemaFile : selectedAppSchemaFiles) {
            schemaUrls.add(".." + File.separator + ".." + File.separator + "appschemas" + schemaFile);
        }
        configWriter.writeConfig(xmlWriter, jdbcId, schemaUrls);
        xmlWriter.close();
        IOUtils.closeQuietly(fos);
        System.out.println("Wrote to file " + tmpConfigFile);

        // let the resource manager do the dirty work
        try {
            FeatureStoreManager fsMgr = ws.getResourceManager(FeatureStoreManager.class);
            ResourceIdentifier<FeatureStore> id = new DefaultResourceIdentifier<FeatureStore>(
                    FeatureStoreProvider.class, getFeatureStoreId());
            ResourceLocation<FeatureStore> loc = new IncorporealResourceLocation<FeatureStore>(
                    readFileToByteArray(tmpConfigFile), id);
            ws.add(loc);
            ResourceMetadata<FeatureStore> md = ws.getResourceMetadata(FeatureStoreProvider.class,
                    getFeatureStoreId());
            Config c = new Config(md, fsMgr, "/console/featurestore/sql/wizard4", false);
            return c.edit();
        } catch (Throwable t) {
            LOG.error(t.getMessage(), t);
            FacesMessage fm = new FacesMessage(SEVERITY_ERROR, "Unable to create config: " + t.getMessage(),
                    null);
            FacesContext.getCurrentInstance().addMessage(null, fm);
            return null;
        }
    } catch (Throwable t) {
        LOG.error(t.getMessage(), t);
        String msg = "Error generating feature store configuration.";
        FacesMessage fm = new FacesMessage(SEVERITY_ERROR, msg, t.getMessage());
        FacesContext.getCurrentInstance().addMessage(null, fm);
        return "/console/featurestore/sql/wizard3";
    }
}

From source file:org.deegree.console.featurestore.MappingWizardSQL.java

public String generateConfig() {

    try {//from   w  ww . j a v a 2 s .c o  m
        ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
        DeegreeWorkspace ws = ((WorkspaceBean) ctx.getApplicationMap().get("workspace")).getActiveWorkspace();

        CRSRef storageCrs = CRSManager.getCRSRef(this.storageCrs);
        boolean createBlobMapping = storageMode.equals("hybrid") || storageMode.equals("blob");
        boolean createRelationalMapping = storageMode.equals("hybrid") || storageMode.equals("relational");
        GeometryStorageParams geometryParams = new GeometryStorageParams(storageCrs, storageSrid, DIM_2);
        AppSchemaMapper mapper = new AppSchemaMapper(appSchema, createBlobMapping, createRelationalMapping,
                geometryParams, Math.min(tableNameLength, columnNameLength), true, false);
        mappedSchema = mapper.getMappedSchema();
        SQLFeatureStoreConfigWriter configWriter = new SQLFeatureStoreConfigWriter(mappedSchema);
        File tmpConfigFile = File.createTempFile("fsconfig", ".xml");
        FileOutputStream fos = new FileOutputStream(tmpConfigFile);
        XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(fos);
        xmlWriter = new IndentingXMLStreamWriter(xmlWriter);

        List<String> schemaUrls = new ArrayList<String>(selectedAppSchemaFiles.length);
        for (String schemaFile : selectedAppSchemaFiles) {
            schemaUrls.add(".." + File.separator + ".." + File.separator + "appschemas" + schemaFile);
        }
        configWriter.writeConfig(xmlWriter, jdbcId, schemaUrls);
        xmlWriter.close();
        IOUtils.closeQuietly(fos);
        System.out.println("Wrote to file " + tmpConfigFile);

        // let the resource manager do the dirty work

        ConfigManager mgr = (ConfigManager) ctx.getSessionMap().get("configManager");

        // let the resource manager do the dirty work
        try {
            FeatureStoreManager fsMgr = ws.getSubsystemManager(FeatureStoreManager.class);
            this.resourceState = fsMgr.createResource(getFeatureStoreId(), new FileInputStream(tmpConfigFile));
            Config c = new Config(this.resourceState, mgr, fsMgr, "/console/featurestore/sql/wizard4", false);
            return c.edit();
        } catch (Throwable t) {
            LOG.error(t.getMessage(), t);
            FacesMessage fm = new FacesMessage(SEVERITY_ERROR, "Unable to create config: " + t.getMessage(),
                    null);
            FacesContext.getCurrentInstance().addMessage(null, fm);
            return null;
        }
    } catch (Throwable t) {
        LOG.error(t.getMessage(), t);
        String msg = "Error generating feature store configuration.";
        FacesMessage fm = new FacesMessage(SEVERITY_ERROR, msg, t.getMessage());
        FacesContext.getCurrentInstance().addMessage(null, fm);
        return "/console/featurestore/sql/wizard3";
    }
}

From source file:org.deegree.filter.xml.Filter200XMLEncoderParameterizedTest.java

@Test
public void testExport() throws Exception {
    Filter filter = parseFilter(filterUnderTest);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLStreamWriter out = XMLOutputFactory.newInstance().createXMLStreamWriter(bos);
    IndentingXMLStreamWriter writer = new IndentingXMLStreamWriter(out);
    Filter200XMLEncoder.export(filter, writer);
    out.close();//  w w  w.  j  a v a2  s  . co m

    assertThat("Failed test: " + testName, the(bos.toString()), isSimilarTo(the(filterUnderTest)));
}

From source file:org.deegree.geometry.wkbadapter.WKBReaderTest.java

@Test
public void testWKBToGML() throws Exception {
    ICRS crs = CRSManager.lookup("EPSG:4326");

    InputStream is = WKBReaderTest.class.getResourceAsStream(BASE_DIR + "Polygon.wkb");
    byte[] wkb = IOUtils.toByteArray(is);

    Polygon geom = (Polygon) WKBReader.read(wkb, crs);
    assertTrue(geom.getGeometryType() == GeometryType.PRIMITIVE_GEOMETRY);

    StringWriter sw = new StringWriter();
    XMLOutputFactory outFactory = XMLOutputFactory.newInstance();
    outFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);

    XMLStreamWriter writer = outFactory.createXMLStreamWriter(sw);
    writer.setDefaultNamespace(CommonNamespaces.GML3_2_NS);
    GMLStreamWriter gmlSw = GMLOutputFactory.createGMLStreamWriter(GMLVersion.GML_32, writer);
    gmlSw.write(geom);//from   www. jav a  2  s. c o  m
    writer.close();

    String s = "<gml:posList>5.148530 59.951879 5.134692 59.736522 5.561175 59.728897 5.577771 59.944188 5.148530 59.951879</gml:posList>";
    assertTrue(sw.toString().contains(s));
}

From source file:org.deegree.metadata.iso.ISORecordTest.java

private byte[] writeOut(OMElement filterEl, List<XPath> paths) throws Exception {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(bos);
    if (paths != null) {
        writer = new FilteringXMLStreamWriter(writer, paths);
    }//from   w w  w .  j av a  2 s  .  com
    filterEl.serialize(writer);
    writer.close();
    return bos.toByteArray();
}