Example usage for org.xml.sax.helpers AttributesImpl addAttribute

List of usage examples for org.xml.sax.helpers AttributesImpl addAttribute

Introduction

In this page you can find the example usage for org.xml.sax.helpers AttributesImpl addAttribute.

Prototype

public void addAttribute(String uri, String localName, String qName, String type, String value) 

Source Link

Document

Add an attribute to the end of the list.

Usage

From source file:org.apache.syncope.core.util.ImportExport.java

private void doExportTable(final TransformerHandler handler, final Connection conn, final String tableName)
        throws SQLException, SAXException {

    AttributesImpl attrs = new AttributesImpl();

    PreparedStatement stmt = null;
    ResultSet rs = null;//from  ww  w.  ja v  a2 s. c  o m
    ResultSet pkeyRS = null;

    try {
        // ------------------------------------
        // retrieve primary keys to perform an ordered select

        final DatabaseMetaData meta = conn.getMetaData();
        pkeyRS = meta.getPrimaryKeys(null, null, tableName);

        final StringBuilder orderBy = new StringBuilder();

        while (pkeyRS.next()) {
            final String columnName = pkeyRS.getString("COLUMN_NAME");

            if (columnName != null) {
                if (orderBy.length() > 0) {
                    orderBy.append(",");
                }

                orderBy.append(columnName);
            }
        }

        // ------------------------------------
        stmt = conn.prepareStatement(
                "SELECT * FROM " + tableName + " a" + (orderBy.length() > 0 ? " ORDER BY " + orderBy : ""));

        rs = stmt.executeQuery();
        for (int rowNo = 0; rs.next(); rowNo++) {
            attrs.clear();

            final ResultSetMetaData rsMeta = rs.getMetaData();

            for (int i = 0; i < rsMeta.getColumnCount(); i++) {
                final String columnName = rsMeta.getColumnName(i + 1);
                final Integer columnType = rsMeta.getColumnType(i + 1);

                // Retrieve value taking care of binary values.
                String value = getValues(rs, columnName, columnType);

                if (value != null) {
                    attrs.addAttribute("", "", columnName, "CDATA", value);
                }
            }

            handler.startElement("", "", tableName, attrs);
            handler.endElement("", "", tableName);
        }
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
        if (pkeyRS != null) {
            try {
                pkeyRS.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
    }
}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandler.java

/**
 * Processes a {@code <field-map-ref>} element.
 *
 * @param attrs/* ww  w.  ja v a 2  s.  c o m*/
 *            List of element attributes
 *
 * @throws SAXException
 *             if error occurs parsing element
 */
@SuppressWarnings("unchecked")
private void processFieldMapReference(Attributes attrs) throws SAXException {
    if (currField == null) {
        throw new SAXParseException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                "ConfigParserHandler.malformed.configuration3", FIELD_MAP_REF_ELMT, FIELD_ELMT, FIELD_LOC_ELMT),
                currParseLocation);
    }

    if (CollectionUtils.isEmpty(currField.getLocators()) && currLocatorData == null) {
        throw new SAXException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                "ConfigParserHandler.element.no.binding", FIELD_MAP_REF_ELMT, FIELD_LOC_ELMT,
                getLocationInfo()));
    }

    String reference = null;
    for (int i = 0; i < attrs.getLength(); i++) {
        String attName = attrs.getQName(i);
        String attValue = attrs.getValue(i);
        if (RESOURCE_ATTR.equals(attName)) {
            reference = attValue;
        }
    }

    notEmpty(reference, FIELD_MAP_REF_ELMT, RESOURCE_ATTR);

    Object val = Utils.getMapValueByPath(reference, resourcesMap);

    if (val instanceof Map) {
        AttributesImpl mappingAttrs = new AttributesImpl();
        for (Map.Entry<String, ?> entry : ((Map<String, ?>) val).entrySet()) {
            mappingAttrs.clear();
            mappingAttrs.addAttribute(null, null, SOURCE_ATTR, null, entry.getKey());
            mappingAttrs.addAttribute(null, null, TARGET_ATTR, null, String.valueOf(entry.getValue()));

            processFieldMap(mappingAttrs);
        }
    }
}

From source file:org.syncope.core.report.UserReportlet.java

private void doExtract(final ContentHandler handler, final UserReportletConf conf,
        final List<SyncopeUser> users) throws SAXException, ReportException {

    AttributesImpl atts = new AttributesImpl();
    for (SyncopeUser user : users) {
        atts.clear();/*  w ww.  j av a 2s  .  c  om*/

        for (Feature feature : conf.getFeatures()) {
            String type = null;
            String value = null;
            switch (feature) {
            case id:
                type = XSD_LONG;
                value = String.valueOf(user.getId());
                break;

            case username:
                type = XSD_STRING;
                value = user.getUsername();
                break;

            case workflowId:
                type = XSD_LONG;
                value = String.valueOf(user.getWorkflowId());
                break;

            case status:
                type = XSD_STRING;
                value = user.getStatus();
                break;

            case creationDate:
                type = XSD_DATETIME;
                value = user.getCreationDate() == null ? "" : DATE_FORMAT.get().format(user.getCreationDate());
                break;

            case lastLoginDate:
                type = XSD_DATETIME;
                value = user.getLastLoginDate() == null ? ""
                        : DATE_FORMAT.get().format(user.getLastLoginDate());
                break;

            case changePwdDate:
                type = XSD_DATETIME;
                value = user.getChangePwdDate() == null ? ""
                        : DATE_FORMAT.get().format(user.getChangePwdDate());
                break;

            case passwordHistorySize:
                type = XSD_INT;
                value = String.valueOf(user.getPasswordHistory().size());
                break;

            case failedLoginCount:
                type = XSD_INT;
                value = String.valueOf(user.getFailedLogins());
                break;

            default:
            }

            if (type != null && value != null) {
                atts.addAttribute("", "", feature.name(), type, value);
            }
        }

        handler.startElement("", "", "user", atts);

        // Using UserTO for attribute values, since the conversion logic of
        // values to String is already encapsulated there
        UserTO userTO = userDataBinder.getUserTO(user);

        doExtractAttributes(handler, userTO, conf.getAttrs(), conf.getDerAttrs(), conf.getVirAttrs());

        if (conf.getFeatures().contains(Feature.memberships)) {
            handler.startElement("", "", "memberships", null);

            for (MembershipTO memb : userTO.getMemberships()) {
                atts.clear();

                atts.addAttribute("", "", "id", XSD_LONG, String.valueOf(memb.getId()));
                atts.addAttribute("", "", "roleId", XSD_LONG, String.valueOf(memb.getRoleId()));
                atts.addAttribute("", "", "roleName", XSD_STRING, String.valueOf(memb.getRoleName()));
                handler.startElement("", "", "membership", atts);

                doExtractAttributes(handler, memb, memb.getAttributeMap().keySet(),
                        memb.getDerivedAttributeMap().keySet(), memb.getVirtualAttributeMap().keySet());

                if (conf.getFeatures().contains(Feature.resources)) {
                    Membership actualMemb = user.getMembership(memb.getRoleId());
                    if (actualMemb == null) {
                        LOG.warn("Unexpected: cannot find membership for " + "role {} for user {}",
                                memb.getRoleId(), user);
                    } else {
                        doExtractResources(handler, roleDataBinder.getRoleTO(actualMemb.getSyncopeRole()));
                    }
                }

                handler.endElement("", "", "membership");
            }

            handler.endElement("", "", "memberships");
        }

        if (conf.getFeatures().contains(Feature.resources)) {
            doExtractResources(handler, userTO);
        }

        handler.endElement("", "", "user");
    }
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement.java

/**
 * Gets the attributes of the element in the form of a {@link org.xml.sax.Attributes}.
 * @param element the element to read the attributes from
 * @return the attributes/*w  ww  . jav a2  s  .  c  o m*/
 */
protected AttributesImpl readAttributes(final HtmlElement element) {
    final AttributesImpl attributes = new AttributesImpl();
    for (final DomAttr entry : element.getAttributesMap().values()) {
        final String name = entry.getName();
        final String value = entry.getValue();
        attributes.addAttribute(null, name, name, null, value);
    }

    return attributes;
}

From source file:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.FeatureCatalogue.java

private void addOperationToAttributes(Operation op, AttributesImpl atts) {

    if (atts != null && op != null) {
        atts.addAttribute("", "mode", "", "CDATA", op.toString());
    }//from  ww  w. j a  v  a 2s .c om
}

From source file:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.FeatureCatalogue.java

private void appendImageInfo(List<ImageMetadata> images) throws SAXException {

    if (!includeDiagrams) {
        return;/*from ww  w  .  j  ava  2s.  c  o  m*/
    }

    Collections.sort(images, new Comparator<ImageMetadata>() {

        @Override
        public int compare(ImageMetadata o1, ImageMetadata o2) {
            return o1.getId().compareTo(o2.getId());
        }
    });

    writer.startElement("images");

    for (ImageMetadata img : images) {

        // TBD: at the moment this is only used by the docx transformation
        // the information could therefore be moved to a separate file
        AttributesImpl atts = new AttributesImpl();
        atts.addAttribute("", "id", "", "CDATA", img.getId());
        atts.addAttribute("", "idAsInt", "", "CDATA", "" + imgIntegerIdCounter);
        imgIntegerIdCounter = imgIntegerIdCounter + imgIntegerIdStepwidth;
        atts.addAttribute("", "name", "", "CDATA", img.getName());
        atts.addAttribute("", "height", "", "CDATA", "" + img.getHeight());
        atts.addAttribute("", "width", "", "CDATA", "" + img.getWidth());
        atts.addAttribute("", "relPath", "", "CDATA", img.getRelPathToFile());

        writer.emptyElement("image", atts);

        // also keep track of the image metadata for later use
        imageSet.add(img);
    }

    writer.endElement("images");
}

From source file:de.tudarmstadt.ukp.lmf.writer.xml.LMFXmlWriter.java

/**
 * This method consumes a LMF Object and transforms it to XML. The method
 * iterates over all fields of a class and searches for the {@link AccessType} annotations.
 * Depending on the value of the annotation, the method reads the values of the objects
 * fields by invoking a getter or by directly accessing the field.
 * //  w w w  . j ava  2 s. c o m
 * @param lmfObject An LMF Object for which an Element should be created
 * @param writeEndElement If TRUE the closing Tag for the XML-Element will be created
 *  
 * @throws IllegalAccessException when a direct access to a field of the class is for some reason not possible 
 * @throws IllegalArgumentException when a direct access to a field of the class is for some reason not possible 
 * @throws SAXException if writing to XML-file is for some reason not possible
 */
@SuppressWarnings("unchecked")
private void doTransform(Object lmfObject, boolean writeEndElement)
        throws IllegalArgumentException, IllegalAccessException, SAXException {

    Class<?> something = lmfObject.getClass();
    String elementName = something.getSimpleName();
    int hibernateSuffixIdx = elementName.indexOf("_$$");
    if (hibernateSuffixIdx > 0)
        elementName = elementName.substring(0, hibernateSuffixIdx);
    AttributesImpl atts = new AttributesImpl();
    List<Object> children = new ArrayList<Object>();

    // find all field, also the inherited ones 
    ArrayList<Field> fields = new ArrayList<Field>();
    fields.addAll(Arrays.asList(something.getDeclaredFields()));
    Class<?> superClass = something.getSuperclass();
    while (superClass != null) {
        fields.addAll(Arrays.asList(superClass.getDeclaredFields()));
        superClass = superClass.getSuperclass();
    }

    // Iterating over all fields
    for (Field field : fields) {
        String fieldName = field.getName().replace("_", "");
        Class<?> fieldClass = field.getType();
        VarType varType = field.getAnnotation(VarType.class);
        // No VarType-Annotation found for the field, then don't save to XML 
        if (varType == null)
            continue;

        EVarType type = varType.type();

        // VarType is NONE, don't save to XML
        if (type.equals(EVarType.NONE))
            continue;

        Object retObj = null;

        /*
         * Determine how to access the variable
         */
        AccessType accessType = field.getAnnotation(AccessType.class);
        if (accessType == null || accessType.equals(EAccessType.GETTER)) {
            // access using a canonical getter
            String setFieldName = fieldName;

            if (fieldName.startsWith("is")) // E.g. isHead --> setHead
                setFieldName = setFieldName.replaceFirst("is", "");

            // Get-Method for the field
            String getFuncName = setFieldName.substring(0, 1).toUpperCase() + setFieldName.substring(1);
            if (fieldClass.equals(Boolean.class)) {
                getFuncName = "is" + getFuncName;
            } else
                getFuncName = "get" + getFuncName;

            Method getMethod = null;
            try {
                getMethod = something.getMethod(getFuncName);
                retObj = getMethod.invoke(lmfObject); // Run the Get-Method
            } catch (Exception e) {
                logger.warn("There was an error on accessing the method " + getFuncName + " in " + elementName
                        + " class. Falling back to field access");
                field.setAccessible(true);
                retObj = field.get(lmfObject);
            }
        } else {
            // Directly read the value of the field
            field.setAccessible(true);
            retObj = field.get(lmfObject);
        }

        if (retObj != null) {
            if (type.equals(EVarType.ATTRIBUTE)) { // Save Attribute to the new element
                atts.addAttribute("", "", fieldName, "CDATA", retObj.toString());
            } else if (type.equals(EVarType.IDREF)) { // Save IDREFs as attribute of the new element
                atts.addAttribute("", "", fieldName, "CDATA", ((IHasID) retObj).getId());
            } else if (type.equals(EVarType.CHILD)) { // Transform children of the new element to XML
                children.add(retObj);
            } else if (type.equals(EVarType.CHILDREN) && writeEndElement) {
                for (Object obj : (Iterable<Object>) retObj) {
                    children.add(obj);
                }
            } else if (type.equals(EVarType.ATTRIBUTE_OPTIONAL)) {
                atts.addAttribute("", "", fieldName, "CDATA", retObj.toString());
            } else if (type.equals(EVarType.IDREFS)) {
                String attrValue = "";
                for (Object obj : (Iterable<Object>) retObj) {
                    attrValue += ((IHasID) obj).getId() + " ";
                }
                if (!attrValue.isEmpty())
                    atts.addAttribute("", "", fieldName, "CDATA",
                            attrValue.substring(0, attrValue.length() - 1));
            }
        } else { // Element is null, save only if it is a non-optional Attribute or IDREF
            if (type.equals(EVarType.ATTRIBUTE) || type.equals(EVarType.IDREF)) { // Save Attribute to the new element
                //atts.addAttribute("", "", fieldName, "CDATA", "NULL");
            }
        }
    }

    // Save the current element and its children
    th.startElement("", "", elementName, atts);
    for (Object child : children) {
        //System.out.println("CHILD: "+child.getClass().getSimpleName());
        doTransform(child, true);
    }
    if (writeEndElement)
        th.endElement("", "", elementName);
}

From source file:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.FeatureCatalogue.java

public void initialise(PackageInfo p, Model m, Options o, ShapeChangeResult r, boolean diagOnly)
        throws ShapeChangeAbortException {
    pi = p;//from w  w w .  java2  s  .  c  om
    model = m;
    options = o;
    result = r;

    try {

        if (!initialised) {
            initialised = true;

            String pathToJavaExe_ = options.parameter(this.getClass().getName(), PARAM_JAVA_EXE_PATH);
            if (pathToJavaExe_ != null && pathToJavaExe_.trim().length() > 0) {
                pathToJavaExe = pathToJavaExe_.trim();
                if (!pathToJavaExe.startsWith("\"")) {
                    pathToJavaExe = "\"" + pathToJavaExe;
                }
                if (!pathToJavaExe.endsWith("\"")) {
                    pathToJavaExe = pathToJavaExe + "\"";
                }

                String jo_tmp = options.parameter(this.getClass().getName(), PARAM_JAVA_OPTIONS);
                if (jo_tmp != null && jo_tmp.trim().length() > 0) {
                    javaOptions = jo_tmp.trim();
                }

                /*
                 * check path - and potentially also options - by invoking
                 * the exe
                 */
                List<String> cmds = new ArrayList<String>();
                cmds.add(pathToJavaExe);
                if (javaOptions != null) {
                    cmds.add(javaOptions);
                }
                cmds.add("-version");

                ProcessBuilder pb = new ProcessBuilder(cmds);

                try {
                    Process proc = pb.start();

                    StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream());
                    StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream());

                    errorGobbler.start();
                    outputGobbler.start();

                    errorGobbler.join();
                    outputGobbler.join();

                    int exitVal = proc.waitFor();

                    if (exitVal != 0) {
                        if (errorGobbler.hasResult()) {
                            MessageContext mc = result.addFatalError(this, 21, StringUtils.join(cmds, " "),
                                    "" + exitVal);
                            mc.addDetail(this, 27, errorGobbler.getResult());
                        } else {
                            result.addFatalError(this, 21, StringUtils.join(cmds, " "), "" + exitVal);
                        }
                        throw new ShapeChangeAbortException();
                    }

                } catch (InterruptedException e) {
                    result.addFatalError(this, 22);
                    throw new ShapeChangeAbortException();
                }
            }

            encounteredAppSchemasByName = new TreeMap<String, Integer>();

            initialiseFromOptions();

            String s = null;

            Model refModel_tmp = getReferenceModel();

            if (refModel_tmp != null) {

                /*
                 * Ensure that IDs used in the reference model are unique to
                 * that model and do not get mixed up with the IDs of the
                 * input model.
                 * 
                 * REQUIREMENT for model diff: two objects with equal ID
                 * must represent the same model element. If a model element
                 * is deleted in the reference model, then a new model
                 * element in the input model must not have the same ID.
                 * 
                 * It looks like this cannot be guaranteed. Therefore we add
                 * a prefix to the IDs of the model elements in the
                 * reference model.
                 */
                refModel = new GenericModel(refModel_tmp);
                refModel_tmp.shutdown();

                refModel.addPrefixToModelElementIDs("refmodel_");
            }

            String xmlName = outputFilename + ".tmp.xml";

            // Check whether we can use the given output directory
            File outputDirectoryFile = new File(outputDirectory);
            boolean exi = outputDirectoryFile.exists();
            if (!exi) {
                outputDirectoryFile.mkdirs();
                exi = outputDirectoryFile.exists();
            }
            boolean dir = outputDirectoryFile.isDirectory();
            boolean wrt = outputDirectoryFile.canWrite();
            boolean rea = outputDirectoryFile.canRead();
            if (!exi || !dir || !wrt || !rea) {
                result.addFatalError(this, 12, outputDirectory);
                throw new ShapeChangeAbortException();
            }

            String encoding_ = encoding == null ? "UTF-8" : model.characterEncoding();

            OutputStream fout = new FileOutputStream(outputDirectory + "/" + xmlName);
            OutputStream bout = new BufferedOutputStream(fout, streamBufferSize);
            OutputStreamWriter outputXML = new OutputStreamWriter(bout, encoding_);

            writer = new XMLWriter(outputXML, encoding_);

            writer.forceNSDecl("http://www.w3.org/2001/XMLSchema-instance", "xsi");

            writer.startDocument();

            writer.processingInstruction("xml-stylesheet", "type='text/xsl' href='./html.xsl'");

            writer.comment("Feature catalogue created using ShapeChange");

            AttributesImpl atts = new AttributesImpl();
            atts.addAttribute("http://www.w3.org/2001/XMLSchema-instance", "noNamespaceSchemaLocation",
                    "xsi:noNamespaceSchemaLocation", "CDATA", "FC.xsd");
            writer.startElement("", "FeatureCatalogue", "", atts);

            s = options.parameter(this.getClass().getName(), "name");
            if (s != null && s.length() > 0)
                writer.dataElement("name", s);
            else
                writer.dataElement("name", "unknown");

            s = options.parameter(this.getClass().getName(), "scope");

            if (s != null && s.length() > 0)
                PrintLineByLine(s, "scope", null);
            else {
                writer.dataElement("scope", "unknown");
            }

            s = options.parameter(this.getClass().getName(), "versionNumber");
            if (s != null && s.length() > 0)
                writer.dataElement("versionNumber", s);
            else
                writer.dataElement("versionNumber", "unknown");

            s = options.parameter(this.getClass().getName(), "versionDate");
            if (s != null && s.length() > 0)
                writer.dataElement("versionDate", s);
            else
                writer.dataElement("versionDate", "unknown");

            s = options.parameter(this.getClass().getName(), "producer");
            if (s != null && s.length() > 0)
                writer.dataElement("producer", s);
            else
                writer.dataElement("producer", "unknown");
        }

        // we need to compute the diff for each application schema
        if (refModel != null) {

            SortedSet<PackageInfo> set = refModel.schemas(p.name());

            if (set.size() == 1) {

                /*
                 * Get the full names of classes (in lower case) from the
                 * input schema so that later we can look them up by their
                 * full name (within the schema, not in the model).
                 */
                inputSchemaClassesByFullNameInSchema = new HashMap<String, ClassInfo>();
                for (ClassInfo ci : model.classes(pi)) {
                    inputSchemaClassesByFullNameInSchema.put(ci.fullNameInSchema().toLowerCase(Locale.ENGLISH),
                            ci);
                }

                // compute diffs
                differ = new Differ();
                refPackage = set.iterator().next();
                SortedMap<Info, SortedSet<DiffElement>> pi_diffs = differ.diff(p, refPackage);

                // merge diffs for pi with existing diffs (from other
                // schemas)
                differ.merge(diffs, pi_diffs);

                // log the diffs found for pi
                for (Entry<Info, SortedSet<DiffElement>> me : pi_diffs.entrySet()) {

                    MessageContext mc = result.addInfo(
                            "Model difference - " + me.getKey().fullName().replace(p.fullName(), p.name()));

                    for (DiffElement diff : me.getValue()) {
                        String s = diff.change + " " + diff.subElementType;
                        if (diff.subElementType == ElementType.TAG)
                            s += "(" + diff.tag + ")";
                        if (diff.subElement != null)
                            s += " " + diff.subElement.name();
                        else if (diff.diff != null)
                            s += " " + (new diff_match_patch()).diff_prettyHtml(diff.diff);
                        else
                            s += " ???";
                        mc.addDetail(s);
                    }
                }

                /*
                 * switch to default xslt for html diff - unless the
                 * configuration explicitly names an XSLT file to use
                 */
                if (options.parameter(this.getClass().getName(), "xslhtmlFile") == null) {
                    xslhtmlfileName = DEFAULT_XSL_HTML_DIFF_FILE_NAME;
                }

            } else {
                result.addWarning(null, 308, p.name());
                refModel = null;
            }
        }

        writer.startElement("ApplicationSchema", "id", "_P" + pi.id());

        /*
         * Determine if app schema with same name has been encountered
         * before, and choose name accordingly
         */

        String nameForAppSchema = null;

        if (encounteredAppSchemasByName.containsKey(pi.name())) {
            int count = encounteredAppSchemasByName.get(pi.name()).intValue();
            count++;
            nameForAppSchema = pi.name() + " (" + count + ")";
            encounteredAppSchemasByName.put(pi.name(), new Integer(count));
        } else {
            nameForAppSchema = pi.name();
            encounteredAppSchemasByName.put(pi.name(), new Integer(1));
        }

        // now set the name of the application schema
        writer.dataElement("name", nameForAppSchema);

        String s = pi.definition();
        if (s != null && s.length() > 0) {
            PrintLineByLine(s, "definition", null);
        }
        s = pi.description();
        if (s != null && s.length() > 0) {
            PrintLineByLine(s, "description", null);
        }

        s = pi.version();
        if (s != null && s.length() > 0) {
            writer.dataElement("versionNumber", s);
        }

        writer.startElement("taggedValues");

        s = pi.taggedValue(TransformationConstants.TRF_TV_NAME_GENERATIONDATETIME);
        if (s != null && s.trim().length() > 0) {
            writer.dataElement(TransformationConstants.TRF_TV_NAME_GENERATIONDATETIME, PrepareToPrint(s));
        }

        writer.endElement("taggedValues");

        if (pi.getDiagrams() != null) {
            appendImageInfo(pi.getDiagrams());
        }

        writer.endElement("ApplicationSchema");

        /*
         * Check if there are any deletions of classes or packages that are
         * owned by the application schema package.
         */

        if (hasDiff(pi, ElementType.SUBPACKAGE, Operation.DELETE)) {

            Set<DiffElement> pkgdiffs = getDiffs(pi, ElementType.SUBPACKAGE, Operation.DELETE);

            for (DiffElement diff : pkgdiffs) {

                // child package was deleted
                PrintPackage((PackageInfo) diff.subElement, Operation.DELETE);
            }

        }

        printContainedPackages(pi);

        /*
         * NOTE: inserted or unchanged classes are handled in
         * process(ClassInfo) method
         */
        printDeletedClasses(pi);

    } catch (Exception e) {

        String msg = e.getMessage();
        if (msg != null) {
            result.addError(msg);
        }
        e.printStackTrace(System.err);
    }
}

From source file:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.FeatureCatalogue.java

private void PrintPropertyDetail(PropertyInfo propi, String assocId, Operation op) throws SAXException {

    String propiid = "_A" + propi.id();
    propiid = options.internalize(propiid);

    if (propi.isAttribute()) {
        writer.startElement("FeatureAttribute", "id", propiid, op);
    } else {//from  w w w.j a v a 2 s.c  o  m
        writer.startElement("RelationshipRole", "id", propiid, op);
    }

    PrintDescriptors(propi, false, op);

    String s = propi.cardinality().toString();
    s = checkDiff(s, propi, ElementType.MULTIPLICITY);
    String cardinalityText = PrepareToPrint(s);
    cardinalityText = options.internalize(cardinalityText);

    writer.dataElement("cardinality", cardinalityText, op);

    if (!propi.isAttribute() && !propi.isNavigable()) {
        PrintLineByLine("false", "isNavigable", op);
    }

    if (propi.isDerived()) {
        PrintLineByLine("true", "isDerived", op);
    }

    s = propi.initialValue();
    if (propi.isAttribute() && s != null && s.length() > 0) {
        PrintLineByLine(PrepareToPrint(s), "initialValue", op);
    }

    writer.startElement("taggedValues");

    s = propi.taggedValue("name");
    if (s != null && s.trim().length() > 0) {
        writer.dataElement("name", PrepareToPrint(s), op);
    }
    String[] tags = propi.taggedValuesForTag("length");
    if (tags != null && tags.length > 0) {
        for (String tag : tags) {
            writer.dataElement("length", PrepareToPrint(tag), op);
        }
    }

    writer.endElement("taggedValues");

    if (includeVoidable) {
        if (propi.voidable()) {
            writer.dataElement("voidable", "true", op);
        } else {
            writer.dataElement("voidable", "false", op);
        }
    }

    if (propi.isOrdered()) {
        writer.dataElement("orderIndicator", "1", op);
    } else {
        writer.dataElement("orderIndicator", "0", op);
    }
    if (propi.isUnique()) {
        writer.dataElement("uniquenessIndicator", "1", op);
    } else {
        writer.dataElement("uniquenessIndicator", "0", op);
    }

    Type ti = propi.typeInfo();
    if (!propi.isAttribute() && !propi.isComposition()) {
        if (ti != null) {

            AttributesImpl atts = new AttributesImpl();

            ClassInfo cix = lookupClassById(ti.id);
            if (cix != null) {
                String tiid = "_C" + cix.id();
                tiid = options.internalize(tiid);

                atts.addAttribute("", "idref", "", "CDATA", tiid);
            }
            atts.addAttribute("", "category", "", "CDATA", featureTerm.toLowerCase() + " type");
            addOperationToAttributes(op, atts);
            writer.dataElement("", "FeatureTypeIncluded", "", atts,
                    checkDiff(ti.name, propi, ElementType.VALUETYPE));
        }
        writer.emptyElement("relation", "idref", assocId);

        PropertyInfo propi2 = propi.reverseProperty();
        if (propi2 != null && ExportProperty(propi2) && propi2.isNavigable()) {

            String propi2id = "_A" + propi2.id();
            propi2id = options.internalize(propi2id);

            writer.emptyElement("InverseRole", "idref", propi2id, op);
        }

    } else {
        if (ti != null) {

            ClassInfo cix;

            if (op != Operation.DELETE) {
                cix = model.classById(ti.id);
            } else {
                cix = refModel.classById(ti.id);
            }

            if (cix != null) {

                int cat = cix.category();
                String cixname = cix.name();
                cixname = checkDiff(cixname, propi, ElementType.VALUETYPE);
                cixname = options.internalize(cixname);

                switch (cat) {
                case Options.CODELIST:
                case Options.ENUMERATION:

                    AttributesImpl atts = new AttributesImpl();

                    if (cat == Options.CODELIST) {
                        atts.addAttribute("", "category", "", "CDATA", "code list");

                        if (includeCodelistURI) {
                            String cl = cix.taggedValue("codeList");
                            if (cl == null || cl.isEmpty()) {
                                cl = cix.taggedValue("vocabulary");
                            }
                            if (cl != null && !cl.isEmpty()) {
                                atts.addAttribute("", "codeList", "", "CDATA", options.internalize(cl));
                            }
                        }

                    } else if (cat == Options.ENUMERATION && !cixname.equals("Boolean")) {
                        atts.addAttribute("", "category", "", "CDATA", "enumeration");
                    }
                    addOperationToAttributes(op, atts);
                    writer.dataElement("", "ValueDataType", "", atts, PrepareToPrint(cixname));

                    if (!cixname.equals("Boolean")) {
                        writer.dataElement("ValueDomainType", "1", op);
                        for (PropertyInfo ei : cix.properties().values()) {
                            if (ei != null && ExportValue(ei)) {

                                String eiid = "_A" + ei.id();
                                eiid = options.internalize(eiid);

                                writer.emptyElement("enumeratedBy", "idref", eiid);
                            }
                        }

                        if (diffs != null && diffs.get(cix) != null) {
                            for (DiffElement diff : diffs.get(cix)) {
                                if (diff.subElementType == ElementType.ENUM
                                        && diff.change == Operation.DELETE) {

                                    writer.emptyElement("enumeratedBy", "idref",
                                            "_A" + ((PropertyInfo) diff.subElement).id());
                                }
                            }
                        }

                        if (op != Operation.DELETE) {
                            if (cix.inSchema(propi.inClass().pkg()))
                                enumerations.add(cix);
                        } else {
                            if (cix.inSchema(refPackage))
                                enumerations.add(cix);
                        }

                        // FIXME if (cix.inSchema(propi.inClass().pkg()))
                        // enumerations.add(cix);
                    } else {
                        writer.dataElement("ValueDomainType", "0", op);
                    }
                    break;
                default:

                    String cixid = "_C" + cix.id();
                    cixid = options.internalize(cixid);

                    AttributesImpl atts2 = new AttributesImpl();
                    atts2.addAttribute("", "idref", "", "CDATA", cixid);

                    if (cat == Options.FEATURE || cat == Options.OKSTRAFID) {

                        String fttext = featureTerm.toLowerCase() + " type";
                        fttext = options.internalize(fttext);

                        atts2.addAttribute("", "category", "", "CDATA", fttext);

                    } else if (cat == Options.DATATYPE || cat == Options.OKSTRAKEY) {
                        atts2.addAttribute("", "category", "", "CDATA", "data type");
                    } else if (cat == Options.UNION) {
                        atts2.addAttribute("", "category", "", "CDATA", "union data type");
                    } else if (cat == Options.BASICTYPE) {
                        atts2.addAttribute("", "category", "", "CDATA", "basic type");
                    }
                    addOperationToAttributes(op, atts2);
                    writer.dataElement("", "ValueDataType", "", atts2, PrepareToPrint(cixname));

                    writer.dataElement("ValueDomainType", "0", op);
                    break;
                }
            } else {
                String tiname = ti.name;
                tiname = checkDiff(tiname, propi, ElementType.VALUETYPE);
                tiname = options.internalize(tiname);

                writer.dataElement("ValueDataType", PrepareToPrint(tiname), op);
            }
        } else {
            writer.dataElement("ValueDataType", "(unknown)", op);
        }
    }

    if (propi.isAttribute()) {
        writer.endElement("FeatureAttribute");
    } else {
        writer.endElement("RelationshipRole");
    }
}

From source file:com.microsoft.tfs.client.clc.commands.Command.java

private void displayPendingChangeAsXML(final PendingChange change) throws SAXException {
    Check.notNull(change, "change"); //$NON-NLS-1$
    Check.notNull(xmlWriter, "this.xmlWriter"); //$NON-NLS-1$

    final AttributesImpl changeAttributes = new AttributesImpl();

    final String localItem;
    final String serverItem;

    /*//from  w  w w  . j a  va 2  s. co m
     * If the change is an undone rename (and the change type is not
     * undelete), we need to swap the source and destination for them to
     * make sense to the user.
     */
    if (change.isUndone() && change.getChangeType().contains(ChangeType.RENAME)
            && !change.getChangeType().contains(ChangeType.UNDELETE)) {
        localItem = change.getSourceLocalItem();
        serverItem = change.getSourceServerItem();
    } else {
        localItem = change.getLocalItem();
        serverItem = change.getServerItem();
    }

    changeAttributes.addAttribute("", "", CommonXMLNames.SERVER_ITEM, "CDATA", serverItem); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    if (localItem != null) {
        changeAttributes.addAttribute("", "", CommonXMLNames.LOCAL_ITEM, "CDATA", localItem); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    }

    changeAttributes.addAttribute("", "", CommonXMLNames.VERSION, "CDATA", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
            Integer.toString(change.getVersion()));

    changeAttributes.addAttribute("", //$NON-NLS-1$
            "", //$NON-NLS-1$
            CommonXMLNames.DATE, "CDATA", //$NON-NLS-1$
            SimpleXMLWriter.ISO_DATE_FORMAT.format(change.getCreationDate().getTime()));
    changeAttributes.addAttribute("", "", CommonXMLNames.LOCK, "CDATA", change.getLockLevelName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    changeAttributes.addAttribute("", //$NON-NLS-1$
            "", //$NON-NLS-1$
            CommonXMLNames.CHANGE_TYPE, "CDATA", //$NON-NLS-1$
            change.getChangeType().toUIString(false, change));

    /*
     * If the source server item and server item paths differ, we have a
     * rename, move, etc., and want to print the source item.
     */
    if (change.getSourceServerItem() != null
            && !ServerPath.equals(change.getSourceServerItem(), change.getServerItem())) {
        changeAttributes.addAttribute("", //$NON-NLS-1$
                "", //$NON-NLS-1$
                CommonXMLNames.SOURCE_SERVER_ITEM, "CDATA", //$NON-NLS-1$
                change.getSourceServerItem());
    }

    if (change.getItemType() == ItemType.FILE
            && change.getEncoding() != VersionControlConstants.ENCODING_UNCHANGED) {
        changeAttributes.addAttribute("", //$NON-NLS-1$
                "", //$NON-NLS-1$
                CommonXMLNames.FILE_TYPE, "CDATA", //$NON-NLS-1$
                new FileEncoding(change.getEncoding()).getName());
    }

    if (change.getDeletionID() != 0) {
        changeAttributes.addAttribute("", //$NON-NLS-1$
                "", //$NON-NLS-1$
                CommonXMLNames.DELETION_ID, "CDATA", //$NON-NLS-1$
                Integer.toString(change.getDeletionID()));
    }

    xmlWriter.startElement("", "", CommonXMLNames.PENDING_CHANGE, changeAttributes); //$NON-NLS-1$ //$NON-NLS-2$
    xmlWriter.endElement("", "", CommonXMLNames.PENDING_CHANGE); //$NON-NLS-1$ //$NON-NLS-2$
}