Search in sources :

Example 36 with XMLStreamWriter

use of javax.xml.stream.XMLStreamWriter in project webservices-axiom by apache.

the class TestGetSAXSourceWithPushOMDataSource method runTest.

@Override
protected void runTest() throws Throwable {
    OMFactory factory = metaFactory.getOMFactory();
    OMSourcedElement sourcedElement = factory.createOMElement(new AbstractPushOMDataSource() {

        @Override
        public void serialize(XMLStreamWriter writer) throws XMLStreamException {
            scenario.serialize(writer);
        }

        @Override
        public boolean isDestructiveWrite() {
            return false;
        }
    });
    Iterator<Map.Entry<String, String>> it = scenario.getNamespaceContext().entrySet().iterator();
    OMElement parent;
    if (it.hasNext()) {
        Map.Entry<String, String> binding = it.next();
        parent = factory.createOMElement("parent", factory.createOMNamespace(binding.getValue(), binding.getKey()));
        while (it.hasNext()) {
            binding = it.next();
            parent.declareNamespace(factory.createOMNamespace(binding.getValue(), binding.getKey()));
        }
    } else {
        parent = factory.createOMElement("parent", null);
    }
    parent.addChild(sourcedElement);
    SAXSource saxSource = (serializeParent ? parent : sourcedElement).getSAXSource(true);
    OMElement element = OMXMLBuilderFactory.createOMBuilder(factory, saxSource, false).getDocumentElement();
    if (serializeParent) {
        element = element.getFirstElement();
    }
    scenario.validate(element, false);
}
Also used : OMElement(org.apache.axiom.om.OMElement) OMSourcedElement(org.apache.axiom.om.OMSourcedElement) OMFactory(org.apache.axiom.om.OMFactory) SAXSource(javax.xml.transform.sax.SAXSource) XMLStreamException(javax.xml.stream.XMLStreamException) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) AbstractPushOMDataSource(org.apache.axiom.om.ds.AbstractPushOMDataSource) Map(java.util.Map)

Example 37 with XMLStreamWriter

use of javax.xml.stream.XMLStreamWriter in project dhis2-core by dhis2.

the class DefaultAdxDataService method saveDataValueSetInternal.

private ImportSummary saveDataValueSetInternal(InputStream in, ImportOptions importOptions, TaskId id) {
    notifier.clear(id).notify(id, "ADX parsing process started");
    ImportOptions adxImportOptions = ObjectUtils.firstNonNull(importOptions, ImportOptions.getDefaultImportOptions()).instance().setNotificationLevel(NotificationLevel.OFF);
    // Get import options
    IdScheme dataSetIdScheme = importOptions.getIdSchemes().getDataSetIdScheme();
    IdScheme dataElementIdScheme = importOptions.getIdSchemes().getDataElementIdScheme();
    // Create meta-data maps
    CachingMap<String, DataSet> dataSetMap = new CachingMap<>();
    CachingMap<String, DataElement> dataElementMap = new CachingMap<>();
    // Get meta-data maps
    IdentifiableObjectCallable<DataSet> dataSetCallable = new IdentifiableObjectCallable<>(identifiableObjectManager, DataSet.class, dataSetIdScheme, null);
    IdentifiableObjectCallable<DataElement> dataElementCallable = new IdentifiableObjectCallable<>(identifiableObjectManager, DataElement.class, dataElementIdScheme, null);
    // Heat cache
    if (importOptions.isPreheatCacheDefaultFalse()) {
        dataSetMap.load(identifiableObjectManager.getAll(DataSet.class), o -> o.getPropertyValue(dataSetIdScheme));
        dataElementMap.load(identifiableObjectManager.getAll(DataElement.class), o -> o.getPropertyValue(dataElementIdScheme));
    }
    XMLReader adxReader = XMLFactory.getXMLReader(in);
    ImportSummary importSummary;
    adxReader.moveToStartElement(AdxDataService.ROOT, AdxDataService.NAMESPACE);
    ExecutorService executor = Executors.newSingleThreadExecutor();
    // Give the DXF import a different notification task ID so it doesn't conflict with notifications from this level.
    TaskId dxfTaskId = new TaskId(TaskCategory.DATAVALUE_IMPORT_INTERNAL, id.getUser());
    int groupCount = 0;
    try (PipedOutputStream pipeOut = new PipedOutputStream()) {
        Future<ImportSummary> futureImportSummary = executor.submit(new AdxPipedImporter(dataValueSetService, adxImportOptions, dxfTaskId, pipeOut, sessionFactory));
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        XMLStreamWriter dxfWriter = factory.createXMLStreamWriter(pipeOut);
        List<ImportConflict> adxConflicts = new LinkedList<>();
        dxfWriter.writeStartDocument("1.0");
        dxfWriter.writeStartElement("dataValueSet");
        dxfWriter.writeDefaultNamespace("http://dhis2.org/schema/dxf/2.0");
        notifier.notify(id, "Starting to import ADX data groups.");
        while (adxReader.moveToStartElement(AdxDataService.GROUP, AdxDataService.NAMESPACE)) {
            notifier.update(id, "Importing ADX data group: " + groupCount);
            // note this returns conflicts which are detected at ADX level
            adxConflicts.addAll(parseAdxGroupToDxf(adxReader, dxfWriter, adxImportOptions, dataSetMap, dataSetCallable, dataElementMap, dataElementCallable));
            groupCount++;
        }
        // end dataValueSet
        dxfWriter.writeEndElement();
        dxfWriter.writeEndDocument();
        pipeOut.flush();
        importSummary = futureImportSummary.get(TOTAL_MINUTES_TO_WAIT, TimeUnit.MINUTES);
        importSummary.getConflicts().addAll(adxConflicts);
        importSummary.getImportCount().incrementIgnored(adxConflicts.size());
    } catch (AdxException ex) {
        importSummary = new ImportSummary();
        importSummary.setStatus(ImportStatus.ERROR);
        importSummary.setDescription("Data set import failed within group number: " + groupCount);
        importSummary.getConflicts().add(ex.getImportConflict());
        notifier.update(id, NotificationLevel.ERROR, "ADX data import done", true);
        log.warn("Import failed: " + DebugUtils.getStackTrace(ex));
    } catch (IOException | XMLStreamException | InterruptedException | ExecutionException | TimeoutException ex) {
        importSummary = new ImportSummary();
        importSummary.setStatus(ImportStatus.ERROR);
        importSummary.setDescription("Data set import failed within group number: " + groupCount);
        notifier.update(id, NotificationLevel.ERROR, "ADX data import done", true);
        log.warn("Import failed: " + DebugUtils.getStackTrace(ex));
    }
    executor.shutdown();
    notifier.update(id, INFO, "ADX data import done", true).addTaskSummary(id, importSummary);
    ImportCount c = importSummary.getImportCount();
    log.info("ADX data import done, imported: " + c.getImported() + ", updated: " + c.getUpdated() + ", deleted: " + c.getDeleted() + ", ignored: " + c.getIgnored());
    return importSummary;
}
Also used : XMLOutputFactory(javax.xml.stream.XMLOutputFactory) TaskId(org.hisp.dhis.scheduling.TaskId) DataSet(org.hisp.dhis.dataset.DataSet) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) PipedOutputStream(java.io.PipedOutputStream) DataElement(org.hisp.dhis.dataelement.DataElement) CachingMap(org.hisp.dhis.commons.collection.CachingMap) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) ExecutionException(java.util.concurrent.ExecutionException) XMLReader(org.hisp.staxwax.reader.XMLReader) ImportConflict(org.hisp.dhis.dxf2.importsummary.ImportConflict) TimeoutException(java.util.concurrent.TimeoutException) ImportCount(org.hisp.dhis.dxf2.importsummary.ImportCount) IdScheme(org.hisp.dhis.common.IdScheme) IOException(java.io.IOException) IdentifiableObjectCallable(org.hisp.dhis.system.callable.IdentifiableObjectCallable) LinkedList(java.util.LinkedList) XMLStreamException(javax.xml.stream.XMLStreamException) ExecutorService(java.util.concurrent.ExecutorService) ImportOptions(org.hisp.dhis.dxf2.common.ImportOptions)

Example 38 with XMLStreamWriter

use of javax.xml.stream.XMLStreamWriter in project kernel by exoplatform.

the class InitialContextBinder method saveBindings.

/**
 * Export references into xml-file.
 *
 * @throws XMLStreamException
 *          if any exception occurs during export
 * @throws FileNotFoundException
 *          if can't open output stream from file
 */
protected synchronized void saveBindings() throws FileNotFoundException, XMLStreamException {
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    XMLStreamWriter writer = outputFactory.createXMLStreamWriter(PrivilegedFileHelper.fileOutputStream(bindingsStorePath), "UTF-8");
    writer.writeStartDocument("UTF-8", "1.0");
    writer.writeStartElement(BIND_REFERENCES_ELEMENT);
    for (Entry<String, Reference> entry : bindings.entrySet()) {
        String bindName = entry.getKey();
        Reference reference = entry.getValue();
        writer.writeStartElement(REFERENCE_ELEMENT);
        writer.writeAttribute(BIND_NAME_ATTR, bindName);
        if (reference.getClassName() != null) {
            writer.writeAttribute(CLASS_NAME_ATTR, reference.getClassName());
        }
        if (reference.getFactoryClassName() != null) {
            writer.writeAttribute(FACTORY_ATTR, reference.getFactoryClassName());
        }
        if (reference.getFactoryClassLocation() != null) {
            writer.writeAttribute(FACTORY_LOCATION_ATTR, reference.getFactoryClassLocation());
        }
        writer.writeStartElement(REFADDR_ELEMENT);
        for (int i = 0; i < reference.size(); i++) {
            writer.writeStartElement(PROPERTY_ELEMENT);
            writer.writeAttribute(reference.get(i).getType(), (String) reference.get(i).getContent());
            writer.writeEndElement();
        }
        writer.writeEndElement();
        writer.writeEndElement();
    }
    writer.writeEndElement();
    writer.writeEndDocument();
}
Also used : XMLOutputFactory(javax.xml.stream.XMLOutputFactory) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) Reference(javax.naming.Reference)

Example 39 with XMLStreamWriter

use of javax.xml.stream.XMLStreamWriter in project cxf by apache.

the class AbstractBPBeanDefinitionParser method mapElementToJaxbProperty.

protected void mapElementToJaxbProperty(ParserContext ctx, MutableBeanMetadata bean, Element data, String propertyName, Class<?> c) {
    try {
        XMLStreamWriter xmlWriter = null;
        Unmarshaller u = null;
        try {
            StringWriter writer = new StringWriter();
            xmlWriter = StaxUtils.createXMLStreamWriter(writer);
            StaxUtils.copy(data, xmlWriter);
            xmlWriter.flush();
            MutableBeanMetadata factory = ctx.createMetadata(MutableBeanMetadata.class);
            factory.setClassName(c.getName());
            factory.setFactoryComponent(createPassThrough(ctx, new JAXBBeanFactory(getContext(c), c)));
            factory.setFactoryMethod("createJAXBBean");
            factory.addArgument(createValue(ctx, writer.toString()), String.class.getName(), 0);
            bean.addProperty(propertyName, factory);
        } catch (Exception ex) {
            u = getContext(c).createUnmarshaller();
            u.setEventHandler(null);
            Object obj;
            if (c != null) {
                obj = u.unmarshal(data, c);
            } else {
                obj = u.unmarshal(data);
            }
            if (obj instanceof JAXBElement<?>) {
                JAXBElement<?> el = (JAXBElement<?>) obj;
                obj = el.getValue();
            }
            if (obj != null) {
                MutablePassThroughMetadata value = ctx.createMetadata(MutablePassThroughMetadata.class);
                value.setObject(obj);
                bean.addProperty(propertyName, value);
            }
        } finally {
            StaxUtils.close(xmlWriter);
            JAXBUtils.closeUnmarshaller(u);
        }
    } catch (JAXBException e) {
        throw new RuntimeException("Could not parse configuration.", e);
    }
}
Also used : MutablePassThroughMetadata(org.apache.aries.blueprint.mutable.MutablePassThroughMetadata) JAXBException(javax.xml.bind.JAXBException) JAXBElement(javax.xml.bind.JAXBElement) XMLStreamException(javax.xml.stream.XMLStreamException) JAXBException(javax.xml.bind.JAXBException) MutableBeanMetadata(org.apache.aries.blueprint.mutable.MutableBeanMetadata) StringWriter(java.io.StringWriter) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) Unmarshaller(javax.xml.bind.Unmarshaller)

Example 40 with XMLStreamWriter

use of javax.xml.stream.XMLStreamWriter in project cxf by apache.

the class AbstractBeanDefinitionParser method mapElementToJaxbBean.

public AbstractBeanDefinition mapElementToJaxbBean(Element data, Class<?> cls, Class<?> factory, Class<?> jaxbClass, String method, Object... args) {
    StringWriter writer = new StringWriter();
    XMLStreamWriter xmlWriter = StaxUtils.createXMLStreamWriter(writer);
    try {
        StaxUtils.copy(data, xmlWriter);
        xmlWriter.flush();
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    } finally {
        StaxUtils.close(xmlWriter);
    }
    BeanDefinitionBuilder jaxbbean = BeanDefinitionBuilder.rootBeanDefinition(cls);
    if (factory != null) {
        jaxbbean.getRawBeanDefinition().setFactoryBeanName(factory.getName());
    }
    jaxbbean.getRawBeanDefinition().setFactoryMethodName(method);
    jaxbbean.addConstructorArgValue(writer.toString());
    jaxbbean.addConstructorArgValue(getContext(jaxbClass));
    if (args != null) {
        for (Object o : args) {
            jaxbbean.addConstructorArgValue(o);
        }
    }
    return jaxbbean.getBeanDefinition();
}
Also used : BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) StringWriter(java.io.StringWriter) XMLStreamException(javax.xml.stream.XMLStreamException) XMLStreamWriter(javax.xml.stream.XMLStreamWriter)

Aggregations

XMLStreamWriter (javax.xml.stream.XMLStreamWriter)209 XMLStreamException (javax.xml.stream.XMLStreamException)84 StringWriter (java.io.StringWriter)47 Test (org.junit.Test)47 ByteArrayOutputStream (java.io.ByteArrayOutputStream)40 XMLOutputFactory (javax.xml.stream.XMLOutputFactory)40 XMLStreamReader (javax.xml.stream.XMLStreamReader)32 QName (javax.xml.namespace.QName)26 Document (org.w3c.dom.Document)26 Fault (org.apache.cxf.interceptor.Fault)25 IOException (java.io.IOException)23 OutputStream (java.io.OutputStream)21 ByteArrayInputStream (java.io.ByteArrayInputStream)17 StreamSource (javax.xml.transform.stream.StreamSource)17 StringReader (java.io.StringReader)16 JAXBException (javax.xml.bind.JAXBException)14 DOMSource (javax.xml.transform.dom.DOMSource)14 MessagePartInfo (org.apache.cxf.service.model.MessagePartInfo)14 Message (org.apache.cxf.message.Message)13 Element (org.w3c.dom.Element)11