Example usage for javax.xml.stream XMLOutputFactory newInstance

List of usage examples for javax.xml.stream XMLOutputFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.stream XMLOutputFactory newInstance.

Prototype

public static XMLOutputFactory newInstance() throws FactoryConfigurationError 

Source Link

Document

Creates a new instance of the factory in exactly the same manner as the #newFactory() method.

Usage

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Tests the {@link CastorMarshaller#marshal(Object, XMLEventWriter)} method when jaxbElement is null. </p> {@link
 * IllegalArgumentException} is expected.
 *
 * @throws Exception if any error occurs during test
 *///from   ww  w.j  a  v a 2  s . co m
@Test(expected = IllegalArgumentException.class)
public void testMarshallXMLEventWriterNull1() throws Exception {

    StringWriter writer = new StringWriter();
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    marshaller.marshal(null, outputFactory.createXMLEventWriter(writer));
}

From source file:eionet.cr.util.odp.ODPDatasetsPacker.java

/**
 * Writes a ZIP archive entry file for the given indicator.
 *
 * @param zipOutput ZIP output where the entry goes into.
 * @param indSubject The indicator whose for whom the entry is written.
 * @param index 0-based index of the indicator (in the indicator list received from dataabse) that is being written.
 *
 * @throws XMLStreamException Thrown by methods from the {@link XMLStreamWriter} that is used by called methods.
 *//*from www . j  a va  2s. c om*/
private void writeDatasetEntry(ZipArchiveOutputStream zipOutput, SubjectDTO indSubject, int index)
        throws XMLStreamException {

    // Prepare indicator URI.
    String uri = indSubject.getUri();

    // Prepare indicator skos:notation.
    String skosNotation = indSubject.getObjectValue(Predicates.SKOS_NOTATION);
    if (StringUtils.isBlank(skosNotation)) {
        skosNotation = URIUtil.extractURILabel(uri);
    }

    // Prepare indicator skos:prefLabel.
    String skosPrefLabel = indSubject.getObjectValue(Predicates.SKOS_PREF_LABEL);
    if (StringUtils.isBlank(skosPrefLabel)) {
        skosPrefLabel = skosNotation;
    }

    // Prepare indicator skos:altLabel.
    String skosAltLabel = indSubject.getObjectValue(Predicates.SKOS_ALT_LABEL);
    if (StringUtils.isBlank(skosAltLabel)) {
        skosAltLabel = skosNotation;
    }

    // Prepare indicator description.
    String indicatorDescription = buildIndicatorDescription(indSubject);

    // Prepare issued date from the main dataset.
    String dctIssued = mainDstSubject.getObjectValue(Predicates.DCTERMS_ISSUED);

    // Prepare modification date from the main dataset.
    List<String> modifiedDates = mainDstSubject.getObjectValues(Predicates.DCTERMS_MODIFIED);
    String dctModified = StringUtils.EMPTY;
    if (CollectionUtils.isNotEmpty(modifiedDates)) {
        Collections.sort(modifiedDates);
        dctModified = modifiedDates.get(modifiedDates.size() - 1).trim();
    }
    if (StringUtils.isBlank(dctModified)) {
        dctModified = Util.virtuosoDateToString(new Date());
    }

    // Prepare the main dataset's identifier.
    String mainDstIdentifier = URIUtil.extractURILabel(mainDstSubject.getUri());
    String mainDstIdentifierForLinks = mainDstIdentifier.replace('-', '_');

    // Prepare download URLs.
    String csvDownloadUrl = "http://digital-agenda-data.eu/download/" + mainDstIdentifier + ".csv.zip";
    String ttlDownloadUrl = "http://digital-agenda-data.eu/download/" + mainDstIdentifier + ".ttl.zip";
    String codelistsDownloadUrl = "http://digital-agenda-data.eu/datasets/" + mainDstIdentifierForLinks
            + "/@@codelists";
    String dsdDownloadUrl = "http://digital-agenda-data.eu/datasets/" + mainDstIdentifierForLinks
            + "/@@structure";
    String observationsCsvDownloadUrl = buildIndicatorObservationsDownloadUrl(datasetUri, uri, "text/csv");
    String observationsRdfDownloadUrl = buildIndicatorObservationsDownloadUrl(datasetUri, uri,
            "application/rdf+xml");
    addLastModificationDate(csvDownloadUrl);
    addLastModificationDate(ttlDownloadUrl);

    // Prepare the main dataset's status.
    String datasetStatus = mainDstSubject.getObjectValue(Predicates.ADMS_STATUS);
    if (StringUtils.isBlank(datasetStatus)) {
        datasetStatus = "http://purl.org/adms/status/UnderDevelopment";
    }

    // Prepare STAX indenting writer based on a Java XMLStreamWriter that is based on the given zipped output.
    XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(zipOutput, ENCODING);
    IndentingXMLStreamWriter writer = new IndentingXMLStreamWriter(xmlWriter);

    // Start the XML document
    writer.writeStartDocument(ENCODING, "1.0");

    // Register all relevant namespaces.
    registerNamespaces(DATASET_FILE_NAMESPACES, writer);

    // Write root element start tag + default namespace
    writer.writeStartElement(Namespace.RDF.getUri(), "RDF");
    writer.writeDefaultNamespace(DEFAULT_NAMESPACE.getUri());

    // Write all other namespace prefixes.
    for (Namespace namespace : DATASET_FILE_NAMESPACES) {
        writer.writeNamespace(namespace.getPrefix(), namespace.getUri());
    }

    // Start the dataset tag.
    writer.writeStartElement(Namespace.DCAT.getUri(), "Dataset");
    writer.writeAttribute(Namespace.RDF.getUri(), "about", uri);

    // Write dct:title
    writer.writeStartElement(Namespace.DCT.getUri(), "title");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters(skosPrefLabel);
    writer.writeEndElement();

    // Write dct:alternative
    writer.writeStartElement(Namespace.DCT.getUri(), "alternative");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters(skosAltLabel);
    writer.writeEndElement();

    // Write dct:description
    writer.writeStartElement(Namespace.DCT.getUri(), "description");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters(indicatorDescription);
    writer.writeEndElement();

    // Write dct:identifier
    writer.writeStartElement(Namespace.DCT.getUri(), "identifier");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters(skosNotation);
    writer.writeEndElement();

    // Write ecodp:interoperabilityLevel
    writer.writeStartElement(Namespace.ECODP.getUri(), "interoperabilityLevel");
    writer.writeEmptyElement(Namespace.SKOS.getUri(), "Concept");
    writer.writeAttribute(Namespace.RDF.getUri(), "about",
            "http://open-data.europa.eu/kos/interoperability-level/Legal");
    writer.writeEndElement();

    // Write ecodp:datasetType
    writer.writeStartElement(Namespace.ECODP.getUri(), "datasetType");
    writer.writeEmptyElement(Namespace.SKOS.getUri(), "Concept");
    writer.writeAttribute(Namespace.RDF.getUri(), "about",
            "http://open-data.europa.eu/kos/dataset-type/Statistical");
    writer.writeEndElement();

    // Write ecodp:isDocumentedBy for the main dataset's visualisation page.
    writer.writeStartElement(Namespace.ECODP.getUri(), "isDocumentedBy");
    writer.writeAttribute(Namespace.RDF.getUri(), "parseType", "Resource");
    writer.writeStartElement(Namespace.ECODP.getUri(), "documentationType");
    writer.writeEmptyElement(Namespace.SKOS.getUri(), "Concept");
    writer.writeAttribute(Namespace.RDF.getUri(), "about",
            "http://open-data.europa.eu/kos/documentation-type/RelatedDocumentation");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.ECODP.getUri(), "accessURL");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "datatype",
            "http://www.w3.org/2001/XMLSchema#anyURI");
    writer.writeCharacters("http://digital-agenda-data.eu/charts/analyse-one-indicator-and-compare-countries#"
            + "chart={\"indicator-group\":\"any\",\"indicator\":\"" + skosNotation + "\"}");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCT.getUri(), "title");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("Dataset visualizations.");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCT.getUri(), "description");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters(
            "Dynamically generated visualizations (i.e. charts, diagrams) of the dataset contents.");
    writer.writeEndElement();
    writer.writeEndElement();

    // Write ecodp:isDocumentedBy for the main home page about the main dataset.
    writer.writeStartElement(Namespace.ECODP.getUri(), "isDocumentedBy");
    writer.writeAttribute(Namespace.RDF.getUri(), "parseType", "Resource");
    writer.writeStartElement(Namespace.ECODP.getUri(), "documentationType");
    writer.writeEmptyElement(Namespace.SKOS.getUri(), "Concept");
    writer.writeAttribute(Namespace.RDF.getUri(), "about",
            "http://open-data.europa.eu/kos/documentation-type/MainDocumentation");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.ECODP.getUri(), "accessURL");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "datatype",
            "http://www.w3.org/2001/XMLSchema#anyURI");
    writer.writeCharacters("http://digital-agenda-data.eu/datasets/" + mainDstIdentifierForLinks);
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCT.getUri(), "title");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("Parent dataset homepage.");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCT.getUri(), "description");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("Main information about metadata, structure, "
            + "links to downloads, used in the parent dataset this indicator comes from.");
    writer.writeEndElement();
    writer.writeEndElement();

    // Write ecodp:isDocumentedBy for the DSD download.
    writer.writeStartElement(Namespace.ECODP.getUri(), "isDocumentedBy");
    writer.writeAttribute(Namespace.RDF.getUri(), "parseType", "Resource");
    writer.writeStartElement(Namespace.ECODP.getUri(), "documentationType");
    writer.writeEmptyElement(Namespace.SKOS.getUri(), "Concept");
    writer.writeAttribute(Namespace.RDF.getUri(), "about",
            "http://open-data.europa.eu/kos/documentation-type/RelatedDocumentation");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.ECODP.getUri(), "accessURL");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "datatype",
            "http://www.w3.org/2001/XMLSchema#anyURI");
    writer.writeCharacters(dsdDownloadUrl);
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCT.getUri(), "title");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("Data Structrue Definition of the parent dataset.");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCT.getUri(), "description");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("RDF/XML formatted Data Structrue Definition of the parent dataset.");
    writer.writeEndElement();
    writer.writeEndElement();

    // Write ecodp:isDocumentedBy for the Codelists download.
    writer.writeStartElement(Namespace.ECODP.getUri(), "isDocumentedBy");
    writer.writeAttribute(Namespace.RDF.getUri(), "parseType", "Resource");
    writer.writeStartElement(Namespace.ECODP.getUri(), "documentationType");
    writer.writeEmptyElement(Namespace.SKOS.getUri(), "Concept");
    writer.writeAttribute(Namespace.RDF.getUri(), "about",
            "http://open-data.europa.eu/kos/documentation-type/RelatedDocumentation");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.ECODP.getUri(), "accessURL");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "datatype",
            "http://www.w3.org/2001/XMLSchema#anyURI");
    writer.writeCharacters(codelistsDownloadUrl);
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCT.getUri(), "title");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("Metadata codelists used in the parent dataset.");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCT.getUri(), "description");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters(
            "RDF/XML formatted codelists for metadata used in the parent dataset this indicator comes from.");
    writer.writeEndElement();
    writer.writeEndElement();

    // Write dcat:distribution for the SPARQL query that returns indicator observations in CSV format.
    writer.writeStartElement(Namespace.DCAT.getUri(), "distribution");
    writer.writeAttribute(Namespace.RDF.getUri(), "parseType", "Resource");
    writer.writeStartElement(Namespace.DCT.getUri(), "title");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("All available observations for the indicator, in CSV format.");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCAT.getUri(), "accessURL");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "datatype",
            "http://www.w3.org/2001/XMLSchema#anyURI");
    writer.writeCharacters(observationsCsvDownloadUrl);
    writer.writeEndElement();
    writer.writeEmptyElement(Namespace.RDF.getUri(), "type");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "resource",
            "http://www.w3.org/TR/vocab-dcat#Download");
    writer.writeStartElement(Namespace.ECODP.getUri(), "distributionFormat");
    writer.writeCharacters("text/csv");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCT.getUri(), "description");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("All indicator observations in CSV format. "
            + "A simple query that returns table-file having a flat structure, "
            + "with one row for each statistical observation and one column for each dimension or attribute.");
    writer.writeEndElement();
    writer.writeEndElement();

    // Write dcat:distribution for the SPARQL query that returns indicator observations in RDF format.
    writer.writeStartElement(Namespace.DCAT.getUri(), "distribution");
    writer.writeAttribute(Namespace.RDF.getUri(), "parseType", "Resource");
    writer.writeStartElement(Namespace.DCT.getUri(), "title");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("All available observations for the indicator, in RDF/XML format.");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCAT.getUri(), "accessURL");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "datatype",
            "http://www.w3.org/2001/XMLSchema#anyURI");
    writer.writeCharacters(observationsRdfDownloadUrl);
    writer.writeEndElement();
    writer.writeEmptyElement(Namespace.RDF.getUri(), "type");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "resource",
            "http://www.w3.org/TR/vocab-dcat#Download");
    writer.writeStartElement(Namespace.ECODP.getUri(), "distributionFormat");
    writer.writeCharacters("application/rdf+xml");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCT.getUri(), "description");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("All indicator observations in RDF/XML format. "
            + "A simple query that returns observations as triples in RDF/XML format.");
    writer.writeEndElement();
    writer.writeEndElement();

    // Write dcat:distribution for the SPARQL endpoint.
    writer.writeStartElement(Namespace.DCAT.getUri(), "distribution");
    writer.writeAttribute(Namespace.RDF.getUri(), "parseType", "Resource");
    writer.writeStartElement(Namespace.DCT.getUri(), "title");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("SPARQL endpoint of the entire parent dataset.");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCAT.getUri(), "accessURL");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "datatype",
            "http://www.w3.org/2001/XMLSchema#anyURI");
    writer.writeCharacters("http://digital-agenda-data.eu/data/sparql");
    writer.writeEndElement();
    writer.writeEmptyElement(Namespace.RDF.getUri(), "type");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "resource",
            "http://www.w3.org/TR/vocab-dcat#WebService");
    writer.writeStartElement(Namespace.ECODP.getUri(), "distributionFormat");
    writer.writeCharacters("webservice/sparql");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCT.getUri(), "description");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters(
            "SPARQL endpoint for querying and creating applications based on the most recent data.");
    writer.writeEndElement();
    writer.writeEndElement();

    // Write dcat:distribution for the CSV download link.
    writer.writeStartElement(Namespace.DCAT.getUri(), "distribution");
    writer.writeAttribute(Namespace.RDF.getUri(), "parseType", "Resource");
    writer.writeStartElement(Namespace.DCT.getUri(), "title");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("CSV download of the entire parent dataset.");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCAT.getUri(), "accessURL");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "datatype",
            "http://www.w3.org/2001/XMLSchema#anyURI");
    writer.writeCharacters(csvDownloadUrl);
    writer.writeEndElement();
    writer.writeEmptyElement(Namespace.RDF.getUri(), "type");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "resource",
            "http://www.w3.org/TR/vocab-dcat#Download");
    writer.writeStartElement(Namespace.ECODP.getUri(), "distributionFormat");
    writer.writeCharacters("text/csv");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCT.getUri(), "description");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("Zipped and CSV-formatted entire parent dataset: " + mainDstIdentifier);
    writer.writeEndElement();
    String lastModificationDate = getLastModificationDateString(csvDownloadUrl);
    if (StringUtils.isNotBlank(lastModificationDate)) {
        writer.writeStartElement(Namespace.DCT.getUri(), "modified");
        writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "datatype",
                "http://www.w3.org/2001/XMLSchema#dateTime");
        writer.writeCharacters(lastModificationDate);
        writer.writeEndElement();
    }
    writer.writeEndElement();

    // Write dcat:distribution for the TTL download link.
    writer.writeStartElement(Namespace.DCAT.getUri(), "distribution");
    writer.writeAttribute(Namespace.RDF.getUri(), "parseType", "Resource");
    writer.writeStartElement(Namespace.DCT.getUri(), "title");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("N3/Turtle download of the entire parent dataset.");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCAT.getUri(), "accessURL");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "datatype",
            "http://www.w3.org/2001/XMLSchema#anyURI");
    writer.writeCharacters(ttlDownloadUrl);
    writer.writeEndElement();
    writer.writeEmptyElement(Namespace.RDF.getUri(), "type");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "resource",
            "http://www.w3.org/TR/vocab-dcat#Download");
    writer.writeStartElement(Namespace.ECODP.getUri(), "distributionFormat");
    writer.writeCharacters("text/n3");
    writer.writeEndElement();
    writer.writeStartElement(Namespace.DCT.getUri(), "description");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("Zipped and N3-formatted entire parent dataset: " + mainDstIdentifier);
    writer.writeEndElement();
    lastModificationDate = getLastModificationDateString(ttlDownloadUrl);
    if (StringUtils.isNotBlank(lastModificationDate)) {
        writer.writeStartElement(Namespace.DCT.getUri(), "modified");
        writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "datatype",
                "http://www.w3.org/2001/XMLSchema#dateTime");
        writer.writeCharacters(lastModificationDate);
        writer.writeEndElement();
    }
    writer.writeEndElement();

    // Write reference areas.
    List<String> refAreas = indicatorToRefAreas.get(uri);
    if (CollectionUtils.isNotEmpty(refAreas)) {
        for (String refArea : refAreas) {

            String odpCountry = ODPCountryMappings.getMappingFor(refArea);
            if (StringUtils.isNotBlank(odpCountry)) {
                writer.writeStartElement(Namespace.DCT.getUri(), "spatial");
                writer.writeEmptyElement(Namespace.SKOS.getUri(), "Concept");
                writer.writeAttribute(Namespace.RDF.getUri(), "about", odpCountry);
                writer.writeEndElement();
            } else {
                LOGGER.info("Found no ODP mapping for " + refArea);
            }
        }
    }

    // Write dct:publisher
    writer.writeStartElement(Namespace.DCT.getUri(), "publisher");
    writer.writeEmptyElement(Namespace.SKOS.getUri(), "Concept");
    writer.writeAttribute(Namespace.RDF.getUri(), "about",
            "http://publications.europa.eu/resource/authority/corporate-body/CNECT");
    writer.writeEndElement();

    // Write ecodp:contactPoint
    writer.writeStartElement(Namespace.ECODP.getUri(), "contactPoint");
    writer.writeStartElement(Namespace.FOAF.getUri(), "agent");
    writer.writeAttribute(Namespace.RDF.getUri(), "about",
            "http://publications.europa.eu/resource/authority/corporate-body/CNECT/C4");
    writer.writeEmptyElement(Namespace.FOAF.getUri(), "mbox");
    writer.writeAttribute(Namespace.RDF.getUri(), "resource", "mailto:CNECT-F4@ec.europa.eu");
    writer.writeEmptyElement(Namespace.FOAF.getUri(), "workplaceHomepage");
    writer.writeAttribute(Namespace.RDF.getUri(), "resource", "http://digital-agenda-data.eu/");
    writer.writeStartElement(Namespace.FOAF.getUri(), "name");
    writer.writeAttribute(Namespace.XML.getPrefix(), Namespace.XML.getUri(), "lang", "en");
    writer.writeCharacters("DG CONNECT Unit F4 Knowledge Base");
    writer.writeEndElement();
    writer.writeEndElement();
    writer.writeEndElement();

    // Write dct:issued
    if (StringUtils.isNotEmpty(dctIssued)) {
        writer.writeStartElement(Namespace.DCT.getUri(), "issued");
        writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "datatype",
                "http://www.w3.org/2001/XMLSchema#dateTime");
        writer.writeCharacters(dctIssued);
        writer.writeEndElement();
    }

    // Write dct:modified (mandatory, so don't even check if empty)
    writer.writeStartElement(Namespace.DCT.getUri(), "modified");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "datatype",
            "http://www.w3.org/2001/XMLSchema#dateTime");
    writer.writeCharacters(dctModified);
    writer.writeEndElement();

    // Write dct:license
    writer.writeStartElement(Namespace.DCT.getUri(), "license");
    writer.writeEmptyElement(Namespace.SKOS.getUri(), "Concept");
    writer.writeAttribute(Namespace.RDF.getUri(), "about",
            "http://open-data.europa.eu/kos/licence/EuropeanCommission");
    writer.writeEndElement();

    // Write ecodp:datasetStatus
    writer.writeStartElement(Namespace.ECODP.getUri(), "datasetStatus");
    writer.writeEmptyElement(Namespace.SKOS.getUri(), "Concept");
    writer.writeAttribute(Namespace.RDF.getUri(), "about", StringUtils.replace(datasetStatus,
            "http://purl.org/adms/status/", "http://open-data.europa.eu/kos/dataset-status/"));
    writer.writeEndElement();

    // Write dct:language
    writer.writeStartElement(Namespace.DCT.getUri(), "language");
    writer.writeEmptyElement(Namespace.SKOS.getUri(), "Concept");
    writer.writeAttribute(Namespace.RDF.getUri(), "about",
            "http://publications.europa.eu/resource/authority/language/ENG");
    writer.writeEndElement();

    // Write ecodp:accrualPeriodicity
    writer.writeEmptyElement(Namespace.ECODP.getUri(), "accrualPeriodicity");
    writer.writeAttribute(Namespace.RDF.getPrefix(), Namespace.RDF.getUri(), "resource",
            "http://open-data.europa.eu/kos/accrual-periodicity/other");

    // Write dct:temporal
    Integer earliestObservationYear = indicatorYears.get(uri);
    if (earliestObservationYear != null && earliestObservationYear.intValue() > 0) {

        writer.writeStartElement(Namespace.DCT.getUri(), "temporal");
        writer.writeAttribute(Namespace.RDF.getUri(), "parseType", "Resource");
        writer.writeStartElement(Namespace.ECODP.getUri(), "periodStart");
        writer.writeCharacters(earliestObservationYear.toString());
        writer.writeEndElement();
        writer.writeEndElement();
    }

    // End the dataset tag.
    writer.writeEndElement();

    // End the root tag.
    writer.writeEndElement();

    // End the document
    writer.writeEndDocument();
}

From source file:com.norconex.committer.idol.IdolCommitter.java

/**
 * Commits the addition operations.//from   ww  w.  j a  va 2  s .  co m
 * @param addOperations additions
 */
public void dreAddData(List<IAddOperation> addOperations) {
    if (addOperations.isEmpty()) {
        return;
    }
    if (LOG.isInfoEnabled()) {
        LOG.info("Sending " + addOperations.size() + " documents for addition to " + createURL());
    }

    StringBuilder b = new StringBuilder();
    b.append(createURL());

    if (isCFS()) {
        b.append("action=ingest&adds=");
        StringWriter xml = new StringWriter();
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        try {
            XMLStreamWriter writer = factory.createXMLStreamWriter(xml);
            writer.writeStartElement("adds");
            buildCfsXmlBatchContent(writer, addOperations);
            writer.writeEndElement();
            writer.flush();
            writer.close();
            b.append(URLEncoder.encode(xml.toString(), CharEncoding.UTF_8));
        } catch (Exception e) {
            throw new CommitterException("Cannot create XML.", e);
        }
        postToIDOL(b.toString(), StringUtils.EMPTY);
    } else {
        b.append("DREADDDATA?");
        QueryString qs = new QueryString();
        for (String key : dreAddDataParams.keySet()) {
            qs.addString(key, dreAddDataParams.get(key));
        }
        String addURL = qs.applyOnURL(b.toString());
        String idxBatch = buildIdxBatchContent(addOperations);
        postToIDOL(addURL, idxBatch);
    }
    if (LOG.isInfoEnabled()) {
        LOG.debug("Done sending additions to " + createURL());
    }
}

From source file:com.liferay.portal.util.LocalizationImpl.java

public String removeLocalization(String xml, String key, String requestedLanguageId, boolean cdata,
        boolean localized) {

    if (Validator.isNull(xml)) {
        return StringPool.BLANK;
    }/*from   ww  w  .  ja v a  2 s .  co  m*/

    xml = _sanitizeXML(xml);

    String systemDefaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault());

    XMLStreamReader xmlStreamReader = null;
    XMLStreamWriter xmlStreamWriter = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        String availableLocales = StringPool.BLANK;
        String defaultLanguageId = StringPool.BLANK;

        // Read root node

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            availableLocales = xmlStreamReader.getAttributeValue(null, _AVAILABLE_LOCALES);
            defaultLanguageId = xmlStreamReader.getAttributeValue(null, _DEFAULT_LOCALE);

            if (Validator.isNull(defaultLanguageId)) {
                defaultLanguageId = systemDefaultLanguageId;
            }
        }

        if ((availableLocales != null) && (availableLocales.indexOf(requestedLanguageId) != -1)) {

            availableLocales = StringUtil.remove(availableLocales, requestedLanguageId, StringPool.COMMA);

            UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

            XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();

            xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(unsyncStringWriter);

            xmlStreamWriter.writeStartDocument();
            xmlStreamWriter.writeStartElement(_ROOT);

            if (localized) {
                xmlStreamWriter.writeAttribute(_AVAILABLE_LOCALES, availableLocales);
                xmlStreamWriter.writeAttribute(_DEFAULT_LOCALE, defaultLanguageId);
            }

            _copyNonExempt(xmlStreamReader, xmlStreamWriter, requestedLanguageId, defaultLanguageId, cdata);

            xmlStreamWriter.writeEndElement();
            xmlStreamWriter.writeEndDocument();

            xmlStreamWriter.close();
            xmlStreamWriter = null;

            xml = unsyncStringWriter.toString();
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (Exception e) {
            }
        }

        if (xmlStreamWriter != null) {
            try {
                xmlStreamWriter.close();
            } catch (Exception e) {
            }
        }
    }

    return xml;
}

From source file:log4JToXml.xmlToProperties.XmlToLog4jConverterImpl.java

private void addDTDDeclaration(String filename) throws XMLStreamException {
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent dtd = eventFactory//from   www  . j  a  v a 2  s . c  om
            .createDTD("<!DOCTYPE log4j:configuration SYSTEM \"" + tempDTD.getAbsolutePath() + "\">");

    XMLInputFactory inFactory = XMLInputFactory.newInstance();
    XMLOutputFactory outFactory = XMLOutputFactory.newInstance();

    XMLEventReader reader = inFactory.createXMLEventReader(new StreamSource(filename));
    reader = new DTDReplacer(reader, dtd);
    XMLEventWriter writer = outFactory.createXMLEventWriter(documentStream);
    writer.add(reader);
    writer.flush();

    writer.close();
}

From source file:com.smartbear.jenkins.plugins.testcomplete.TcLogParser.java

public TcLogInfo parse(BuildListener listener) {
    try {/* ww  w. java2 s .c  o  m*/
        ZipFile logArchive = new ZipFile(log);

        Node descriptionTopLevelNode = NodeUtils.getRootDocumentNodeFromArchive(logArchive,
                DESCRIPTION_ENTRY_NAME);
        if (descriptionTopLevelNode == null) {
            throw new ParsingException("Unable to obtain description top-level node.");
        }

        long startTime = Utils
                .safeConvertDate(NodeUtils.getTextProperty(descriptionTopLevelNode, START_TIME_PROPERTY_NAME));
        long stopTime = Utils
                .safeConvertDate(NodeUtils.getTextProperty(descriptionTopLevelNode, STOP_TIME_PROPERTY_NAME));

        int testCount = 0;
        try {
            testCount = Integer
                    .parseInt(NodeUtils.getTextProperty(descriptionTopLevelNode, TEST_COUNT_PROPERTY_NAME));
        } catch (NumberFormatException e) {
            // Do nothing
        }

        int warningCount = 0;
        try {
            warningCount = Integer
                    .parseInt(NodeUtils.getTextProperty(descriptionTopLevelNode, WARNING_COUNT_PROPERTY_NAME));
        } catch (NumberFormatException e) {
            // Do nothing
        }

        int errorCount = 0;
        try {
            errorCount = Integer
                    .parseInt(NodeUtils.getTextProperty(descriptionTopLevelNode, ERROR_COUNT_PROPERTY_NAME));
        } catch (NumberFormatException e) {
            // Do nothing
        }

        TcLogInfo logInfo = new TcLogInfo(startTime, stopTime, testCount, errorCount, warningCount);

        String xml = null;

        if (generateJUnitReports) {
            XMLStreamWriter xmlStreamWriter = null;
            try {
                StringWriter stringWriter = new StringWriter();
                xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(stringWriter);
                convertToXML(logArchive, logInfo, xmlStreamWriter);
                xmlStreamWriter.flush();
                xmlStreamWriter.close();
                xmlStreamWriter = null;
                xml = stringWriter.toString();
            } catch (Exception e) {
                TcLog.error(listener, Messages.TcTestBuilder_ExceptionOccurred(), e.toString());
            } finally {
                if (xmlStreamWriter != null) {
                    xmlStreamWriter.close();
                }
            }
        }

        logInfo.setXML(xml);

        return logInfo;
    } catch (Exception e) {
        TcLog.error(listener, Messages.TcTestBuilder_ExceptionOccurred(), e.toString());
        return null;
    }
}

From source file:eu.scape_project.planning.xml.ProjectExportAction.java

/**
 * Dumps binary data to provided file. It results in an XML file with a
 * single element: data./*from w ww.j  a v a2s  . c  om*/
 * 
 * @param id
 * @param data
 * @param f
 * @param encoder
 * @throws IOException
 */
private static void writeBinaryData(int id, InputStream data, File f) throws IOException {

    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {
        XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(f));

        writer.writeStartDocument(PlanXMLConstants.ENCODING, "1.0");
        writer.writeStartElement("data");
        writer.writeAttribute("id", "" + id);

        Base64InputStream base64EncodingIn = new Base64InputStream(data, true,
                PlanXMLConstants.BASE64_LINE_LENGTH, PlanXMLConstants.BASE64_LINE_BREAK);

        OutputStream out = new WriterOutputStream(new XMLStreamContentWriter(writer),
                PlanXMLConstants.ENCODING);
        // read the binary data and encode it on the fly
        IOUtils.copy(base64EncodingIn, out);
        out.flush();

        // all data is written - end 
        writer.writeEndElement();
        writer.writeEndDocument();

        writer.flush();
        writer.close();

    } catch (XMLStreamException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

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

        writeBoolElement(writer, "cookiesDisabled", cookiesDisabled);
        writeStringElement(writer, "authMethod", authMethod);
        writeStringElement(writer, "authUsername", authUsername);
        writeStringElement(writer, "authPassword", authPassword);
        writeStringElement(writer, "authUsernameField", authUsernameField);
        writeStringElement(writer, "authPasswordField", authPasswordField);
        writeStringElement(writer, "authURL", authURL);
        writeStringElement(writer, "authHostname", authHostname);
        writeIntElement(writer, "authPort", authPort);
        writeStringElement(writer, "authFormCharset", authFormCharset);
        writeStringElement(writer, "authWorkstation", authWorkstation);
        writeStringElement(writer, "authDomain", authDomain);
        writeStringElement(writer, "authRealm", authRealm);
        writeStringElement(writer, "proxyHost", proxyHost);
        writeIntElement(writer, "proxyPort", proxyPort);
        writeStringElement(writer, "proxyScheme", proxyScheme);
        writeStringElement(writer, "proxyUsername", proxyUsername);
        writeStringElement(writer, "proxyPassword", proxyPassword);
        writeStringElement(writer, "proxyRealm", proxyRealm);
        writer.writeEndElement();
        writeIntElement(writer, "connectionTimeout", connectionTimeout);
        writeIntElement(writer, "socketTimeout", socketTimeout);
        writeIntElement(writer, "connectionRequestTimeout", connectionRequestTimeout);
        writeStringElement(writer, "connectionCharset", connectionCharset);
        writeBoolElement(writer, "expectContinueEnabled", expectContinueEnabled);
        writeIntElement(writer, "maxRedirects", maxRedirects);
        writeStringElement(writer, "localAddress", localAddress);
        writeBoolElement(writer, "staleConnectionCheckDisabled", staleConnectionCheckDisabled);
        writeIntElement(writer, "maxConnections", maxConnections);

        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}

From source file:eu.artist.postmigration.eubt.helpers.SOAPHelper.java

/**
 * @param migratedSoapEnvelope/*from w  w w .jav a 2s .  c  o m*/
 * @return
 * @throws XMLStreamException
 * @throws FactoryConfigurationError
 * @throws IOException
 */
public static String storeSoapEnvelopeToFile(final SOAPEnvelope migratedSoapEnvelope,
        final String migratedResponseFileFolder) throws EUBTException {
    // store created soap envelope in a file
    final String migratedResponseFileLocation = migratedResponseFileFolder
            + migratedSoapEnvelope.getSOAPBodyFirstElementLocalName() + ".xml";
    XMLStreamWriter writer;
    try {
        writer = new IndentingXMLStreamWriter(XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new FileWriter(migratedResponseFileLocation)));
        migratedSoapEnvelope.serialize(writer);
        writer.flush();
    } catch (XMLStreamException e) {
        throw new EUBTException(
                "Failed to create stream writer, or serialize or flush output. Detailed Exception: " + e);
    } catch (FactoryConfigurationError e) {
        throw new EUBTException("Failed to configure xml output factory. Detailed Exception: " + e);
    } catch (IOException e) {
        throw new EUBTException("General I/O Exception (wrong path, file location?). Detailed Exception: " + e);
    }
    return migratedResponseFileLocation;
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

private InputStream addAtomEditLink(final InputStream content, final String title, final String href)
        throws Exception {
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();

    final ByteArrayOutputStream copy = new ByteArrayOutputStream();
    IOUtils.copy(content, copy);// ww w .  j a  v a 2  s  .c  om

    IOUtils.closeQuietly(content);

    XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLEventWriter writer = xof.createXMLEventWriter(bos);

    try {
        // check edit link existence
        final XmlElement editLink = getAtomElement(reader, writer, LINK,
                Collections.<Map.Entry<String, String>>singletonList(
                        new AbstractMap.SimpleEntry<String, String>("rel", "edit")));
        writer.add(editLink.getStart());
        writer.add(editLink.getContentReader());
        writer.add(editLink.getEnd());
        writer.add(reader);
    } catch (Exception e) {
        reader.close();
        reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

        bos = new ByteArrayOutputStream();
        writer = xof.createXMLEventWriter(bos);

        final XmlElement entryElement = getAtomElement(reader, writer, "entry");

        writer.add(entryElement.getStart());
        addAtomElement(IOUtils.toInputStream(
                String.format("<link rel=\"edit\" title=\"%s\" href=\"%s\" />", title, href)), writer);
        writer.add(entryElement.getContentReader());
        writer.add(entryElement.getEnd());

        writer.add(reader);

        writer.flush();
        writer.close();
    } finally {
        reader.close();
    }

    return new ByteArrayInputStream(bos.toByteArray());
}