Example usage for javax.xml.stream XMLStreamWriter writeStartDocument

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

Introduction

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

Prototype

public void writeStartDocument(String encoding, String version) throws XMLStreamException;

Source Link

Document

Write the XML Declaration.

Usage

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);/*ww  w .  j ava 2  s .co 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.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 w w .  j av  a2 s .co 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.protocol.wps.client.wps100.ExecuteResponse100Reader.java

/**
 * <ul>//w ww.  j  a  v a 2s. c om
 * <li>Precondition: cursor must point at the <code>START_ELEMENT</code> event (&lt;wps:ComplexData&gt;)</li>
 * <li>Postcondition: cursor points at the corresponding <code>END_ELEMENT</code> event (&lt;/wps:ComplexData&gt;)</li>
 * </ul>
 * 
 * @return
 * @throws XMLStreamException
 * @throws IOException
 */
private ExecutionOutput parseComplexOutput(CodeType id) throws XMLStreamException {

    ComplexFormat attribs = parseComplexAttributes();

    StreamBufferStore tmpSink = new StreamBufferStore();
    try {
        if (attribs.getMimeType().startsWith("text/xml")
                || attribs.getMimeType().startsWith("application/xml")) {
            XMLOutputFactory fac = XMLOutputFactory.newInstance();
            fac.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
            XMLStreamWriter xmlWriter = fac.createXMLStreamWriter(tmpSink, "UTF-8");

            XMLStreamUtils.nextElement(reader);

            xmlWriter.writeStartDocument("UTF-8", "1.0");
            if (reader.getEventType() == START_ELEMENT) {
                XMLAdapter.writeElement(xmlWriter, reader);
                XMLStreamUtils.nextElement(reader);
            } else {
                LOG.debug("Response document contains empty complex data output '" + id + "'");
            }
            xmlWriter.writeEndDocument();
            xmlWriter.close();

        } else {
            if ("base64".equals(attribs.getEncoding())) {
                String base64String = reader.getElementText();
                byte[] bytes = Base64.decodeBase64(base64String);
                tmpSink.write(bytes);
            } else {
                LOG.warn("The encoding of binary data (found at response location " + reader.getLocation()
                        + ") is not base64. Currently only for this format the decoding can be performed. Skipping the data.");
            }
        }
        tmpSink.close();
    } catch (IOException e) {
        LOG.error(e.getMessage());
    }
    return new ComplexOutput(id, tmpSink, attribs.getMimeType(), attribs.getEncoding(), attribs.getEncoding());
}

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

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

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

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

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

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

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

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

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

From source file:org.eclipse.koneki.protocols.omadm.client.basic.DMBasicSession.java

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

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

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

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

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

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

From source file:org.eclipse.smila.datamodel.tools.DatamodelSerializationUtils.java

/**
 * Serialize2string./*from   w w w.  j  av  a2s.  com*/
 * 
 * @param id
 *          the id
 * 
 * @return the string
 */
public static String serialize2string(final Id id) {
    if (id == null) {
        return null;
    }
    try {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        XMLStreamWriter writer = null;
        try {
            writer = getStaxWriterFactory().createXMLStreamWriter(out, "utf-8");
            writer.writeStartDocument("utf-8", "1.1");
            getIdWriter().writeId(writer, id);
            writer.writeEndDocument();
            return out.toString("utf-8");
        } catch (final Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (final XMLStreamException e) {
                    ; // nothing to do
                }
            } // if
            if (out != null) {
                IOUtils.closeQuietly(out);
            }
        } // finally
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.smila.datamodel.tools.DatamodelSerializationUtils.java

/**
 * Serializes a Record into a ByteArrayOutputStream. It does NOT serialize Attachment values, only their names !
 * /*  w  ww.  j ava 2 s.  c  o m*/
 * @param record
 *          the record
 * @return the ByteArrayOutputStream
 */
public static ByteArrayOutputStream serialize2stream(final Record record) {
    if (record == null) {
        return null;
    }

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    XMLStreamWriter writer = null;
    try {
        writer = getStaxWriterFactory().createXMLStreamWriter(out, "utf-8");
        writer.writeStartDocument("utf-8", "1.1");
        getRecordWriter().writeRecord(writer, record);
        writer.writeEndDocument();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    } catch (final Throwable t) {
        throw new RuntimeException(t);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (final XMLStreamException e) {
                ; // nothing to do
            }
        } // if
        if (out != null) {
            IOUtils.closeQuietly(out);
        }
    } // finally
    return out;
}

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

protected File createSingleMetadata(String groupId, String artifactId, String version)
        throws FileNotFoundException {
    File temp = null;/*from  w w  w  .  j  a  va2s. c o m*/
    try {
        String filename = getUniqueFilename("maven-metadata.xml");
        temp = File.createTempFile(filename, null);

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

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

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

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

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

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

protected File createMultiMetadata(String groupId, String artifactId, String current_version,
        List<String> v_list) throws FileNotFoundException {
    File temp = null;/*from   ww  w .  ja v a2  s .  co m*/
    try {
        String filename = getUniqueFilename("maven-metadata.xml");
        temp = File.createTempFile(filename, null);

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

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

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

            String elderVersion;
            if (v_list.size() > 0) {
                Collections.sort(v_list); // sort list
                elderVersion = v_list.get(0); // get first element
            } else
                elderVersion = current_version;
            v_list.add(current_version);

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

            writer.writeStartElement("versions");
            writer.writeStartElement("versioning");

            for (Iterator<String> iterator = v_list.iterator(); iterator.hasNext();) {
                writer.writeStartElement("version");
                writer.writeCharacters(iterator.next());
                writer.writeEndElement();
            }

            writer.writeEndElement();
            writer.writeEndElement();

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

From source file:org.flowable.bpmn.converter.export.DefinitionsRootExport.java

@SuppressWarnings("unchecked")
public static void writeRootElement(BpmnModel model, XMLStreamWriter xtw, String encoding) throws Exception {
    xtw.writeStartDocument(encoding, "1.0");

    // start definitions root element
    xtw.writeStartElement(ELEMENT_DEFINITIONS);
    xtw.setDefaultNamespace(BPMN2_NAMESPACE);
    xtw.writeDefaultNamespace(BPMN2_NAMESPACE);
    xtw.writeNamespace(XSI_PREFIX, XSI_NAMESPACE);
    xtw.writeNamespace(XSD_PREFIX, SCHEMA_NAMESPACE);
    xtw.writeNamespace(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE);
    xtw.writeNamespace(BPMNDI_PREFIX, BPMNDI_NAMESPACE);
    xtw.writeNamespace(OMGDC_PREFIX, OMGDC_NAMESPACE);
    xtw.writeNamespace(OMGDI_PREFIX, OMGDI_NAMESPACE);
    for (String prefix : model.getNamespaces().keySet()) {
        if (!defaultNamespaces.contains(prefix) && StringUtils.isNotEmpty(prefix))
            xtw.writeNamespace(prefix, model.getNamespaces().get(prefix));
    }/*from   w  w w.  j a  va2 s  .c  om*/
    xtw.writeAttribute(TYPE_LANGUAGE_ATTRIBUTE, SCHEMA_NAMESPACE);
    xtw.writeAttribute(EXPRESSION_LANGUAGE_ATTRIBUTE, XPATH_NAMESPACE);
    if (StringUtils.isNotEmpty(model.getTargetNamespace())) {
        xtw.writeAttribute(TARGET_NAMESPACE_ATTRIBUTE, model.getTargetNamespace());
    } else {
        xtw.writeAttribute(TARGET_NAMESPACE_ATTRIBUTE, PROCESS_NAMESPACE);
    }

    BpmnXMLUtil.writeCustomAttributes(model.getDefinitionsAttributes().values(), xtw, model.getNamespaces(),
            defaultAttributes);
}