Example usage for javax.xml.stream XMLStreamWriter close

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

Introduction

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

Prototype

public void close() throws XMLStreamException;

Source Link

Document

Close this writer and free any resources associated with the writer.

Usage

From source file:org.apache.synapse.commons.json.JsonDataSource.java

public void serialize(XMLStreamWriter xmlWriter) throws XMLStreamException {
    XMLStreamReader reader = getReader();
    xmlWriter.writeStartDocument();//from   w  w w . j  a va  2s  . c  o m
    while (reader.hasNext()) {
        int x = reader.next();
        switch (x) {
        case XMLStreamConstants.START_ELEMENT:
            xmlWriter.writeStartElement(reader.getPrefix(), reader.getLocalName(), reader.getNamespaceURI());
            int namespaceCount = reader.getNamespaceCount();
            for (int i = namespaceCount - 1; i >= 0; i--) {
                xmlWriter.writeNamespace(reader.getNamespacePrefix(i), reader.getNamespaceURI(i));
            }
            int attributeCount = reader.getAttributeCount();
            for (int i = 0; i < attributeCount; i++) {
                xmlWriter.writeAttribute(reader.getAttributePrefix(i), reader.getAttributeNamespace(i),
                        reader.getAttributeLocalName(i), reader.getAttributeValue(i));
            }
            break;
        case XMLStreamConstants.START_DOCUMENT:
            break;
        case XMLStreamConstants.CHARACTERS:
            xmlWriter.writeCharacters(reader.getText());
            break;
        case XMLStreamConstants.CDATA:
            xmlWriter.writeCData(reader.getText());
            break;
        case XMLStreamConstants.END_ELEMENT:
            xmlWriter.writeEndElement();
            break;
        case XMLStreamConstants.END_DOCUMENT:
            xmlWriter.writeEndDocument();
            break;
        case XMLStreamConstants.SPACE:
            break;
        case XMLStreamConstants.COMMENT:
            xmlWriter.writeComment(reader.getText());
            break;
        case XMLStreamConstants.DTD:
            xmlWriter.writeDTD(reader.getText());
            break;
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            xmlWriter.writeProcessingInstruction(reader.getPITarget(), reader.getPIData());
            break;
        case XMLStreamConstants.ENTITY_REFERENCE:
            xmlWriter.writeEntityRef(reader.getLocalName());
            break;
        default:
            throw new OMException();
        }
    }
    xmlWriter.writeEndDocument();
    xmlWriter.flush();
    xmlWriter.close();
}

From source file:org.apache.syncope.client.cli.commands.migrate.MigrateConf.java

private static void exec(final String src, final String dst) throws XMLStreamException, IOException {
    XMLStreamWriter writer = new PrettyPrintXMLStreamWriter(
            OUTPUT_FACTORY.createXMLStreamWriter(new FileWriter(dst)), 2);
    writer.writeStartDocument("UTF-8", "1.0");
    writer.writeStartElement("dataset");

    StringWriter reporterSW = new StringWriter();
    XMLStreamWriter reporter = new PrettyPrintXMLStreamWriter(OUTPUT_FACTORY.createXMLStreamWriter(reporterSW),
            2);//from   w  ww .  j a  va 2 s.  c  o  m
    reporter.writeStartDocument("UTF-8", "1.0");
    reporter.writeStartElement("dataset");

    InputStream inputStream = Files.newInputStream(Paths.get(src));
    XMLStreamReader reader = INPUT_FACTORY.createXMLStreamReader(inputStream);
    reader.nextTag(); // root
    reader.nextTag(); // dataset

    writer.writeStartElement("AnyType");
    writer.writeAttribute("id", "USER");
    writer.writeAttribute("kind", "USER");
    writer.writeEndElement();

    writer.writeStartElement("AnyTypeClass");
    writer.writeAttribute("id", "BaseUser");
    writer.writeEndElement();

    writer.writeStartElement("AnyType_AnyTypeClass");
    writer.writeAttribute("anyType_id", "USER");
    writer.writeAttribute("anyTypeClass_id", "BaseUser");
    writer.writeEndElement();

    writer.writeStartElement("AnyType");
    writer.writeAttribute("id", "GROUP");
    writer.writeAttribute("kind", "GROUP");
    writer.writeEndElement();

    writer.writeStartElement("AnyTypeClass");
    writer.writeAttribute("id", "BaseGroup");
    writer.writeEndElement();

    writer.writeStartElement("AnyType_AnyTypeClass");
    writer.writeAttribute("anyType_id", "GROUP");
    writer.writeAttribute("anyTypeClass_id", "BaseGroup");
    writer.writeEndElement();

    writer.writeStartElement("AnyTypeClass");
    writer.writeAttribute("id", "BaseUMembership");
    writer.writeEndElement();

    Set<String> connInstanceCapabilities = new HashSet<>();

    String lastUUID;
    String syncopeConf = UUID.randomUUID().toString();
    Map<String, String> cPlainAttrs = new HashMap<>();
    Map<String, String> policies = new HashMap<>();
    Map<String, String> connInstances = new HashMap<>();
    Map<String, String> provisions = new HashMap<>();
    Map<String, String> mappings = new HashMap<>();
    Map<String, String> tasks = new HashMap<>();
    Map<String, String> notifications = new HashMap<>();
    Map<String, String> reports = new HashMap<>();

    String globalAccountPolicy = null;
    String globalPasswordPolicy = null;
    while (reader.hasNext()) {
        if (reader.isStartElement()) {
            switch (reader.getLocalName().toLowerCase()) {
            case "syncopeconf":
                writer.writeStartElement("SyncopeConf");
                writer.writeAttribute("id", syncopeConf);
                writer.writeEndElement();
                break;

            case "cschema":
                writer.writeStartElement("SyncopeSchema");
                writer.writeAttribute("id", getAttributeValue(reader, "name"));

                writer.writeStartElement("PlainSchema");
                copyAttrs(reader, writer);
                writer.writeAttribute("id", getAttributeValue(reader, "name"));
                writer.writeEndElement();
                break;

            case "cattr":
                writer.writeStartElement("CPlainAttr");
                copyAttrs(reader, writer, "owner_id", "schema_name");
                lastUUID = UUID.randomUUID().toString();
                writer.writeAttribute("id", lastUUID);
                writer.writeAttribute("owner_id", syncopeConf);
                writer.writeAttribute("schema_id", getAttributeValue(reader, "schema_name"));
                writer.writeEndElement();
                cPlainAttrs.put(getAttributeValue(reader, "id"), lastUUID);
                break;

            case "cattrvalue":
                writer.writeStartElement("CPlainAttrValue");
                copyAttrs(reader, writer, "attribute_id");
                writer.writeAttribute("id", UUID.randomUUID().toString());
                writer.writeAttribute("attribute_id",
                        cPlainAttrs.get(getAttributeValue(reader, "attribute_id")));
                writer.writeEndElement();
                break;

            case "uschema":
                writer.writeStartElement("SyncopeSchema");
                writer.writeAttribute("id", getAttributeValue(reader, "name"));

                writer.writeStartElement("PlainSchema");
                copyAttrs(reader, writer);
                writer.writeAttribute("id", getAttributeValue(reader, "name"));
                writer.writeAttribute("anyTypeClass_id", "BaseUser");
                writer.writeEndElement();
                break;

            case "uderschema":
                writer.writeStartElement("SyncopeSchema");
                writer.writeAttribute("id", getAttributeValue(reader, "name"));

                writer.writeStartElement("DerSchema");
                copyAttrs(reader, writer);
                writer.writeAttribute("id", getAttributeValue(reader, "name"));
                writer.writeAttribute("anyTypeClass_id", "BaseUser");
                writer.writeEndElement();
                break;

            case "uvirschema":
                reporter.writeStartElement("VirSchema");
                copyAttrs(reader, reporter);
                reporter.writeAttribute("key", getAttributeValue(reader, "name"));
                reporter.writeEndElement();
                break;

            case "rschema":
                writer.writeStartElement("SyncopeSchema");
                writer.writeAttribute("id", getAttributeValue(reader, "name"));

                writer.writeStartElement("PlainSchema");
                copyAttrs(reader, writer);
                writer.writeAttribute("id", getAttributeValue(reader, "name"));
                writer.writeAttribute("anyTypeClass_id", "BaseGroup");
                writer.writeEndElement();
                break;

            case "rderschema":
                writer.writeStartElement("SyncopeSchema");
                writer.writeAttribute("id", getAttributeValue(reader, "name"));

                writer.writeStartElement("DerSchema");
                copyAttrs(reader, writer);
                writer.writeAttribute("id", getAttributeValue(reader, "name"));
                writer.writeAttribute("anyTypeClass_id", "BaseGroup");
                writer.writeEndElement();
                break;

            case "rvirschema":
                reporter.writeStartElement("VirSchema");
                reporter.writeAttribute("key", getAttributeValue(reader, "name"));
                copyAttrs(reader, reporter);
                reporter.writeEndElement();
                break;

            case "mschema":
                writer.writeStartElement("SyncopeSchema");
                writer.writeAttribute("id", getAttributeValue(reader, "name"));

                writer.writeStartElement("PlainSchema");
                copyAttrs(reader, writer);
                writer.writeAttribute("id", getAttributeValue(reader, "name"));
                writer.writeAttribute("anyTypeClass_id", "BaseUMembership");
                writer.writeEndElement();
                break;

            case "mderschema":
                writer.writeStartElement("SyncopeSchema");
                writer.writeAttribute("id", getAttributeValue(reader, "name"));

                writer.writeStartElement("DerSchema");
                copyAttrs(reader, writer);
                writer.writeAttribute("id", getAttributeValue(reader, "name"));
                writer.writeAttribute("anyTypeClass_id", "BaseUMembership");
                writer.writeEndElement();
                break;

            case "mvirschema":
                reporter.writeStartElement("VirSchema");
                copyAttrs(reader, reporter);
                reporter.writeAttribute("key", getAttributeValue(reader, "name"));
                reporter.writeEndElement();
                break;

            case "policy":
                String policyId = getAttributeValue(reader, "id");
                lastUUID = UUID.randomUUID().toString();
                policies.put(policyId, lastUUID);

                ObjectNode specification = (ObjectNode) OBJECT_MAPPER
                        .readTree(getAttributeValue(reader, "specification"));

                switch (getAttributeValue(reader, "DTYPE")) {
                case "SyncPolicy":
                    writer.writeStartElement("PullPolicy");
                    writer.writeAttribute("id", lastUUID);
                    writer.writeAttribute("description", getAttributeValue(reader, "description"));
                    writer.writeEndElement();
                    break;

                case "PasswordPolicy":
                    writer.writeStartElement("PasswordPolicy");
                    writer.writeAttribute("id", lastUUID);
                    writer.writeAttribute("description", getAttributeValue(reader, "description"));

                    if ("GLOBAL_PASSWORD".equalsIgnoreCase(getAttributeValue(reader, "type"))) {
                        globalPasswordPolicy = lastUUID;
                    }

                    JsonNode allowNullPassword = specification.get("allowNullPassword");
                    if (allowNullPassword != null) {
                        writer.writeAttribute("allowNullPassword", allowNullPassword.asBoolean() ? "1" : "0");
                        specification.remove("allowNullPassword");
                    }
                    JsonNode historyLength = specification.get("historyLength");
                    if (historyLength != null) {
                        writer.writeAttribute("historyLength", historyLength.asText());
                        specification.remove("historyLength");
                    }
                    specification.put("@class", "org.apache.syncope.common.lib.policy.DefaultPasswordRuleConf");
                    writer.writeEndElement();

                    writer.writeStartElement("PasswordRuleConfInstance");
                    writer.writeAttribute("id", lastUUID);
                    writer.writeAttribute("passwordPolicy_id", lastUUID);
                    writer.writeAttribute("serializedInstance", specification.toString());
                    writer.writeEndElement();
                    break;

                case "AccountPolicy":
                    writer.writeStartElement("AccountPolicy");
                    writer.writeAttribute("id", lastUUID);
                    writer.writeAttribute("description", getAttributeValue(reader, "description"));

                    if ("GLOBAL_ACCOUNT".equalsIgnoreCase(getAttributeValue(reader, "type"))) {
                        globalAccountPolicy = lastUUID;
                    }

                    JsonNode propagateSuspension = specification.get("propagateSuspension");
                    if (propagateSuspension != null) {
                        writer.writeAttribute("propagateSuspension",
                                propagateSuspension.asBoolean() ? "1" : "0");
                        specification.remove("propagateSuspension");
                    }
                    JsonNode permittedLoginRetries = specification.get("permittedLoginRetries");
                    if (permittedLoginRetries != null) {
                        writer.writeAttribute("maxAuthenticationAttempts", permittedLoginRetries.asText());
                        specification.remove("permittedLoginRetries");
                    }
                    specification.put("@class", "org.apache.syncope.common.lib.policy.DefaultAccountRuleConf");
                    writer.writeEndElement();

                    writer.writeStartElement("AccountRuleConfInstance");
                    writer.writeAttribute("id", lastUUID);
                    writer.writeAttribute("accountPolicy_id", lastUUID);
                    writer.writeAttribute("serializedInstance", specification.toString());
                    writer.writeEndElement();
                    break;

                default:
                }
                break;

            case "conninstance":
                lastUUID = UUID.randomUUID().toString();
                connInstances.put(getAttributeValue(reader, "id"), lastUUID);

                writer.writeStartElement("ConnInstance");
                copyAttrs(reader, writer);
                writer.writeAttribute("id", lastUUID);
                writer.writeEndElement();
                break;

            case "conninstance_capabilities":
                String connInstanceId = getAttributeValue(reader, "connInstance_id");
                String connInstanceKey = connInstances.get(connInstanceId);

                String capabilities = getAttributeValue(reader, "capabilities");
                if (capabilities.startsWith("ONE_PHASE_")) {
                    capabilities = capabilities.substring(10);
                } else if (capabilities.startsWith("TWO_PHASES_")) {
                    capabilities = capabilities.substring(11);
                }
                if (!connInstanceCapabilities.contains(connInstanceId + capabilities)) {
                    writer.writeStartElement("ConnInstance_capabilities");
                    writer.writeAttribute("connInstance_id", connInstanceKey);
                    writer.writeAttribute("capability", capabilities);
                    writer.writeEndElement();

                    connInstanceCapabilities.add(connInstanceId + capabilities);
                }
                break;

            case "externalresource":
                writer.writeStartElement("ExternalResource");
                copyAttrs(reader, writer, "syncTraceLevel", "userializedSyncToken", "rserializedSyncToken",
                        "propagationMode", "propagationPrimary", "connector_id", "syncPolicy_id",
                        "passwordPolicy_id", "creator", "lastModifier", "creationDate", "lastChangeDate");

                writer.writeAttribute("id", getAttributeValue(reader, "name"));
                writer.writeAttribute("connector_id",
                        connInstances.get(getAttributeValue(reader, "connector_id")));

                writer.writeAttribute("provisioningTraceLevel", getAttributeValue(reader, "syncTraceLevel"));

                String syncPolicyKey = policies.get(getAttributeValue(reader, "syncPolicy_id"));
                if (StringUtils.isNotBlank(syncPolicyKey)) {
                    writer.writeAttribute("pullPolicy_id", syncPolicyKey);
                }

                String passwordPolicyKey = policies.get(getAttributeValue(reader, "passwordPolicy_id"));
                if (StringUtils.isNotBlank(passwordPolicyKey)) {
                    writer.writeAttribute("passwordPolicy_id", passwordPolicyKey);
                }

                writer.writeEndElement();
                break;

            case "externalresource_propactions":
                writer.writeStartElement("ExternalResource_PropActions");

                writer.writeAttribute("resource_id", getAttributeValue(reader, "externalResource_name"));

                String propActionClassName = getAttributeValue(reader, "element");
                switch (propActionClassName) {
                case "org.apache.syncope.core.propagation.impl.LDAPMembershipPropagationActions":
                    propActionClassName = "org.apache.syncope.core.provisioning.java.propagation."
                            + "LDAPMembershipPropagationActions";
                    break;

                case "org.apache.syncope.core.propagation.impl.LDAPPasswordPropagationActions":
                    propActionClassName = "org.apache.syncope.core.provisioning.java.propagation."
                            + "LDAPPasswordPropagationActions";
                    break;

                case "org.apache.syncope.core.propagation.impl.DBPasswordPropagationActions":
                    propActionClassName = "org.apache.syncope.core.provisioning.java.propagation."
                            + "DBPasswordPropagationActions";
                    break;

                default:
                }
                writer.writeAttribute("actionClassName", propActionClassName);
                writer.writeEndElement();
                break;

            case "policy_externalresource":
                writer.writeStartElement("AccountPolicy_ExternalResource");
                writer.writeAttribute("accountPolicy_id",
                        policies.get(getAttributeValue(reader, "account_policy_id")));
                writer.writeAttribute("resource_id", getAttributeValue(reader, "resource_name"));
                writer.writeEndElement();
                break;

            case "umapping":
                String umappingId = getAttributeValue(reader, "id");
                lastUUID = UUID.randomUUID().toString();
                provisions.put(umappingId, lastUUID);

                writer.writeStartElement("Provision");
                writer.writeAttribute("id", lastUUID);
                writer.writeAttribute("resource_id", getAttributeValue(reader, "resource_name"));
                writer.writeAttribute("anyType_id", "USER");
                writer.writeAttribute("objectClass", "__ACCOUNT__");
                writer.writeEndElement();

                lastUUID = UUID.randomUUID().toString();
                mappings.put(umappingId, lastUUID);

                writer.writeStartElement("Mapping");
                writer.writeAttribute("id", lastUUID);
                writer.writeAttribute("provision_id", provisions.get(umappingId));

                String uaccountLink = getAttributeValue(reader, "accountlink");
                if (StringUtils.isNotBlank(uaccountLink)) {
                    writer.writeAttribute("connObjectLink", uaccountLink);
                }
                writer.writeEndElement();
                break;

            case "umappingitem":
                String uIntMappingType = getAttributeValue(reader, "intMappingType");
                if (uIntMappingType.endsWith("VirtualSchema")) {
                    reporter.writeStartElement("MappingItem");
                    copyAttrs(reader, reporter, "accountid", "intMappingType");
                    reporter.writeEndElement();
                } else {
                    writer.writeStartElement("MappingItem");
                    copyAttrs(reader, writer, "accountid", "intMappingType", "mapping_id", "intMappingType",
                            "intAttrName");
                    writer.writeAttribute("id", UUID.randomUUID().toString());
                    writer.writeAttribute("mapping_id", mappings.get(getAttributeValue(reader, "mapping_id")));
                    writer.writeAttribute("connObjectKey", getAttributeValue(reader, "accountid"));

                    writeIntAttrName(uIntMappingType, "intAttrName",
                            mappings.get(getAttributeValue(reader, "intAttrName")), writer);

                    writer.writeEndElement();
                }
                break;

            case "rmapping":
                String rmappingId = "10" + getAttributeValue(reader, "id");
                lastUUID = UUID.randomUUID().toString();
                provisions.put(rmappingId, lastUUID);

                writer.writeStartElement("Provision");
                writer.writeAttribute("id", lastUUID);
                writer.writeAttribute("resource_id", getAttributeValue(reader, "resource_name"));
                writer.writeAttribute("anyType_id", "GROUP");
                writer.writeAttribute("objectClass", "__GROUP__");
                writer.writeEndElement();

                lastUUID = UUID.randomUUID().toString();
                mappings.put(rmappingId, lastUUID);

                writer.writeStartElement("Mapping");
                writer.writeAttribute("id", lastUUID);
                writer.writeAttribute("provision_id", provisions.get(rmappingId));

                String raccountLink = getAttributeValue(reader, "accountlink");
                if (StringUtils.isNotBlank(raccountLink)) {
                    writer.writeAttribute("connObjectLink", raccountLink);
                }
                writer.writeEndElement();
                break;

            case "rmappingitem":
                String rIntMappingType = getAttributeValue(reader, "intMappingType");
                if (rIntMappingType.endsWith("VirtualSchema")) {
                    reporter.writeStartElement("MappingItem");
                    copyAttrs(reader, reporter, "accountid", "intMappingType");
                    reporter.writeEndElement();
                } else {
                    writer.writeStartElement("MappingItem");
                    copyAttrs(reader, writer, "accountid", "intMappingType", "mapping_id", "intAttrName");
                    writer.writeAttribute("id", UUID.randomUUID().toString());
                    writer.writeAttribute("mapping_id",
                            mappings.get("10" + getAttributeValue(reader, "mapping_id")));
                    writer.writeAttribute("connObjectKey", getAttributeValue(reader, "accountid"));

                    writeIntAttrName(rIntMappingType, "intAttrName",
                            mappings.get(getAttributeValue(reader, "intAttrName")), writer);

                    writer.writeEndElement();
                }
                break;

            case "task":
                writer.writeStartElement("Task");
                copyAttrs(reader, writer, "DTYPE", "propagationMode", "subjectType", "subjectId",
                        "xmlAttributes", "jobClassName", "userTemplate", "roleTemplate", "userFilter",
                        "roleFilter", "propagationOperation", "syncStatus", "fullReconciliation",
                        "resource_name");

                lastUUID = UUID.randomUUID().toString();
                tasks.put(getAttributeValue(reader, "id"), lastUUID);

                writer.writeAttribute("id", lastUUID);

                String resourceName = getAttributeValue(reader, "resource_name");
                if (StringUtils.isNotBlank(resourceName)) {
                    writer.writeAttribute("resource_id", resourceName);
                }

                String name = getAttributeValue(reader, "name");
                if (StringUtils.isNotBlank(name)) {
                    writer.writeAttribute("name", name);
                }

                switch (getAttributeValue(reader, "DTYPE")) {
                case "PropagationTask":
                    writer.writeAttribute("DTYPE", "PropagationTask");
                    writer.writeAttribute("anyTypeKind", getAttributeValue(reader, "subjectType"));
                    writer.writeAttribute("anyKey", getAttributeValue(reader, "subjectId"));
                    writer.writeAttribute("attributes", getAttributeValue(reader, "xmlAttributes"));
                    writer.writeAttribute("operation", getAttributeValue(reader, "propagationOperation"));
                    writer.writeEndElement();
                    break;

                case "SyncTask":
                    writer.writeAttribute("DTYPE", "PullTask");
                    writer.writeAttribute("syncStatus", getAttributeValue(reader, "syncStatus"));

                    String fullReconciliation = getAttributeValue(reader, "fullReconciliation");
                    if ("1".equals(fullReconciliation)) {
                        writer.writeAttribute("pullMode", "FULL_RECONCILIATION");
                    } else if ("0".equals(fullReconciliation)) {
                        writer.writeAttribute("pullMode", "INCREMENTAL");
                    }

                    writer.writeEndElement();

                    String userTemplate = getAttributeValue(reader, "userTemplate");
                    if (StringUtils.isNotBlank(userTemplate)) {
                        ObjectNode template = (ObjectNode) OBJECT_MAPPER.readTree(userTemplate);
                        JsonNode plainAttrs = template.remove("attrs");
                        template.set("plainAttrs", plainAttrs);

                        writer.writeStartElement("AnyTemplatePullTask");
                        writer.writeAttribute("id", UUID.randomUUID().toString());
                        writer.writeAttribute("pullTask_id", lastUUID);
                        writer.writeAttribute("anyType_id", "USER");
                        writer.writeAttribute("template", template.toString());
                        writer.writeEndElement();
                    }
                    String roleTemplate = getAttributeValue(reader, "roleTemplate");
                    if (StringUtils.isNotBlank(roleTemplate)) {
                        ObjectNode template = (ObjectNode) OBJECT_MAPPER.readTree(roleTemplate);
                        JsonNode plainAttrs = template.remove("attrs");
                        template.set("plainAttrs", plainAttrs);

                        writer.writeStartElement("AnyTemplatePullTask");
                        writer.writeAttribute("id", UUID.randomUUID().toString());
                        writer.writeAttribute("pullTask_id", lastUUID);
                        writer.writeAttribute("anyType_id", "GROUP");
                        writer.writeAttribute("template", template.toString());
                        writer.writeEndElement();
                    }
                    break;

                case "SchedTask":
                    writer.writeAttribute("DTYPE", "SchedTask");
                    writer.writeAttribute("jobDelegateClassName", getAttributeValue(reader, "jobClassName"));
                    writer.writeEndElement();
                    break;

                case "NotificationTask":
                    writer.writeAttribute("DTYPE", "NotificationTask");
                    writer.writeEndElement();
                    break;

                case "PushTask":
                    writer.writeAttribute("DTYPE", "PushTask");
                    writer.writeEndElement();

                    String userFilter = getAttributeValue(reader, "userFilter");
                    if (StringUtils.isNotBlank(userFilter)) {
                        writer.writeStartElement("PushTaskAnyFilter");
                        writer.writeAttribute("id", UUID.randomUUID().toString());
                        writer.writeAttribute("pushTask_id", lastUUID);
                        writer.writeAttribute("anyType_id", "USER");
                        writer.writeAttribute("fiql", userFilter);
                        writer.writeEndElement();
                    }
                    String roleFilter = getAttributeValue(reader, "roleFilter");
                    if (StringUtils.isNotBlank(roleFilter)) {
                        writer.writeStartElement("PushTaskAnyFilter");
                        writer.writeAttribute("id", UUID.randomUUID().toString());
                        writer.writeAttribute("pushTask_id", lastUUID);
                        writer.writeAttribute("anyType_id", "GROUP");
                        writer.writeAttribute("fiql", roleFilter);
                        writer.writeEndElement();
                    }
                    break;

                default:
                }
                break;

            case "taskexec":
                writer.writeStartElement("TaskExec");
                copyAttrs(reader, writer, "task_id");
                writer.writeAttribute("id", UUID.randomUUID().toString());
                writer.writeAttribute("task_id", tasks.get(getAttributeValue(reader, "task_id")));
                writer.writeEndElement();
                break;

            case "synctask_actionsclassnames":
                writer.writeStartElement("PullTask_actionsClassNames");
                writer.writeAttribute("pullTask_id", tasks.get(getAttributeValue(reader, "syncTask_id")));

                String syncActionClassName = getAttributeValue(reader, "element");
                switch (syncActionClassName) {
                case "org.apache.syncope.core.sync.impl.LDAPMembershipSyncActions":
                    syncActionClassName = "org.apache.syncope.core.provisioning.java.pushpull.LDAPMembershipPullActions";
                    break;

                case "org.apache.syncope.core.sync.impl.LDAPPasswordSyncActions":
                    syncActionClassName = "org.apache.syncope.core.provisioning.java.pushpull.LDAPPasswordPullActions";
                    break;

                case "org.apache.syncope.core.sync.impl.DBPasswordSyncActions":
                    syncActionClassName = "org.apache.syncope.core.provisioning.java.pushpull.DBPasswordPullActions";
                    break;

                default:
                }
                writer.writeAttribute("actionClassName", syncActionClassName);
                writer.writeEndElement();
                break;

            case "notification":
                writer.writeStartElement("Notification");

                lastUUID = UUID.randomUUID().toString();
                notifications.put(getAttributeValue(reader, "id"), lastUUID);

                writer.writeAttribute("id", lastUUID);

                copyAttrs(reader, writer, "recipientAttrType", "template", "userAbout", "roleAbout",
                        "recipients", "recipientAttrName");

                String recipientAttrType = getAttributeValue(reader, "recipientAttrType");
                writeIntAttrName(recipientAttrType, "recipientAttrName",
                        mappings.get(getAttributeValue(reader, "recipientAttrName")), writer);

                String recipients = getAttributeValue(reader, "recipients");
                if (StringUtils.isNotBlank(recipients)) {
                    writer.writeAttribute("recipientsFIQL", getAttributeValue(reader, "recipients"));
                }
                writer.writeAttribute("template_id", getAttributeValue(reader, "template"));
                writer.writeEndElement();

                String userAbout = getAttributeValue(reader, "userAbout");
                if (StringUtils.isNotBlank(userAbout)) {
                    writer.writeStartElement("AnyAbout");
                    writer.writeAttribute("id", UUID.randomUUID().toString());
                    writer.writeAttribute("notification_id", lastUUID);
                    writer.writeAttribute("anyType_id", "USER");
                    writer.writeAttribute("filter", userAbout);
                    writer.writeEndElement();
                }
                String roleAbout = getAttributeValue(reader, "roleAbout");
                if (StringUtils.isNotBlank(roleAbout)) {
                    writer.writeStartElement("AnyAbout");
                    writer.writeAttribute("id", UUID.randomUUID().toString());
                    writer.writeAttribute("notification_id", lastUUID);
                    writer.writeAttribute("anyType_id", "GROUP");
                    writer.writeAttribute("filter", roleAbout);
                    writer.writeEndElement();
                }
                break;

            case "notification_events":
                writer.writeStartElement("Notification_events");
                copyAttrs(reader, writer, "notification_id", "events");
                writer.writeAttribute("notification_id",
                        notifications.get(getAttributeValue(reader, "notification_id")));
                writer.writeAttribute("event",
                        getAttributeValue(reader, "events").replaceAll("Controller", "Logic"));
                writer.writeEndElement();
                break;

            case "notificationtask_recipients":
                writer.writeStartElement("NotificationTask_recipients");
                copyAttrs(reader, writer, "notificationTask_id");
                writer.writeAttribute("notificationTask_id",
                        tasks.get(getAttributeValue(reader, "notificationTask_id")));
                writer.writeEndElement();
                break;

            case "report":
                writer.writeStartElement("Report");
                copyAttrs(reader, writer);

                lastUUID = UUID.randomUUID().toString();
                reports.put(getAttributeValue(reader, "id"), lastUUID);

                writer.writeAttribute("id", lastUUID);
                writer.writeAttribute("name", getAttributeValue(reader, "name"));

                writer.writeEndElement();
                break;

            case "reportletconfinstance":
                writer.writeStartElement("ReportletConfInstance");
                copyAttrs(reader, writer, "report_id");

                writer.writeAttribute("id", UUID.randomUUID().toString());
                writer.writeAttribute("report_id", reports.get(getAttributeValue(reader, "report_id")));

                writer.writeEndElement();
                break;

            case "reportexec":
                writer.writeStartElement("ReportExec");
                copyAttrs(reader, writer, "report_id");

                writer.writeAttribute("id", UUID.randomUUID().toString());
                writer.writeAttribute("report_id", reports.get(getAttributeValue(reader, "report_id")));

                writer.writeEndElement();
                break;

            case "securityquestion":
                writer.writeStartElement("SecurityQuestion");
                copyAttrs(reader, writer);
                writer.writeAttribute("id", UUID.randomUUID().toString());
                writer.writeEndElement();
                break;

            default:
            }
        }

        reader.next();
    }

    writer.writeStartElement("Realm");
    writer.writeAttribute("id", UUID.randomUUID().toString());
    writer.writeAttribute("name", "/");
    if (globalAccountPolicy != null) {
        writer.writeAttribute("accountPolicy_id", globalAccountPolicy);
    }
    if (globalPasswordPolicy != null) {
        writer.writeAttribute("passwordPolicy_id", globalPasswordPolicy);
    }
    writer.writeEndElement();

    writer.writeEndElement();
    writer.writeEndDocument();
    writer.close();

    reporter.writeEndElement();
    reporter.writeEndDocument();
    reporter.close();
    System.out.println("\nVirtual items, require manual intervention:\n" + reporterSW.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;/*  ww w  . jav a 2s.  com*/
    }

    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()}.
 * //from www . ja  v  a 2  s . com
 * @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 w w  w. java  2  s .  com*/
 * @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()}.
 * /*from w  ww .  j a v a  2  s  .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);/*w w w .j  a  v a2 s. 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.commons.xml.stax.FilteringXMLStreamWriterTest.java

private void writeDocument(XMLStreamWriter writer) throws XMLStreamException {
    writer.writeStartDocument();// w  w  w.j  av  a  2  s  .com
    writer.setPrefix("app", app);
    writer.setPrefix("nix", nix);
    writer.setPrefix("alles", alles);
    writer.writeStartElement(app, "a");
    writer.writeNamespace("app", app);
    writer.writeNamespace("nix", nix);
    writer.writeNamespace("alles", alles);
    writer.writeStartElement(app, "b");
    writer.writeStartElement(nix, "c");
    writer.writeStartElement(app, "d");
    writer.writeEndElement();
    writer.writeStartElement(alles, "e");
    writer.writeCharacters("sometext");
    writer.writeEndElement();
    writer.writeStartElement(app, "b");
    writer.writeStartElement(nix, "c");
    writer.writeEndElement();
    writer.writeEndElement();
    writer.writeEndElement();
    writer.writeEndElement();
    writer.writeEndElement();
    writer.close();
}

From source file:org.deegree.commons.xml.stax.FilteringXMLStreamWriterTest.java

@Test
public void testFilteringXPathSetPrefixBug() throws Exception {
    final XMLAdapter input = new XMLAdapter(
            FilteringXMLStreamWriterTest.class.getResourceAsStream("filtering_xpath_set_prefix.xml"));
    final List<String> list = new ArrayList<String>();
    list.add("/app:a/nix:d");
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLStreamWriter writer = getWriter(list, bos);
    input.getRootElement().serialize(writer);
    writer.close();
    byte[] actual = bos.toByteArray();
    byte[] expected = IOUtils.toByteArray(
            FilteringXMLStreamWriterTest.class.getResourceAsStream("filtering_xpath_set_prefix_expected.xml"));
    Assert.assertArrayEquals(expected, actual);
}

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

public String generateConfig() {

    try {//from   ww w .  j ava2  s . co 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";
    }
}