Example usage for javax.xml.stream XMLStreamWriter writeStartElement

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

Introduction

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

Prototype

public void writeStartElement(String localName) throws XMLStreamException;

Source Link

Document

Writes a start tag to the output.

Usage

From source file:com.concursive.connect.web.modules.api.services.BackupService.java

private void save(XMLStreamWriter writer, DataRecord record, String recordId, Object object,
        PacketContext context) throws Exception {
    // Data record
    writer.writeCharacters("  ");
    writer.writeStartElement("dataRecord");
    writer.writeAttribute("name", record.getName());
    writer.writeAttribute("id", recordId);
    writer.writeCharacters(System.getProperty("line.separator"));
    // Data fields
    for (DataField thisField : record) {
        writer.writeCharacters("    ");
        writer.writeStartElement(thisField.getName());
        if (thisField.getValue() != null) {
            if (StringUtils.countLines(thisField.getValue()) > 1) {
                writer.writeCData(thisField.getValue());
            } else {
                writer.writeCharacters(thisField.getValue());
            }/*from w  ww  . j a  v a  2s  . com*/
        } else {
            writer.writeCharacters(DataRecord.NULL);
        }
        writer.writeEndElement();
        writer.writeCharacters(System.getProperty("line.separator"));
    }

    // If this is a file, stream it too
    if (object instanceof FileItem) {
        // Find the file in the filesystem
        File file = new File(context.getBaseFilePath()
                + DateUtils.getDatePath(record.getValueAsTimestamp("modified")) + record.getValue("filename"));
        if (!file.exists()) {
            LOG.error("File not found: " + file.getAbsolutePath());
        } else {
            // If there is a fileAttachment, then attach it as base64
            writer.writeCharacters("    ");
            writer.writeStartElement("fileAttachment");
            // Convert to base64 and append
            writer.writeCData(new String(Base64.encodeBase64(FileUtils.getBytesFromFile(file), true)));
            // Close the element
            writer.writeEndElement();
            writer.writeCharacters(System.getProperty("line.separator"));
        }
    }

    // Close the record
    writer.writeCharacters("  ");
    writer.writeEndElement();
    writer.writeCharacters(System.getProperty("line.separator"));
}

From source file:XMLWriteTest.java

/**
 * Writers an SVG document of the current drawing.
 * @param writer the document destination
 *//*from   w  w w.j a v a  2 s .  c  o  m*/
public void writeDocument(XMLStreamWriter writer) throws XMLStreamException {
    writer.writeStartDocument();
    writer.writeDTD("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 20000802//EN\" "
            + "\"http://www.w3.org/TR/2000/CR-SVG-20000802/DTD/svg-20000802.dtd\">");
    writer.writeStartElement("svg");
    writer.writeAttribute("width", "" + getWidth());
    writer.writeAttribute("height", "" + getHeight());
    for (int i = 0; i < rects.size(); i++) {
        Color c = colors.get(i);
        Rectangle2D r = rects.get(i);
        writer.writeEmptyElement("rect");
        writer.writeAttribute("x", "" + r.getX());
        writer.writeAttribute("y", "" + r.getY());
        writer.writeAttribute("width", "" + r.getWidth());
        writer.writeAttribute("height", "" + r.getHeight());
        writer.writeAttribute("fill", colorToString(c));
    }
    writer.writeEndDocument(); // closes svg element
}

From source file:com.concursive.connect.web.modules.api.services.BackupService.java

public boolean process(TransactionItem transactionItem, Connection db) throws Exception {

    LOG.debug("Backup requested...");

    // TODO: Fix cyclical/endless backups; need to keep an array of ids already archived
    // TODO: Fix if lookup value is -1, then a lookup is not needed

    DataRecordFactory factory = DataRecordFactory.INSTANCE;

    // Override the default response packet so that the returned data records
    // can be replayed using the RestoreService; stream the output
    PacketContext packetContext = transactionItem.getPacketContext();
    packetContext.setReturnType(PacketContext.RETURN_DATARECORDS);

    // Start with the original record(s) being backed up
    LOG.debug("Performing buildList query");
    Object object = transactionItem.getObject();
    if (object instanceof java.util.AbstractList || object instanceof java.util.AbstractMap) {
        Object result = TransactionItem.doExecute(transactionItem.getObject(), db, TransactionItem.SELECT,
                packetContext, "buildList");
        // TODO: check result
    } else {//from   w  ww .jav  a 2s  .c  o  m
        Object newObject = ObjectUtils.constructObject(object.getClass(), db, ObjectUtils.getParamAsInt(object,
                factory.retrieveUniqueField(transactionItem.getName() + "List")));
        transactionItem.setObject(newObject);
    }

    // Start backup recursion...
    //   Consider lower-memory options to stream records without holding in memory
    //   option 1: use pagedList to get x record(s) at a time
    //   option 2: consider queue for limiting backup requests and asynchronous backups

    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    OutputStream outputStream = null;
    if (packetContext.getOutputStream() == null) {
        outputStream = packetContext.getResponse().getOutputStream();
    } else {
        outputStream = packetContext.getOutputStream();
    }
    XMLStreamWriter writer = outputFactory.createXMLStreamWriter(outputStream, "utf-8");
    writer.writeStartDocument();
    writer.writeCharacters(System.getProperty("line.separator"));
    writer.writeStartElement("concursive");
    writer.writeCharacters(System.getProperty("line.separator"));

    ArrayList<String> addedRecords = new ArrayList<String>();
    addRecords(writer, transactionItem.getObject(), transactionItem, packetContext, db, addedRecords);
    writer.writeEndElement();
    writer.writeCharacters(System.getProperty("line.separator"));
    writer.flush();
    writer.close();

    return true;
}

From source file:com.marklogic.client.impl.CombinedQueryBuilderImpl.java

private String makeXMLCombinedQuery(CombinedQueryDefinitionImpl qdef) {
    try {/*from   ww w .  ja  va2 s.  c  o m*/
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String qtext = qdef.qtext;
        StructuredQueryDefinition structuredQuery = qdef.structuredQuery;
        RawQueryDefinition rawQuery = qdef.rawQuery;
        QueryOptionsWriteHandle options = qdef.options;
        String sparql = qdef.sparql;
        if (rawQuery != null && rawQuery instanceof RawCombinedQueryDefinition) {
            CombinedQueryDefinitionImpl combinedQdef = parseCombinedQuery(
                    (RawCombinedQueryDefinition) rawQuery);
            rawQuery = combinedQdef.rawQuery;
            if (qtext == null)
                qtext = combinedQdef.qtext;
            if (options == null)
                options = combinedQdef.options;
            if (sparql == null)
                sparql = combinedQdef.sparql;
        }

        XMLStreamWriter serializer = makeXMLSerializer(out);

        serializer.writeStartDocument();
        serializer.writeStartElement("search");
        if (qtext != null) {
            serializer.writeStartElement("qtext");
            serializer.writeCharacters(qtext);
            serializer.writeEndElement();
        } else {
            serializer.writeCharacters("");
        }
        if (sparql != null) {
            serializer.writeStartElement("sparql");
            serializer.writeCharacters(sparql);
            serializer.writeEndElement();
        }
        serializer.flush();
        String structure = "";
        if (structuredQuery != null)
            structure = structuredQuery.serialize();
        if (rawQuery != null)
            structure = HandleAccessor.contentAsString(rawQuery.getHandle());
        out.write(structure.getBytes("UTF-8"));
        out.flush();
        if (options != null) {
            HandleImplementation handleBase = HandleAccessor.as(options);
            Object value = handleBase.sendContent();
            if (value instanceof OutputStreamSender) {
                ((OutputStreamSender) value).write(out);
            } else {
                out.write(HandleAccessor.contentAsString(options).getBytes("UTF-8"));
            }
            out.flush();
        }

        serializer.writeEndElement();
        serializer.writeEndDocument();
        serializer.flush();
        serializer.close();
        return out.toString("UTF-8");
    } catch (Exception e) {
        throw new MarkLogicIOException(e);
    }
}

From source file:com.norconex.collector.http.delay.impl.DefaultDelayResolver.java

@Override
public void saveToXML(Writer out) throws IOException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {/*from  www . j  a  v  a 2s. c  o  m*/
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);
        writer.writeStartElement("delay");
        writer.writeAttribute("class", getClass().getCanonicalName());
        writer.writeAttribute("default", Long.toString(defaultDelay));
        writer.writeAttribute("scope", scope);
        writer.writeAttribute("ignoreRobotsCrawlDelay", Boolean.toString(ignoreRobotsCrawlDelay));

        for (DelaySchedule schedule : schedules) {
            writer.writeStartElement("schedule");
            if (schedule.getDayOfWeekRange() != null) {
                writer.writeAttribute("dayOfWeek", "from " + schedule.getDayOfWeekRange().getMinimum() + " to "
                        + schedule.getDayOfWeekRange().getMaximum());
            }
            if (schedule.getDayOfMonthRange() != null) {
                writer.writeAttribute("dayOfMonth", "from " + schedule.getDayOfMonthRange().getMinimum()
                        + " to " + schedule.getDayOfMonthRange().getMaximum());
            }
            if (schedule.getTimeRange() != null) {
                writer.writeAttribute("time", "from " + schedule.getTimeRange().getLeft().toString("HH:MM")
                        + " to " + schedule.getTimeRange().getRight().toString("HH:MM"));
            }
            writer.writeEndElement();
        }
        writer.writeEndElement();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}

From source file:com.norconex.collector.http.client.impl.DefaultHttpClientInitializer.java

private void writeSimpleElement(XMLStreamWriter writer, String name, String value) throws XMLStreamException {
    writer.writeStartElement(name);
    writer.writeCharacters(value);//from   w  w  w . j  ava  2 s .c om
    writer.writeEndElement();
}

From source file:com.github.fritaly.graphml4j.LabelStyle.java

void writeTo(XMLStreamWriter writer, String label) throws XMLStreamException {
    Validate.notNull(writer, "The given stream writer is null");

    // y:NodeLabel
    writer.writeStartElement("y:NodeLabel");
    writer.writeAttribute("alignement", textAlignment.getValue());
    writer.writeAttribute("autoSizePolicy", sizePolicy.getValue());
    writer.writeAttribute("fontFamily", fontFamily);
    writer.writeAttribute("fontSize", Integer.toString(fontSize));
    writer.writeAttribute("fontStyle", fontStyle.getValue());
    writer.writeAttribute("modelName", placement.getValue());
    writer.writeAttribute("modelPosition", position.getValue());

    if (borderDistance != 0.0f) {
        writer.writeAttribute("borderDistance", String.format("%.1f", borderDistance));
    }/*from  ww  w . ja  v  a 2s  .com*/
    if (rotationAngle != 0.0f) {
        writer.writeAttribute("rotationAngle", String.format("%.1f", rotationAngle));
    }

    if (backgroundColor != null) {
        writer.writeAttribute("backgroundColor", Utils.encode(backgroundColor));
    } else {
        writer.writeAttribute("hasBackgroundColor", "false");
    }
    if (lineColor != null) {
        writer.writeAttribute("lineColor", Utils.encode(lineColor));
    } else {
        writer.writeAttribute("hasLineColor", "false");
    }
    if (hasInsets()) {
        writer.writeAttribute("bottomInset", Integer.toString(bottomInset));
        writer.writeAttribute("topInset", Integer.toString(topInset));
        writer.writeAttribute("leftInset", Integer.toString(leftInset));
        writer.writeAttribute("rightInset", Integer.toString(rightInset));
    }

    writer.writeAttribute("textColor", Utils.encode(textColor));
    writer.writeAttribute("visible", Boolean.toString(visible));

    if (underlinedText) {
        writer.writeAttribute("underlinedText", Boolean.toString(underlinedText));
    }

    writer.writeCharacters(label);
    writer.writeEndElement(); // </y:NodeLabel>
}

From source file:com.hazelcast.simulator.probes.probes.impl.HdrLatencyDistributionResult.java

@Override
public void writeTo(XMLStreamWriter writer) {
    Histogram tmp = histogram.copy();//  ww  w  .ja  v a  2 s. c  o m
    int size = tmp.getNeededByteBufferCapacity();
    ByteBuffer byteBuffer = ByteBuffer.allocate(size);
    int bytesWritten = tmp.encodeIntoCompressedByteBuffer(byteBuffer);
    byteBuffer.rewind();
    byteBuffer.limit(bytesWritten);
    String encodedData = Base64.encodeBase64String(byteBuffer.array());
    try {
        writer.writeStartElement(ProbesResultXmlElements.HDR_LATENCY_DATA.getName());
        writer.writeCData(encodedData);
        writer.writeEndElement();
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.norconex.collector.http.client.impl.DefaultHttpClientInitializer.java

@Override
public void saveToXML(Writer out) throws IOException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {/*from  w w w .  j  a  va 2 s . c  om*/
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);
        writer.writeStartElement("httpClientInitializer");
        writer.writeAttribute("class", getClass().getCanonicalName());

        writeSimpleElement(writer, "cookiesDisabled", Boolean.toString(cookiesDisabled));
        writeSimpleElement(writer, "userAgent", userAgent);
        writeSimpleElement(writer, "authMethod", authMethod);
        writeSimpleElement(writer, "authUsername", authUsername);
        writeSimpleElement(writer, "authPassword", authPassword);
        writeSimpleElement(writer, "authUsernameField", authUsernameField);
        writeSimpleElement(writer, "authPasswordField", authPasswordField);
        writeSimpleElement(writer, "authURL", authURL);
        writeSimpleElement(writer, "authHostname", authHostname);
        writeSimpleElement(writer, "authPort", Integer.toString(authPort));
        writeSimpleElement(writer, "authRealm", authRealm);
        writeSimpleElement(writer, "proxyHost", proxyHost);
        writeSimpleElement(writer, "proxyPort", Integer.toString(proxyPort));
        writeSimpleElement(writer, "proxyUsername", proxyUsername);
        writeSimpleElement(writer, "proxyPassword", proxyPassword);
        writeSimpleElement(writer, "proxyRealm", proxyRealm);
        writer.writeEndElement();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}

From source file:com.amalto.core.storage.services.SystemModels.java

@POST
@Path("{model}")
@ApiOperation("Get impacts of the model update with the new XSD provided as request content. Changes will not be performed !")
public String analyzeModelChange(@ApiParam("Model name") @PathParam("model") String modelName,
        @ApiParam("Optional language to get localized result") @QueryParam("lang") String locale,
        InputStream dataModel) {/* w w  w.j a  va 2  s .co  m*/
    Map<ImpactAnalyzer.Impact, List<Change>> impacts;
    List<String> typeNamesToDrop = new ArrayList<String>();
    if (!isSystemStorageAvailable()) {
        impacts = new EnumMap<>(ImpactAnalyzer.Impact.class);
        for (ImpactAnalyzer.Impact impact : impacts.keySet()) {
            impacts.put(impact, Collections.<Change>emptyList());
        }
    } else {
        StorageAdmin storageAdmin = ServerContext.INSTANCE.get().getStorageAdmin();
        Storage storage = storageAdmin.get(modelName, StorageType.MASTER);
        if (storage == null) {
            LOGGER.warn(
                    "Container '" + modelName + "' does not exist. Skip impact analyzing for model change."); //$NON-NLS-1$//$NON-NLS-2$
            return StringUtils.EMPTY;
        }

        if (storage.getType() == StorageType.SYSTEM) {
            LOGGER.debug("No model update for system storage"); //$NON-NLS-1$
            return StringUtils.EMPTY;
        }
        // Compare new data model with existing data model
        MetadataRepository previousRepository = storage.getMetadataRepository();
        MetadataRepository newRepository = new MetadataRepository();
        newRepository.load(dataModel);
        Compare.DiffResults diffResults = Compare.compare(previousRepository, newRepository);
        // Analyzes impacts on the select storage
        impacts = storage.getImpactAnalyzer().analyzeImpacts(diffResults);
        List<ComplexTypeMetadata> typesToDrop = storage.findSortedTypesToDrop(diffResults, true);
        Set<String> tableNamesToDrop = storage.findTablesToDrop(typesToDrop);
        for (String tableName : tableNamesToDrop) {
            if (previousRepository.getInstantiableTypes()
                    .contains(previousRepository.getComplexType(tableName))) {
                typeNamesToDrop.add(tableName);
            }
        }
    }
    // Serialize results to XML
    StringWriter resultAsXml = new StringWriter();
    XMLStreamWriter writer = null;
    try {
        writer = XMLOutputFactory.newFactory().createXMLStreamWriter(resultAsXml);
        writer.writeStartElement("result"); //$NON-NLS-1$
        {
            for (Map.Entry<ImpactAnalyzer.Impact, List<Change>> category : impacts.entrySet()) {
                writer.writeStartElement(category.getKey().name().toLowerCase());
                List<Change> changes = category.getValue();
                for (Change change : changes) {
                    writer.writeStartElement("change"); //$NON-NLS-1$
                    {
                        writer.writeStartElement("message"); //$NON-NLS-1$
                        {
                            Locale messageLocale;
                            if (StringUtils.isEmpty(locale)) {
                                messageLocale = Locale.getDefault();
                            } else {
                                messageLocale = new Locale(locale);
                            }
                            writer.writeCharacters(change.getMessage(messageLocale));
                        }
                        writer.writeEndElement();
                    }
                    writer.writeEndElement();
                }
                writer.writeEndElement();
            }
            writer.writeStartElement("entitiesToDrop"); //$NON-NLS-1$
            for (String typeName : typeNamesToDrop) {
                writer.writeStartElement("entity"); //$NON-NLS-1$
                writer.writeCharacters(typeName);
                writer.writeEndElement();
            }
            writer.writeEndElement();
        }
        writer.writeEndElement();
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    } finally {
        if (writer != null) {
            try {
                writer.flush();
            } catch (XMLStreamException e) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Could not flush XML content.", e); //$NON-NLS-1$
                }
            }
        }
    }
    return resultAsXml.toString();
}