Example usage for javax.xml.stream XMLInputFactory newInstance

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

Introduction

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

Prototype

public static XMLInputFactory 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:edu.jhu.hlt.concrete.ingesters.webposts.WebPostIngester.java

/**
 *
 *///from  w  w  w .  jav  a2 s  .c o  m
public WebPostIngester() {
    this.inF = XMLInputFactory.newInstance();
    this.dtf = ISODateTimeFormat.dateTimeParser().withZoneUTC();
    // UTC time!
    // Local time will cause the DST switch exception:
    // 2009-03-08T02:00:02: this instant does not exist under America/NewYork
    // time zone, hence an exception raised
    // To fix this, consider all time as UTC.
    // @tongfei
}

From source file:org.lieuofs.geo.territoire.biz.dao.EtatTerritoireFichierXmlDao.java

/**************************************************/

@PostConstruct//w  ww.j av  a2  s.  com
public void chargerResource()
        throws IOException, XMLStreamException, FactoryConfigurationError, ParseException {
    XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(fichier.getInputStream(),
            this.charsetName);
    EtatTerritoirePersistant etatTerritoire = null;
    while (reader.hasNext()) {
        XMLEvent event = (XMLEvent) reader.next();
        if (event.isStartElement()) {
            StartElement element = (StartElement) event;
            String nomElem = element.getName().toString();
            if ("country".equals(nomElem)) {
                etatTerritoire = new EtatTerritoirePersistant();
            } else if ("id".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setNumeroOFS(Integer.parseInt(characters.getData()));
            } else if ("unId".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                if (null == etatTerritoire.getInfosISO())
                    etatTerritoire.setInfosISO(new InfosONUetISO3166());
                etatTerritoire.getInfosISO().setCodeNumeriqueONU(Integer.parseInt(characters.getData()));
            } else if ("iso2Id".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                if (null == etatTerritoire.getInfosISO())
                    etatTerritoire.setInfosISO(new InfosONUetISO3166());
                etatTerritoire.getInfosISO().setCodeIsoAlpha2(characters.getData());
            } else if ("iso3Id".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                if (null == etatTerritoire.getInfosISO())
                    etatTerritoire.setInfosISO(new InfosONUetISO3166());
                etatTerritoire.getInfosISO().setCodeIsoAlpha3(characters.getData());
            } else if ("shortNameDe".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterFormeCourte("de", characters.getData());
            } else if ("shortNameFr".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterFormeCourte("fr", characters.getData());
            } else if ("shortNameIt".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterFormeCourte("it", characters.getData());
            } else if ("shortNameEn".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterFormeCourte("en", characters.getData());
            } else if ("officialNameDe".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterDesignationOfficielle("de", characters.getData());
            } else if ("officialNameFr".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterDesignationOfficielle("fr", characters.getData());
            } else if ("officialNameIt".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterDesignationOfficielle("it", characters.getData());
            } else if ("continent".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setNumContinent(Integer.parseInt(characters.getData()));
            } else if ("region".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setNumRegion(Integer.parseInt(characters.getData()));
            } else if ("state".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setEtat(Boolean.valueOf(characters.getData()));
            } else if ("areaState".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setNumEtatRattachement(Integer.parseInt(characters.getData()));
            } else if ("unMember".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setMembreONU(Boolean.valueOf(characters.getData()));
            } else if ("unEntryDate".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setDateEntreeONU(dateFmt.parse(characters.getData()));
            } else if ("recognizedCh".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setReconnuSuisse(Boolean.valueOf(characters.getData()));
            } else if ("recognizedDate".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setDateReconnaissance(dateFmt.parse(characters.getData()));
            } else if ("remarkDe".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterRemarque("de", characters.getData());
            } else if ("remarkFr".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterRemarque("fr", characters.getData());
            } else if ("remarkIt".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterRemarque("it", characters.getData());
            } else if ("entryValid".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setValide(Boolean.valueOf(characters.getData()));
            } else if ("dateOfChange".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setDateDernierChangement(dateFmt.parse(characters.getData()));
            }
        } else if (event.isEndElement()) {
            EndElement element = (EndElement) event;
            if ("country".equals(element.getName().toString())) {
                stockerEtatTerritoire(etatTerritoire);
            }
        }
    }
}

From source file:hudson.model.ExternalRun.java

/**
 * Instead of performing a build, accept the log and the return code from a
 * remote machine.//ww  w .j av  a  2  s . c  om
 *
 * <p> The format of the XML is:
 *
 * <pre><xmp>
 * <run>
 *  <log>...console output...</log>
 *  <result>exit code</result>
 * </run>
 * </xmp></pre>
 */
@SuppressWarnings({ "Since15" })
public void acceptRemoteSubmission(final Reader in) throws IOException {
    final long[] duration = new long[1];
    run(new Runner() {
        private String elementText(XMLStreamReader r) throws XMLStreamException {
            StringBuilder buf = new StringBuilder();
            while (true) {
                int type = r.next();
                if (type == CHARACTERS || type == CDATA) {
                    buf.append(r.getTextCharacters(), r.getTextStart(), r.getTextLength());
                } else {
                    return buf.toString();
                }
            }
        }

        public Result run(BuildListener listener) throws Exception {
            PrintStream logger = null;
            try {
                logger = new PrintStream(new DecodingStream(listener.getLogger()));

                XMLInputFactory xif = XMLInputFactory.newInstance();
                XMLStreamReader p = xif.createXMLStreamReader(in);

                p.nextTag(); // get to the <run>
                p.nextTag(); // get to the <log>

                charset = p.getAttributeValue(null, "content-encoding");
                while (p.next() != END_ELEMENT) {
                    int type = p.getEventType();
                    if (type == CHARACTERS || type == CDATA) {
                        logger.print(p.getText());
                    }
                }
                p.nextTag(); // get to <result>

                Result r = Integer.parseInt(elementText(p)) == 0 ? Result.SUCCESS : Result.FAILURE;

                p.nextTag(); // get to <duration> (optional)
                if (p.getEventType() == START_ELEMENT && p.getLocalName().equals("duration")) {
                    duration[0] = Long.parseLong(elementText(p));
                }

                return r;
            } finally {
                IOUtils.closeQuietly(logger);
            }
        }

        public void post(BuildListener listener) {
            // do nothing
        }

        public void cleanUp(BuildListener listener) {
            // do nothing
        }
    });

    if (duration[0] != 0) {
        super.duration = duration[0];
        // save the updated duration
        save();
    }
}

From source file:net.bulletin.pdi.xero.step.XeroGetStep.java

@Override
public boolean init(StepMetaInterface smi, StepDataInterface sdi) {
    XeroGetStepMeta meta = (XeroGetStepMeta) smi;
    XeroGetStepData data = (XeroGetStepData) sdi;
    boolean result = false;

    try {/*from   w w w . j ava  2  s.  co m*/
        data.setOAuthMessage(openXero(meta));

        try {

            xmlChunker = new XMLChunkerImpl(XMLInputFactory.newInstance().createXMLStreamReader(
                    data.getOAuthMessage().getBodyAsStream()), getContainerElementsStack(meta));

            result = true;
        } catch (Exception ioe) {
            throw new KettleException("unable to process the xero input as xml", ioe);
        }

    } catch (KettleException ke) {
        logError("unable to initialize the xero step", ke);
    }

    return result && super.init(smi, sdi);
}

From source file:com.activiti.image.BpmnImageTest.java

protected BpmnModel getBpmnModel(String file) throws Exception {
    BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
    InputStream xmlStream = this.getClass().getClassLoader().getResourceAsStream(file);
    XMLInputFactory xif = XMLInputFactory.newInstance();
    InputStreamReader in = new InputStreamReader(xmlStream);
    XMLStreamReader xtr = xif.createXMLStreamReader(in);
    BpmnModel bpmnModel = xmlConverter.convertToBpmnModel(xtr);
    return bpmnModel;
}

From source file:com.evolveum.polygon.connector.hcm.DocumentProcessing.java

public Map<String, Object> parseXMLData(HcmConnectorConfiguration conf, ResultsHandler handler,
        Map<String, Object> schemaAttributeMap, Filter query) {

    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {/*  w  w w.  j  a v  a 2s. c o m*/

        String uidAttributeName = conf.getUidAttribute();
        String primariId = conf.getPrimaryId();
        String startName = "";
        String value = null;

        StringBuilder assignmentXMLBuilder = null;

        List<String> builderList = new ArrayList<String>();

        Integer nOfIterations = 0;
        Boolean isSubjectToQuery = false;
        Boolean isAssigment = false;
        Boolean evaluateAttr = true;
        Boolean specificAttributeQuery = false;

        XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(conf.getFilePath()));
        List<String> dictionary = populateDictionary(FIRSTFLAG);

        if (!attrsToGet.isEmpty()) {

            attrsToGet.add(uidAttributeName);
            attrsToGet.add(primariId);
            specificAttributeQuery = true;
            evaluateAttr = false;
            LOGGER.ok("The uid and primary id were added to the queried attribute list");

            schemaAttributeMap = modifySchemaAttributeMap(schemaAttributeMap);
        }

        while (eventReader.hasNext()) {

            XMLEvent event = eventReader.nextEvent();

            Integer code = event.getEventType();

            if (code == XMLStreamConstants.START_ELEMENT) {

                StartElement startElement = event.asStartElement();
                startName = startElement.getName().getLocalPart();

                if (!evaluateAttr && attrsToGet.contains(startName)) {

                    evaluateAttr = true;
                }

                if (!elementIsEmployeeData) {

                    if (startName.equals(EMPLOYEES)) {

                        if (dictionary.contains(nOfIterations.toString())) {
                            LOGGER.ok("The defined number of iterations has been hit: {0}",
                                    nOfIterations.toString());
                            break;
                        } else {
                            startName = "";
                            elementIsEmployeeData = true;
                            nOfIterations++;
                        }
                    }
                } else if (evaluateAttr) {

                    if (!isAssigment) {
                        if (!ASSIGNMENTTAG.equals(startName)) {

                        } else {
                            assignmentXMLBuilder = new StringBuilder();
                            isAssigment = true;
                        }
                    } else {

                        builderList = processAssignment(startName, null, START, builderList);
                    }

                    if (multiValuedAttributesList.contains(startName)) {

                        elementIsMultiValued = true;
                    }

                }

            } else if (elementIsEmployeeData) {

                if (code == XMLStreamConstants.CHARACTERS && evaluateAttr) {

                    Characters characters = event.asCharacters();

                    if (!characters.isWhiteSpace()) {

                        StringBuilder valueBuilder;
                        if (value != null) {
                            valueBuilder = new StringBuilder(value).append("")
                                    .append(characters.getData().toString());
                        } else {
                            valueBuilder = new StringBuilder(characters.getData().toString());
                        }
                        value = valueBuilder.toString();
                        // value = StringEscapeUtils.escapeXml10(value);
                        // LOGGER.info("The attribute value for: {0} is
                        // {1}", startName, value);
                    }
                } else if (code == XMLStreamConstants.END_ELEMENT) {

                    EndElement endElement = event.asEndElement();
                    String endName = endElement.getName().getLocalPart();

                    isSubjectToQuery = checkFilter(endName, value, query, uidAttributeName);

                    if (!isSubjectToQuery) {
                        attributeMap.clear();
                        elementIsEmployeeData = false;
                        value = null;

                        endName = EMPLOYEES;
                    }

                    if (endName.equals(EMPLOYEES)) {

                        attributeMap = handleEmployeeData(attributeMap, schemaAttributeMap, handler,
                                uidAttributeName, primariId);

                        elementIsEmployeeData = false;

                    } else if (evaluateAttr) {

                        if (endName.equals(startName)) {
                            if (value != null) {

                                if (!isAssigment) {
                                    if (!elementIsMultiValued) {

                                        attributeMap.put(startName, value);
                                    } else {

                                        multiValuedAttributeBuffer.put(startName, value);
                                    }
                                } else {

                                    value = StringEscapeUtils.escapeXml10(value);
                                    builderList = processAssignment(endName, value, VALUE, builderList);

                                    builderList = processAssignment(endName, null, END, builderList);
                                }
                                // LOGGER.info("Attribute name: {0} and the
                                // Attribute value: {1}", endName, value);
                                value = null;
                            }
                        } else {
                            if (endName.equals(ASSIGNMENTTAG)) {

                                builderList = processAssignment(endName, null, CLOSE, builderList);

                                // if (assigmentIsActive) {

                                for (String records : builderList) {
                                    assignmentXMLBuilder.append(records);

                                }
                                attributeMap.put(ASSIGNMENTTAG, assignmentXMLBuilder.toString());
                                // } else {
                                // }

                                builderList = new ArrayList<String>();
                                // assigmentIsActive = false;
                                isAssigment = false;

                            } else if (multiValuedAttributesList.contains(endName)) {
                                processMultiValuedAttributes(multiValuedAttributeBuffer);
                            }
                        }

                    }
                    if (specificAttributeQuery && evaluateAttr) {

                        evaluateAttr = false;
                    }
                }
            } else if (code == XMLStreamConstants.END_DOCUMENT) {
                handleBufferedData(uidAttributeName, primariId, handler);
            }
        }

    } catch (FileNotFoundException e) {
        StringBuilder errorBuilder = new StringBuilder("File not found at the specified path.")
                .append(e.getLocalizedMessage());
        LOGGER.error("File not found at the specified path: {0}", e);
        throw new ConnectorIOException(errorBuilder.toString());
    } catch (XMLStreamException e) {

        LOGGER.error("Unexpected processing error while parsing the .xml document : {0}", e);

        StringBuilder errorBuilder = new StringBuilder(
                "Unexpected processing error while parsing the .xml document. ")
                        .append(e.getLocalizedMessage());

        throw new ConnectorIOException(errorBuilder.toString());
    }
    return attributeMap;

}

From source file:de.tuebingen.uni.sfs.germanet.api.IliLoader.java

/**
 * Loads <code>IliRecords</code> from the specified stream into this
 * <code>IliLoader</code>'s <code>GermaNet</code> object.
 * @param inputStream the stream containing <code>IliRecords</code> data
 * @throws javax.xml.stream.XMLStreamException
 *//*www  .  j  av  a2  s. c  o  m*/
protected void loadILI(InputStream inputStream) throws XMLStreamException {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader parser = factory.createXMLStreamReader(inputStream);
    int event;
    String nodeName;
    logger.debug("Loading input stream interLingualIndex_DE-EN.xml...");

    //Parse entire file, looking for ili record start elements
    while (parser.hasNext()) {
        event = parser.next();
        switch (event) {
        case XMLStreamConstants.START_DOCUMENT:
            namespace = parser.getNamespaceURI();
            break;
        case XMLStreamConstants.START_ELEMENT:
            nodeName = parser.getLocalName();
            if (nodeName.equals(GermaNet.XML_ILI_RECORD)) {
                IliRecord ili = processIliRecord(parser);
                germaNet.addIliRecord(ili);
            }
            break;
        }
    }
    parser.close();
    logger.debug("Done.");
}

From source file:com.marklogic.contentpump.AggregateXMLReader.java

@Override
public void initialize(InputSplit inSplit, TaskAttemptContext context)
        throws IOException, InterruptedException {
    initConfig(context);/* w  w w .j  a v  a  2s . c  o  m*/
    initAggConf(context);

    f = XMLInputFactory.newInstance();
    setFile(((FileSplit) inSplit).getPath());
    fs = file.getFileSystem(context.getConfiguration());
    FileStatus status = fs.getFileStatus(file);
    if (status.isDirectory()) {
        iterator = new FileIterator((FileSplit) inSplit, context);
        inSplit = iterator.next();
    }
    initStreamReader(inSplit);
}

From source file:fr.inria.oak.paxquery.pact.io.XmlNavTreePatternInputFormat.java

@Override
public void open(FileInputSplit split) throws IOException {
    super.open(split);

    this.documentID = split.getPath().toString();

    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {//from   w  ww. jav a 2 s. c o m
        this.streamReader = factory.createXMLStreamReader(this.stream);
    } catch (XMLStreamException e) {
        logger.error("XMLStreamException", e);
    }

    this.extractor = new SingleDocumentExtractor(this.navigationTreePattern, this.streamReader);
}

From source file:edu.harvard.i2b2.eclipse.plugins.fr.ws.FrServiceDriver.java

/**
 * Function to convert Ont requestVdo to OMElement
 * /*www.ja  v a2  s  .com*/
 * @param requestVdo   String requestVdo to send to Ont web service
 * @return An OMElement containing the Ont web service requestVdo
 */
public static OMElement getFrPayLoad(String requestVdo) throws Exception {
    OMElement lineItem = null;
    try {
        StringReader strReader = new StringReader(requestVdo);
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader reader = xif.createXMLStreamReader(strReader);

        StAXOMBuilder builder = new StAXOMBuilder(reader);
        lineItem = builder.getDocumentElement();
    } catch (FactoryConfigurationError e) {
        log.error(e.getMessage());
        throw new Exception(e);
    }
    return lineItem;
}