List of usage examples for javax.xml.stream.events StartElement getAttributeByName
public Attribute getAttributeByName(QName name);
From source file:com.msopentech.odatajclient.testservice.utils.AbstractUtilities.java
private Map.Entry<String, Boolean> getTargetInfo(final StartElement element, final String linkName) throws Exception { final InputStream metadata = fsManager.readFile(Constants.METADATA, Accept.XML); XMLEventReader reader = XMLUtilities.getEventReader(metadata); final String associationName = element.getAttributeByName(new QName("Relationship")).getValue(); final Map.Entry<Integer, XmlElement> association = XMLUtilities.getAtomElement(reader, null, "Association", Collections.<Map.Entry<String, String>>singleton(new SimpleEntry<String, String>("Name", associationName.substring(associationName.lastIndexOf(".") + 1))), 0, 4, 4, false);/*from w w w . ja va 2 s. co m*/ final InputStream associationContent = association.getValue().toStream(); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(associationContent, bos); IOUtils.closeQuietly(associationContent); reader.close(); reader = XMLUtilities.getEventReader(new ByteArrayInputStream(bos.toByteArray())); final Map.Entry<Integer, XmlElement> associationEnd = XMLUtilities.getAtomElement(reader, null, "End", Collections.<Map.Entry<String, String>>singleton(new SimpleEntry<String, String>("Role", linkName)), 0, -1, -1, false); final String target = associationEnd.getValue().getStart().getAttributeByName(new QName("Type")).getValue(); final boolean feed = associationEnd.getValue().getStart().getAttributeByName(new QName("Multiplicity")) .getValue().equals("*"); return new SimpleEntry<String, Boolean>(target, feed); }
From source file:json_to_xml_1.java
public int execute(String args[]) throws ProgramTerminationException { this.getInfoMessages().clear(); if (args.length < 2) { throw constructTermination("messageArgumentsMissing", null, getI10nString("messageArgumentsMissingUsage") + "\n\tjson_to_xml_1 " + getI10nString("messageParameterList") + "\n"); }/*from w ww . j a v a 2 s . co m*/ File resultInfoFile = new File(args[1]); try { resultInfoFile = resultInfoFile.getCanonicalFile(); } catch (SecurityException ex) { throw constructTermination("messageResultInfoFileCantGetCanonicalPath", ex, null, resultInfoFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageResultInfoFileCantGetCanonicalPath", ex, null, resultInfoFile.getAbsolutePath()); } if (resultInfoFile.exists() == true) { if (resultInfoFile.isFile() == true) { if (resultInfoFile.canWrite() != true) { throw constructTermination("messageResultInfoFileIsntWritable", null, null, resultInfoFile.getAbsolutePath()); } } else { throw constructTermination("messageResultInfoPathIsntAFile", null, null, resultInfoFile.getAbsolutePath()); } } json_to_xml_1.resultInfoFile = resultInfoFile; File jobFile = new File(args[0]); try { jobFile = jobFile.getCanonicalFile(); } catch (SecurityException ex) { throw constructTermination("messageJobFileCantGetCanonicalPath", ex, null, jobFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageJobFileCantGetCanonicalPath", ex, null, jobFile.getAbsolutePath()); } if (jobFile.exists() != true) { throw constructTermination("messageJobFileDoesntExist", null, null, jobFile.getAbsolutePath()); } if (jobFile.isFile() != true) { throw constructTermination("messageJobPathIsntAFile", null, null, jobFile.getAbsolutePath()); } if (jobFile.canRead() != true) { throw constructTermination("messageJobFileIsntReadable", null, null, jobFile.getAbsolutePath()); } System.out.println("json_to_xml_1: " + getI10nStringFormatted("messageCallDetails", jobFile.getAbsolutePath(), resultInfoFile.getAbsolutePath())); File inputFile = null; File outputFile = null; try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); InputStream in = new FileInputStream(jobFile); XMLEventReader eventReader = inputFactory.createXMLEventReader(in); while (eventReader.hasNext() == true) { XMLEvent event = eventReader.nextEvent(); if (event.isStartElement() == true) { String tagName = event.asStartElement().getName().getLocalPart(); if (tagName.equals("json-input-file") == true) { StartElement inputFileElement = event.asStartElement(); Attribute pathAttribute = inputFileElement.getAttributeByName(new QName("path")); if (pathAttribute == null) { throw constructTermination("messageJobFileEntryIsMissingAnAttribute", null, null, jobFile.getAbsolutePath(), tagName, "path"); } String inputFilePath = pathAttribute.getValue(); if (inputFilePath.isEmpty() == true) { throw constructTermination("messageJobFileAttributeValueIsEmpty", null, null, jobFile.getAbsolutePath(), tagName, "path"); } inputFile = new File(inputFilePath); if (inputFile.isAbsolute() != true) { inputFile = new File( jobFile.getAbsoluteFile().getParent() + File.separator + inputFilePath); } try { inputFile = inputFile.getCanonicalFile(); } catch (SecurityException ex) { throw constructTermination("messageInputFileCantGetCanonicalPath", ex, null, new File(inputFilePath).getAbsolutePath(), jobFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageInputFileCantGetCanonicalPath", ex, null, new File(inputFilePath).getAbsolutePath(), jobFile.getAbsolutePath()); } if (inputFile.exists() != true) { throw constructTermination("messageInputFileDoesntExist", null, null, inputFile.getAbsolutePath(), jobFile.getAbsolutePath()); } if (inputFile.isFile() != true) { throw constructTermination("messageInputPathIsntAFile", null, null, inputFile.getAbsolutePath(), jobFile.getAbsolutePath()); } if (inputFile.canRead() != true) { throw constructTermination("messageInputFileIsntReadable", null, null, inputFile.getAbsolutePath(), jobFile.getAbsolutePath()); } } else if (tagName.equals("xml-output-file") == true) { StartElement outputFileElement = event.asStartElement(); Attribute pathAttribute = outputFileElement.getAttributeByName(new QName("path")); if (pathAttribute == null) { throw constructTermination("messageJobFileEntryIsMissingAnAttribute", null, null, jobFile.getAbsolutePath(), tagName, "path"); } String outputFilePath = pathAttribute.getValue(); if (outputFilePath.isEmpty() == true) { throw constructTermination("messageJobFileAttributeValueIsEmpty", null, null, jobFile.getAbsolutePath(), tagName, "path"); } outputFile = new File(outputFilePath); if (outputFile.isAbsolute() != true) { outputFile = new File( jobFile.getAbsoluteFile().getParent() + File.separator + outputFilePath); } try { outputFile = outputFile.getCanonicalFile(); } catch (SecurityException ex) { throw constructTermination("messageOutputFileCantGetCanonicalPath", ex, null, new File(outputFilePath).getAbsolutePath(), jobFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageOutputFileCantGetCanonicalPath", ex, null, new File(outputFilePath).getAbsolutePath(), jobFile.getAbsolutePath()); } if (outputFile.exists() == true) { if (outputFile.isFile() == true) { if (outputFile.canWrite() != true) { throw constructTermination("messageOutputFileIsntWritable", null, null, outputFile.getAbsolutePath()); } } else { throw constructTermination("messageOutputPathIsntAFile", null, null, outputFile.getAbsolutePath()); } } } } } } catch (XMLStreamException ex) { throw constructTermination("messageJobFileErrorWhileReading", ex, null, jobFile.getAbsolutePath()); } catch (SecurityException ex) { throw constructTermination("messageJobFileErrorWhileReading", ex, null, jobFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageJobFileErrorWhileReading", ex, null, jobFile.getAbsolutePath()); } if (inputFile == null) { throw constructTermination("messageJobFileNoInputFile", null, null, jobFile.getAbsolutePath()); } if (outputFile == null) { throw constructTermination("messageJobFileNoOutputFile", null, null, jobFile.getAbsolutePath()); } StringBuilder stringBuilder = new StringBuilder(); try { JSONObject json = new JSONObject(new JSONTokener(new BufferedReader(new FileReader(inputFile)))); stringBuilder.append(XML.toString(json)); } catch (Exception ex) { throw constructTermination("messageConversionError", ex, null, inputFile.getAbsolutePath()); } try { BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.write( "<!-- This file was created by json_to_xml_1, which is free software licensed under the GNU Affero General Public License 3 or any later version (see https://github.com/publishing-systems/digital_publishing_workflow_tools/ and http://www.publishing-systems.org). -->\n"); writer.write(stringBuilder.toString()); writer.flush(); writer.close(); } catch (FileNotFoundException ex) { throw constructTermination("messageOutputFileWritingError", ex, null, outputFile.getAbsolutePath()); } catch (UnsupportedEncodingException ex) { throw constructTermination("messageOutputFileWritingError", ex, null, outputFile.getAbsolutePath()); } catch (IOException ex) { throw constructTermination("messageOutputFileWritingError", ex, null, outputFile.getAbsolutePath()); } return 0; }
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());//from w w w . j ava2s .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:microsoft.exchange.webservices.data.core.EwsXmlReader.java
/** * Read attribute value from QName.//from w ww. j a va2s.co m * * @param qName QName of the attribute * @return Attribute Value * @throws Exception thrown if attribute value can not be read */ private String readAttributeValue(QName qName) throws Exception { if (this.presentEvent.isStartElement()) { StartElement startElement = this.presentEvent.asStartElement(); Attribute attr = startElement.getAttributeByName(qName); if (null != attr) { return attr.getValue(); } else { return null; } } else { String errMsg = String.format("Could not fetch attribute %s", qName.toString()); throw new Exception(errMsg); } }
From source file:ca.uhn.fhir.parser.XmlParser.java
private <T> T doXmlLoop(XMLEventReader streamReader, ParserState<T> parserState) { ourLog.trace("Entering XML parsing loop with state: {}", parserState); try {//from w ww . j ava 2 s .com List<String> heldComments = new ArrayList<String>(1); while (streamReader.hasNext()) { XMLEvent nextEvent = streamReader.nextEvent(); try { switch (nextEvent.getEventType()) { case XMLStreamConstants.START_ELEMENT: { StartElement elem = nextEvent.asStartElement(); String namespaceURI = elem.getName().getNamespaceURI(); if ("extension".equals(elem.getName().getLocalPart())) { Attribute urlAttr = elem.getAttributeByName(new QName("url")); String url; if (urlAttr == null || isBlank(urlAttr.getValue())) { getErrorHandler().missingRequiredElement(new ParseLocation("extension"), "url"); url = null; } else { url = urlAttr.getValue(); } parserState.enteringNewElementExtension(elem, url, false); } else if ("modifierExtension".equals(elem.getName().getLocalPart())) { Attribute urlAttr = elem.getAttributeByName(new QName("url")); String url; if (urlAttr == null || isBlank(urlAttr.getValue())) { getErrorHandler().missingRequiredElement(new ParseLocation("modifierExtension"), "url"); url = null; } else { url = urlAttr.getValue(); } parserState.enteringNewElementExtension(elem, url, true); } else { String elementName = elem.getName().getLocalPart(); parserState.enteringNewElement(namespaceURI, elementName); } if (!heldComments.isEmpty()) { for (String next : heldComments) { parserState.commentPre(next); } heldComments.clear(); } @SuppressWarnings("unchecked") Iterator<Attribute> attributes = elem.getAttributes(); for (Iterator<Attribute> iter = attributes; iter.hasNext();) { Attribute next = iter.next(); parserState.attributeValue(next.getName().getLocalPart(), next.getValue()); } break; } case XMLStreamConstants.END_DOCUMENT: case XMLStreamConstants.END_ELEMENT: { if (!heldComments.isEmpty()) { for (String next : heldComments) { parserState.commentPost(next); } heldComments.clear(); } parserState.endingElement(); // if (parserState.isComplete()) { // return parserState.getObject(); // } break; } case XMLStreamConstants.CHARACTERS: { parserState.string(nextEvent.asCharacters().getData()); break; } case XMLStreamConstants.COMMENT: { Comment comment = (Comment) nextEvent; String commentText = comment.getText(); heldComments.add(commentText); break; } } parserState.xmlEvent(nextEvent); } catch (DataFormatException e) { throw new DataFormatException("DataFormatException at [" + nextEvent.getLocation().toString() + "]: " + e.getMessage(), e); } } return parserState.getObject(); } catch (XMLStreamException e) { throw new DataFormatException(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. ja va 2 s . c o m 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:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
private InputStream writeFromStartToEndElement(final StartElement element, final XMLEventReader reader, final boolean document) throws XMLStreamException { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLOutputFactory xof = XMLOutputFactory.newInstance(); final XMLEventWriter writer = xof.createXMLEventWriter(bos); final QName name = element.getName(); if (document) { final XMLEventFactory eventFactory = XMLEventFactory.newInstance(); writer.add(eventFactory.createStartDocument("UTF-8", "1.0")); writer.add(element);//from w ww . j a v a2s. c om if (element.getAttributeByName(new QName(ATOM_DATASERVICE_NS)) == null) { writer.add(eventFactory.createNamespace(ATOM_PROPERTY_PREFIX.substring(0, 1), DATASERVICES_NS)); } if (element.getAttributeByName(new QName(ATOM_METADATA_NS)) == null) { writer.add(eventFactory.createNamespace(ATOM_METADATA_PREFIX.substring(0, 1), METADATA_NS)); } } else { writer.add(element); } XMLEvent event = element; while (reader.hasNext() && !(event.isEndElement() && name.equals(event.asEndElement().getName()))) { event = reader.nextEvent(); writer.add(event); } writer.flush(); writer.close(); return new ByteArrayInputStream(bos.toByteArray()); }
From source file:nl.nn.adapterframework.validation.XSD.java
public void init() throws ConfigurationException { if (noNamespaceSchemaLocation != null) { url = ClassUtils.getResourceURL(classLoader, noNamespaceSchemaLocation); if (url == null) { throw new ConfigurationException("Cannot find [" + noNamespaceSchemaLocation + "]"); }//from w w w . ja v a 2 s . co m resourceTarget = noNamespaceSchemaLocation; toString = noNamespaceSchemaLocation; } else { if (resource != null) { url = ClassUtils.getResourceURL(classLoader, resource); if (url == null) { throw new ConfigurationException("Cannot find [" + resource + "]"); } resourceTarget = resource; toString = resource; if (resourceInternalReference != null) { resourceTarget = resourceTarget + "-" + resourceInternalReference + ".xsd"; toString = toString + "!" + resourceInternalReference; } } else if (sourceXsds == null) { throw new ConfigurationException( "None of noNamespaceSchemaLocation, resource or mergedResources is specified"); } else { resourceTarget = "["; toString = "["; boolean first = true; for (XSD xsd : sourceXsds) { if (first) { first = false; } else { resourceTarget = resourceTarget + ", "; toString = toString + ", "; } resourceTarget = resourceTarget + xsd.getResourceTarget().replaceAll("/", "_"); toString = toString + xsd.toString(); } resourceTarget = resourceTarget + "].xsd"; toString = toString + "]"; } if (parentLocation == null) { this.parentLocation = ""; } } try { InputStream in = getInputStream(); XMLEventReader er = XmlUtils.INPUT_FACTORY.createXMLEventReader(in, XmlUtils.STREAM_FACTORY_ENCODING); int elementDepth = 0; while (er.hasNext()) { XMLEvent e = er.nextEvent(); switch (e.getEventType()) { case XMLStreamConstants.START_ELEMENT: elementDepth++; StartElement el = e.asStartElement(); if (el.getName().equals(SchemaUtils.SCHEMA)) { Attribute a = el.getAttributeByName(SchemaUtils.TNS); if (a != null) { xsdTargetNamespace = a.getValue(); } Iterator<Namespace> nsIterator = el.getNamespaces(); while (nsIterator.hasNext() && StringUtils.isEmpty(xsdDefaultNamespace)) { Namespace ns = nsIterator.next(); if (StringUtils.isEmpty(ns.getPrefix())) { xsdDefaultNamespace = ns.getNamespaceURI(); } } } else if (el.getName().equals(SchemaUtils.IMPORT)) { Attribute a = el.getAttributeByName(SchemaUtils.NAMESPACE); if (a != null) { boolean skip = false; ArrayList ans = null; if (StringUtils.isNotEmpty(getImportedNamespacesToIgnore())) { ans = new ArrayList(Arrays.asList(getImportedNamespacesToIgnore().split(","))); } if (StringUtils.isNotEmpty(a.getValue()) && ans != null) { if (ans.contains(a.getValue())) { skip = true; } } if (!skip) { importedNamespaces.add(a.getValue()); } } } else if (el.getName().equals(SchemaUtils.ELEMENT)) { if (elementDepth == 2) { rootTags.add(el.getAttributeByName(SchemaUtils.NAME).getValue()); } } break; case XMLStreamConstants.END_ELEMENT: elementDepth--; break; } } this.targetNamespace = xsdTargetNamespace; if (namespace == null) { // In case WsdlXmlValidator doesn't have schemaLocation namespace = xsdTargetNamespace; } } catch (IOException e) { String message = "IOException reading XSD"; LOG.error(message, e); throw new ConfigurationException(message, e); } catch (XMLStreamException e) { String message = "XMLStreamException reading XSD"; LOG.error(message, e); throw new ConfigurationException(message, e); } }
From source file:nl.nn.adapterframework.validation.XSD.java
public Set<XSD> getXsdsRecursive(Set<XSD> xsds, boolean ignoreRedefine) throws ConfigurationException { try {//from w w w. j av a 2 s . c om InputStream in = getInputStream(); if (in == null) return null; XMLEventReader er = XmlUtils.INPUT_FACTORY.createXMLEventReader(in, XmlUtils.STREAM_FACTORY_ENCODING); while (er.hasNext()) { XMLEvent e = er.nextEvent(); switch (e.getEventType()) { case XMLStreamConstants.START_ELEMENT: StartElement el = e.asStartElement(); if (el.getName().equals(SchemaUtils.IMPORT) || el.getName().equals(SchemaUtils.INCLUDE) || (el.getName().equals(SchemaUtils.REDEFINE) && !ignoreRedefine)) { Attribute schemaLocationAttribute = el.getAttributeByName(SchemaUtils.SCHEMALOCATION); Attribute namespaceAttribute = el.getAttributeByName(SchemaUtils.NAMESPACE); String namespace = this.namespace; boolean addNamespaceToSchema = this.addNamespaceToSchema; if (el.getName().equals(SchemaUtils.IMPORT)) { if (namespaceAttribute == null && StringUtils.isEmpty(xsdDefaultNamespace) && StringUtils.isNotEmpty(xsdTargetNamespace)) { //TODO: concerning import without namespace when in head xsd default namespace doesn't exist and targetNamespace does) namespace = null; } else { if (namespaceAttribute != null) { namespace = namespaceAttribute.getValue(); } else { namespace = targetNamespace; } } } if (schemaLocationAttribute != null) { boolean skip = false; if (el.getName().equals(SchemaUtils.IMPORT) && namespaceAttribute == null) { if (StringUtils.isNotEmpty(xsdDefaultNamespace) && StringUtils.isNotEmpty(xsdTargetNamespace)) { //ignore import without namespace when in head xsd default namespace and targetNamespace exists) skip = true; } } if (!skip) { String sl = schemaLocationAttribute.getValue(); ArrayList aslti = null; if (StringUtils.isNotEmpty(getImportedSchemaLocationsToIgnore())) { aslti = new ArrayList( Arrays.asList(getImportedSchemaLocationsToIgnore().split(","))); } if (StringUtils.isNotEmpty(sl) && aslti != null) { if (isUseBaseImportedSchemaLocationsToIgnore()) { sl = FilenameUtils.getName(sl); } if (aslti.contains(sl)) { skip = true; } } } if (!skip) { ArrayList ans = null; if (StringUtils.isNotEmpty(getImportedNamespacesToIgnore())) { ans = new ArrayList(Arrays.asList(getImportedNamespacesToIgnore().split(","))); } if (StringUtils.isNotEmpty(namespace) && ans != null) { if (ans.contains(namespace)) { skip = true; } } } if (!skip) { XSD x = new XSD(); x.setClassLoader(classLoader); x.setNamespace(namespace); x.setResource(getResourceBase() + schemaLocationAttribute.getValue()); x.setAddNamespaceToSchema(addNamespaceToSchema); x.setImportedSchemaLocationsToIgnore(getImportedSchemaLocationsToIgnore()); x.setUseBaseImportedSchemaLocationsToIgnore( isUseBaseImportedSchemaLocationsToIgnore()); x.setImportedNamespacesToIgnore(getImportedNamespacesToIgnore()); x.setParentLocation(getResourceBase()); x.setRootXsd(false); x.init(); if (xsds.add(x)) { x.getXsdsRecursive(xsds, ignoreRedefine); } } } } break; } } } catch (IOException e) { String message = "IOException reading XSD"; LOG.error(message, e); throw new ConfigurationException(message, e); } catch (XMLStreamException e) { String message = "XMLStreamException reading XSD"; LOG.error(message, e); throw new ConfigurationException(message, e); } return xsds; }
From source file:org.apache.olingo.client.core.serialization.AtomDeserializer.java
private Property property(final XMLEventReader reader, final StartElement start) throws XMLStreamException, EdmPrimitiveTypeException { final Property property = new Property(); if (propertyValueQName.equals(start.getName())) { // retrieve name from context final Attribute context = start.getAttributeByName(contextQName); if (context != null) { property.setName(StringUtils.substringAfterLast(context.getValue(), "/")); }/*from www . ja v a 2s . c o m*/ } else { property.setName(start.getName().getLocalPart()); } valuable(property, reader, start); return property; }