List of usage examples for javax.xml.stream.events EndElement getName
public QName getName();
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 {//from w w w . j a v a 2s . com 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:edu.jhu.hlt.concrete.ingesters.bolt.BoltForumPostIngester.java
@Override public Communication fromCharacterBasedFile(final Path path) throws IngestException { if (!Files.exists(path)) throw new IngestException("No file at: " + path.toString()); AnalyticUUIDGeneratorFactory f = new AnalyticUUIDGeneratorFactory(); AnalyticUUIDGenerator gen = f.create(); Communication c = new Communication(); c.setUuid(gen.next());/*w ww.ja v a 2 s. c o m*/ c.setType(this.getKind()); c.setMetadata(TooledMetadataConverter.convert(this)); try { ExistingNonDirectoryFile ef = new ExistingNonDirectoryFile(path); c.setId(ef.getName().split("\\.")[0]); } catch (NoSuchFileException | NotFileException e) { // might throw if path is a directory. throw new IngestException(path.toString() + " is not a file, or is a directory."); } String content; try (InputStream is = Files.newInputStream(path); BufferedInputStream bin = new BufferedInputStream(is, 1024 * 8 * 8);) { content = IOUtils.toString(bin, StandardCharsets.UTF_8); c.setText(content); } catch (IOException e) { throw new IngestException(e); } try (InputStream is = Files.newInputStream(path); BufferedInputStream bin = new BufferedInputStream(is, 1024 * 8 * 8); BufferedReader reader = new BufferedReader(new InputStreamReader(bin, StandardCharsets.UTF_8));) { XMLEventReader rdr = null; try { rdr = inF.createXMLEventReader(reader); // Below method moves the reader // to the first post element. Section headline = handleHeadline(rdr, content); headline.setUuid(gen.next()); c.addToSectionList(headline); int start = headline.getTextSpan().getStart(); int ending = headline.getTextSpan().getEnding(); if (ending < start) ending = start; // @tongfei: handle empty headlines String htxt = c.getText().substring(start, ending); LOGGER.debug("headline text: {}", htxt); // Section indices. int sectNumber = 1; int subSect = 0; // Move iterator to post start element. this.iterateToPosts(rdr); // Offset pointer. int currOff = -1; SectionFactory sf = new SectionFactory(gen); // First post element. while (rdr.hasNext()) { XMLEvent nextEvent = rdr.nextEvent(); currOff = nextEvent.getLocation().getCharacterOffset(); if (currOff > 0) { int currOffPlus = currOff + 20; int currOffLess = currOff - 20; LOGGER.debug("Offset: {}", currOff); if (currOffPlus < content.length()) LOGGER.debug("Surrounding text: {}", content.substring(currOffLess, currOffPlus)); } // First: see if document is going to end. // If yes: exit. if (nextEvent.isEndDocument()) break; // XMLEvent peeker = rdr.peek(); // Check if start element. if (nextEvent.isStartElement()) { StartElement se = nextEvent.asStartElement(); QName name = se.getName(); final String localName = name.getLocalPart(); LOGGER.debug("Hit start element: {}", localName); //region // Add sections for authors and datetimes for each bolt post // by Tongfei Chen Attribute attrAuthor = se.getAttributeByName(QName.valueOf("author")); Attribute attrDateTime = se.getAttributeByName(QName.valueOf("datetime")); if (attrAuthor != null && attrDateTime != null) { int loc = attrAuthor.getLocation().getCharacterOffset(); int sectAuthorBeginningOffset = loc + "<post author=\"".length(); Section sectAuthor = sf.fromTextSpan(new TextSpan(sectAuthorBeginningOffset, sectAuthorBeginningOffset + attrAuthor.getValue().length()), "author"); c.addToSectionList(sectAuthor); int sectDateTimeBeginningOffset = sectAuthorBeginningOffset + attrAuthor.getValue().length() + " datetime=".length(); Section sectDateTime = sf.fromTextSpan( new TextSpan(sectDateTimeBeginningOffset, sectDateTimeBeginningOffset + attrDateTime.getValue().length()), "datetime"); c.addToSectionList(sectDateTime); } //endregion // Move past quotes, images, and links. if (localName.equals(QUOTE_LOCAL_NAME)) { this.handleQuote(rdr); } else if (localName.equals(IMG_LOCAL_NAME)) { this.handleImg(rdr); } else if (localName.equals(LINK_LOCAL_NAME)) { this.handleLink(rdr); } // not a start element } else if (nextEvent.isCharacters()) { Characters chars = nextEvent.asCharacters(); int coff = chars.getLocation().getCharacterOffset(); if (!chars.isWhiteSpace()) { // content to be captured String fpContent = chars.getData(); LOGGER.debug("Character offset: {}", coff); LOGGER.debug("Character based data: {}", fpContent); // LOGGER.debug("Character data via offset diff: {}", content.substring(coff - fpContent.length(), coff)); SimpleImmutableEntry<Integer, Integer> pads = trimSpacing(fpContent); final int tsb = currOff + pads.getKey(); final int tse = currOff + fpContent.length() - pads.getValue(); final String subs = content.substring(tsb, tse); if (subs.replaceAll("\\p{Zs}", "").replaceAll("\\n", "").isEmpty()) { LOGGER.info("Found empty section: skipping."); continue; } LOGGER.debug("Section text: {}", subs); TextSpan ts = new TextSpan(tsb, tse); Section s = sf.fromTextSpan(ts, "post"); List<Integer> intList = new ArrayList<>(); intList.add(sectNumber); intList.add(subSect); s.setNumberList(intList); c.addToSectionList(s); subSect++; } } else if (nextEvent.isEndElement()) { EndElement ee = nextEvent.asEndElement(); currOff = ee.getLocation().getCharacterOffset(); QName name = ee.getName(); String localName = name.getLocalPart(); LOGGER.debug("Hit end element: {}", localName); if (localName.equalsIgnoreCase(POST_LOCAL_NAME)) { sectNumber++; subSect = 0; } } } return c; } catch (XMLStreamException | ConcreteException | StringIndexOutOfBoundsException x) { throw new IngestException(x); } finally { if (rdr != null) try { rdr.close(); } catch (XMLStreamException e) { // not likely. LOGGER.info("Error closing XMLReader.", e); } } } catch (IOException e) { throw new IngestException(e); } }
From source file:edu.monash.merc.system.parser.xml.HPAWSXmlParser.java
public List<HPAEntryBean> parseHPAXml(String fileName, XMLInputFactory2 factory2) { xmlif2 = factory2;/*from w w w .j a v a 2 s.c om*/ logger.info("Starting to parse " + fileName); List<HPAEntryBean> hpaEntryBeans = new ArrayList<HPAEntryBean>(); XMLEventReader2 xmlEventReader = null; try { xmlEventReader = (XMLEventReader2) xmlif2.createXMLEventReader(new FileInputStream(fileName)); QName entryQN = new QName(ELE_ENTRY); QName versionQN = new QName(ATTR_VERSION); QName urlQN = new QName(ATTR_URL); QName nameQN = new QName(ELE_NAME); QName identiferQN = new QName(ELE_IDENTIFIER); QName idQN = new QName(ATTR_ID); QName xrefQN = new QName(ELE_XREF); QName dbQN = new QName(ATTR_DB); QName tissueExpQN = new QName(ELE_TISSUE_EXPRESSION); QName typeQN = new QName(ATTR_TYPE); QName verificationQN = new QName(ELE_VERIFICATION); QName dataQN = new QName(ELE_DATA); QName tissueQN = new QName(ELE_TISSUE); QName statusQN = new QName(ATTR_STATUS); QName cellTypeQN = new QName(ELE_CELLTYPE); QName levelQN = new QName(ELE_LEVEL); QName antibodyQN = new QName(ELE_ANTIBODY); String version = null; String url = null; String geneName = null; String geneAccession = null; String dbNameForIdentifier = null; String xrefAc = null; String xrefDb = null; boolean tissueExpressionPresent = false; boolean antibodyPresent = false; String tissueStatus = null; String tissue = null; String cellType = null; String levelType = null; String level = null; String verificationType = null; String verification = null; HPAEntryBean hpaEntryBean = null; GeneBean geneBean = null; List<DbSourceAcEntryBean> dbSourceAcEntryBeans = new ArrayList<DbSourceAcEntryBean>(); List<PEEvidenceBean> peAntiIHCNormEvidenceBeans = new ArrayList<PEEvidenceBean>(); PEEvidenceBean antiIHCNormEvidenceBean = null; AccessionBean identifiedAcBean = null; while (xmlEventReader.hasNextEvent()) { //eventType = reader.next(); XMLEvent event = xmlEventReader.nextEvent(); if (event.isStartElement()) { StartElement element = event.asStartElement(); //hpa entry if (element.getName().equals(entryQN)) { //start to create a hpaEntryBean hpaEntryBean = new HPAEntryBean(); //create a GeneBean geneBean = new GeneBean(); //create a list of DbSourceAcEntryBean to store all DbSource and Ac dbSourceAcEntryBeans = new ArrayList<DbSourceAcEntryBean>(); //create a list of PEEvidenceBean to store all antibody evidencs for the current gene peAntiIHCNormEvidenceBeans = new ArrayList<PEEvidenceBean>(); //get the version attribute Attribute versionAttr = element.getAttributeByName(versionQN); if (versionAttr != null) { version = versionAttr.getValue(); } //get the url attribute Attribute urlAttr = element.getAttributeByName(urlQN); if (urlAttr != null) { url = urlAttr.getValue(); } } //parse the gene name in the name element if (element.getName().equals(nameQN)) { if (xmlEventReader.peek().isCharacters()) { event = xmlEventReader.nextEvent(); Characters geneCharacters = event.asCharacters(); if (geneCharacters != null) { geneName = geneCharacters.getData(); } } } //parse the ensg accession and db in the identifier element if (element.getName().equals(identiferQN)) { Attribute idAttr = element.getAttributeByName(idQN); if (idAttr != null) { geneAccession = idAttr.getValue(); } Attribute dbAttr = element.getAttributeByName(dbQN); if (dbAttr != null) { dbNameForIdentifier = dbAttr.getValue(); } } //parse all db and accession pair in xref element if (element.getName().equals(xrefQN)) { Attribute idAttr = element.getAttributeByName(idQN); if (idAttr != null) { xrefAc = idAttr.getValue(); } Attribute dbAttr = element.getAttributeByName(dbQN); if (dbAttr != null) { xrefDb = dbAttr.getValue(); } } //parse tissueExpression if (element.getName().equals(tissueExpQN)) { //we only focus on the tissueExpression element in the path /entry/tissueExpression if (!antibodyPresent) { //set the tissueExpression present flag into true; tissueExpressionPresent = true; //create a list of PEEvidenceBean to store the PEEvidence for antibody peAntiIHCNormEvidenceBeans = new ArrayList<PEEvidenceBean>(); } } //parse the verification element to get reliability or validation value if (element.getName().equals(verificationQN)) { //we only focus on the verification element in the path /entry/tissueExpression/verification if (!antibodyPresent && tissueExpressionPresent) { Attribute verifAttr = element.getAttributeByName(typeQN); if (verifAttr != null) { verificationType = element.getAttributeByName(typeQN).getValue(); } if (xmlEventReader.peek().isCharacters()) { event = xmlEventReader.nextEvent(); verification = event.asCharacters().getData(); } } } //start of the data element if (element.getName().equals(dataQN)) { //we only focus on the data element in the path /entry/tissueExpression/data if (!antibodyPresent && tissueExpressionPresent) { antiIHCNormEvidenceBean = new PEEvidenceBean(); TPBDataTypeBean dataTypeBean = createTPBDataTypeBeanForPEANTIIHCNORM(); antiIHCNormEvidenceBean.setTpbDataTypeBean(dataTypeBean); } } //start of tissue if (element.getName().equals(tissueQN)) { //we only focus on the tissue element in the path /entry/tissueExpression/data/tissue if (!antibodyPresent && tissueExpressionPresent) { Attribute tissueStatusAttr = element.getAttributeByName(statusQN); if (tissueStatusAttr != null) { tissueStatus = tissueStatusAttr.getValue(); } if (xmlEventReader.peek().isCharacters()) { event = xmlEventReader.nextEvent(); tissue = event.asCharacters().getData(); } } } //start of cellType if (element.getName().equals(cellTypeQN)) { //we only focus on the cellType element in the path /entry/tissueExpression/data/cellType if (!antibodyPresent && tissueExpressionPresent) { if (xmlEventReader.peek().isCharacters()) { event = xmlEventReader.nextEvent(); cellType = event.asCharacters().getData(); } } } //start of level if (element.getName().equals(levelQN)) { //we only focus on the level element in the path /entry/tissueExpression/data/level if (!antibodyPresent && tissueExpressionPresent) { Attribute typeAttr = element.getAttributeByName(typeQN); if (typeAttr != null) { levelType = typeAttr.getValue(); } if (xmlEventReader.peek().isCharacters()) { event = xmlEventReader.nextEvent(); level = event.asCharacters().getData(); } } } //start of antibody element if (element.getName().equals(antibodyQN)) { //we have to setup antibodyPresent flag as true antibodyPresent = true; } } //End of element if (event.isEndElement()) { EndElement endElement = event.asEndElement(); //hpa entry end if (endElement.getName().equals(entryQN)) { //set hpa version hpaEntryBean.setHpaVersion(version); //hpaEntryBean set gene bean hpaEntryBean.setGeneBean(geneBean); //create the primary dbsource bean DBSourceBean primaryDbSourceBean = createPrimaryDBSourceBeanForHPA(); //set the primary DBSourceBean hpaEntryBean.setPrimaryDbSourceBean(primaryDbSourceBean); //set the identified accesion bean hpaEntryBean.setIdentifiedAccessionBean(identifiedAcBean); //set DbSourceAcEntryBean list hpaEntryBean.setDbSourceAcEntryBeans(dbSourceAcEntryBeans); //set all the PeAntiIHCBody evidences if (peAntiIHCNormEvidenceBeans.size() == 0) { peAntiIHCNormEvidenceBeans.add(createNonePEEvidence(url)); } hpaEntryBean.setPeAntiIHCNormEvidencesBeans(peAntiIHCNormEvidenceBeans); //add the current hpa entry bean into list hpaEntryBeans.add(hpaEntryBean); //reset version and url version = null; url = null; identifiedAcBean = null; } //end of gene name, populate the gene name if (endElement.getName().equals(nameQN)) { //set gene name geneBean.setDisplayName(geneName); } //end of identifier, populating for gene accession, db and accessions if any if (endElement.getName().equals(identiferQN)) { //set the gene accession geneBean.setEnsgAccession(geneAccession); identifiedAcBean = createIdentifiedAcBean(geneAccession, dbNameForIdentifier); //create a DbSourceAcEntryBean based on the identifier element DbSourceAcEntryBean dbSourceAcEntryBean = createDbSourceAcEntry(dbNameForIdentifier, geneAccession); //add this DbSourceAcEntryBean into list dbSourceAcEntryBeans.add(dbSourceAcEntryBean); } //end of xref element. populate for db and accessions if any if (endElement.getName().equals(xrefQN)) { //create a DbSourceAcEntryBean based on the xref element DbSourceAcEntryBean dbSourceAcEntryBean = createDbSourceAcEntry(xrefDb, xrefAc); //add this DbSoureAcEntryBean into list dbSourceAcEntryBeans.add(dbSourceAcEntryBean); //set rest of db and accession values xrefDb = null; xrefAc = null; } //end of the tissueExpression if (endElement.getName().equals(tissueExpQN)) { //we only focus on the tissueExpression element in the path /entry/tissueExpression if (!antibodyPresent) { //the tissueExpression is end. we have to reset tissueExpressionPresent, //verificationType and verification values under the tissueExpression element level //reset tissueExpression present flag into false tissueExpressionPresent = false; //reset verification type verificationType = null; //reset verification value verification = null; } } //end of data element if (endElement.getName().equals(dataQN)) { //we only focus on the data element in the path /entry/tissueExpression/data if (!antibodyPresent && tissueExpressionPresent) { //we only consider the tissue status is normal one if (StringUtils.endsWithIgnoreCase(tissueStatus, TISSUE_STATUS_NORMAL)) { setAntiEvidence(antiIHCNormEvidenceBean, url, verification, tissue, cellType, level, levelType); //add anti evidence peAntiIHCNormEvidenceBeans.add(antiIHCNormEvidenceBean); } //the data element is end. we have to reset the tissueStatus, tissue, cellType and level values under the data element level tissueStatus = null; tissue = null; cellType = null; level = null; levelType = null; } } //end of antibody if (endElement.getName().equals(antibodyQN)) { //we have to reset antibodyPresent flag as false antibodyPresent = false; } } //End of XML document if (event.isEndDocument()) { // finished to parse the whole document; break; } } } catch (Exception ex) { logger.error(ex); throw new DMXMLParserException(ex); } finally { if (xmlEventReader != null) { try { xmlEventReader.close(); } catch (Exception e) { //ignore whatever caught. } } } return hpaEntryBeans; }
From source file:microsoft.exchange.webservices.data.core.EwsXmlReader.java
/** * Determines whether current element is a end element. * * @param namespacePrefix the namespace prefix * @param localName the local name * @return boolean/*from w ww . j a v a 2 s .c o m*/ */ public boolean isEndElement(String namespacePrefix, String localName) { boolean isEndElement = false; if (this.presentEvent.isEndElement()) { EndElement endElement = this.presentEvent.asEndElement(); QName qName = endElement.getName(); isEndElement = qName.getLocalPart().equals(localName) && qName.getPrefix().equals(namespacePrefix); } return isEndElement; }
From source file:microsoft.exchange.webservices.data.core.EwsXmlReader.java
/** * Determines whether current element is a end element. * * @param xmlNamespace the xml namespace * @param localName the local name/* www .ja va2s .c o m*/ * @return boolean */ public boolean isEndElement(XmlNamespace xmlNamespace, String localName) { boolean isEndElement = false; /* * if(localName.equals("Body")) { return true; } else */ if (this.presentEvent.isEndElement()) { EndElement endElement = this.presentEvent.asEndElement(); QName qName = endElement.getName(); isEndElement = qName.getLocalPart().equals(localName) && (qName.getPrefix().equals(EwsUtilities.getNamespacePrefix(xmlNamespace)) || qName.getNamespaceURI().equals(EwsUtilities.getNamespaceUri(xmlNamespace))); } return isEndElement; }
From source file:com.logiware.accounting.domain.EdiInvoice.java
private void removeElementType(EndElement endElement) throws Exception { if (isHeader) { if ("Applicationreference".equalsIgnoreCase(endElement.getName().toString())) { elementType = null;/*from ww w.ja v a 2 s . c o m*/ } else if ("Reference".equalsIgnoreCase(endElement.getName().toString())) { elementType = null; } else if ("Sender".equalsIgnoreCase(endElement.getName().toString())) { elementType = null; } } else if (isBody) { User user = new UserDAO().findUserName("system"); if (isInformation) { if ("Invoice".equalsIgnoreCase(endElement.getName().toString())) { elementType = null; } else if ("RelatedReferences".equalsIgnoreCase(endElement.getName().toString())) { elementType = null; } else if ("Parties".equalsIgnoreCase(endElement.getName().toString())) { if (elementType.equalsIgnoreCase("Vendor")) { isBank = false; } if (null == ediInvoiceParties) { ediInvoiceParties = new ArrayList<EdiInvoiceParty>(); } ediInvoiceParties.add(party); elementType = null; } else if ("PaymentTerms".equalsIgnoreCase(endElement.getName().toString())) { elementType = null; } else if ("Bank".equalsIgnoreCase(endElement.getName().toString())) { if (null == ediInvoiceBanks) { ediInvoiceBanks = new ArrayList<EdiInvoiceBank>(); } ediInvoiceBanks.add(bank); } else if ("ShipmentInformation".equalsIgnoreCase(endElement.getName().toString())) { elementType = null; } } else if (isDetails) { if ("Detail".equalsIgnoreCase(endElement.getName().toString())) { if (null == ediInvoiceDetails) { ediInvoiceDetails = new ArrayList<EdiInvoiceDetail>(); } detail.setInvoiceStatus("0"); detail.setChargeStatus(""); detail.setUpdatedBy(user); detail.setUpdatedDate(new Date()); ediInvoiceDetails.add(detail); elementType = null; } } else if (isSummary) { if ("TotalMonetaryAmount".equalsIgnoreCase(endElement.getName().toString())) { elementType = null; } else if ("TotalMonetaryAmountGroupByVAT".equalsIgnoreCase(endElement.getName().toString())) { elementType = null; } } } }
From source file:edu.unc.lib.dl.util.TripleStoreQueryServiceMulgaraImpl.java
/** * @param query/*w ww. j av a2s. c o m*/ * an ITQL command * @return the message returned by Mulgara * @throws RemoteException * for communication failure */ public String storeCommand(String query) { String result = null; String response = this.sendTQL(query); if (response != null) { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); try (StringReader sr = new StringReader(response)) { XMLEventReader r = factory.createXMLEventReader(sr); boolean inMessage = false; StringBuffer message = new StringBuffer(); while (r.hasNext()) { XMLEvent e = r.nextEvent(); if (e.isStartElement()) { StartElement s = e.asStartElement(); if ("message".equals(s.getName().getLocalPart())) { inMessage = true; } } else if (e.isEndElement()) { EndElement end = e.asEndElement(); if ("message".equals(end.getName().getLocalPart())) { inMessage = false; } } else if (inMessage && e.isCharacters()) { message.append(e.asCharacters().getData()); } } r.close(); result = message.toString(); } catch (XMLStreamException e) { e.printStackTrace(); } } return result; }
From source file:com.logiware.accounting.domain.EdiInvoice.java
private void createEcuLineInvoice(File file) throws Exception { InputStream inputStream = null; XMLEventReader eventReader = null; try {/*from ww w. ja v a 2s.c o m*/ XMLInputFactory inputFactory = XMLInputFactory.newInstance(); inputStream = new FileInputStream(file); eventReader = inputFactory.createXMLEventReader(inputStream); while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if (event.isStartElement()) { StartElement startElement = event.asStartElement(); if ("Header".equalsIgnoreCase(startElement.getName().toString())) { isHeader = true; elements.add("Header"); } else if ("Body".equalsIgnoreCase(startElement.getName().toString())) { isBody = true; elements.add("Body"); } else if (isBody && "Information".equalsIgnoreCase(startElement.getName().toString())) { isInformation = true; elements.add("Information"); } else if (isBody && !isInformation && "Details".equalsIgnoreCase(startElement.getName().toString())) { isDetails = true; elements.add("Details"); } else if (isBody && !isInformation && !isDetails && "Summary".equalsIgnoreCase(startElement.getName().toString())) { isSummary = true; elements.add("Summary"); } else if (null == elementType) { setElementType(startElement); } else if (null != elementType && null == characterType) { setCharacterType(startElement); } } else if (event.isCharacters()) { setValue(event.asCharacters()); } else if (event.isEndElement()) { EndElement endElement = event.asEndElement(); if (null != characterType && null != elementType) { removeCharacterType(); } else if (null != elementType) { removeElementType(endElement); } else if (isSummary && "Summary".equalsIgnoreCase(endElement.getName().toString())) { isSummary = false; } else if (isDetails && "Details".equalsIgnoreCase(endElement.getName().toString())) { isDetails = false; } else if (isBody && "Information".equalsIgnoreCase(endElement.getName().toString())) { isInformation = false; } else if ("Body".equalsIgnoreCase(endElement.getName().toString())) { isBody = false; } else if ("Header".equalsIgnoreCase(endElement.getName().toString())) { isHeader = false; } } } this.company = Company.ECU_LINE; status = new EdiInvoiceDAO().getStatus(vendorNumber, invoiceNumber); if (!elements.contains("Header")) { throw new AccountingException("Bad File. <Header> element missing"); } else if (!elements.contains("Body")) { throw new AccountingException("Bad File. <Body> missing"); } else if (!elements.contains("Information")) { throw new AccountingException("Bad File. <Information> element under <Body> missing"); } else if (!elements.contains("Details")) { throw new AccountingException("Bad File. <Details> element under <Body> missing"); } else if (!elements.contains("Summary")) { throw new AccountingException("Bad File. <Summary> element under <Body> missing"); } else if (!elements.contains("Applicationreference")) { throw new AccountingException("Bad File. <Applicationreference> element under <Header> missing"); } else if (!elements.contains("Reference")) { throw new AccountingException("Bad File. <Reference> element under <Header> missing"); } else if (!elements.contains("Sender")) { throw new AccountingException("Bad File. <Sender> element under <Header> missing"); } else if (!elements.contains("Code")) { throw new AccountingException("Bad File. <Code> element under <Sender> of <Header> missing"); } else if (!elements.contains("Invoice")) { throw new AccountingException( "Bad File. <Invoice> element under <Information> element of <Body> missing"); } else if (!elements.contains("RelatedReferences")) { throw new AccountingException( "Bad File. <RelatedReferences> element under <Information> element of <Body> missing"); } else if (!elements.contains("BY")) { throw new AccountingException( "Bad File. <Parties Qualifier=\"BY\"> under <Information> element of <Body> missing"); } else if (!elements.contains("SU")) { throw new AccountingException( "Bad File. <Parties Qualifier=\"SU\"> under <Information> element of <Body> missing"); } else if (!elements.contains("PaymentTerms")) { throw new AccountingException( "Bad File. <PaymentTerms> element under <Information> element of <Body> missing"); } else if (!elements.contains("ShipmentInformation")) { throw new AccountingException( "Bad File. <ShipmentInformation> element under <Information> element of <Body> missing"); } else if (!elements.contains("Detail")) { throw new AccountingException( "Bad File. <Detail> element under <Details> element of <Body> missing"); } else if (!elements.contains("TotalMonetaryAmount")) { throw new AccountingException( "Bad File. <TotalMonetaryAmount> element under <Summary> element of <Body> missing"); } else if (!elements.contains("TotalMonetaryAmountGroupByVAT")) { throw new AccountingException( "Bad File. <TotalMonetaryAmountGroupByVAT> element under <Summary> element of <Body> missing"); } } catch (Exception e) { throw e; } finally { if (null != eventReader) { eventReader.close(); } if (null != inputStream) { inputStream.close(); } } }
From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlFilterReader.java
private void processEndElement(EndElement event) throws XPathExpressionException, IOException { //System.out.println( "EE=" + event ); boolean buffering = currentlyBuffering(); Level child = stack.pop();/*w w w . ja v a 2s . c o m*/ if (buffering) { if (child.node == child.scopeNode) { processBufferedElement(child); } } else { if (!isEmptyElement) { QName n = event.getName(); writer.write("</"); String p = n.getPrefix(); if (p != null && !p.isEmpty()) { writer.write(p); writer.write(":"); } writer.write(n.getLocalPart()); writer.write(">"); } child.node.getParentNode().removeChild(child.node); } }
From source file:org.omegat.util.TMXReader2.java
protected void parseTu(StartElement element) throws Exception { currentTu.clear();/* w w w. j a va 2s . c om*/ currentTu.changeid = getAttributeValue(element, "changeid"); currentTu.changedate = parseISO8601date(getAttributeValue(element, "changedate")); currentTu.creationid = getAttributeValue(element, "creationid"); currentTu.creationdate = parseISO8601date(getAttributeValue(element, "creationdate")); while (true) { XMLEvent e = xml.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_ELEMENT: StartElement eStart = (StartElement) e; if ("tuv".equals(eStart.getName().getLocalPart())) { parseTuv(eStart); } else if ("prop".equals(eStart.getName().getLocalPart())) { parseProp(eStart); } else if ("note".equals(eStart.getName().getLocalPart())) { parseNote(eStart); } break; case XMLEvent.END_ELEMENT: EndElement eEnd = (EndElement) e; if ("tu".equals(eEnd.getName().getLocalPart())) { return; } break; } } }