Example usage for javax.xml.stream XMLStreamWriter writeCharacters

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

Introduction

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

Prototype

public void writeCharacters(String text) throws XMLStreamException;

Source Link

Document

Write text to the output

Usage

From source file:org.sfs.nodes.compute.container.GetContainer.java

@Override
public void handle(final SfsRequest httpServerRequest) {

    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();
    aVoid().flatMap(new Authenticate(httpServerRequest))
            .flatMap(new ValidateActionAuthenticated(httpServerRequest))
            .map(aVoid -> fromSfsRequest(httpServerRequest)).map(new ValidateContainerPath())
            .flatMap(new LoadAccountAndContainer(vertxContext))
            .flatMap(new ValidateActionContainerListObjects(httpServerRequest)).flatMap(persistentContainer -> {

                HttpServerResponse httpServerResponse = httpServerRequest.response();

                MultiMap queryParams = httpServerRequest.params();
                MultiMap headerParams = httpServerRequest.headers();

                String format = queryParams.get(FORMAT);
                String accept = headerParams.get(ACCEPT);

                MediaType parsedAccept = null;

                if (equalsIgnoreCase("xml", format)) {
                    parsedAccept = APPLICATION_XML_UTF_8;
                } else if (equalsIgnoreCase("json", format)) {
                    parsedAccept = JSON_UTF_8;
                }/*from w w  w.  j av a 2  s .com*/

                if (parsedAccept == null) {
                    if (!isNullOrEmpty(accept)) {
                        parsedAccept = parse(accept);
                    }
                }

                if (parsedAccept == null || (!PLAIN_TEXT_UTF_8.is(parsedAccept)
                        && !APPLICATION_XML_UTF_8.is(parsedAccept) && !JSON_UTF_8.equals(parsedAccept))) {
                    parsedAccept = PLAIN_TEXT_UTF_8;
                }

                Observable<Optional<ContainerStats>> oContainerStats;
                boolean hasPrefix = !Strings.isNullOrEmpty(queryParams.get(SfsHttpQueryParams.PREFIX));
                if (hasPrefix) {
                    oContainerStats = just(persistentContainer)
                            .flatMap(new LoadContainerStats(httpServerRequest.vertxContext()))
                            .map(Optional::of);
                } else {
                    oContainerStats = Defer.just(Optional.<ContainerStats>absent());
                }

                Observable<ObjectList> oObjectListing = just(persistentContainer)
                        .flatMap(new ListObjects(httpServerRequest));

                MediaType finalParsedAccept = parsedAccept;
                return combineSinglesDelayError(oContainerStats, oObjectListing,
                        (containerStats, objectList) -> {

                            if (containerStats.isPresent()) {

                                Metadata metadata = persistentContainer.getMetadata();

                                for (String key : metadata.keySet()) {
                                    SortedSet<String> values = metadata.get(key);
                                    if (values != null && !values.isEmpty()) {
                                        httpServerResponse.putHeader(
                                                format("%s%s", X_ADD_CONTAINER_META_PREFIX, key), values);
                                    }
                                }

                                httpServerResponse.putHeader(X_CONTAINER_OBJECT_COUNT,
                                        valueOf(containerStats.get().getObjectCount()));
                                httpServerResponse.putHeader(X_CONTAINER_BYTES_USED,
                                        BigDecimal.valueOf(containerStats.get().getBytesUsed())
                                                .setScale(0, ROUND_HALF_UP).toString());
                            }

                            BufferOutputStream bufferOutputStream = new BufferOutputStream();

                            if (JSON_UTF_8.is(finalParsedAccept)) {

                                try {
                                    JsonFactory jsonFactory = vertxContext.verticle().jsonFactory();
                                    JsonGenerator jg = jsonFactory.createGenerator(bufferOutputStream, UTF8);
                                    jg.writeStartArray();

                                    for (ListedObject listedObject : ordered(objectList.getObjects())) {

                                        jg.writeStartObject();
                                        jg.writeStringField("hash",
                                                base16().lowerCase().encode(listedObject.getEtag()));
                                        jg.writeStringField("last_modified",
                                                toDateTimeString(listedObject.getLastModified()));
                                        jg.writeNumberField("bytes", listedObject.getLength());
                                        jg.writeStringField("content_type", listedObject.getContentType());
                                        jg.writeStringField("name", listedObject.getName());
                                        jg.writeEndObject();
                                    }

                                    jg.writeEndArray();
                                    jg.close();
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }

                            } else if (APPLICATION_XML_UTF_8.is(finalParsedAccept)) {

                                String charset = UTF_8.toString();
                                XMLStreamWriter writer = null;
                                try {
                                    writer = newFactory().createXMLStreamWriter(bufferOutputStream, charset);

                                    writer.writeStartDocument(charset, "1.0");

                                    writer.writeStartElement("container");

                                    writer.writeAttribute("name",
                                            fromPaths(persistentContainer.getId()).containerName().get());

                                    for (ListedObject listedObject : ordered(objectList.getObjects())) {

                                        writer.writeStartElement("object");

                                        writer.writeStartElement("name");
                                        writer.writeCharacters(listedObject.getName());
                                        writer.writeEndElement();

                                        writer.writeStartElement("hash");
                                        writer.writeCharacters(
                                                base16().lowerCase().encode(listedObject.getEtag()));
                                        writer.writeEndElement();

                                        writer.writeStartElement("bytes");
                                        writer.writeCharacters(valueOf(listedObject.getLength()));
                                        writer.writeEndElement();

                                        writer.writeStartElement("content_type");
                                        writer.writeCharacters(listedObject.getContentType());
                                        writer.writeEndElement();

                                        writer.writeStartElement("last_modified");
                                        writer.writeCharacters(
                                                toDateTimeString(listedObject.getLastModified()));
                                        writer.writeEndElement();

                                        writer.writeEndElement();
                                    }

                                    writer.writeEndElement();

                                    writer.writeEndDocument();

                                } catch (XMLStreamException e) {
                                    throw new RuntimeException(e);
                                } finally {
                                    try {
                                        if (writer != null) {
                                            writer.close();
                                        }
                                    } catch (XMLStreamException e) {
                                        LOGGER.warn(e.getLocalizedMessage(), e);
                                    }
                                }

                            } else {
                                String charset = UTF_8.toString();
                                try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                                        bufferOutputStream, charset)) {
                                    for (ListedObject listedObject : ordered(objectList.getObjects())) {
                                        outputStreamWriter.write(listedObject.getName());
                                        outputStreamWriter.write("\n");
                                    }
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                            objectList.clear();
                            return bufferOutputStream;
                        }).flatMap(bufferOutputStream -> {
                            Buffer buffer = bufferOutputStream.toBuffer();
                            httpServerResponse.putHeader(HttpHeaders.CONTENT_TYPE, finalParsedAccept.toString())
                                    .putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(buffer.length()));
                            return AsyncIO.append(buffer, httpServerRequest.response());
                        });
            }).single().subscribe(new ConnectionCloseTerminus<Void>(httpServerRequest) {
                @Override
                public void onNext(Void aVoid) {

                }
            }

    );

}

From source file:com.flexive.core.IMParser.java

/**
 * Parse an identify stdOut result (from in) and convert it to an XML content
 *
 * @param in identify response// ww  w .j  a  v a 2  s .  c o  m
 * @return XML content
 * @throws XMLStreamException on errors
 * @throws IOException        on errors
 */
public static String parse(InputStream in) throws XMLStreamException, IOException {
    StringWriter sw = new StringWriter(2000);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(sw);
    writer.writeStartDocument();

    int lastLevel = 0, level, lastNonValueLevel = 1;
    boolean valueEntry;
    String curr = null;
    String[] entry;
    try {
        while ((curr = br.readLine()) != null) {
            if (curr.indexOf(':') == -1 || curr.trim().length() == 0) {
                System.out.println("skipping: [" + curr + "]");
                continue; //ignore lines without ':'
            }
            level = getLevel(curr);
            curr = curr.trim();
            if (level == 0 && curr.startsWith("Image:")) {
                writer.writeStartElement("Image");
                entry = curr.split(": ");
                if (entry.length >= 2)
                    writer.writeAttribute("source", entry[1]);
                lastLevel = level;
                continue;
            }
            if (!(valueEntry = pNumeric.matcher(curr).matches())) {
                while (level < lastLevel--)
                    writer.writeEndElement();
                lastNonValueLevel = level;
            } else
                level = lastNonValueLevel + 1;
            if (curr.endsWith(":")) {
                writer.writeStartElement(cleanElement(curr.substring(0, curr.lastIndexOf(':'))));
                lastLevel = level + 1;
                continue;
            } else if (pColormap.matcher(curr).matches()) {
                writer.writeStartElement(cleanElement(curr.substring(0, curr.lastIndexOf(':'))));
                writer.writeAttribute("colors", curr.split(": ")[1].trim());
                lastLevel = level + 1;
                continue;
            }
            entry = curr.split(": ");
            if (entry.length == 2) {
                if (!valueEntry) {
                    writer.writeStartElement(cleanElement(entry[0]));
                    writer.writeCharacters(entry[1]);
                    writer.writeEndElement();
                } else {
                    writer.writeEmptyElement("value");
                    writer.writeAttribute("key", cleanElement(entry[0]));
                    writer.writeAttribute("data", entry[1]);
                    //                        writer.writeEndElement();
                }
            } else {
                //                    System.out.println("unknown line: "+curr);
            }
            lastLevel = level;
        }
    } catch (Exception e) {
        System.err.println("Error at [" + curr + "]:" + e.getMessage());
        e.printStackTrace();
    }

    writer.writeEndDocument();
    writer.flush();
    writer.close();
    return sw.getBuffer().toString();
}

From source file:com.flexive.shared.media.impl.FxMediaImageMagickEngine.java

/**
 * Parse an identify stdOut result (from in) and convert it to an XML content
 *
 * @param in identify response/*ww  w  . j  a  v  a 2  s .  c  o m*/
 * @return XML content
 * @throws XMLStreamException on errors
 * @throws IOException        on errors
 */
public static String parse(InputStream in) throws XMLStreamException, IOException {
    StringWriter sw = new StringWriter(2000);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(sw);
    writer.writeStartDocument();

    int lastLevel = 0, level, lastNonValueLevel = 1;
    boolean valueEntry;
    String curr = null;
    String[] entry;
    try {
        while ((curr = br.readLine()) != null) {
            level = getLevel(curr);
            if (level == 0 && curr.startsWith("Image:")) {
                writer.writeStartElement("Image");
                entry = curr.split(": ");
                if (entry.length >= 2)
                    writer.writeAttribute("source", entry[1]);
                lastLevel = level;
                continue;
            }
            if (!(valueEntry = pNumeric.matcher(curr).matches())) {
                while (level < lastLevel--)
                    writer.writeEndElement();
                lastNonValueLevel = level;
            } else
                level = lastNonValueLevel + 1;
            if (curr.endsWith(":")) {
                writer.writeStartElement(
                        curr.substring(0, curr.lastIndexOf(':')).trim().replaceAll("[ :]", "-"));
                lastLevel = level + 1;
                continue;
            } else if (pColormap.matcher(curr).matches()) {
                writer.writeStartElement(
                        curr.substring(0, curr.lastIndexOf(':')).trim().replaceAll("[ :]", "-"));
                writer.writeAttribute("colors", curr.split(": ")[1].trim());
                lastLevel = level + 1;
                continue;
            }
            entry = curr.split(": ");
            if (entry.length == 2) {
                if (!valueEntry) {
                    writer.writeStartElement(entry[0].trim().replaceAll("[ :]", "-"));
                    writer.writeCharacters(entry[1]);
                    writer.writeEndElement();
                } else {
                    writer.writeEmptyElement("value");
                    writer.writeAttribute("key", entry[0].trim().replaceAll("[ :]", "-"));
                    writer.writeAttribute("data", entry[1]);
                    //                        writer.writeEndElement();
                }
            } else {
                //                    System.out.println("unknown line: "+curr);
            }
            lastLevel = level;
        }
    } catch (Exception e) {
        LOG.error("Error at [" + curr + "]:" + e.getMessage(), e);
    }
    writer.writeEndDocument();
    writer.flush();
    writer.close();
    return sw.getBuffer().toString();
}

From source file:ca.uhn.fhir.parser.XmlParser.java

private void writeOptionalTagWithTextNode(XMLStreamWriter theEventWriter, String theTagName,
        InstantDt theInstantDt) throws XMLStreamException {
    if (theInstantDt.getValue() != null) {
        theEventWriter.writeStartElement(theTagName);
        theEventWriter.writeCharacters(theInstantDt.getValueAsString());
        theEventWriter.writeEndElement();
    }/*from   w w  w  .java 2 s  .c  o  m*/
}

From source file:ca.uhn.fhir.parser.XmlParser.java

private void writeTagWithTextNode(XMLStreamWriter theEventWriter, String theElementName, IdDt theIdDt)
        throws XMLStreamException {
    theEventWriter.writeStartElement(theElementName);
    if (StringUtils.isNotBlank(theIdDt.getValue())) {
        theEventWriter.writeCharacters(theIdDt.getValue());
    }//from w ww. j  ava2s.  c om
    theEventWriter.writeEndElement();
}

From source file:ca.uhn.fhir.parser.XmlParser.java

private void writeTagWithTextNode(XMLStreamWriter theEventWriter, String theElementName, StringDt theStringDt)
        throws XMLStreamException {
    theEventWriter.writeStartElement(theElementName);
    if (StringUtils.isNotBlank(theStringDt.getValue())) {
        theEventWriter.writeCharacters(theStringDt.getValue());
    }/* w w w  . jav  a2s  .co m*/
    theEventWriter.writeEndElement();
}

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) {/*from w w w.  j  a  v  a  2 s  .c  o  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();
}

From source file:ca.uhn.fhir.parser.XmlParser.java

private void writeOptionalTagWithTextNode(XMLStreamWriter theEventWriter, String theElementName,
        StringDt theTextValue) throws XMLStreamException {
    if (StringUtils.isNotBlank(theTextValue.getValue())) {
        theEventWriter.writeStartElement(theElementName);
        theEventWriter.writeCharacters(theTextValue.getValue());
        theEventWriter.writeEndElement();
    }//from w  ww  .  j a v  a  2 s  . c  o m
}

From source file:de.shadowhunt.subversion.internal.PropertiesUpdateOperation.java

@Override
protected HttpUriRequest createRequest() {
    final URI uri = URIUtils.createURI(repository, resource);
    final DavTemplateRequest request = new DavTemplateRequest("PROPPATCH", uri);

    if (lockToken != null) {
        request.addHeader("If", "<" + uri + "> (<" + lockToken + ">)");
    }/* w ww . j  a v  a 2s  .  c  o m*/

    final Writer body = new StringBuilderWriter();
    try {
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("propertyupdate");
        writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE);
        writer.setPrefix(XmlConstants.SUBVERSION_CUSTOM_PREFIX, XmlConstants.SUBVERSION_CUSTOM_NAMESPACE);
        writer.writeNamespace(XmlConstants.SUBVERSION_CUSTOM_PREFIX, XmlConstants.SUBVERSION_CUSTOM_NAMESPACE);
        writer.setPrefix(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE);
        writer.writeNamespace(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE);
        writer.setPrefix(XmlConstants.SUBVERSION_SVN_PREFIX, XmlConstants.SUBVERSION_SVN_NAMESPACE);
        writer.writeNamespace(XmlConstants.SUBVERSION_SVN_PREFIX, XmlConstants.SUBVERSION_SVN_NAMESPACE);
        writer.writeStartElement(type.action);
        writer.writeStartElement("prop");
        for (final ResourceProperty property : properties) {
            final String prefix = property.getType().getPrefix();
            if (type == Type.SET) {
                writer.writeStartElement(prefix, ResourcePropertyUtils.escapedKeyNameXml(property.getName()));
                writer.writeCharacters(property.getValue());
                writer.writeEndElement();
            } else {
                writer.writeEmptyElement(prefix, property.getName());
            }
        }
        writer.writeEndElement(); // prop
        writer.writeEndElement(); // set || delete
        writer.writeEndElement(); // propertyupdate
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    final String bodyWithMakers = body.toString();
    final String bodyWithoutMakers = ResourcePropertyUtils.filterMarker(bodyWithMakers);
    request.setEntity(new StringEntity(bodyWithoutMakers, CONTENT_TYPE_XML));
    return request;
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private static void writeSimpleElement(XMLStreamWriter xml, String elementName, String characters)
        throws XMLStreamException {
    xml.writeStartElement(elementName);/*from   www .j  a va 2  s  .com*/
    xml.writeCharacters(characters);
    xml.writeEndElement();
}