Example usage for javax.xml.stream XMLStreamWriter writeAttribute

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

Introduction

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

Prototype

public void writeAttribute(String localName, String value) throws XMLStreamException;

Source Link

Document

Writes an attribute to the output stream without a prefix.

Usage

From source file:org.gtdfree.model.GTDDataXMLTools.java

static public void store(GTDModel model, OutputStream out, ActionFilter filter)
        throws IOException, XMLStreamException, FactoryConfigurationError {

    if (filter == null) {
        filter = new DummyFilter(true);
    }//from   w  w w . j  a v  a  2 s . co m
    XMLStreamWriter w = XMLOutputFactory.newInstance().createXMLStreamWriter(out, "UTF-8"); //$NON-NLS-1$

    w.writeStartDocument("UTF-8", "1.0"); //$NON-NLS-1$ //$NON-NLS-2$

    w.writeCharacters(EOL);
    w.writeCharacters(EOL);

    w.writeStartElement("gtd-data"); //$NON-NLS-1$
    w.writeAttribute("version", "2.2"); //$NON-NLS-1$ //$NON-NLS-2$
    w.writeAttribute("modified", ApplicationHelper.formatLongISO(new Date())); //$NON-NLS-1$
    w.writeAttribute("lastActionID", Integer.toString(model.getLastActionID())); //$NON-NLS-1$
    w.writeCharacters(EOL);
    w.writeCharacters(EOL);

    // Write folders

    Folder[] fn = model.toFoldersArray();
    w.writeStartElement("lists"); //$NON-NLS-1$
    w.writeCharacters(EOL);

    for (int i = 0; i < fn.length; i++) {
        Folder ff = fn[i];
        if (ff.isMeta() || !filter.isAcceptable(ff, null)) {
            continue;
        }
        w.writeCharacters(SKIP);
        w.writeStartElement("list"); //$NON-NLS-1$
        w.writeAttribute("id", String.valueOf(ff.getId())); //$NON-NLS-1$
        w.writeAttribute("name", ff.getName()); //$NON-NLS-1$
        w.writeAttribute("type", ff.getType().toString()); //$NON-NLS-1$
        w.writeAttribute("closed", Boolean.toString(ff.isClosed())); //$NON-NLS-1$
        if (ff.getCreated() != null)
            w.writeAttribute("created", Long.toString(ff.getCreated().getTime())); //$NON-NLS-1$
        if (ff.getModified() != null)
            w.writeAttribute("modified", Long.toString(ff.getModified().getTime())); //$NON-NLS-1$
        if (ff.getResolved() != null)
            w.writeAttribute("resolved", Long.toString(ff.getResolved().getTime())); //$NON-NLS-1$
        if (!ff.isInBucket() && ff.getDescription() != null) {
            w.writeAttribute("description", ApplicationHelper.escapeControls(ff.getDescription())); //$NON-NLS-1$
        }
        w.writeCharacters(EOL);

        for (Action a : ff) {

            if (!filter.isAcceptable(ff, a)) {
                continue;
            }

            w.writeCharacters(SKIPSKIP);
            w.writeStartElement("action"); //$NON-NLS-1$
            w.writeAttribute("id", Integer.toString(a.getId())); //$NON-NLS-1$
            w.writeAttribute("created", Long.toString(a.getCreated().getTime())); //$NON-NLS-1$
            w.writeAttribute("resolution", a.getResolution().toString()); //$NON-NLS-1$
            if (a.getResolved() != null)
                w.writeAttribute("resolved", Long.toString(a.getResolved().getTime())); //$NON-NLS-1$
            if (a.getModified() != null)
                w.writeAttribute("modified", Long.toString(a.getModified().getTime())); //$NON-NLS-1$
            if (a.getDescription() != null)
                w.writeAttribute("description", ApplicationHelper.escapeControls(a.getDescription())); //$NON-NLS-1$
            if (a.getStart() != null)
                w.writeAttribute("start", Long.toString(a.getStart().getTime())); //$NON-NLS-1$
            if (a.getRemind() != null)
                w.writeAttribute("remind", Long.toString(a.getRemind().getTime())); //$NON-NLS-1$
            if (a.getDue() != null)
                w.writeAttribute("due", Long.toString(a.getDue().getTime())); //$NON-NLS-1$
            if (a.getType() != null)
                w.writeAttribute("type", a.getType().toString()); //$NON-NLS-1$
            if (a.getUrl() != null)
                w.writeAttribute("url", a.getUrl().toString()); //$NON-NLS-1$
            if (a.isQueued())
                w.writeAttribute("queued", Boolean.toString(a.isQueued())); //$NON-NLS-1$
            if (a.getProject() != null)
                w.writeAttribute("project", a.getProject().toString()); //$NON-NLS-1$
            if (a.getPriority() != null)
                w.writeAttribute("priority", a.getPriority().toString()); //$NON-NLS-1$
            w.writeEndElement();
            w.writeCharacters(EOL);
        }
        w.writeCharacters(SKIP);
        w.writeEndElement();
        w.writeCharacters(EOL);
    }
    w.writeEndElement();
    w.writeCharacters(EOL);

    // Write projects
    Project[] pn = model.toProjectsArray();
    w.writeStartElement("projects"); //$NON-NLS-1$
    w.writeCharacters(EOL);

    for (int i = 0; i < pn.length; i++) {
        Project ff = pn[i];

        if (!filter.isAcceptable(ff, null)) {
            continue;
        }

        w.writeCharacters(SKIP);
        w.writeStartElement("project"); //$NON-NLS-1$
        w.writeAttribute("id", String.valueOf(ff.getId())); //$NON-NLS-1$
        w.writeAttribute("name", ff.getName()); //$NON-NLS-1$
        w.writeAttribute("closed", String.valueOf(ff.isClosed())); //$NON-NLS-1$
        if (ff.getCreated() != null)
            w.writeAttribute("created", Long.toString(ff.getCreated().getTime())); //$NON-NLS-1$
        if (ff.getModified() != null)
            w.writeAttribute("modified", Long.toString(ff.getModified().getTime())); //$NON-NLS-1$
        if (ff.getResolved() != null)
            w.writeAttribute("resolved", Long.toString(ff.getResolved().getTime())); //$NON-NLS-1$

        if (ff.getDescription() != null) {
            w.writeAttribute("description", ApplicationHelper.escapeControls(ff.getDescription())); //$NON-NLS-1$
        }

        StringBuilder sb = new StringBuilder();

        for (Action a : ff) {
            if (!filter.isAcceptable(ff, a)) {
                continue;
            }
            if (sb.length() > 0) {
                sb.append(","); //$NON-NLS-1$
            }
            sb.append(a.getId());
        }
        w.writeAttribute("actions", sb.toString()); //$NON-NLS-1$
        w.writeEndElement();
        w.writeCharacters(EOL);
    }
    w.writeEndElement();
    w.writeCharacters(EOL);

    // Write queue
    Folder f = model.getQueue();

    if (filter.isAcceptable(f, null)) {
        w.writeStartElement("queue"); //$NON-NLS-1$
        w.writeAttribute("id", String.valueOf(f.getId())); //$NON-NLS-1$
        w.writeAttribute("name", f.getName()); //$NON-NLS-1$

        StringBuilder sb = new StringBuilder();
        Iterator<Action> i = f.iterator();
        if (i.hasNext()) {
            sb.append(i.next().getId());
        }
        while (i.hasNext()) {
            sb.append(","); //$NON-NLS-1$
            sb.append(i.next().getId());
        }
        w.writeAttribute("actions", sb.toString()); //$NON-NLS-1$
        w.writeEndElement();
        w.writeCharacters(EOL);
    }

    // containers
    w.writeEndElement();
    w.writeEndDocument();

    w.flush();
    w.close();

    //changed=false;

}

From source file:org.icgc.dcc.portal.manifest.writer.GNOSManifestWriter.java

private static void startXmlDocument(XMLStreamWriter writer, long timestamp) throws XMLStreamException {
    writer.writeStartDocument(FILE_ENCODING, "1.0");
    writer.writeStartElement(GNOS_ROOT);
    writer.writeAttribute("date", formatToUtc(new Date(timestamp)));
}

From source file:org.icgc.dcc.portal.manifest.writer.GNOSManifestWriter.java

private static void addDownloadUrlEntryToXml(XMLStreamWriter writer, String id, String downloadUrl,
        int rowCount) throws XMLStreamException {
    writer.writeStartElement(GNOS_RECORD);
    writer.writeAttribute("id", String.valueOf(rowCount));

    addXmlElement(writer, GNOS_RECORD_ID, id);
    addXmlElement(writer, GNOS_RECORD_URI, downloadUrl);

    writer.writeStartElement(GNOS_FILES);
}

From source file:org.icgc.dcc.portal.manifest.writer.GNOSManifestWriter.java

private static void addFileInfoEntriesToXml(XMLStreamWriter writer, Iterable<ManifestFile> info)
        throws XMLStreamException {
    for (val file : info) {
        writer.writeStartElement(GNOS_FILE);

        addXmlElement(writer, GNOS_FILE_NAME, file.getName());
        addXmlElement(writer, GNOS_FILE_SIZE, file.getSize() + "");

        writer.writeStartElement(GNOS_CHECK_SUM);
        writer.writeAttribute("type", "md5");
        writer.writeCharacters(file.getMd5sum());
        writer.writeEndElement();//from  w w  w. j  av  a 2 s  .c o  m

        writer.writeEndElement();
    }
}

From source file:org.intermine.api.tracker.xml.TemplateTrackBinding.java

/**
 * Convert a TemplateTrack to XML and write XML to given writer.
 * @param uos the UserObjectStore// w ww.  j  a v a2 s .c o  m
 * @param writer the XMLStreamWriter to write to
 */
public static void marshal(ObjectStore uos, XMLStreamWriter writer) {
    Connection conn = null;
    Statement stm = null;
    ResultSet rs = null;

    try {
        writer.writeCharacters("\n");
        writer.writeStartElement(TEMPLATETRACKS);
        conn = ((ObjectStoreWriterInterMineImpl) uos).getConnection();
        String sql = "SELECT templatename, username, sessionidentifier,timestamp " + "FROM "
                + TrackerUtil.TEMPLATE_TRACKER_TABLE;
        stm = conn.createStatement();
        rs = stm.executeQuery(sql);
        while (rs.next()) {
            writer.writeCharacters("\n");
            writer.writeStartElement(TEMPLATETRACK);
            writer.writeAttribute("templatename", rs.getString(1));
            String username = rs.getString(2);
            if (!StringUtils.isBlank(username)) {
                writer.writeAttribute("username", username);
            }
            writer.writeAttribute("sessionidentifier", rs.getString(3));
            writer.writeAttribute("timestamp", rs.getTimestamp(4).toString());
            writer.writeEndElement();
        }
        writer.writeCharacters("\n");
        writer.writeEndElement();
    } catch (SQLException sqle) {
        LOG.error("The templatetrack table does't exist!", sqle);
        try {
            writer.writeEndElement();
        } catch (XMLStreamException e) {
        }
    } catch (XMLStreamException e) {
        throw new RuntimeException("exception while marshalling template tracks", e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
                if (stm != null) {
                    stm.close();
                }
            } catch (SQLException e) {
                LOG.error("Problem closing  resources.", e);
            }
        }
        ((ObjectStoreWriterInterMineImpl) uos).releaseConnection(conn);
    }
}

From source file:org.intermine.api.xml.ProfileManagerBinding.java

/**
 * Convert the contents of a ProfileManager to XML and write the XML to the given writer.
 * @param profileManager the ProfileManager
 * @param writer the XMLStreamWriter to write to
 *///www .  jav a 2  s  .c  o m
public static void marshal(ProfileManager profileManager, XMLStreamWriter writer) {
    try {
        writer.writeStartElement("userprofiles");
        String profileVersion = getProfileVersion(profileManager.getProfileObjectStoreWriter());
        writer.writeAttribute(MetadataManager.PROFILE_FORMAT_VERSION, profileVersion);
        List<?> usernames = profileManager.getProfileUserNames();

        for (Object userName : usernames) {
            Profile profile = profileManager.getProfile((String) userName);
            LOG.info("Writing profile: " + profile.getUsername());
            long startTime = System.currentTimeMillis();

            ProfileBinding.marshal(profile, profileManager.getProductionObjectStore(), writer,
                    profileManager.getVersion(), getClassKeys(profileManager.getProductionObjectStore()));

            long totalTime = System.currentTimeMillis() - startTime;
            LOG.info("Finished writing profile: " + profile.getUsername() + " took " + totalTime + "ms.");
        }

        TrackManagerBinding.marshal(profileManager.getProfileObjectStoreWriter(), writer);
        writer.writeEndElement();
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.intermine.pathquery.PathQueryBinding.java

/**
 * Marshal to an XMLStreamWriter./*from  w  w w  . j  a v  a2 s  .com*/
 *
 * @param query the PathQuery
 * @param queryName the name of the query
 * @param modelName the model name
 * @param writer the xml stream writer to write to
 * @param version the version number of the xml format, an attribute of the ProfileManager
 */
public void doMarshal(PathQuery query, String queryName, String modelName, XMLStreamWriter writer,
        int version) {
    try {
        writer.writeStartElement("query");
        writer.writeAttribute("name", queryName);
        writer.writeAttribute("model", modelName);
        writer.writeAttribute("view", StringUtil.join(query.getView(), " "));
        if (query.getDescription() != null) {
            writer.writeAttribute("longDescription", query.getDescription());
        } else {
            writer.writeAttribute("longDescription", "");
        }
        StringBuilder sort = new StringBuilder();
        boolean needComma = false;
        for (OrderElement oe : query.getOrderBy()) {
            if (needComma) {
                sort.append(" ");
            }
            needComma = true;
            sort.append(oe.getOrderPath() + (oe.getDirection().equals(OrderDirection.ASC) ? " asc" : " desc"));
        }
        String sortString = sort.toString();
        if (!"".equals(sortString)) {
            writer.writeAttribute("sortOrder", sortString);
        }
        String logic = query.getConstraintLogic();
        boolean hasMultipleConstraints = false;
        if ((logic != null) && (logic.length() > 1)) {
            writer.writeAttribute("constraintLogic", query.getConstraintLogic());
            hasMultipleConstraints = true;
        }
        marshalPathQueryJoinStyle(query, writer);
        marshalPathQueryDescriptions(query, writer);
        marshalPathQueryConstraints(query, writer, hasMultipleConstraints);
        writer.writeEndElement();
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.intermine.pathquery.PathQueryBinding.java

/**
 * Create XML for the join style in a PathQuery.
 *///from  w ww .j  a va2 s.  co m
private static void marshalPathQueryJoinStyle(PathQuery query, XMLStreamWriter writer)
        throws XMLStreamException {
    for (Map.Entry<String, OuterJoinStatus> entry : query.getOuterJoinStatus().entrySet()) {
        writer.writeEmptyElement("join");
        writer.writeAttribute("path", entry.getKey());
        writer.writeAttribute("style", entry.getValue().toString());
        //writer.writeEndElement();
    }
}

From source file:org.intermine.pathquery.PathQueryBinding.java

/**
 * Create XML for the path descriptions in a PathQuery.
 *//*from   www .jav  a2 s. c  o  m*/
private static void marshalPathQueryDescriptions(PathQuery query, XMLStreamWriter writer)
        throws XMLStreamException {
    for (Map.Entry<String, String> entry : query.getDescriptions().entrySet()) {
        String path = entry.getKey();
        String description = entry.getValue();
        writer.writeEmptyElement("pathDescription");
        writer.writeAttribute("pathString", path);
        writer.writeAttribute("description", description);
    }
}

From source file:org.intermine.pathquery.PathQueryBinding.java

/**
 * Create XML for the constraints in a PathQuery.
 *//*  ww w.  ja  v  a  2s  .c  o  m*/
private void marshalPathQueryConstraints(PathQuery query, XMLStreamWriter writer,
        boolean hasMultipleConstraints) throws XMLStreamException {
    for (Map.Entry<PathConstraint, String> constraint : query.getConstraints().entrySet()) {
        boolean emptyElement = true;
        if (constraint.getKey() instanceof PathConstraintMultiValue) {
            emptyElement = false;
        }

        if (emptyElement) {
            writer.writeEmptyElement("constraint");
        } else {
            writer.writeStartElement("constraint");
        }
        writer.writeAttribute("path", constraint.getKey().getPath());
        if ((constraint.getValue() != null) && (hasMultipleConstraints)) {
            writer.writeAttribute("code", constraint.getValue());
        }
        doAdditionalConstraintStuff(query, constraint.getKey(), writer);
        if (constraint.getKey() instanceof PathConstraintAttribute) {
            writer.writeAttribute("op", "" + constraint.getKey().getOp());
            String outputValue = ((PathConstraintAttribute) constraint.getKey()).getValue();
            writer.writeAttribute("value", "" + outputValue);
        } else if (constraint.getKey() instanceof PathConstraintNull) {
            writer.writeAttribute("op", "" + constraint.getKey().getOp());
        } else if (constraint.getKey() instanceof PathConstraintSubclass) {
            writer.writeAttribute("type", ((PathConstraintSubclass) constraint.getKey()).getType());
        } else if (constraint.getKey() instanceof PathConstraintBag) {
            writer.writeAttribute("op", "" + constraint.getKey().getOp());
            writer.writeAttribute("value", ((PathConstraintBag) constraint.getKey()).getBag());
        } else if (constraint.getKey() instanceof PathConstraintIds) {
            writer.writeAttribute("op", "" + constraint.getKey().getOp());
            StringBuilder sb = new StringBuilder();
            boolean needComma = false;
            for (Integer id : ((PathConstraintIds) constraint.getKey()).getIds()) {
                if (needComma) {
                    sb.append(", ");
                }
                needComma = true;
                sb.append("" + id);
            }
            writer.writeAttribute("ids", sb.toString());
        } else if (constraint.getKey() instanceof PathConstraintMultiValue) {
            // Includes PathConstraintRange, which is serialised in the exact same manner.
            writer.writeAttribute("op", "" + constraint.getKey().getOp());

            for (String value : ((PathConstraintMultiValue) constraint.getKey()).getValues()) {
                if (value == null) {
                    writer.writeStartElement("nullValue");
                    writer.writeEndElement();
                } else {
                    if (!value.equals(value.trim())) {
                        throw new XMLStreamException("Value in MultiValue starts or ends with "
                                + "whitespace - this query cannot be represented in XML");
                    }
                    writer.writeStartElement("value");
                    writer.writeCharacters(value);
                    writer.writeEndElement();
                }
            }
        } else if (constraint.getKey() instanceof PathConstraintLoop) {
            writer.writeAttribute("op", "" + constraint.getKey().getOp());
            writer.writeAttribute("loopPath", ((PathConstraintLoop) constraint.getKey()).getLoopPath());
        } else if (constraint.getKey() instanceof PathConstraintLookup) {
            writer.writeAttribute("op", "" + constraint.getKey().getOp());
            writer.writeAttribute("value", ((PathConstraintLookup) constraint.getKey()).getValue());
            String extraValue = ((PathConstraintLookup) constraint.getKey()).getExtraValue();
            if (extraValue != null) {
                writer.writeAttribute("extraValue", extraValue);
            }
        } else {
            throw new IllegalStateException(
                    "Unrecognised constraint type " + constraint.getKey().getClass().getName());
        }
        if (!emptyElement) {
            writer.writeEndElement();
        }
    }
}