Java Code Examples for org.xml.sax.InputSource

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Airports, under directory /src/com/nadmm/airports/wx/.

Source file: AirSigmetParser.java

  19 
vote

public void parse(File xml,AirSigmet airSigmet){
  try {
    airSigmet.fetchTime=xml.lastModified();
    InputSource input=new InputSource(new FileReader(xml));
    SAXParserFactory factory=SAXParserFactory.newInstance();
    SAXParser parser=factory.newSAXParser();
    AirSigmetHandler handler=new AirSigmetHandler(airSigmet);
    XMLReader xmlReader=parser.getXMLReader();
    xmlReader.setContentHandler(handler);
    xmlReader.parse(input);
  }
 catch (  Exception e) {
  }
}
 

Example 2

From project and-bible, under directory /IgnoreAndBibleExperiments/experiments/.

Source file: ZVerseBackendLite.java

  19 
vote

public Element getOsis(Key key,SwordBookMetaData sbmd) throws BookException {
  try {
    String plain=getRawText(key);
    StringReader in=new StringReader("<div>" + plain + "</div>");
    InputSource is=new InputSource(in);
    SAXBuilder builder=new SAXBuilder();
    Document doc=builder.build(is);
    Element div=doc.getRootElement();
    return div;
  }
 catch (  Exception e) {
    throw new BookException(UserMsg.READ_FAIL,e,new Object[]{key.getName()});
  }
}
 

Example 3

From project android-rss, under directory /src/main/java/org/mcsoxford/rss/.

Source file: RSSParser.java

  18 
vote

/** 
 * Parses input stream as an RSS 2.0 feed.
 * @return in-memory representation of an RSS feed
 * @throws IllegalArgumentException if either argument is {@code null}
 */
private RSSFeed parse(SAXParser parser,InputStream feed) throws SAXException, IOException {
  if (parser == null) {
    throw new IllegalArgumentException("RSS parser must not be null.");
  }
 else   if (feed == null) {
    throw new IllegalArgumentException("RSS feed must not be null.");
  }
  final InputSource source=new InputSource(feed);
  final XMLReader xmlreader=parser.getXMLReader();
  final RSSHandler handler=new RSSHandler(config);
  xmlreader.setContentHandler(handler);
  xmlreader.parse(source);
  return handler.feed();
}
 

Example 4

From project Application-Builder, under directory /src/main/java/org/silverpeas/xml/.

Source file: ClasspathEntityResolver.java

  18 
vote

private InputSource resolveInClasspath(String publicId,String systemId) throws SAXException, IOException {
  InputSource result=resolveInClasspath(publicId);
  if (result == null) {
    result=resolveInClasspath(systemId);
  }
  if (result == null) {
    result=new InputSource(new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes("UTF-8")));
  }
  return result;
}
 

Example 5

From project Archimedes, under directory /br.org.archimedes.io.xml.tests/plugin-test/br/org/archimedes/io/xml/parsers/.

Source file: NPointParserTestHelper.java

  18 
vote

protected Node getNodeLine(String xmlSample) throws Exception {
  DocumentBuilderFactory docBuilderFactory=DocumentBuilderFactory.newInstance();
  DocumentBuilder docBuilder=null;
  docBuilder=docBuilderFactory.newDocumentBuilder();
  StringReader ir=new StringReader(xmlSample);
  InputSource is=new InputSource(ir);
  Document doc=docBuilder.parse(is);
  doc.normalize();
  return doc.getFirstChild();
}
 

Example 6

From project as3-commons-jasblocks, under directory /src/main/java/org/as3commons/asblocks/impl/.

Source file: SWCResourceRoot.java

  18 
vote

private Document loadDoc(InputStream in) throws ParserConfigurationException, SAXException, IOException {
  DocumentBuilderFactory fact=DocumentBuilderFactory.newInstance();
  DocumentBuilder builder=fact.newDocumentBuilder();
  InputSource is=new InputSource(in);
  is.setSystemId(CATALOG_FILENAME);
  return builder.parse(is);
}
 

Example 7

From project BBC-News-Reader, under directory /src/org/mcsoxford/rss/.

Source file: RSSParser.java

  18 
vote

/** 
 * Parses input stream as an RSS 2.0 feed.
 * @return in-memory representation of an RSS feed
 * @throws IllegalArgumentException if either argument is {@code null}
 */
private RSSFeed parse(SAXParser parser,InputStream feed) throws SAXException, IOException {
  if (parser == null) {
    throw new IllegalArgumentException("RSS parser must not be null.");
  }
 else   if (feed == null) {
    throw new IllegalArgumentException("RSS feed must not be null.");
  }
  final InputSource source=new InputSource(feed);
  final XMLReader xmlreader=parser.getXMLReader();
  final RSSHandler handler=new RSSHandler(config);
  xmlreader.setContentHandler(handler);
  xmlreader.parse(source);
  return handler.feed();
}
 

Example 8

From project bioportal-service, under directory /src/main/java/edu/mayo/cts2/framework/plugin/service/bioportal/rest/.

Source file: BioportalRestUtils.java

  18 
vote

/** 
 * Gets the document.
 * @param xml the xml
 * @return the document
 */
public static Document getDocument(String xml){
  StringReader reader=new StringReader(xml);
  InputSource inputStream=new InputSource(reader);
  Document doc;
  try {
synchronized (DOCUMENT_BUILDER) {
      doc=DOCUMENT_BUILDER.parse(inputStream);
    }
  }
 catch (  Exception e) {
    throw new Cts2RuntimeException(e);
  }
  return doc;
}
 

Example 9

From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/.

Source file: Parser.java

  18 
vote

/** 
 * Parse an input stream for blueprint xml. 
 * @param inputStream The data to parse. The caller is responsible for closing the stream afterwards. 
 * @throws Exception on parse error
 */
public void parse(InputStream inputStream) throws Exception {
  InputSource inputSource=new InputSource(inputStream);
  DocumentBuilder builder=getDocumentBuilderFactory().newDocumentBuilder();
  Document doc=builder.parse(inputSource);
  documents.add(doc);
}
 

Example 10

From project boilerpipe, under directory /boilerpipe-core/src/demo/de/l3s/boilerpipe/demo/.

Source file: UsingSAX.java

  18 
vote

public static void main(final String[] args) throws Exception {
  URL url;
  url=new URL("http://www.l3s.de/web/page11g.do?sp=page11g&link=ln104g&stu1g.LanguageISOCtxParam=en");
  final InputSource is=HTMLFetcher.fetch(url).toInputSource();
  final BoilerpipeSAXInput in=new BoilerpipeSAXInput(is);
  final TextDocument doc=in.getTextDocument();
  System.out.println(ArticleExtractor.INSTANCE.getText(doc));
}
 

Example 11

From project boilerpipe_1, under directory /boilerpipe-core/src/demo/de/l3s/boilerpipe/demo/.

Source file: UsingSAX.java

  18 
vote

public static void main(final String[] args) throws Exception {
  URL url;
  url=new URL("http://www.l3s.de/web/page11g.do?sp=page11g&link=ln104g&stu1g.LanguageISOCtxParam=en");
  final InputSource is=HTMLFetcher.fetch(url).toInputSource();
  final BoilerpipeSAXInput in=new BoilerpipeSAXInput(is);
  final TextDocument doc=in.getTextDocument();
  System.out.println(ArticleExtractor.INSTANCE.getText(doc));
}
 

Example 12

From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/xmlconfig/.

Source file: CdkEntityResolver.java

  18 
vote

@Override public InputSource resolveEntity(String publicId,String systemId) throws SAXException, IOException {
  InputSource entity=null;
  if (null != systemId) {
    entity=resolveSystemId(systemId);
  }
  return entity;
}
 

Example 13

From project codjo-broadcast, under directory /codjo-broadcast-gui/src/main/java/net/codjo/broadcast/gui/plugin/.

Source file: BroadcastGuiPlugin.java

  18 
vote

void loadBroadcastGenericSelectorPreference(){
  if (PreferenceFactory.containsPreferenceId(BROADCAST_SELECTOR_PREFERENCE_ID)) {
    return;
  }
  InputSource inputSource=new InputSource(getClass().getResourceAsStream(BROADCAST_SELECTOR_PREFERENCE_FILE));
  madGuiPlugin.getConfiguration().addPreferenceMapping(inputSource);
}
 

Example 14

From project codjo-imports, under directory /codjo-imports-gui/src/main/java/net/codjo/imports/gui/plugin/.

Source file: ImportGuiPlugin.java

  18 
vote

void loadImportPreferences(){
  if (PreferenceFactory.containsPreferenceId(FIELD_IMPORT_PREFERENCE_ID) && PreferenceFactory.containsPreferenceId(IMPORT_SETTINGS_PREFERENCE_ID)) {
    return;
  }
  InputSource inputSource=new InputSource(getClass().getResourceAsStream(IMPORT_PREFERENCE_FILE_NAME));
  madGuiPlugin.getConfiguration().addPreferenceMapping(inputSource);
}
 

Example 15

From project codjo-segmentation, under directory /codjo-segmentation-gui/src/main/java/net/codjo/segmentation/gui/plugin/.

Source file: SegmentationGuiPlugin.java

  18 
vote

private void loadPreferences(){
  if (containsPreferenceId(CLASSIFICATION_WINDOW_PREFERENCE_ID) && containsPreferenceId(CLASS_STRUCT_WINDOW_PREFERENCE_ID)) {
    return;
  }
  InputSource inputSource=new InputSource(getClass().getResourceAsStream(PREFERENCE_FILE_NAME));
  madGuiPlugin.getConfiguration().addPreferenceMapping(inputSource);
}
 

Example 16

From project components, under directory /common/common/src/test/java/org/switchyard/component/common/selector/.

Source file: OperationSelectorTest.java

  18 
vote

@Override protected Document extractDomDocument(String content) throws Exception {
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
  DocumentBuilder builder=factory.newDocumentBuilder();
  InputSource is=new InputSource(new StringReader(extractString(content)));
  return builder.parse(is);
}
 

Example 17

From project core_1, under directory /transform/src/main/java/org/switchyard/transform/ootb/io/.

Source file: InputStreamTransforms.java

  18 
vote

/** 
 * Transform to InputSource.
 * @param inStream Input Stream.
 * @return InputSource.
 */
@Transformer public InputSource toInputSource(InputStream inStream){
  byte[] bytes=toBytes(inStream);
  InputSource inputSource=new InputSource();
  inputSource.setByteStream(new ByteArrayInputStream(bytes));
  return inputSource;
}
 

Example 18

From project core_5, under directory /exo.core.component.xml-processing/src/main/java/org/exoplatform/services/xml/resolving/impl/.

Source file: XMLResolver.java

  18 
vote

public InputSource resolveEntity(String publicId,String systemId) throws SAXException, IOException {
  String entity=null;
  if (publicIDPrefer_ && publicId != null && publicId.length() != 0)   entity=publicIDs_.get(publicId);
  if (entity == null && systemId != null && systemId.length() != 0)   entity=systemIDs_.get(systemId);
  if (entity == null && publicId != null && publicId.length() != 0)   entity=publicIDs_.get(publicId);
  if (entity != null) {
    if (PrivilegedSystemHelper.getResource(entity) != null) {
      InputSource src=new InputSource(PrivilegedSystemHelper.getResourceAsStream(entity));
      src.setSystemId(PrivilegedSystemHelper.getResource(entity).getPath());
      return src;
    }
  }
  return null;
}
 

Example 19

From project DigitbooksExamples, under directory /DigitbooksExamples/src/fr/digitbooks/android/examples/chapitre08/.

Source file: DigitbooksGuestbookXml.java

  18 
vote

public List<HashMap<String,String>> parse(String xml) throws Exception {
  if (xml == null) {
    return null;
  }
  mData=new ArrayList<HashMap<String,String>>();
  InputSource inputSource=new InputSource(new StringReader(xml));
  SAXParserFactory spf=SAXParserFactory.newInstance();
  SAXParser sp=spf.newSAXParser();
  XMLReader xr=sp.getXMLReader();
  xr.setContentHandler(this);
  xr.parse(inputSource);
  return mData;
}
 

Example 20

From project android-client_1, under directory /src/com/googlecode/asmack/.

Source file: XMLUtils.java

  17 
vote

/** 
 * Turn an XML String into a DOM.
 * @param xml The xml String.
 * @return A XML Document.
 * @throws SAXException In case of invalid XML.
 */
public static Document getDocument(String xml) throws SAXException {
  try {
    DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
    return documentBuilder.parse(new InputSource(new StringReader(xml)));
  }
 catch (  ParserConfigurationException e) {
    throw new IllegalStateException("Parser not configured",e);
  }
catch (  IOException e) {
    throw new IllegalStateException("IOException on read-from-memory",e);
  }
}
 

Example 21

From project Android-Flashcards, under directory /src/com/secretsockssoftware/androidflashcards/.

Source file: AndroidFlashcards.java

  17 
vote

static protected Lesson parseXML(File file,String default_name) throws Exception {
  XMLReader xr=XMLReaderFactory.createXMLReader();
  FCParser fcp=new FCParser();
  xr.setContentHandler(fcp);
  xr.setErrorHandler(fcp);
  FileReader r=new FileReader(file);
  xr.parse(new InputSource(r));
  String name=fcp.getName();
  if (name == "")   name=default_name;
  String description=fcp.getDesc();
  return new Lesson(fcp.getCards(),name,description);
}
 

Example 22

From project android-tether, under directory /src/og/android/tether/.

Source file: RSSReader.java

  17 
vote

void parseRSS(InputStream feed){
  XMLReader parser=null;
  try {
    parser=XMLReaderFactory.createXMLReader();
    parser.setContentHandler(getRSSContentHandler());
    parser.parse(new InputSource(feed));
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
catch (  SAXException e) {
    e.printStackTrace();
  }
}
 

Example 23

From project AndroidExamples, under directory /RSSExample/src/com/robertszkutak/androidexamples/rss/.

Source file: RSSExampleActivity.java

  17 
vote

@Override protected RSSFeed doInBackground(String... RSSuri){
  try {
    URL url=new URL(RSSuri[0]);
    SAXParserFactory factory=SAXParserFactory.newInstance();
    SAXParser parser=factory.newSAXParser();
    XMLReader xmlreader=parser.getXMLReader();
    RSSHandler theRssHandler=new RSSHandler();
    xmlreader.setContentHandler(theRssHandler);
    InputSource is=new InputSource(url.openStream());
    xmlreader.parse(is);
    return theRssHandler.getFeed();
  }
 catch (  Exception ee) {
    return null;
  }
}
 

Example 24

From project arquillian-container-tomcat, under directory /tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/.

Source file: EmbeddedContextConfig.java

  17 
vote

/** 
 * Process the META-INF/context.xml descriptor in the web application root. This descriptor is not processed when a webapp is added programmatically through a StandardContext
 */
protected void applicationContextConfig(){
  ServletContext servletContext=context.getServletContext();
  InputStream stream=servletContext.getResourceAsStream("/" + Constants.ApplicationContextXml);
  if (stream == null) {
    return;
  }
synchronized (contextDigester) {
    URL url=null;
    try {
      url=servletContext.getResource("/" + Constants.ApplicationContextXml);
    }
 catch (    MalformedURLException e) {
      throw new AssertionError("/" + Constants.ApplicationContextXml + " should not be considered a malformed URL");
    }
    InputSource is=new InputSource(url.toExternalForm());
    is.setByteStream(stream);
    contextDigester.push(context);
    try {
      contextDigester.parse(is);
    }
 catch (    Exception e) {
      ok=false;
      log.error("Parse error in context.xml for " + context.getName(),e);
    }
 finally {
      contextDigester.reset();
      try {
        if (stream != null) {
          stream.close();
        }
      }
 catch (      IOException e) {
        log.error("Error closing context.xml for " + context.getName(),e);
      }
    }
  }
  log.debug("Done processing " + Constants.ApplicationContextXml + " descriptor");
}
 

Example 25

From project arquillian_deprecated, under directory /containers/glassfish-remote-3.1/src/main/java/org/jboss/arquillian/container/glassfish/remote_3_1/.

Source file: GlassFishRestDeployableContainer.java

  17 
vote

private ProtocolMetaData parseForProtocolMetaData(String xmlResponse) throws XPathExpressionException {
  final ProtocolMetaData protocolMetaData=new ProtocolMetaData();
  final HTTPContext httpContext=new HTTPContext(this.configuration.getRemoteServerAddress(),this.configuration.getRemoteServerHttpPort());
  final XPath xpath=XPathFactory.newInstance().newXPath();
  NodeList servlets=(NodeList)xpath.evaluate("/map/entry[@key = 'properties']/map/entry[@value = 'Servlet']",new InputSource(new StringReader(xmlResponse)),XPathConstants.NODESET);
  for (int i=0; i < servlets.getLength(); i++) {
    httpContext.add(new Servlet(servlets.item(i).getAttributes().getNamedItem("key").getNodeValue(),this.deploymentName));
  }
  protocolMetaData.addContext(httpContext);
  return protocolMetaData;
}
 

Example 26

From project AsmackService, under directory /src/com/googlecode/asmack/.

Source file: XMLUtils.java

  17 
vote

/** 
 * Turn an XML String into a DOM.
 * @param xml The xml String.
 * @return A XML Document.
 * @throws SAXException In case of invalid XML.
 */
public static Document getDocument(String xml) throws SAXException {
  try {
    DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
    return documentBuilder.parse(new InputSource(new StringReader(xml)));
  }
 catch (  ParserConfigurationException e) {
    throw new IllegalStateException("Parser not configured",e);
  }
catch (  IOException e) {
    throw new IllegalStateException("IOException on read-from-memory",e);
  }
}
 

Example 27

From project azure-sdk-for-java-samples, under directory /WAAD.WebSSO.JAVA/java/code/libraries/waad-federation/src/main/java/com/microsoft/samples/federation/.

Source file: SamlTokenValidator.java

  17 
vote

private static Document getDocument(String doc) throws ParserConfigurationException, SAXException, IOException {
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  DocumentBuilder documentbuilder=factory.newDocumentBuilder();
  return documentbuilder.parse(new InputSource(new StringReader(doc)));
}
 

Example 28

From project blacktie, under directory /blacktie-admin-services/src/main/java/org/jboss/narayana/blacktie/administration/.

Source file: BlacktieStompAdministrationService.java

  17 
vote

Element stringToElement(String s) throws Exception {
  StringReader sreader=new StringReader(s);
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
  DocumentBuilder parser=factory.newDocumentBuilder();
  Document doc=parser.parse(new InputSource(sreader));
  return doc.getDocumentElement();
}
 

Example 29

From project blog_1, under directory /miniprojects/generic-pojo-mappers/src/main/java/net/jakubholy/blog/genericmappers/xml/.

Source file: XmlElements.java

  17 
vote

private static Document parseXmlToDocument(String xml) throws RuntimeException {
  DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
  builderFactory.setNamespaceAware(true);
  try {
    DocumentBuilder builder=builderFactory.newDocumentBuilder();
    InputSource is=new InputSource(new StringReader(xml));
    return builder.parse(is);
  }
 catch (  SAXException e) {
    throw new RuntimeException("Parsing XML failed: " + e + ", xml: "+ xml,e);
  }
catch (  IOException e) {
    throw new RuntimeException("Parsing XML failed: " + e + ", xml: "+ xml,e);
  }
catch (  ParserConfigurationException e) {
    throw new RuntimeException("Parsing XML failed: " + e + ", xml: "+ xml,e);
  }
}
 

Example 30

From project BMach, under directory /src/jsyntaxpane/actions/.

Source file: XmlPrettifyAction.java

  17 
vote

@Override public void actionPerformed(ActionEvent e){
  if (transformer == null) {
    return;
  }
  JTextComponent target=getTextComponent(e);
  try {
    SyntaxDocument sdoc=ActionUtils.getSyntaxDocument(target);
    StringWriter out=new StringWriter(sdoc.getLength());
    StringReader reader=new StringReader(target.getText());
    InputSource src=new InputSource(reader);
    Document doc=getDocBuilder().parse(src);
    getTransformer().transform(new DOMSource(doc),new StreamResult(out));
    target.setText(out.toString());
  }
 catch (  SAXParseException ex) {
    showErrorMessage(target,String.format("XML error: %s\nat(%d, %d)",ex.getMessage(),ex.getLineNumber(),ex.getColumnNumber()));
    ActionUtils.setCaretPosition(target,ex.getLineNumber(),ex.getColumnNumber() - 1);
  }
catch (  TransformerException ex) {
    showErrorMessage(target,ex.getMessageAndLocation());
  }
catch (  SAXException ex) {
    showErrorMessage(target,ex.getLocalizedMessage());
  }
catch (  IOException ex) {
    showErrorMessage(target,ex.getLocalizedMessage());
  }
}
 

Example 31

From project bpelunit, under directory /net.bpelunit.framework/src/main/java/net/bpelunit/framework/control/util/.

Source file: ParseUtil.java

  17 
vote

/** 
 * Gets a WSDL Definition (WSDL4J API) from the given WSDL file.
 * @param filename Absolute path of the WSDL file.
 * @param searchCache Searches the cache for Definition. If found returns cached Definition if this flag is set to true.
 * @param toCache If set to true put the the created Definition object in the cache for future lookups.
 * @throws IOException Encapsulates WSDLException, FileNotFoundException
 * @see #getWsdlDefinition(String)
 */
public static Definition getWsdlDefinition(String filename,boolean searchCache,boolean toCache) throws IOException {
  File wsdl=new File(filename);
  Definition definition=fParsedDefinitions.get(filename);
  if (searchCache && definition != null) {
    return definition;
  }
  try {
    WSDLReader reader=WSDLFactory.newInstance().newWSDLReader();
    InputSource source=new InputSource(new FileInputStream(wsdl));
    definition=reader.readWSDL(filename,source);
  }
 catch (  WSDLException e) {
    throw new IOException("Error while reading definition from WSDL file \"" + wsdl.getAbsolutePath() + "\".",e);
  }
catch (  FileNotFoundException e) {
    throw new IOException(e);
  }
  if (toCache) {
    fParsedDefinitions.put(filename,definition);
  }
  return definition;
}
 

Example 32

From project BPMN2-Editor-for-Eclipse, under directory /org.eclipse.bpmn2.modeler.ui/src/org/eclipse/bpmn2/modeler/ui/.

Source file: BPMN2ContentDescriber.java

  17 
vote

private synchronized String doDescribe(Reader contents) throws IOException {
  try {
    InputSource source=new InputSource(contents);
    parser=new RootElementParser();
    parser.parse(source);
  }
 catch (  AcceptedException e) {
    return e.acceptedRootElement;
  }
catch (  RejectedException e) {
    return null;
  }
catch (  Exception e) {
    return null;
  }
 finally {
    parser=null;
  }
  return null;
}
 

Example 33

From project cascading, under directory /src/xml/cascading/operation/xml/.

Source file: TagSoupParser.java

  17 
vote

/** 
 * @see cascading.operation.Function#operate(cascading.flow.FlowProcess,cascading.operation.FunctionCall) 
 */
public void operate(FlowProcess flowProcess,FunctionCall functionCall){
  try {
    StringWriter writer=new StringWriter();
    XMLWriter xmlWriter=new XMLWriter(writer);
    xmlWriter.setPrefix(getSchema().getURI(),"");
    xmlWriter.setOutputProperty(XMLWriter.OMIT_XML_DECLARATION,"yes");
    InputSource source=new InputSource(new StringReader((String)functionCall.getArguments().getObject(0)));
    getParser().setContentHandler(xmlWriter);
    getParser().parse(source);
    functionCall.getOutputCollector().add(new Tuple(writer.getBuffer().toString()));
  }
 catch (  SAXNotRecognizedException exception) {
    LOG.warn("ignoring TagSoup exception",exception);
  }
catch (  SAXNotSupportedException exception) {
    LOG.warn("ignoring TagSoup exception",exception);
  }
catch (  IOException exception) {
    LOG.warn("ignoring TagSoup exception",exception);
  }
catch (  SAXException exception) {
    LOG.warn("ignoring TagSoup exception",exception);
  }
}
 

Example 34

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/inputtools/jplugin/.

Source file: GenericChukwaMetricsList.java

  17 
vote

public void fromXml(String xml) throws Exception {
  InputSource is=new InputSource(new StringReader(xml));
  Document doc=docBuilder.parse(is);
  Element root=doc.getDocumentElement();
  setRecordType(root.getTagName());
  long timestamp=Long.parseLong(root.getAttribute("ts"));
  setTimestamp(timestamp);
  NodeList children=root.getChildNodes();
  for (int i=0; i < children.getLength(); i++) {
    if (!children.item(i).getNodeName().equals("Metrics")) {
      continue;
    }
    NamedNodeMap attrs=children.item(i).getAttributes();
    if (attrs == null) {
      continue;
    }
    GenericChukwaMetrics metrics=new GenericChukwaMetrics();
    for (int a=0; a < attrs.getLength(); a++) {
      Attr attr=(Attr)attrs.item(a);
      String name=attr.getName();
      String value=attr.getValue();
      if (name.equals("key")) {
        metrics.setKey(value);
      }
 else {
        metrics.put(name,value);
      }
    }
    addMetrics(metrics);
  }
}
 

Example 35

From project CineShowTime-Android, under directory /Libraries/CineShowTime/src/com/binomed/showtime/android/util/.

Source file: CineShowtimeFactory.java

  17 
vote

private InputSource getXmlSource(){
  if (xmlSource == null) {
    xmlSource=new InputSource();
  }
  return xmlSource;
}
 

Example 36

From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/azure/client/.

Source file: MicrosoftAzureModelUtils.java

  17 
vote

private static Document parse(final String xml) throws MicrosoftAzureException {
  try {
    DocumentBuilder documentBuilder=createDocumentBuilder();
    Document xmlDoc=documentBuilder.parse(new InputSource(new StringReader(xml)));
    xmlDoc.normalizeDocument();
    return xmlDoc;
  }
 catch (  SAXException e) {
    throw new MicrosoftAzureException("Failed to parse XML Response from server. Response was: " + xml + ", Error was: "+ e.getMessage(),e);
  }
catch (  IOException e) {
    throw new MicrosoftAzureException("Failed to parse XML Response from server. Response was: " + xml + ", Error was: "+ e.getMessage(),e);
  }
}
 

Example 37

From project CloudReports, under directory /src/main/java/cloudreports/extensions/.

Source file: ExtensionsLoader.java

  17 
vote

/** 
 * Loads an instance of <code>Document</code> that contains the  classnames.xml file.
 * @return                          a <code>Document</code> object containing the classnames.xml file.
 * @since                           1.0
 */
private static Document getClassnamesXml(){
  File classnamesXmlFile=new File(classnamesXmlPath);
  if (!classnamesXmlFile.exists() || !classnamesXmlFile.isFile()) {
    return null;
  }
  DocumentBuilder db;
  try {
    db=DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is=new InputSource(classnamesXmlFile.toURI().toURL().openStream());
    Document classnamesXmlDocument=db.parse(is);
    return classnamesXmlDocument;
  }
 catch (  Exception ex) {
    Logger.getLogger(ExtensionsLoader.class.getName()).log(Level.INFO,null,ex);
    return null;
  }
}
 

Example 38

From project cocos2d, under directory /cocos2d-android/src/org/cocos2d/utils/.

Source file: PlistParser.java

  17 
vote

private static Object parsePlist(InputStream in){
  try {
    SAXParserFactory factory=SAXParserFactory.newInstance();
    SAXParser parser=factory.newSAXParser();
    PlistParser handler=new PlistParser();
    BufferedReader reader=new BufferedReader(new InputStreamReader(in),8192);
    parser.parse(new InputSource(reader),handler);
    return handler.rootDict;
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 39

From project codjo-control, under directory /codjo-control-common/src/main/java/net/codjo/control/common/loader/.

Source file: XmlMapperHelper.java

  17 
vote

public InputSource resolveEntity(String publicId,String systemId) throws IOException {
  File entityFile=new File(root,systemId.substring("file://".length(),systemId.length()));
  APP.info("Chargement de l'entit de systemeId=" + systemId + "  partir du fichier "+ entityFile+ " ");
  if (!entityFile.exists()) {
    throw new IllegalArgumentException("Fichier introuvable : " + entityFile);
  }
  return new InputSource(new FileInputStream(entityFile));
}
 

Example 40

From project codjo-webservices, under directory /codjo-webservices-common/src/main/java/com/tilab/wsig/soap/.

Source file: SoapToJade.java

  17 
vote

/** 
 * convert
 * @param soapMessage
 * @param wsigService
 * @param operationName
 * @return
 * @throws Exception
 */
public Object convert(Message soapRequest,WSIGService wsigService,String operationName) throws Exception {
  Object actionObj=null;
  String soapMessage=soapRequest.getSOAPPartAsString();
  if (xr == null) {
    throw new Exception("Parser not initialized");
  }
  onto=wsigService.getOnto();
  xr.parse(new InputSource(new StringReader(soapMessage)));
  Vector<ParameterInfo> params=getParameters();
  ActionBuilder actionBuilder=wsigService.getActionBuilder(operationName);
  actionObj=actionBuilder.getAgentAction(params);
  return actionObj;
}
 

Example 41

From project cogroo4, under directory /cogroo-gc/src/main/java/org/cogroo/errorreport/.

Source file: ErrorReportAccess.java

  17 
vote

public ErrorReport getErrorReport(Reader xml){
  ErrorReport errorReport=null;
  try {
    InputSource inputSource=new InputSource(xml);
    ClassLoader cl=ErrorReport.class.getClassLoader();
    if (cl == null) {
      LOGGER.error("couldn't create class loader.");
    }
    JAXBContext context=JAXBContext.newInstance(PACKAGE,cl);
    Unmarshaller unmarshaller=context.createUnmarshaller();
    unmarshaller.setEventHandler(new ValidationEventHandler(){
      @SuppressWarnings("synthetic-access") public boolean handleEvent(      ValidationEvent ve){
        if (ve.getSeverity() != ValidationEvent.WARNING) {
          ValidationEventLocator vel=ve.getLocator();
          LOGGER.warn("Line:Col[" + vel.getLineNumber() + ":"+ vel.getColumnNumber()+ "]:"+ ve.getMessage());
        }
        return true;
      }
    }
);
    errorReport=(ErrorReport)unmarshaller.unmarshal(inputSource);
  }
 catch (  JAXBException e) {
    LOGGER.error("Error parsing file",e);
    throw new RulesException("Failed reading file");
  }
  return errorReport;
}
 

Example 42

From project com.idega.content, under directory /src/java/com/idega/content/themes/helpers/business/.

Source file: ThemesEntityResolver.java

  17 
vote

public InputSource resolveEntity(String publicID,String systemID) throws SAXException, IOException {
  if (publicID == null || systemID == null) {
    return null;
  }
  for (int i=0; i < ThemesConstants.DOCUMENT_PUBLIC_IDS.size(); i++) {
    if (publicID.indexOf(ThemesConstants.DOCUMENT_PUBLIC_IDS.get(i)) != -1 && systemID.indexOf(ThemesConstants.DOCUMENT_SYSTEM_IDS.get(i)) != -1) {
      return new InputSource(new ByteArrayInputStream(ThemesConstants.DOCUMENT_HEADER.getBytes()));
    }
  }
  return null;
}
 

Example 43

From project core_4, under directory /legacy-tests/src/main/java/org/ajax4jsf/tests/org/apache/shale/test/config/.

Source file: ConfigParser.java

  17 
vote

/** 
 * <p>Parse the specified JavaServer Faces configuration resource, causing the appropriate JSF artifacts to be registered with the mock object hierarchy.</p>
 * @param url <code>URL</code> of the configuration resource to parse
 * @exception IOException if an input/output error occurs
 * @exception SAXException if a parsing error occurs
 */
public void parse(URL url) throws IOException, SAXException {
  Digester digester=digester();
  ApplicationFactory factory=(ApplicationFactory)FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
  Application application=factory.getApplication();
  digester.push(application);
  try {
    digester.parse(new InputSource(url.openStream()));
  }
  finally {
    digester.clear();
  }
}
 

Example 44

From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/xml/.

Source file: XMLUtils.java

  17 
vote

public static String getXPathValue(IFile file,String xPath) throws Exception {
  DocumentBuilderFactory docFactory=DocumentBuilderFactory.newInstance();
  docFactory.setNamespaceAware(false);
  docFactory.setValidating(false);
  DocumentBuilder builder=docFactory.newDocumentBuilder();
  XPathFactory factory=XPathFactory.newInstance();
  XPath xpath=factory.newXPath();
  final XPathExpression exp=xpath.compile(xPath);
  Document doc=builder.parse(new InputSource(file.getContents()));
  final NodeList nodeList=(NodeList)exp.evaluate(doc,XPathConstants.NODESET);
  return XMLUtils.getNodeValue(nodeList);
}
 

Example 45

From project des, under directory /daemon/lib/apache-log4j-1.2.16/src/main/java/org/apache/log4j/chainsaw/.

Source file: LoadXMLAction.java

  17 
vote

/** 
 * Loads the contents of file into the model
 * @param aFile the file to extract events from
 * @return the number of events loaded
 * @throws SAXException if an error occurs
 * @throws IOException if an error occurs
 */
private int loadFile(String aFile) throws SAXException, IOException {
synchronized (mParser) {
    final StringBuffer buf=new StringBuffer();
    buf.append("<?xml version=\"1.0\" standalone=\"yes\"?>\n");
    buf.append("<!DOCTYPE log4j:eventSet ");
    buf.append("[<!ENTITY data SYSTEM \"file:///");
    buf.append(aFile);
    buf.append("\">]>\n");
    buf.append("<log4j:eventSet xmlns:log4j=\"Claira\">\n");
    buf.append("&data;\n");
    buf.append("</log4j:eventSet>\n");
    final InputSource is=new InputSource(new StringReader(buf.toString()));
    mParser.parse(is);
    return mHandler.getNumEvents();
  }
}
 

Example 46

From project descriptors, under directory /metadata-parser-test/src/teststatic/java/org/jboss/shrinkwrap/descriptor/test/ironjacamar/.

Source file: DtdParserTest.java

  17 
vote

@Test public void testConnector() throws Exception {
  final String dtdFile="src/test/resources/dtd/connector_1_0.dtd";
  final InputSource in=new InputSource(new FileReader(dtdFile));
  final TestDtdEventListener dtdEventListener=new TestDtdEventListener("j2ee","org.jboss.shrinkwrap.descriptor.test.api.connector10","org.jboss.shrinkwrap.descriptor.test.impl.connector10",dtdFile);
  final DTDParser parser=new DTDParser();
  parser.setDtdHandler(dtdEventListener);
  parser.parse(in);
  final Metadata metadata=dtdEventListener.getMetadata();
  MetadataDescriptor metadataDescriptor=new MetadataDescriptor("ConnectorDescriptor");
  metadataDescriptor.setRootElementName("connector");
  metadataDescriptor.setRootElementType("j2ee:connector");
  metadataDescriptor.setSchemaName(dtdFile);
  metadataDescriptor.setPackageApi("org.jboss.shrinkwrap.descriptor.test.api.connector10");
  metadataDescriptor.setPackageImpl("org.jboss.shrinkwrap.descriptor.test.impl.connector10");
  metadataDescriptor.setNamespace("j2ee");
  metadata.getMetadataDescriptorList().add(metadataDescriptor);
  metadata.preResolveDataTypes();
  new MetadataUtil().log(metadata);
  new DomWriter().write(metadata,"/tmp/connector_1_0.xml");
}
 

Example 47

From project dev-examples, under directory /iteration-demo/src/main/java/org/richfaces/demo/.

Source file: TreeNodeParser.java

  17 
vote

public void parse(URL url) throws IOException, SAXException {
  InputStream is=null;
  try {
    is=url.openStream();
    reader.setContentHandler(this);
    reader.parse(new InputSource(is));
  }
  finally {
    Closeables.closeQuietly(is);
  }
}
 

Example 48

From project dozer, under directory /core/src/main/java/org/dozer/loader/xml/.

Source file: DozerResolver.java

  17 
vote

public InputSource resolveEntity(String publicId,String systemId){
  log.debug("Trying to resolve XML entity with public ID [{}] and system ID [{}]",publicId,systemId);
  if (systemId != null && systemId.indexOf(DozerConstants.XSD_NAME) > systemId.lastIndexOf("/")) {
    String fileName=systemId.substring(systemId.indexOf(DozerConstants.XSD_NAME));
    log.debug("Trying to locate [{}] in classpath",fileName);
    try {
      DozerClassLoader classLoader=BeanContainer.getInstance().getClassLoader();
      URL url=classLoader.loadResource(fileName);
      InputStream stream=url.openStream();
      InputSource source=new InputSource(stream);
      source.setPublicId(publicId);
      source.setSystemId(systemId);
      log.debug("Found beanmapping XML Schema [{}] in classpath",systemId);
      return source;
    }
 catch (    Exception ex) {
      log.error("Could not resolve beanmapping XML Schema [" + systemId + "]: not found in classpath",ex);
    }
  }
  return null;
}
 

Example 49

From project dreamDroid, under directory /src/net/reichholf/dreamdroid/parsers/.

Source file: GenericSaxParser.java

  17 
vote

@Override public boolean parse(String input){
  try {
    mError=false;
    mErrorText=null;
    ByteArrayInputStream bais=new ByteArrayInputStream(input.getBytes());
    InputSource is=new InputSource();
    is.setByteStream(bais);
    SAXParserFactory spf=SAXParserFactory.newInstance();
    spf.setValidating(false);
    SAXParser sp=spf.newSAXParser();
    XMLReader xr=sp.getXMLReader();
    xr.setContentHandler(mHandler);
    xr.parse(is);
    return true;
  }
 catch (  ParserConfigurationException e) {
    Log.e(DreamDroid.LOG_TAG,e.toString());
    mError=true;
    mErrorText=e.toString();
    e.printStackTrace();
  }
catch (  SAXException e) {
    Log.e(DreamDroid.LOG_TAG,e.toString());
    mError=true;
    mErrorText=e.toString();
    e.printStackTrace();
  }
catch (  IOException e) {
    Log.e(DreamDroid.LOG_TAG,e.toString());
    mError=true;
    mErrorText=e.toString();
    e.printStackTrace();
  }
  return false;
}
 

Example 50

From project adt-maven-plugin, under directory /src/main/java/com/yelbota/plugins/adt/model/.

Source file: AneModel.java

  16 
vote

private void parseXml(byte[] s) throws MojoFailureException {
  DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
  try {
    DocumentBuilder db=dbf.newDocumentBuilder();
    Document dom=db.parse(new InputSource(new ByteArrayInputStream(s)));
    NodeList nl=dom.getDocumentElement().getChildNodes();
    for (int i=0; i < nl.getLength(); i++) {
      Object uel=nl.item(i);
      if (uel instanceof Element) {
        Element el=(Element)uel;
        String nodeName=el.getNodeName();
        if (nodeName.equals("id"))         id=el.getTextContent();
      }
    }
  }
 catch (  ParserConfigurationException e) {
    throwParseFail(file,e);
  }
catch (  SAXException e) {
    throwParseFail(file,e);
  }
catch (  IOException e) {
    throwParseFail(file,e);
  }
}
 

Example 51

From project android-context, under directory /src/edu/fsu/cs/contextprovider/monitor/.

Source file: WeatherMonitor.java

  16 
vote

@Override public void run(){
  weatherZip=LocationMonitor.getZip();
  URL url;
  try {
    String tmpStr=null;
    String cityParamString=weatherZip;
    Log.d(TAG,"cityParamString: " + cityParamString);
    String queryString="http://www.google.com/ig/api?weather=" + cityParamString;
    url=new URL(queryString.replace(" ","%20"));
    SAXParserFactory spf=SAXParserFactory.newInstance();
    SAXParser sp=spf.newSAXParser();
    XMLReader xr=sp.getXMLReader();
    gwh=new GoogleWeatherHandler();
    xr.setContentHandler(gwh);
    xr.parse(new InputSource(url.openStream()));
    ws=gwh.getWeatherSet();
    if (ws == null)     return;
    WeatherCurrentCondition wcc=ws.getWeatherCurrentCondition();
    if (wcc != null) {
      weatherTemp=null;
      Integer weatherTempInt=wcc.getTempFahrenheit();
      if (weatherTempInt != null) {
        weatherTemp=weatherTempInt;
      }
      weatherCond=wcc.getCondition();
      weatherHumid=wcc.getHumidity();
      weatherWindCond=wcc.getWindCondition();
      weatherHazard=calcHazard();
    }
  }
 catch (  Exception e) {
    Log.e(TAG,"WeatherQueryError",e);
  }
}
 

Example 52

From project android-rackspacecloud, under directory /src/com/rackspace/cloud/servers/api/client/.

Source file: FlavorManager.java

  16 
vote

public ArrayList<Flavor> createList(boolean detail,Context context){
  CustomHttpClient httpclient=new CustomHttpClient(context);
  HttpGet get=new HttpGet(Account.getAccount().getServerUrl() + "/flavors/detail.xml?now=cache_time2");
  ArrayList<Flavor> flavors=new ArrayList<Flavor>();
  get.addHeader("X-Auth-Token",Account.getAccount().getAuthToken());
  try {
    HttpResponse resp=httpclient.execute(get);
    BasicResponseHandler responseHandler=new BasicResponseHandler();
    String body=responseHandler.handleResponse(resp);
    if (resp.getStatusLine().getStatusCode() == 200 || resp.getStatusLine().getStatusCode() == 203) {
      FlavorsXMLParser flavorsXMLParser=new FlavorsXMLParser();
      SAXParser saxParser=SAXParserFactory.newInstance().newSAXParser();
      XMLReader xmlReader=saxParser.getXMLReader();
      xmlReader.setContentHandler(flavorsXMLParser);
      xmlReader.parse(new InputSource(new StringReader(body)));
      flavors=flavorsXMLParser.getFlavors();
    }
  }
 catch (  ClientProtocolException cpe) {
  }
catch (  IOException e) {
  }
catch (  ParserConfigurationException e) {
  }
catch (  SAXException e) {
  }
catch (  FactoryConfigurationError e) {
  }
  return flavors;
}
 

Example 53

From project ant4eclipse, under directory /org.ant4eclipse.ant.pde/src/org/ant4eclipse/ant/pde/.

Source file: TargetPlatformDefinitionDataType.java

  16 
vote

/** 
 * {@inheritDoc}
 */
@Override protected void doValidate(){
  if (this._id == null || "".equals(this._id)) {
    throw new Ant4EclipseException(PdeExceptionCode.ANT_ATTRIBUTE_NOT_SET,"id");
  }
  if (this._targetFile != null) {
    if (!this._targetFile.exists()) {
      throw new Ant4EclipseException(PdeExceptionCode.TARGET_FILE_NOT_FOUND,this._targetFile.toString());
    }
    try {
      XMLReader reader=XMLReaderFactory.createXMLReader();
      reader.setContentHandler(new TargetPlattformContentHandler(this._targetFile,this));
      FileInputStream in=new FileInputStream(this._targetFile);
      try {
        reader.parse(new InputSource(new InputStreamReader(in,"UTF-8")));
      }
  finally {
        in.close();
      }
    }
 catch (    SAXException e) {
      Ant4EclipseException exeption=new Ant4EclipseException(PdeExceptionCode.TARGET_PARSING_FAILED,this._targetFile.toString(),e.toString());
      exeption.initCause(e);
      throw exeption;
    }
catch (    IOException e) {
      Ant4EclipseException exeption=new Ant4EclipseException(PdeExceptionCode.TARGET_PARSING_FAILED,this._targetFile.toString(),e.toString());
      exeption.initCause(e);
      throw exeption;
    }
  }
  if (this._targetPlatformDefinition.getLocations().length == 0) {
    A4ELogging.warn("Target definition with id %s does not contain any locations!",this._id);
  }
  TargetPlatformRegistry targetPlatformRegistry=ServiceRegistryAccess.instance().getService(TargetPlatformRegistry.class);
  targetPlatformRegistry.addTargetPlatformDefinition(this._id,this._targetPlatformDefinition);
}
 

Example 54

From project any23, under directory /core/src/main/java/org/apache/any23/extractor/html/.

Source file: TagSoupParser.java

  16 
vote

private Document parse() throws IOException, SAXException, TransformerException {
  final DOMParser parser=new DOMParser(){
    private QName currentQName;
    private Augmentations currentAugmentations;
    @Override protected Element createElementNode(    QName qName){
      final Element created=super.createElementNode(qName);
      if (qName.equals(currentQName) && currentAugmentations != null) {
        final ElementLocation elementLocation=createElementLocation(currentAugmentations.getItem(AUGMENTATIONS_FEATURE));
        created.setUserData(ELEMENT_LOCATION,elementLocation,null);
      }
      return created;
    }
    @Override public void startElement(    QName qName,    XMLAttributes xmlAttributes,    Augmentations augmentations) throws XNIException {
      super.startElement(qName,xmlAttributes,augmentations);
      currentQName=qName;
      currentAugmentations=augmentations;
    }
    private ElementLocation createElementLocation(    Object obj){
      if (obj == null)       return null;
      String pattern=null;
      try {
        pattern=obj.toString();
        if ("synthesized".equals(pattern))         return null;
        final String[] parts=pattern.split(":");
        return new ElementLocation(Integer.parseInt(parts[0]),Integer.parseInt(parts[1]),Integer.parseInt(parts[3]),Integer.parseInt(parts[4]));
      }
 catch (      Exception e) {
        logger.warn(String.format("Unexpected string format for given augmentation: [%s]",pattern),e);
        return null;
      }
    }
  }
;
  parser.setFeature("http://xml.org/sax/features/namespaces",false);
  parser.setFeature("http://cyberneko.org/html/features/scanner/script/strip-cdata-delims",true);
  parser.setFeature(AUGMENTATIONS_FEATURE,true);
  if (this.encoding != null)   parser.setProperty("http://cyberneko.org/html/properties/default-encoding",this.encoding);
  parser.parse(new InputSource(new SpanCloserInputStream(input)));
  return parser.getDocument();
}
 

Example 55

From project arquillian-rusheye, under directory /rusheye-impl/src/test/java/org/jboss/rusheye/result/writer/.

Source file: TestXmlResultWriter.java

  16 
vote

public void run(){
  try {
    reader=XMLReaderFactory.createXMLReader();
    reader.setFeature(XML_VALIDATION_FEATURE,true);
    reader.setFeature(XML_SCHEMA_FEATURE,true);
    reader.setFeature(XML_SCHEMA_FULL_CHECKING_FEATURE,true);
    reader.setContentHandler(new DefaultHandler());
    reader.setErrorHandler(new PassingSAXErrorHandler());
    reader.parse(new InputSource(in));
  }
 catch (  Exception e) {
    validationMessage=e.getMessage();
    throw new IllegalStateException(e);
  }
 finally {
    latch.countDown();
  }
}
 

Example 56

From project AudioBox.fm-JavaLib, under directory /audiobox.fm-core/src/main/java/fm/audiobox/configurations/.

Source file: DefaultResponseParser.java

  16 
vote

@Override public void parseAsXml(InputStream inputStream,IEntity destEntity) throws ServiceException {
  try {
    SAXParserFactory spf=SAXParserFactory.newInstance();
    SAXParser sp=spf.newSAXParser();
    XMLReader xr=sp.getXMLReader();
    xr.setContentHandler(new XmlParser(destEntity));
    xr.parse(new InputSource(inputStream));
  }
 catch (  ParserConfigurationException e) {
    log.error("An error occurred while instantiating XML Parser",e);
    throw new ServiceException(ServiceException.GENERIC_ERROR,e.getMessage());
  }
catch (  SAXException e) {
    log.error("An error occurred while instantiating XML Parser",e);
    throw new ServiceException(ServiceException.GENERIC_ERROR,e.getMessage());
  }
catch (  IllegalStateException e) {
    log.error("An error occurred while parsing response",e);
    throw new ServiceException(ServiceException.GENERIC_ERROR,e.getMessage());
  }
catch (  IOException e) {
    log.error("An error occurred while parsing response",e);
    throw new ServiceException(ServiceException.GENERIC_ERROR,e.getMessage());
  }
}
 

Example 57

From project aviator, under directory /src/main/java/com/googlecode/aviator/asm/xml/.

Source file: Processor.java

  16 
vote

private void processEntry(final ZipInputStream zis,final ZipEntry ze,final ContentHandlerFactory handlerFactory){
  ContentHandler handler=handlerFactory.createContentHandler();
  try {
    boolean singleInputDocument=inRepresentation == SINGLE_XML;
    if (inRepresentation == BYTECODE) {
      ClassReader cr=new ClassReader(readEntry(zis,ze));
      cr.accept(new SAXClassAdapter(handler,singleInputDocument),0);
    }
 else {
      XMLReader reader=XMLReaderFactory.createXMLReader();
      reader.setContentHandler(handler);
      reader.parse(new InputSource(singleInputDocument ? (InputStream)new ProtectedInputStream(zis) : new ByteArrayInputStream(readEntry(zis,ze))));
    }
  }
 catch (  Exception ex) {
    update(ze.getName(),0);
    update(ex,0);
  }
}
 

Example 58

From project build-info, under directory /build-info-extractor-maven3/src/main/java/org/jfrog/build/extractor/maven/.

Source file: BuildInfoRecorder.java

  16 
vote

private boolean isTestsFailed(List<File> surefireReports){
  XPathFactory factory=XPathFactory.newInstance();
  XPath path=factory.newXPath();
  for (  File report : surefireReports) {
    FileInputStream stream=null;
    try {
      stream=new FileInputStream(report);
      Object evaluate=path.evaluate("/testsuite/@failures",new InputSource(stream),XPathConstants.STRING);
      if (evaluate != null && StringUtils.isNotBlank(evaluate.toString()) && StringUtils.isNumeric(evaluate.toString())) {
        int testsFailed=Integer.parseInt(evaluate.toString());
        return testsFailed != 0;
      }
    }
 catch (    FileNotFoundException e) {
      logger.error("File '" + report.getAbsolutePath() + "' does not exist.");
    }
catch (    XPathExpressionException e) {
      logger.error("Expression /testsuite/@failures is invalid.");
    }
 finally {
      Closeables.closeQuietly(stream);
    }
  }
  return false;
}
 

Example 59

From project C-Cat, under directory /util/src/main/java/gov/llnl/ontology/text/corpora/.

Source file: PubMedDocumentReader.java

  16 
vote

/** 
 * {@inheritDoc}
 */
public Document readDocument(String originalText,String corpusName){
  inAbstract=false;
  inTitle=false;
  inPMID=false;
  inTitle=false;
  labels.clear();
  b.setLength(0);
  try {
    saxParser.parse(new InputSource(new StringReader(originalText)),this);
  }
 catch (  SAXException se) {
    throw new RuntimeException(se);
  }
catch (  IOException ioe) {
    throw new IOError(ioe);
  }
  return new SimpleDocument(corpusName,docText,originalText,key,id,title,labels);
}
 

Example 60

From project closure-templates, under directory /java/src/com/google/template/soy/xliffmsgplugin/.

Source file: XliffParser.java

  16 
vote

/** 
 * Parses the content of a translated XLIFF file and creates a SoyMsgBundle.
 * @param xliffContent The XLIFF content to parse.
 * @return The resulting SoyMsgBundle.
 * @throws SAXException If there's an error parsing the data.
 * @throws SoyMsgException If there's an error in parsing the data.
 */
static SoyMsgBundle parseXliffTargetMsgs(String xliffContent) throws SAXException, SoyMsgException {
  SAXParserFactory saxParserFactory=SAXParserFactory.newInstance();
  SAXParser saxParser;
  try {
    saxParser=saxParserFactory.newSAXParser();
  }
 catch (  ParserConfigurationException pce) {
    throw new AssertionError("Could not get SAX parser for XML.");
  }
  XliffSaxHandler xliffSaxHandler=new XliffSaxHandler();
  try {
    saxParser.parse(new InputSource(new StringReader(xliffContent)),xliffSaxHandler);
  }
 catch (  IOException e) {
    throw new AssertionError("Should not fail in reading a string.");
  }
  return new SoyMsgBundleImpl(xliffSaxHandler.getTargetLocaleString(),xliffSaxHandler.getMsgs());
}
 

Example 61

From project Cloud9, under directory /src/dist/edu/umd/hooka/corpora/.

Source file: ParallelCorpusReader.java

  16 
vote

public ParallelChunk parseString(String xml){
  resultChunk=null;
  try {
    sp.parse(new InputSource(new StringReader(xml)),this);
  }
 catch (  final SAXException se) {
    resultChunk=null;
    se.printStackTrace();
    throw new RuntimeException("SaxE: " + se + "\n"+ xml);
  }
catch (  final IOException ie) {
    resultChunk=null;
    ie.printStackTrace();
    throw new RuntimeException("ioe: " + ie);
  }
  return resultChunk;
}
 

Example 62

From project Codeable_Objects, under directory /SoftObjects/src/com/ui/.

Source file: FileImport.java

  16 
vote

public Point[] getPoints(String xml) throws Exception {
  try {
    DocumentBuilder db=DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc=db.parse(new InputSource(new StringReader(xml)));
    XPath xpath=XPathFactory.newInstance().newXPath();
    XPathExpression expr=xpath.compile("//polygon[@id='collide']/@points");
    String[] pointsAttr=((String)expr.evaluate(doc,XPathConstants.STRING)).split("\\p{Space}");
    Point[] points=new Point[pointsAttr.length];
    for (int i=0; i < pointsAttr.length; ++i) {
      String[] coordinates=pointsAttr[i].split(",");
      points[i]=new Point(Double.valueOf(coordinates[0]),Double.valueOf(coordinates[1]));
    }
    return points;
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 63

From project coffeescript-netbeans, under directory /src/coffeescript/nb/project/sample/.

Source file: CoffeeScriptApplicationWizardIterator.java

  16 
vote

private static void filterProjectXML(FileObject fo,ZipInputStream str,String name) throws IOException {
  try {
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    FileUtil.copy(str,baos);
    Document doc=XMLUtil.parse(new InputSource(new ByteArrayInputStream(baos.toByteArray())),false,false,null,null);
    NodeList nl=doc.getDocumentElement().getElementsByTagName("name");
    if (nl != null) {
      for (int i=0; i < nl.getLength(); i++) {
        Element el=(Element)nl.item(i);
        if (el.getParentNode() != null && "data".equals(el.getParentNode().getNodeName())) {
          NodeList nl2=el.getChildNodes();
          if (nl2.getLength() > 0) {
            nl2.item(0).setNodeValue(name);
          }
          break;
        }
      }
    }
    OutputStream out=fo.getOutputStream();
    try {
      XMLUtil.write(doc,out,"UTF-8");
    }
  finally {
      out.close();
    }
  }
 catch (  Exception ex) {
    Exceptions.printStackTrace(ex);
    writeFile(str,fo);
  }
}
 

Example 64

From project cw-advandroid, under directory /Honeycomb/WeatherFragment/src/com/commonsware/android/weather/.

Source file: WeatherBinder.java

  16 
vote

private ArrayList<Forecast> buildForecasts(String raw) throws Exception {
  ArrayList<Forecast> forecasts=new ArrayList<Forecast>();
  DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
  Document doc=builder.parse(new InputSource(new StringReader(raw)));
  NodeList times=doc.getElementsByTagName("start-valid-time");
  for (int i=0; i < times.getLength(); i++) {
    Element time=(Element)times.item(i);
    Forecast forecast=new Forecast();
    forecasts.add(forecast);
    forecast.setTime(time.getFirstChild().getNodeValue());
  }
  NodeList temps=doc.getElementsByTagName("value");
  for (int i=0; i < temps.getLength(); i++) {
    Element temp=(Element)temps.item(i);
    Forecast forecast=forecasts.get(i);
    forecast.setTemp(new Integer(temp.getFirstChild().getNodeValue()));
  }
  NodeList icons=doc.getElementsByTagName("icon-link");
  for (int i=0; i < icons.getLength(); i++) {
    Element icon=(Element)icons.item(i);
    Forecast forecast=forecasts.get(i);
    forecast.setIcon(icon.getFirstChild().getNodeValue());
  }
  return (forecasts);
}
 

Example 65

From project cw-android, under directory /Internet/Weather/src/com/commonsware/android/internet/.

Source file: WeatherDemo.java

  16 
vote

void buildForecasts(String raw) throws Exception {
  DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
  Document doc=builder.parse(new InputSource(new StringReader(raw)));
  NodeList times=doc.getElementsByTagName("start-valid-time");
  for (int i=0; i < times.getLength(); i++) {
    Element time=(Element)times.item(i);
    Forecast forecast=new Forecast();
    forecasts.add(forecast);
    forecast.setTime(time.getFirstChild().getNodeValue());
  }
  NodeList temps=doc.getElementsByTagName("value");
  for (int i=0; i < temps.getLength(); i++) {
    Element temp=(Element)temps.item(i);
    Forecast forecast=forecasts.get(i);
    forecast.setTemp(new Integer(temp.getFirstChild().getNodeValue()));
  }
  NodeList icons=doc.getElementsByTagName("icon-link");
  for (int i=0; i < icons.getLength(); i++) {
    Element icon=(Element)icons.item(i);
    Forecast forecast=forecasts.get(i);
    forecast.setIcon(icon.getFirstChild().getNodeValue());
  }
}
 

Example 66

From project cw-omnibus, under directory /Internet/Weather/src/com/commonsware/android/weather/.

Source file: WeatherFragment.java

  16 
vote

private ArrayList<Forecast> buildForecasts(String raw) throws Exception {
  ArrayList<Forecast> forecasts=new ArrayList<Forecast>();
  DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
  Document doc=builder.parse(new InputSource(new StringReader(raw)));
  NodeList times=doc.getElementsByTagName("start-valid-time");
  for (int i=0; i < times.getLength(); i++) {
    Element time=(Element)times.item(i);
    Forecast forecast=new Forecast();
    forecasts.add(forecast);
    forecast.setTime(time.getFirstChild().getNodeValue());
  }
  NodeList temps=doc.getElementsByTagName("value");
  for (int i=0; i < temps.getLength(); i++) {
    Element temp=(Element)temps.item(i);
    Forecast forecast=forecasts.get(i);
    forecast.setTemp(new Integer(temp.getFirstChild().getNodeValue()));
  }
  NodeList icons=doc.getElementsByTagName("icon-link");
  for (int i=0; i < icons.getLength(); i++) {
    Element icon=(Element)icons.item(i);
    Forecast forecast=forecasts.get(i);
    forecast.setIcon(icon.getFirstChild().getNodeValue());
  }
  return (forecasts);
}
 

Example 67

From project danbooru-gallery-android, under directory /src/tw/idv/palatis/danboorugallery/siteapi/.

Source file: DanbooruStyleAPI.java

  16 
vote

@Deprecated protected List<Tag> fetchTagsIndexXML(String url_format,int page,String name,int limit){
  TreeSet<Tag> ret=new TreeSet<Tag>(new Tag.CompareById());
  String keywords[]=new HashSet<String>(Arrays.asList(name.split("\\+"))).toArray(new String[]{});
  for (  String keyword : keywords) {
    keyword=keyword.trim().replace(' ','_');
    try {
      URL fetchUrl=new URL(String.format(url_format,page,keyword,limit));
      D.Log.v("DanbooruStyleAPI::fetchTagsIndexXML(): fetching %s",fetchUrl);
      DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
      DocumentBuilder db=dbf.newDocumentBuilder();
      Document doc=db.parse(new InputSource(fetchUrl.openStream()));
      doc.getDocumentElement().normalize();
      NodeList nodes=doc.getElementsByTagName("tag");
      int length=nodes.getLength();
      for (int i=0; i < length; ++i) {
        ret.add(new Tag((Element)nodes.item(i)));
        if (isCanceled())         return null;
      }
    }
 catch (    UnsupportedEncodingException e) {
      D.Log.wtf(e);
    }
catch (    IOException e) {
      D.Log.wtf(e);
    }
catch (    SAXException e) {
      D.Log.wtf(e);
    }
catch (    ParserConfigurationException e) {
      D.Log.wtf(e);
    }
  }
  return Arrays.asList(ret.toArray(new Tag[]{}));
}
 

Example 68

From project dawn-isencia, under directory /com.isencia.passerelle.commons.ume/src/main/java/com/isencia/message/extractor/.

Source file: XmlMessageExtractor.java

  16 
vote

/** 
 * @return
 */
public boolean initialize(){
  if (logger.isTraceEnabled()) {
    logger.trace("initialize() - entry");
  }
  characterFound=false;
  elementCount=0;
  buffer=new StringBuffer();
  try {
    xmlReader=saxParser.getXMLReader();
    xmlReader.setContentHandler(this);
    xmlReader.setErrorHandler(this);
    xmlReader.setFeature("http://xml.org/sax/features/validation",false);
    input=new InputSource(new ReaderWrapper(this.reader));
  }
 catch (  SAXNotRecognizedException e) {
    return false;
  }
catch (  SAXNotSupportedException e) {
    return false;
  }
catch (  SAXException e) {
    return false;
  }
  if (logger.isTraceEnabled()) {
    logger.trace("initialize() - exit");
  }
  return true;
}
 

Example 69

From project DrmLicenseService, under directory /src/com/sonyericsson/android/drm/drmlicenseservice/.

Source file: CustomDataParser.java

  16 
vote

public String parseXML(ByteArrayBuffer xmlData){
  if (xmlData != null && xmlData.length() > 0) {
    try {
      ByteArrayInputStream bais=new ByteArrayInputStream(xmlData.buffer(),0,xmlData.length());
      SAXParserFactory spf=SAXParserFactory.newInstance();
      SAXParser sp=spf.newSAXParser();
      XMLReader xr=sp.getXMLReader();
      CustomDataXmlHandler triggerHandler=new CustomDataXmlHandler();
      xr.setContentHandler(triggerHandler);
      xr.parse(new InputSource(bais));
      String customData=triggerHandler.getCustomData();
      return customData;
    }
 catch (    ParserConfigurationException e) {
    }
catch (    SAXException e) {
    }
catch (    IOException e) {
    }
  }
  return null;
}
 

Example 70

From project activemq-apollo, under directory /apollo-selector/src/main/java/org/apache/activemq/apollo/filter/.

Source file: XalanXPathEvaluator.java

  15 
vote

protected boolean evaluate(InputSource inputSource){
  try {
    DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder dbuilder=factory.newDocumentBuilder();
    Document doc=dbuilder.parse(inputSource);
    CachedXPathAPI cachedXPathAPI=new CachedXPathAPI();
    XObject result=cachedXPathAPI.eval(doc,xpath);
    if (result.bool())     return true;
 else {
      NodeIterator iterator=cachedXPathAPI.selectNodeIterator(doc,xpath);
      return (iterator.nextNode() != null);
    }
  }
 catch (  Throwable e) {
    return false;
  }
}
 

Example 71

From project arquillian-core, under directory /config/impl-base/src/test/java/org/jboss/arquillian/config/descriptor/impl/.

Source file: ArquillianDescriptorTestCase.java

  15 
vote

private void validateXML(String xml) throws Exception {
  DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
  dbf.setValidating(true);
  dbf.setNamespaceAware(true);
  dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage","http://www.w3.org/2001/XMLSchema");
  DocumentBuilder db=dbf.newDocumentBuilder();
  db.setErrorHandler(new ErrorHandler(){
    @Override public void warning(    SAXParseException exception) throws SAXException {
      throw exception;
    }
    @Override public void fatalError(    SAXParseException exception) throws SAXException {
      throw exception;
    }
    @Override public void error(    SAXParseException exception) throws SAXException {
      throw exception;
    }
  }
);
  db.setEntityResolver(new EntityResolver(){
    @Override public InputSource resolveEntity(    String publicId,    String systemId) throws SAXException, IOException {
      if ("http://jboss.org/schema/arquillian/arquillian_1_0.xsd".equals(systemId)) {
        return new InputSource(this.getClass().getClassLoader().getResourceAsStream("arquillian_1_0.xsd"));
      }
      return null;
    }
  }
);
  db.parse(new ByteArrayInputStream(xml.getBytes()));
}
 

Example 72

From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/dbunit/dataset/xml/.

Source file: DtdResolver.java

  15 
vote

/** 
 * @param xmlFile
 * @return name of DTD file specified in the !DOCTYPE or null if not specified.
 */
public String resolveDtdLocation(final String xmlFile){
  final InputStream xmlStream=Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFile);
  try {
    final DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
    builder.setEntityResolver(new EntityResolver(){
      @Override public InputSource resolveEntity(      String publicId,      String systemId) throws SAXException, IOException {
        return new InputSource(new StringReader(""));
      }
    }
);
    final Document document=builder.parse(xmlStream);
    if (document.getDoctype() == null) {
      return null;
    }
    return document.getDoctype().getSystemId();
  }
 catch (  Exception e) {
    throw new RuntimeException("Unable to resolve dtd for " + xmlFile,e);
  }
}
 

Example 73

From project bpm-console, under directory /server/war/src/main/java/org/jboss/bpm/console/server/util/.

Source file: DOMUtils.java

  15 
vote

/** 
 * Parse the given input source and return the root Element
 */
public static Element parse(InputSource source) throws IOException {
  try {
    return getDocumentBuilder().parse(source).getDocumentElement();
  }
 catch (  SAXException se) {
    throw new IOException(se.toString());
  }
 finally {
    InputStream is=source.getByteStream();
    if (is != null) {
      is.close();
    }
    Reader r=source.getCharacterStream();
    if (r != null) {
      r.close();
    }
  }
}
 

Example 74

From project CCR-Validator, under directory /src/main/java/org/openhealthdata/validation/.

Source file: CCRV1SchemaValidator.java

  15 
vote

private void validate(InputStream src){
  ccr=null;
  try {
    SAXSource source=new SAXSource(new InputSource(src));
    validator.validate(source);
    Document xml=parseStreamSource(src,false);
    if (xml != null) {
      JAXBContext jc=JAXBContext.newInstance("org.astm.ccr");
      Unmarshaller um=jc.createUnmarshaller();
      ccr=(ContinuityOfCareRecord)um.unmarshal(xml);
    }
  }
 catch (  SAXException e) {
    logger.log(Level.SEVERE,"Not Valid CCR XML: " + e.getMessage());
  }
catch (  IOException e) {
    logger.log(Level.SEVERE,"Exception during validating",e);
    e.printStackTrace();
  }
catch (  JAXBException e) {
    logger.log(Level.SEVERE,"Exception during unmarshalling XML DOM",e);
    e.printStackTrace();
  }
}
 

Example 75

From project cipango, under directory /cipango-console/src/main/java/org/cipango/console/.

Source file: StatisticGraph.java

  15 
vote

private void GraphType(String resourceName){
  try {
    InputStream templateGraph=getClass().getResourceAsStream(resourceName);
    _template=new RrdGraphDefTemplate(new InputSource(templateGraph));
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 76

From project cloudbees-api-client, under directory /cloudbees-api-client/src/main/java/com/cloudbees/utils/.

Source file: AppConfigHelper.java

  15 
vote

private static void load(ApplicationConfiguration applicationConfiguration,InputSource input,String[] environments,String[] implicitEnvironments){
  Document doc=readXML(input);
  Element rootElement=doc.getDocumentElement();
  if (rootElement.getNodeName().equals("stax-application") || rootElement.getNodeName().equals("stax-web-app") || rootElement.getNodeName().equals("cloudbees-web-app")) {
    AppConfigParser parser=new AppConfigParser();
    parser.load(applicationConfiguration,doc,environments,implicitEnvironments);
  }
}