Java Code Examples for org.xml.sax.XMLReader

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

  18 
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 Android-Flashcards, under directory /src/com/secretsockssoftware/androidflashcards/.

Source file: AndroidFlashcards.java

  18 
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 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 android-tether, under directory /src/og/android/tether/.

Source file: RSSReader.java

  18 
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 5

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 6

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

Source file: SoapToJade.java

  18 
vote

/** 
 * Get SAX parser class name
 * @param s
 * @return parser name
 */
private static String getSaxParserName() throws Exception {
  String saxFactory=System.getProperty("org.xml.sax.driver");
  if (saxFactory != null) {
    return saxFactory;
  }
 else {
    SAXParserFactory newInstance=SAXParserFactory.newInstance();
    SAXParser newSAXParser=newInstance.newSAXParser();
    XMLReader reader=newSAXParser.getXMLReader();
    String name=reader.getClass().getName();
    return name;
  }
}
 

Example 7

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 8

From project E12Planner, under directory /src/com/neoware/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 9

From project flexymind-alpha, under directory /src/com/larvalabs/svgandroid/.

Source file: SVGParser.java

  18 
vote

private static SVG parse(InputStream in,Integer searchColor,Integer replaceColor,boolean whiteMode) throws SVGParseException {
  try {
    long start=System.currentTimeMillis();
    SAXParserFactory spf=SAXParserFactory.newInstance();
    SAXParser sp=spf.newSAXParser();
    XMLReader xr=sp.getXMLReader();
    final Picture picture=new Picture();
    SVGHandler handler=new SVGHandler(picture);
    handler.setColorSwap(searchColor,replaceColor);
    handler.setWhiteMode(whiteMode);
    xr.setContentHandler(handler);
    xr.parse(new InputSource(in));
    SVG result=new SVG(picture,handler.bounds);
    if (!Float.isInfinite(handler.limits.top)) {
      result.setLimits(handler.limits);
    }
    return result;
  }
 catch (  Exception e) {
    throw new SVGParseException(e);
  }
}
 

Example 10

From project galaxyCar, under directory /AndroidColladaLoader/src/ckt/projects/acl/.

Source file: ColladaHandler.java

  18 
vote

public ArrayList<ColladaObject> parseFile(InputStream input){
  try {
    SAXParserFactory spf=SAXParserFactory.newInstance();
    SAXParser sp=spf.newSAXParser();
    XMLReader xr=sp.getXMLReader();
    xr.setContentHandler(this);
    xr.parse(new InputSource(input));
  }
 catch (  Exception e) {
  }
  ArrayList<ColladaObject> result=new ArrayList<ColladaObject>();
  result.add(new ColladaObject(vertices,indices,upAxis));
  return result;
}
 

Example 11

From project gravitext, under directory /gravitext-xmlprod/src/main/java/com/gravitext/xml/tree/.

Source file: SAXUtils.java

  18 
vote

public static Element saxParse(InputSource input) throws SAXException, IOException {
  XMLReader reader=XMLReaderFactory.createXMLReader();
  SAXHandler handler=new SAXHandler();
  reader.setContentHandler(handler);
  reader.parse(input);
  return handler.root();
}
 

Example 12

From project java-cas-client, under directory /cas-client-core/src/main/java/org/jasig/cas/client/util/.

Source file: XmlUtils.java

  18 
vote

/** 
 * Get an instance of an XML reader from the XMLReaderFactory.
 * @return the XMLReader.
 */
public static XMLReader getXmlReader(){
  try {
    final XMLReader reader=XMLReaderFactory.createXMLReader();
    reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false);
    return reader;
  }
 catch (  final SAXException e) {
    throw new RuntimeException("Unable to create XMLReader",e);
  }
}
 

Example 13

From project jboss-jstl-api_spec, under directory /src/main/java/org/apache/taglibs/standard/tag/common/xml/.

Source file: ParseSupport.java

  18 
vote

/** 
 * Parses the given InputSource after, applying the given XMLFilter. 
 */
private Document parseInputSourceWithFilter(InputSource s,XMLFilter f) throws SAXException, IOException {
  if (f != null) {
    Document o=db.newDocument();
    th.setResult(new DOMResult(o));
    XMLReader xr=XMLReaderFactory.createXMLReader();
    xr.setEntityResolver(new JstlEntityResolver(pageContext));
    f.setParent(xr);
    f.setContentHandler(th);
    f.parse(s);
    return o;
  }
 else   return parseInputSource(s);
}
 

Example 14

From project jgraphx, under directory /src/com/mxgraph/reader/.

Source file: mxGraphViewImageReader.java

  18 
vote

/** 
 * Creates the image for the given display XML input source. (Note: The XML is an encoded mxGraphView, not mxGraphModel.)
 * @param inputSource Input source that contains the display XML.
 * @return Returns an image representing the display XML input source.
 */
public static BufferedImage convert(InputSource inputSource,mxGraphViewImageReader viewReader) throws ParserConfigurationException, SAXException, IOException {
  BufferedImage result=null;
  SAXParser parser=SAXParserFactory.newInstance().newSAXParser();
  XMLReader reader=parser.getXMLReader();
  reader.setContentHandler(viewReader);
  reader.parse(inputSource);
  if (viewReader.getCanvas() instanceof mxImageCanvas) {
    result=((mxImageCanvas)viewReader.getCanvas()).destroy();
  }
  return result;
}
 

Example 15

From project jPOS, under directory /jpos/src/main/java/org/jpos/iso/packager/.

Source file: XML2003Packager.java

  18 
vote

private XMLReader createXMLReader() throws SAXException {
  XMLReader reader=null;
  try {
    reader=XMLReaderFactory.createXMLReader();
  }
 catch (  SAXException e) {
    reader=XMLReaderFactory.createXMLReader(System.getProperty("org.xml.sax.driver","org.apache.crimson.parser.XMLReaderImpl"));
  }
  reader.setFeature("http://xml.org/sax/features/validation",false);
  reader.setContentHandler(this);
  reader.setErrorHandler(this);
  return reader;
}
 

Example 16

From project kwegg, under directory /lib/readwrite/opennlp-tools/src/java/opennlp/tools/dictionary/serializer/.

Source file: DictionarySerializer.java

  18 
vote

/** 
 * Creates  {@link Entry}s form the given  {@link InputStream} andforwards these  {@link Entry}s to the  {@link EntryInserter}.
 * @param in
 * @param inserter
 * @throws IOException
 * @throws InvalidFormatException 
 */
public static void create(InputStream in,EntryInserter inserter) throws IOException, InvalidFormatException {
  DictionaryContenthandler profileContentHandler=new DictionaryContenthandler(inserter);
  XMLReader xmlReader;
  try {
    xmlReader=XMLReaderFactory.createXMLReader();
    xmlReader.setContentHandler(profileContentHandler);
    xmlReader.parse(new InputSource(new GZIPInputStream(in)));
  }
 catch (  SAXException e) {
    throw new InvalidFormatException("The profile data stream has" + "an invalid format!",e);
  }
}
 

Example 17

From project lenya, under directory /org.apache.lenya.optional.jcrsource/src/main/java/org/apache/lenya/cms/jcr/usecases/.

Source file: JCRImport.java

  18 
vote

private String getFirstNodeName(InputSource xmlInput) throws SAXException, IOException {
  XMLReader xmlReader=XMLReaderFactory.createXMLReader();
  FirstNodeNameHandler contentHandler=new FirstNodeNameHandler();
  xmlReader.setContentHandler(contentHandler);
  xmlReader.parse(xmlInput);
  return contentHandler.getFirstNodeName();
}
 

Example 18

From project Lily, under directory /global/util/src/main/java/org/lilyproject/util/xml/.

Source file: DocumentHelper.java

  18 
vote

public static Document parseDomWithLocationAttributes(InputSource inputSource) throws SAXException, ParserConfigurationException, TransformerConfigurationException, IOException {
  XMLReader xmlReader=LocalSAXParserFactory.newXmlReader();
  TransformerHandler serializer=LocalTransformerFactory.get().newTransformerHandler();
  DOMResult result=new DOMResult();
  serializer.setResult(result);
  LocationAttributes.Pipe locationPipe=new LocationAttributes.Pipe(serializer);
  xmlReader.setContentHandler(locationPipe);
  xmlReader.parse(inputSource);
  return (Document)result.getNode();
}
 

Example 19

From project litle-sdk-for-java, under directory /lib/jaxb/samples/partial-unmarshalling/src/.

Source file: Main.java

  18 
vote

public static void main(String[] args) throws Exception {
  JAXBContext context=JAXBContext.newInstance("primer");
  SAXParserFactory factory=SAXParserFactory.newInstance();
  factory.setNamespaceAware(true);
  XMLReader reader=factory.newSAXParser().getXMLReader();
  Splitter splitter=new Splitter(context);
  reader.setContentHandler(splitter);
  for (int i=0; i < args.length; i++) {
    reader.parse(new File(args[i]).toURL().toExternalForm());
  }
}
 

Example 20

From project milton, under directory /milton/milton-api/src/test/java/com/bradmcevoy/http/.

Source file: TestSaxHandler.java

  18 
vote

public void testPropFind() throws Exception {
  XMLReader reader=XMLReaderFactory.createXMLReader();
  PropFindSaxHandler handler=new PropFindSaxHandler();
  reader.setContentHandler(handler);
  reader.parse(new InputSource(PropFindSaxHandler.class.getResourceAsStream("/sample_prop_find.xml")));
  Map<QName,String> result=handler.getAttributes();
  assertEquals("httpd/unix-directory",result.get(new QName("DAV:","getcontenttype")));
  assertEquals("",result.get(new QName("DAV:","resourcetype")));
  assertEquals("Thu, 01 Jan 1970 00:00:00 GMT",result.get(new QName("DAV:","getlastmodified")));
  assertEquals("1970-01-01T00:00:00Z",result.get(new QName("DAV:","creationdate")));
}
 

Example 21

From project milton2, under directory /milton-server/src/test/java/io/milton/http/.

Source file: TestSaxHandler.java

  18 
vote

public void testPropFind() throws Exception {
  XMLReader reader=XMLReaderFactory.createXMLReader();
  PropFindSaxHandler handler=new PropFindSaxHandler();
  reader.setContentHandler(handler);
  reader.parse(new InputSource(PropFindSaxHandler.class.getResourceAsStream("/sample_prop_find.xml")));
  Map<QName,String> result=handler.getAttributes();
  assertEquals("httpd/unix-directory",result.get(new QName("DAV:","getcontenttype")));
  assertEquals("",result.get(new QName("DAV:","resourcetype")));
  assertEquals("Thu, 01 Jan 1970 00:00:00 GMT",result.get(new QName("DAV:","getlastmodified")));
  assertEquals("1970-01-01T00:00:00Z",result.get(new QName("DAV:","creationdate")));
}
 

Example 22

From project morphology, under directory /src/tools/java/lv/semti/Vardnicas/.

Source file: Vardnica.java

  18 
vote

public Vardnica(String filename) throws Exception {
  XMLReader xr=XMLReaderFactory.createXMLReader();
  LLVVLas?t?js las?t?js=new LLVVLas?t?js();
  xr.setContentHandler(las?t?js);
  BufferedReader straume=new BufferedReader(new InputStreamReader(new FileInputStream(filename),"UTF8"));
  xr.parse(new InputSource(straume));
}
 

Example 23

From project nuxeo-filesystem-connectors, under directory /nuxeo-generic-wss-front/src/main/java/org/nuxeo/wss/servlet/config/.

Source file: XmlConfigHandler.java

  18 
vote

public static void loadConfig(String configName) throws Exception {
  InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream(configName);
  XMLReader reader;
  reader=XMLReaderFactory.createXMLReader();
  reader.setContentHandler(getInstance());
  reader.setFeature("http://xml.org/sax/features/namespaces",false);
  reader.setFeature("http://xml.org/sax/features/validation",false);
  reader.parse(new InputSource(in));
}
 

Example 24

From project openengsb-framework, under directory /components/common/src/main/java/org/openengsb/core/common/transformations/.

Source file: TransformationUtils.java

  18 
vote

/** 
 * Does the actual parsing.
 */
private static List<TransformationDescription> loadDescrtipionsFromXMLInputSource(InputSource source,String fileName) throws Exception {
  XMLReader xr=XMLReaderFactory.createXMLReader();
  TransformationDescriptionXMLReader reader=new TransformationDescriptionXMLReader(fileName);
  xr.setContentHandler(reader);
  xr.parse(source);
  return reader.getResult();
}
 

Example 25

From project opennlp, under directory /opennlp-tools/src/main/java/opennlp/tools/dictionary/serializer/.

Source file: DictionarySerializer.java

  18 
vote

/** 
 * Creates  {@link Entry}s from the given  {@link InputStream} andforwards these  {@link Entry}s to the  {@link EntryInserter}. After creation is finished the provided  {@link InputStream} is closed.
 * @param in stream to read entries from
 * @param inserter inserter to forward entries to
 * @return isCaseSensitive attribute for Dictionary
 * @throws IOException
 * @throws InvalidFormatException
 */
public static boolean create(InputStream in,EntryInserter inserter) throws IOException, InvalidFormatException {
  DictionaryContenthandler profileContentHandler=new DictionaryContenthandler(inserter);
  XMLReader xmlReader;
  try {
    xmlReader=XMLReaderFactory.createXMLReader();
    xmlReader.setContentHandler(profileContentHandler);
    xmlReader.parse(new InputSource(new UncloseableInputStream(in)));
  }
 catch (  SAXException e) {
    throw new InvalidFormatException("The profile data stream has " + "an invalid format!",e);
  }
  return profileContentHandler.mIsCaseSensitiveDictionary;
}
 

Example 26

From project org.ops4j.pax.useradmin, under directory /pax-useradmin-command/src/main/java/org/ops4j/pax/useradmin/command/internal/xml/.

Source file: XMLDataReader.java

  18 
vote

/** 
 * @see UserAdminDataReader#copy(String,UserAdminDataWriter)
 */
public void copy(String sourceId,UserAdminDataWriter targetWriter) throws CommandException {
  try {
    XMLReader reader=XMLReaderFactory.createXMLReader();
    reader.setContentHandler(new XMLContentImporter(targetWriter));
    InputSource inputSource=new InputSource(sourceId);
    reader.parse(inputSource);
  }
 catch (  SAXException e) {
    throw new CommandException("SAXException when reading data from " + sourceId,e);
  }
catch (  IOException e) {
    throw new CommandException("IOException when reading data from " + sourceId,e);
  }
}
 

Example 27

From project PageTurner, under directory /src/main/java/net/nightwhistler/nucular/parser/.

Source file: Nucular.java

  18 
vote

private static void parseStream(ElementParser rootElementsParser,InputStream stream) throws ParserConfigurationException, SAXException, IOException {
  SAXParserFactory parseFactory=SAXParserFactory.newInstance();
  SAXParser xmlParser=parseFactory.newSAXParser();
  XMLReader xmlIn=xmlParser.getXMLReader();
  StreamParser catalogParser=new StreamParser(rootElementsParser);
  xmlIn.setContentHandler(catalogParser);
  xmlIn.parse(new InputSource(stream));
}
 

Example 28

From project phing-eclipse, under directory /org.ganoro.phing.core/src/org/ganoro/phing/core/contentDescriber/.

Source file: AntHandler.java

  18 
vote

/** 
 * Creates a new SAX parser for use within this instance.
 * @return The newly created parser.
 * @throws ParserConfigurationException If a parser of the given configuration cannot be created.
 * @throws SAXException If something in general goes wrong when creating the parser.
 */
private final SAXParser createParser(SAXParserFactory parserFactory) throws ParserConfigurationException, SAXException, SAXNotRecognizedException, SAXNotSupportedException {
  final SAXParser parser=parserFactory.newSAXParser();
  final XMLReader reader=parser.getXMLReader();
  try {
    reader.setFeature("http://xml.org/sax/features/validation",false);
    reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false);
  }
 catch (  SAXNotRecognizedException e) {
  }
catch (  SAXNotSupportedException e) {
  }
  return parser;
}
 

Example 29

From project radrails, under directory /plugins/org.radrails.rails.core/src/org/radrails/rails/core/railsplugins/.

Source file: RailsPluginsManager.java

  18 
vote

/** 
 * Parses an XML file describing a list of Rails plugins and returns a List of Map objects, containing the plugin attributes mapped to their corresponding values.
 * @param rdr the XML source
 * @return a list of plugin Maps
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
private List<RailsPluginDescriptor> parsePluginsXML(Reader rdr) throws SAXException, ParserConfigurationException, IOException {
  XMLReader reader=SAXParserFactory.newInstance().newSAXParser().getXMLReader();
  RailsPluginsContentHandler handler=new RailsPluginsContentHandler();
  reader.setContentHandler(handler);
  reader.parse(new InputSource(rdr));
  return handler.getRailsPlugins();
}
 

Example 30

From project reader, under directory /src/com/quietlycoding/android/reader/parser/.

Source file: PostListParser.java

  18 
vote

public long syncDb(Handler h,long id,String feedUrl) throws Exception {
  mId=id;
  mUrl=feedUrl;
  final SAXParserFactory fact=SAXParserFactory.newInstance();
  final SAXParser sp=fact.newSAXParser();
  final XMLReader reader=sp.getXMLReader();
  reader.setContentHandler(this);
  reader.setErrorHandler(this);
  final URL url=new URL(mUrl);
  final URLConnection c=url.openConnection();
  c.setRequestProperty("User-Agent","Android/1.5");
  reader.parse(new InputSource(c.getInputStream()));
  return mId;
}
 

Example 31

From project repose, under directory /project-set/components/content-identity-auth-2.0/src/main/java/org/openrepose/rackspace/auth_2_0/identity/parsers/xml/.

Source file: AuthenticationRequestParser.java

  18 
vote

public AuthenticationRequestParser(Unmarshaller unmarshaller){
  this.unmarshaller=unmarshaller;
  this.namespaceFilter=new NamespaceFilter(AUTH_2_0_NAMESPACE,true);
  XMLReader reader=null;
  try {
    reader=XMLReaderFactory.createXMLReader();
  }
 catch (  SAXException ex) {
    LOG.error("Unable to read message body stream. Reason: " + ex.getMessage(),ex);
  }
  this.namespaceFilter.setParent(reader);
}
 

Example 32

From project sandbox, under directory /xwiki-gadgets/src/main/java/org/xwiki/gadgets/internal/.

Source file: GoogleGadgetService.java

  18 
vote

/** 
 * {@inheritDoc}
 * @see GadgetService#parseUserPrefs(String)
 */
public List<UserPref> parseUserPrefs(String gadgetUri){
  try {
    XMLReader xr=xmlReaderFactory.createXMLReader();
    UserPrefsHandler upHandler=new UserPrefsHandler();
    xr.setContentHandler(upHandler);
    xr.parse(new InputSource(gadgetUri));
    return upHandler.getResult();
  }
 catch (  Exception e) {
    LOG.error(String.format("Exception while parsing User Preferences from gadget XML at location %s.",gadgetUri),e);
    return null;
  }
}
 

Example 33

From project SanDisk-HQME-SDK, under directory /projects/HqmeService/project/src/com/hqme/cm/core/.

Source file: Policy.java

  18 
vote

protected void fromString(String xmlContent){
  if (xmlContent != null && xmlContent.length() > 0)   try {
    PolicyParser parser=new PolicyParser();
    SAXParserFactory spf=SAXParserFactory.newInstance();
    SAXParser sp=spf.newSAXParser();
    XMLReader xr=sp.getXMLReader();
    xr.setContentHandler(parser);
    xr.parse(new InputSource(new StringReader(xmlContent)));
  }
 catch (  Exception fault) {
    CmClientUtil.debugLog(getClass(),"fromString",fault);
    throw new IllegalArgumentException(fault);
  }
}
 

Example 34

From project scufl2, under directory /scufl2-ucfpackage/src/main/java/uk/org/taverna/scufl2/ucfpackage/impl/odfdom/pkg/.

Source file: OdfXMLHelper.java

  18 
vote

/** 
 * create an XMLReader with a Resolver set to parse content in a ODF Package
 * @param pkg the ODF Package
 * @return a SAX XMLReader
 * @throws SAXException
 * @throws ParserConfigurationException
 */
public XMLReader newXMLReader(OdfPackage pkg) throws SAXException, ParserConfigurationException {
  SAXParserFactory factory=SAXParserFactory.newInstance();
  factory.setNamespaceAware(true);
  factory.setValidating(false);
  SAXParser parser=factory.newSAXParser();
  XMLReader xmlReader=parser.getXMLReader();
  xmlReader.setFeature("http://xml.org/sax/features/namespaces",true);
  xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes",true);
  xmlReader.setFeature("http://xml.org/sax/features/xmlns-uris",true);
  xmlReader.setEntityResolver(pkg.getEntityResolver());
  return xmlReader;
}
 

Example 35

From project SocialLib, under directory /src/com/expertiseandroid/lib/sociallib/utils/.

Source file: Utils.java

  18 
vote

/** 
 * Parses an XML response
 * @param response the response to parse
 * @param rules the parsing rules to be used
 * @return the list of objects built
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws IOException
 */
public static Object parseXML(ReadableResponse response,ParsingRules rules) throws SAXException, ParserConfigurationException, IOException {
  XMLReader reader=createXMLReader(new DynamicXmlParser(rules));
  String xml=response.getContents();
  InputSource is=new InputSource(new StringReader(xml));
  reader.parse(is);
  return rules.getContents();
}
 

Example 36

From project static-jsfexpression-validator, under directory /static-jsfexpression-validator-jsf12/src/main/java/com/sun/facelets/compiler/.

Source file: JsfelcheckSAXCompiler.java

  18 
vote

private final SAXParser createSAXParser(CompilationHandler handler) throws SAXException, ParserConfigurationException {
  SAXParserFactory factory=SAXParserFactory.newInstance();
  factory.setNamespaceAware(true);
  factory.setFeature("http://xml.org/sax/features/namespace-prefixes",true);
  factory.setFeature("http://xml.org/sax/features/validation",this.isValidating());
  factory.setValidating(this.isValidating());
  SAXParser parser=factory.newSAXParser();
  XMLReader reader=parser.getXMLReader();
  reader.setProperty("http://xml.org/sax/properties/lexical-handler",handler);
  reader.setErrorHandler(handler);
  reader.setEntityResolver(handler);
  return parser;
}
 

Example 37

From project SWOWS, under directory /swows/src/main/java/org/swows/xmlinrdf/.

Source file: DomEncoder2.java

  18 
vote

/** 
 * Encode.
 * @param document the document
 * @return the graph
 */
public static void encode(InputSource inputSAX,String rootUri,Graph graph){
  try {
    XMLReader xmlReader=XMLReaderFactory.createXMLReader();
    xmlReader.setContentHandler(new DocumentEncoder(graph,rootUri));
    xmlReader.parse(inputSAX);
  }
 catch (  SAXException e) {
    throw new RuntimeException(e);
  }
catch (  IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 38

From project XcodeProjectJavaAPI, under directory /src/main/java/com/sap/prd/mobile/ios/mios/xcodeprojreader/jaxb/.

Source file: JAXBPlistParser.java

  18 
vote

private SAXSource createSAXSource(InputSource project,final InputSource dtd) throws SAXException, ParserConfigurationException {
  XMLReader xmlReader=SAXParserFactory.newInstance().newSAXParser().getXMLReader();
  xmlReader.setEntityResolver(new EntityResolver(){
    @Override public InputSource resolveEntity(    String pid,    String sid) throws SAXException {
      if (sid.equals("http://www.apple.com/DTDs/PropertyList-1.0.dtd"))       return dtd;
      throw new SAXException("unable to resolve remote entity, sid = " + sid);
    }
  }
);
  SAXSource ss=new SAXSource(xmlReader,project);
  return ss;
}
 

Example 39

From project xwiki-rendering, under directory /xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/parser/xml/.

Source file: AbstractStreamParser.java

  18 
vote

/** 
 * @param source the content to parse
 * @param listener receive event for each element
 * @throws ParserConfigurationException error when rendering
 * @throws SAXException error when rendering
 * @throws IOException error when rendering
 */
public void parseXML(Reader source,Listener listener) throws ParserConfigurationException, SAXException, IOException {
  SAXParser saxParser=this.parserFactory.newSAXParser();
  XMLReader xmlReader=saxParser.getXMLReader();
  ContentHandlerStreamParser parser=createParser(listener);
  xmlReader.setContentHandler(parser);
  xmlReader.parse(new InputSource(source));
}
 

Example 40

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

Source file: WeatherMonitor.java

  17 
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 41

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

Source file: FlavorManager.java

  17 
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 42

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 43

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

Source file: TargetPlatformDefinitionDataType.java

  17 
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 44

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

Source file: DefaultResponseParser.java

  17 
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 45

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

Source file: Processor.java

  17 
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 46

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

Source file: JAXBBinding.java

  17 
vote

@SuppressWarnings("unchecked") <T>T unmarshal(String schemaLocation,Class<T> bindClass,InputSource inputSource) throws CdkException {
  T unmarshal=null;
  try {
    XMLReader xmlReader=XMLReaderFactory.createXMLReader();
    xmlReader.setEntityResolver(resolver);
    xmlReader.setFeature("http://xml.org/sax/features/validation",true);
    xmlReader.setFeature("http://apache.org/xml/features/validation/schema",true);
    xmlReader.setFeature("http://apache.org/xml/features/validation/dynamic",true);
    Unmarshaller u=JAXBContext.newInstance(bindClass).createUnmarshaller();
    u.setEventHandler(new ValidationEventCollector());
    XIncludeTransformer xIncludeTransformer=new XIncludeTransformer(log);
    if (null != inputSource.getSystemId()) {
      xIncludeTransformer.setBaseUri(new URI(inputSource.getSystemId()));
    }
    UnmarshallerHandler unmarshallerHandler=u.getUnmarshallerHandler();
    xIncludeTransformer.setContentHandler(unmarshallerHandler);
    xIncludeTransformer.setResolver(resolver);
    xmlReader.setContentHandler(xIncludeTransformer);
    xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler",xIncludeTransformer);
    xmlReader.parse(inputSource);
    unmarshal=(T)unmarshallerHandler.getResult();
  }
 catch (  JAXBException e) {
    throw new CdkException("JAXB Unmarshaller error: " + e.getMessage(),e);
  }
catch (  URISyntaxException e) {
    throw new CdkException("Invalid XML source URI: " + e.getMessage(),e);
  }
catch (  IOException e) {
    throw new CdkException("JAXB Unmarshaller input error: " + e.getMessage(),e);
  }
catch (  SAXException e) {
    throw new CdkException("XML error: " + e.getMessage(),e);
  }
 finally {
  }
  return unmarshal;
}
 

Example 47

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

Source file: CineShowtimeRequestManage.java

  17 
vote

private static String getAppEngineUrl(Context context){
  SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(context);
  String appEngineUrl=prefs.getString(CineShowtimeCst.PREF_KEY_APP_ENGINE,null);
  if (appEngineUrl == null) {
    try {
      URLBuilder andShowtimeUriBuilder=new URLBuilder(CineShowTimeEncodingUtil.convertLocaleToEncoding());
      andShowtimeUriBuilder.setProtocol(HttpParamsCst.BINOMED_APP_PROTOCOL);
      andShowtimeUriBuilder.setAdress(HttpParamsCst.BINOMED_APP_URL);
      andShowtimeUriBuilder.completePath(HttpParamsCst.BINOMED_APP_PATH);
      andShowtimeUriBuilder.completePath(HttpParamsCst.SEVER_GET_METHODE);
      String uri=andShowtimeUriBuilder.toUri();
      Log.i(TAG,"send request : " + uri);
      HttpGet getMethod=CineShowtimeFactory.getHttpGet();
      getMethod.setURI(new URI(uri));
      HttpResponse res=CineShowtimeFactory.getHttpClient().execute(getMethod);
      XMLReader reader=CineShowtimeFactory.getXmlReader();
      ParserSimpleResultXml parser=CineShowtimeFactory.getParserSimpleResultXml();
      reader.setContentHandler(parser);
      InputSource inputSource=CineShowtimeFactory.getInputSource();
      inputSource.setByteStream(res.getEntity().getContent());
      reader.parse(inputSource);
      appEngineUrl=parser.getUrl();
      if ((appEngineUrl == null) || (appEngineUrl.length() == 0)) {
        appEngineUrl=HttpParamsCst.BINOMED_APP_URL;
      }
      try {
        Editor editor=prefs.edit();
        editor.putString(CineShowtimeCst.PREF_KEY_APP_ENGINE,appEngineUrl);
        editor.commit();
      }
 catch (      Exception e) {
      }
    }
 catch (    Exception e) {
      appEngineUrl=HttpParamsCst.BINOMED_APP_URL;
    }
    Log.i(TAG,"result : " + appEngineUrl);
  }
  return appEngineUrl;
}
 

Example 48

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

Source file: CCTMXMapInfo.java

  17 
vote

private void parseXMLFile(String xmlFilename){
  try {
    SAXParserFactory saxFactory=SAXParserFactory.newInstance();
    SAXParser parser=saxFactory.newSAXParser();
    XMLReader reader=parser.getXMLReader();
    InputStream is=CCDirector.sharedDirector().getActivity().getResources().getAssets().open(xmlFilename);
    BufferedReader in=new BufferedReader(new InputStreamReader(is));
    CCTMXXMLParser handler=new CCTMXXMLParser();
    reader.setContentHandler(handler);
    reader.parse(new InputSource(in));
  }
 catch (  Exception e) {
    Log.e(LOG_TAG,e.getStackTrace().toString());
  }
}
 

Example 49

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

Source file: TRAXTransformerServiceImpl.java

  17 
vote

private Templates getXSLTemplates(Source source) throws TransformerException, NotSupportedIOTypeException {
  SAXTransformerFactory saxTFactory=(SAXTransformerFactory)SAXTransformerFactory.newInstance();
  TemplatesHandler templateHandler=saxTFactory.newTemplatesHandler();
  XMLReader xmlReader;
  try {
    xmlReader=TRAXTransformerImpl.getXMLReader();
    if (resolvingService != null) {
      xmlReader.setEntityResolver(resolvingService.getEntityResolver());
    }
  }
 catch (  SAXException ex) {
    throw new TransformerException(ex);
  }
  xmlReader.setContentHandler(templateHandler);
  InputSource inputSource=SAXSource.sourceToInputSource(source);
  if (inputSource == null) {
    throw new NotSupportedIOTypeException(source);
  }
  try {
    xmlReader.parse(inputSource);
  }
 catch (  SAXException ex) {
    throw new TransformerException(ex);
  }
catch (  IOException ex) {
    throw new TransformerException(ex);
  }
  return templateHandler.getTemplates();
}
 

Example 50

From project Cours-3eme-ann-e, under directory /XML/examples/sax/.

Source file: SAXExample3.java

  17 
vote

public static void main(String args[]) throws ParserConfigurationException, SAXException {
  SAXParserFactory factory=SAXParserFactory.newInstance();
  factory.setValidating(true);
  XMLReader parser=factory.newSAXParser().getXMLReader();
  parser.setContentHandler(new DefaultHandler());
  parser.setErrorHandler(new MyErrorHandler());
  try {
    parser.parse(args[0]);
    System.out.println("Everything is OK.");
  }
 catch (  IOException e) {
    System.err.printf("Handler in main. I/O error: %s\n",e.getMessage());
  }
catch (  SAXException e) {
    SAXParseException spe=(SAXParseException)e.getException();
    System.err.printf("Handler in main. Parsing error: %s\n",e.getMessage());
    if (spe != null) {
      System.err.println("Additional infos: " + spe.getLineNumber() + "/"+ spe.getColumnNumber());
    }
  }
}
 

Example 51

From project des, under directory /daemon/lib/apache-log4j-1.2.16/contribs/CekiGulcu/.

Source file: Transform.java

  17 
vote

public static void main(String[] args) throws Exception {
  PropertyConfigurator.disableAll();
  PropertyConfigurator.configure("x.lcf");
  Processor processor=Processor.newInstance("xslt");
  XMLReader reader=XMLReaderFactory.createXMLReader();
  TemplatesBuilder templatesBuilder=processor.getTemplatesBuilder();
  reader.setContentHandler(templatesBuilder);
  if (templatesBuilder instanceof LexicalHandler) {
    reader.setProperty("http://xml.org/sax/properties/lexical-handler",templatesBuilder);
  }
  reader.parse(args[0]);
  Templates templates=templatesBuilder.getTemplates();
  Transformer transformer=templates.newTransformer();
  FileOutputStream fos=new FileOutputStream(args[2]);
  Result result=new Result(fos);
  Serializer serializer=SerializerFactory.getSerializer("xml");
  serializer.setOutputStream(fos);
  transformer.setContentHandler(serializer.asContentHandler());
  org.xml.sax.ContentHandler chandler=transformer.getInputContentHandler();
  DC dc=new DC(chandler);
  reader.setContentHandler(dc);
  if (chandler instanceof LexicalHandler) {
    reader.setProperty("http://xml.org/sax/properties/lexical-handler",chandler);
  }
 else {
    reader.setProperty("http://xml.org/sax/properties/lexical-handler",null);
  }
  reader.parse(args[1]);
}
 

Example 52

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 53

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

Source file: CustomDataParser.java

  17 
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 54

From project Eclipse, under directory /com.mobilesorcery.sdk.profiling/src/com/mobilesorcery/sdk/profiling/internal/.

Source file: ProfilingDataParser.java

  17 
vote

public IInvocation parse(InputStream input,ISLDInfo info) throws IOException, ParseException {
  Invocation root=new Invocation(null);
  ProfilingDataParserHandler handler=new ProfilingDataParserHandler(root,info);
  try {
    SAXParserFactory spf=SAXParserFactory.newInstance();
    spf.setValidating(false);
    spf.setNamespaceAware(true);
    SAXParser sp=spf.newSAXParser();
    final XMLReader xr=sp.getXMLReader();
    xr.setContentHandler(handler);
    xr.parse(new InputSource(input));
    return root;
  }
 catch (  IOException e) {
    throw e;
  }
catch (  Exception e) {
    throw new ParseException(e);
  }
}
 

Example 55

From project en4j, under directory /NBPlatformApp/SearchLucene/src/main/java/com/rubenlaguna/en4j/searchlucene/.

Source file: NoteFinderLuceneImpl.java

  17 
vote

private String getTextFromInputSource(InputSource is) throws SAXException, IOException {
  XMLReader xr=new org.ccil.cowan.tagsoup.Parser();
  ContentHandler handler=new MyHandler();
  xr.setContentHandler(handler);
  xr.setErrorHandler(new ErrorHandler(){
    public void warning(    SAXParseException exception) throws SAXException {
      LOG.log(Level.WARNING,"exception while parsing note contents",exception);
    }
    public void error(    SAXParseException exception) throws SAXException {
      LOG.log(Level.WARNING,"exception while parsing note contents",exception);
    }
    public void fatalError(    SAXParseException exception) throws SAXException {
      LOG.log(Level.WARNING,"exception while parsing note contents",exception);
    }
  }
);
  xr.parse(is);
  String text=handler.toString();
  return text;
}
 

Example 56

From project enclojure, under directory /org-enclojure-ide/src/main/java/org/enclojure/ide/asm/xml/.

Source file: Processor.java

  17 
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 57

From project flyingsaucer, under directory /flying-saucer-core/src/main/java/org/xhtmlrenderer/resource/.

Source file: XMLResource.java

  17 
vote

XMLResource createXMLResource(XMLResource target){
  Source input=null;
  DOMResult output=null;
  TransformerFactory xformFactory=null;
  Transformer idTransform=null;
  XMLReader xmlReader=null;
  long st=0L;
  xmlReader=XMLResource.newXMLReader();
  addHandlers(xmlReader);
  setParserFeatures(xmlReader);
  st=System.currentTimeMillis();
  try {
    input=new SAXSource(xmlReader,target.getResourceInputSource());
    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    output=new DOMResult(dbf.newDocumentBuilder().newDocument());
    xformFactory=TransformerFactory.newInstance();
    idTransform=xformFactory.newTransformer();
  }
 catch (  Exception ex) {
    throw new XRRuntimeException("Failed on configuring SAX to DOM transformer.",ex);
  }
  try {
    idTransform.transform(input,output);
  }
 catch (  Exception ex) {
    throw new XRRuntimeException("Can't load the XML resource (using TRaX transformer). " + ex.getMessage(),ex);
  }
  long end=System.currentTimeMillis();
  target.setElapsedLoadTime(end - st);
  XRLog.load("Loaded document in ~" + target.getElapsedLoadTime() + "ms");
  target.setDocument((Document)output.getNode());
  return target;
}
 

Example 58

From project God-Save-The-Bag, under directory /src/com/estudio/cheke/game/gstb/.

Source file: SVGParser.java

  17 
vote

private static SVG parse(InputStream in,Integer searchColor,Integer replaceColor,boolean whiteMode) throws SVGParseException {
  SVGHandler svgHandler=null;
  try {
    SAXParserFactory spf=SAXParserFactory.newInstance();
    SAXParser sp=spf.newSAXParser();
    XMLReader xr=sp.getXMLReader();
    final Picture picture=new Picture();
    svgHandler=new SVGHandler(picture);
    svgHandler.setColorSwap(searchColor,replaceColor);
    svgHandler.setWhiteMode(whiteMode);
    CopyInputStream cin=new CopyInputStream(in);
    IDHandler idHandler=new IDHandler();
    xr.setContentHandler(idHandler);
    xr.parse(new InputSource(cin.getCopy()));
    svgHandler.idXml=idHandler.idXml;
    xr.setContentHandler(svgHandler);
    xr.parse(new InputSource(cin.getCopy()));
    SVG result=new SVG(picture,svgHandler.bounds);
    if (!Float.isInfinite(svgHandler.limits.top)) {
      result.setLimits(svgHandler.limits);
    }
    return result;
  }
 catch (  Exception e) {
    throw new SVGParseException(e);
  }
}
 

Example 59

From project ha-jdbc, under directory /src/main/java/net/sf/hajdbc/xml/.

Source file: XMLDatabaseClusterConfigurationFactory.java

  17 
vote

/** 
 * {@inheritDoc}
 * @see net.sf.hajdbc.DatabaseClusterConfigurationFactory#createConfiguration()
 */
@Override public DatabaseClusterConfiguration<Z,D> createConfiguration() throws SQLException {
  logger.log(Level.INFO,Messages.HA_JDBC_INIT.getMessage(),Version.getVersion(),this.streamFactory);
  try {
    SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema=schemaFactory.newSchema(SCHEMA);
    Unmarshaller unmarshaller=JAXBContext.newInstance(this.targetClass).createUnmarshaller();
    unmarshaller.setSchema(schema);
    XMLReader reader=new PropertyReplacementFilter(XMLReaderFactory.createXMLReader());
    InputSource source=SAXSource.sourceToInputSource(this.streamFactory.createSource());
    return this.targetClass.cast(unmarshaller.unmarshal(new SAXSource(reader,source)));
  }
 catch (  JAXBException e) {
    throw new SQLException(e);
  }
catch (  SAXException e) {
    throw new SQLException(e);
  }
}
 

Example 60

From project HippoCocoonToolkit, under directory /core/src/main/java/net/tirasa/hct/cocoon/sax/.

Source file: HippoRepositoryTransformer.java

  17 
vote

private void document(final HCTConnManager connManager) throws ObjectBeanManagerException, SAXException, IOException, RepositoryException {
  final HippoDocument doc=hctDocument.getHippoDocument(connManager,locale,availability);
  final HippoItemXMLDumper dumper=new HippoItemXMLDumper(this.getSAXConsumer());
  dumper.startHippoItem(doc,doc.getPath());
  for (  Entry<String,Object> entry : doc.getProperties().entrySet()) {
    if (TaggingNodeType.PROP_TAGS.equals(entry.getKey())) {
      dumper.dumpTags((String[])entry.getValue());
    }
 else     if (TaxonomyNodeTypes.HIPPOTAXONOMY_KEYS.equals(entry.getKey())) {
      dumper.dumpTaxonomies(TaxonomyUtils.getTaxonomies(connManager,(String[])entry.getValue()),locale);
    }
 else {
      dumper.dumpField(entry,hctDocument.getDateFormat(),locale);
    }
  }
  for (  HippoDate date : doc.getChildBeans(HippoDate.class)) {
    dumper.dumpDate(date.getName(),date.getCalendar(),hctDocument.getDateFormat(),locale);
  }
  final XMLReader xmlReader=new StartEndDocumentFilter(XMLUtils.createXMLReader(this.getSAXConsumer()));
  xmlReader.setContentHandler(this.getSAXConsumer());
  for (  HippoHtml rtf : doc.getChildBeans(HippoHtml.class)) {
    dumper.dumpHtml(connManager,rtf,xmlReader,hctDocument.getDateFormat(),locale);
  }
  findAndDumpImagesAndAssets(connManager,doc,dumper);
  compounds(connManager,doc,dumper,xmlReader);
  final List<HippoDocument> relDocs=new ArrayList<HippoDocument>();
  for (  RelatedDocs docs : doc.getChildBeans(RelatedDocs.class)) {
    for (    String relDocUuid : docs.getRelatedDocsUuids()) {
      relDocs.add(ObjectUtils.getHippoItemByUuid(connManager,relDocUuid,HippoDocument.class));
    }
  }
  dumper.dumpRelatedDocs(relDocs,Element.DOCUMENT.getName(),true);
  dumper.endHippoItem(doc);
}
 

Example 61

From project ISAvalidator-ISAconverter-BIImanager, under directory /import_layer/src/main/java/org/isatools/tablib/schema/.

Source file: SchemaBuilder.java

  17 
vote

/** 
 * Parses a schema definition from an XML document and returns the corresponding Object model
 */
public static FormatSet loadFormatSetFromXML(InputSource input){
  try {
    XMLReader parser=(XMLReader)Class.forName("org.apache.xerces.parsers.SAXParser").newInstance();
    parser.setFeature("http://xml.org/sax/features/validation",false);
    parser.setFeature("http://xml.org/sax/features/namespaces",false);
    parser.setFeature("http://apache.org/xml/features/validation/schema",false);
    parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking",false);
    SchemaBuilderSAXHandler handler=new SchemaBuilderSAXHandler();
    parser.setContentHandler(handler);
    parser.parse(input);
    FormatSet schema=handler.getFormatSet();
    log.trace("Schema Builder, returning the schema '" + schema.getId() + "'");
    return schema;
  }
 catch (  Exception ex) {
    throw new TabInternalErrorException("SchemaBuilder, error in parsing the XML schema definition: " + ex.getMessage(),ex);
  }
}
 

Example 62

From project jangaroo-tools, under directory /exml/exml-compiler/src/main/java/net/jangaroo/exml/parser/.

Source file: ExmlToConfigClassParser.java

  17 
vote

private static void parseFileWithHandler(File source,ContentHandler handler){
  InputStream inputStream=null;
  try {
    inputStream=new FileInputStream(source);
    XMLReader xr=XMLReaderFactory.createXMLReader();
    xr.setContentHandler(handler);
    xr.parse(new org.xml.sax.InputSource(inputStream));
  }
 catch (  ExmlcException e) {
    e.setFile(source);
    throw e;
  }
catch (  Exception e) {
    throw new ExmlcException("could not parse EXML file",source,e);
  }
 finally {
    try {
      if (inputStream != null) {
        inputStream.close();
      }
    }
 catch (    IOException e) {
    }
  }
}
 

Example 63

From project jboss-modules, under directory /src/test/java/org/jboss/modules/.

Source file: JAXPModuleTest.java

  17 
vote

public void checkXMLReader(Class<?> clazz,boolean fake) throws Exception {
  XMLReader parser=invokeMethod(clazz.newInstance(),"xmlReader");
  Assert.assertEquals(__XMLReaderFactory.class.getName(),parser.getClass().getName());
  Object test=null;
  try {
    test=parser.getProperty("test");
  }
 catch (  Exception ignore) {
  }
  if (fake) {
    Assert.assertEquals("fake-fake-fake",test);
  }
 else {
    Assert.assertFalse("fake-fake-fake".equals(test));
  }
}
 

Example 64

From project jbossportletbridge, under directory /core/portletbridge-impl/src/main/java/org/jboss/portletbridge/config/.

Source file: FacesConfigProcessor.java

  17 
vote

protected void parse(InputStream facesConfig,ParsingLocation location) throws ParsingException {
  try {
    SAXParser parser=saxFactory.newSAXParser();
    XMLReader reader=parser.getXMLReader();
    FacesConfigHandler facesConfigHandler=new FacesConfigHandler(reader);
    reader.setContentHandler(facesConfigHandler);
    reader.setEntityResolver(WebXmlProcessor.NULL_RESOLVER);
    reader.setErrorHandler(facesConfigHandler);
    reader.setDTDHandler(facesConfigHandler);
    reader.parse(new InputSource(facesConfig));
    excludedAttributes.addAll(facesConfigHandler.getExcludedAttributes());
    publicParameterMapping.putAll(facesConfigHandler.getParameterMapping());
    if (location.equals(ParsingLocation.CLASSPATH) || location.equals(ParsingLocation.DEFAULT)) {
      writeBehindRenderResponseWrapper=facesConfigHandler.getRenderResponseWrapperClass();
      writeBehindResourceResponseWrapper=facesConfigHandler.getResourceResponseWrapperClass();
    }
 else     if (location.equals(ParsingLocation.OPTIONAL)) {
      if (null == writeBehindRenderResponseWrapper) {
        writeBehindRenderResponseWrapper=facesConfigHandler.getRenderResponseWrapperClass();
      }
      if (null == writeBehindResourceResponseWrapper) {
        writeBehindResourceResponseWrapper=facesConfigHandler.getResourceResponseWrapperClass();
      }
    }
  }
 catch (  ParserConfigurationException e) {
    throw new ParsingException("SAX Parser configuration error",e);
  }
catch (  SAXException e) {
    logger.log(java.util.logging.Level.WARNING,"Exception at faces-config.xml parsing",e);
  }
catch (  IOException e) {
    logger.log(java.util.logging.Level.WARNING,"Exception at faces-config.xml parsing",e);
  }
}
 

Example 65

From project jdocbook-core, under directory /src/main/java/org/jboss/jdocbook/util/.

Source file: FileUtils.java

  17 
vote

/** 
 * Create a SAXSource from a given <tt>file</tt>. <p/> NOTE: the result <b>is</b>  {@link java.io.BufferedInputStream buffered}.
 * @param file The file from which to generate a SAXSource
 * @param resolver An entity resolver to apply to the file reader.
 * @param valueInjections The values to be injected
 * @return An appropriate SAXSource
 */
public static SAXSource createSAXSource(File file,EntityResolver resolver,final LinkedHashSet<ValueInjection> valueInjections){
  try {
    final InputSource source=createInputSource(file,valueInjections);
    SAXParserFactory factory=new SAXParserFactoryImpl();
    factory.setXIncludeAware(true);
    XMLReader reader=factory.newSAXParser().getXMLReader();
    reader.setEntityResolver(resolver);
    reader.setFeature(Constants.DTD_LOADING_FEATURE,true);
    reader.setFeature(Constants.DTD_VALIDATION_FEATURE,false);
    return new SAXSource(reader,source);
  }
 catch (  ParserConfigurationException e) {
    throw new JDocBookProcessException("unable to build SAX Parser/Factory [" + e.getMessage() + "]",e);
  }
catch (  SAXException e) {
    throw new JDocBookProcessException("unable to build SAX Parser/Factory [" + e.getMessage() + "]",e);
  }
}
 

Example 66

From project jdonframework, under directory /src/com/jdon/util/jdom/.

Source file: XMLFilterBase.java

  17 
vote

/** 
 * Installs lexical handler before a parse. <p>Before every parse, check whether the parent is non-null, and re-register the filter for the lexical events.</p>
 */
private void installLexicalHandler(){
  XMLReader parent=getParent();
  if (parent == null) {
    throw new NullPointerException("No parent for filter");
  }
  for (int i=0; i < LEXICAL_HANDLER_NAMES.length; i++) {
    try {
      parent.setProperty(LEXICAL_HANDLER_NAMES[i],this);
      break;
    }
 catch (    SAXNotRecognizedException ex) {
    }
catch (    SAXNotSupportedException ex) {
    }
  }
}
 

Example 67

From project juel, under directory /samples/src/de/odysseus/el/samples/xml/sax/.

Source file: AttributesFilter.java

  17 
vote

/** 
 * Usage example.
 */
public static void main(String[] args) throws SAXException, IOException {
  ELContext context=new SimpleContext();
  context.getELResolver().setValue(context,null,"home","/foo/bar");
  XMLReader reader=new AttributesFilter(XMLReaderFactory.createXMLReader(),context);
  reader.setContentHandler(new DefaultHandler(){
    @Override public void startElement(    String uri,    String localName,    String qName,    Attributes attributes){
      System.out.println("start " + localName);
      for (int i=0; i < attributes.getLength(); i++) {
        System.out.println("  @" + attributes.getLocalName(i) + " = "+ attributes.getValue(i));
      }
    }
    @Override public void endElement(    String uri,    String localName,    String qName){
      System.out.println("end " + localName);
    }
    @Override public void characters(    char[] ch,    int start,    int length) throws SAXException {
      System.out.println("text: " + new String(ch,start,length));
    }
  }
);
  String xml="<test>foo<math>1+2=${1+2}</math><config file='${home}/config.xml'/>bar</test>";
  reader.parse(new InputSource(new StringReader(xml)));
}
 

Example 68

From project kabeja, under directory /blocks/dxf/src/main/java/org/kabeja/dxf/generator/conf/.

Source file: SAXDXFGenerationContextBuilder.java

  17 
vote

public DXFGenerationContext buildDXFGenerationContext(InputStream in){
  this.initialize();
  context=new DefaultDXFGenerationContext(this.manager);
  try {
    SAXParserFactory factory=SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    XMLReader saxparser=factory.newSAXParser().getXMLReader();
    saxparser.setContentHandler(this);
    saxparser.parse(new InputSource(in));
  }
 catch (  SAXException e) {
    e.printStackTrace();
  }
catch (  IOException ioe) {
    ioe.printStackTrace();
  }
catch (  ParserConfigurationException e) {
    e.printStackTrace();
  }
  return context;
}
 

Example 69

From project LitHub, under directory /LitHub-Android/src/us/lithub/data/.

Source file: BookParser.java

  17 
vote

public static Map<String,String> getBookAttributesFromUpc(String upc){
  try {
    final URL url=new URL("http://isbndb.com/api/books.xml?access_key=MIIRXTQX&index1=isbn&value1=" + upc);
    final SAXParserFactory spf=SAXParserFactory.newInstance();
    final SAXParser sp=spf.newSAXParser();
    final XMLReader xr=sp.getXMLReader();
    final IsbnDbHandler handler=new IsbnDbHandler();
    xr.setContentHandler(handler);
    xr.parse(new InputSource(url.openStream()));
    return handler.getAttributes();
  }
 catch (  MalformedURLException e) {
    Log.e(TAG,e.getMessage());
  }
catch (  SAXException e) {
    Log.e(TAG,e.getMessage());
  }
catch (  ParserConfigurationException e) {
    Log.e(TAG,e.getMessage());
  }
catch (  IOException e) {
    Log.e(TAG,e.getMessage());
  }
  return null;
}
 

Example 70

From project log4j, under directory /contribs/CekiGulcu/.

Source file: Transform.java

  17 
vote

public static void main(String[] args) throws Exception {
  PropertyConfigurator.disableAll();
  PropertyConfigurator.configure("x.lcf");
  Processor processor=Processor.newInstance("xslt");
  XMLReader reader=XMLReaderFactory.createXMLReader();
  TemplatesBuilder templatesBuilder=processor.getTemplatesBuilder();
  reader.setContentHandler(templatesBuilder);
  if (templatesBuilder instanceof LexicalHandler) {
    reader.setProperty("http://xml.org/sax/properties/lexical-handler",templatesBuilder);
  }
  reader.parse(args[0]);
  Templates templates=templatesBuilder.getTemplates();
  Transformer transformer=templates.newTransformer();
  FileOutputStream fos=new FileOutputStream(args[2]);
  Result result=new Result(fos);
  Serializer serializer=SerializerFactory.getSerializer("xml");
  serializer.setOutputStream(fos);
  transformer.setContentHandler(serializer.asContentHandler());
  org.xml.sax.ContentHandler chandler=transformer.getInputContentHandler();
  DC dc=new DC(chandler);
  reader.setContentHandler(dc);
  if (chandler instanceof LexicalHandler) {
    reader.setProperty("http://xml.org/sax/properties/lexical-handler",chandler);
  }
 else {
    reader.setProperty("http://xml.org/sax/properties/lexical-handler",null);
  }
  reader.parse(args[1]);
}
 

Example 71

From project log4jna, under directory /thirdparty/log4j/contribs/CekiGulcu/.

Source file: Transform.java

  17 
vote

public static void main(String[] args) throws Exception {
  PropertyConfigurator.disableAll();
  PropertyConfigurator.configure("x.lcf");
  Processor processor=Processor.newInstance("xslt");
  XMLReader reader=XMLReaderFactory.createXMLReader();
  TemplatesBuilder templatesBuilder=processor.getTemplatesBuilder();
  reader.setContentHandler(templatesBuilder);
  if (templatesBuilder instanceof LexicalHandler) {
    reader.setProperty("http://xml.org/sax/properties/lexical-handler",templatesBuilder);
  }
  reader.parse(args[0]);
  Templates templates=templatesBuilder.getTemplates();
  Transformer transformer=templates.newTransformer();
  FileOutputStream fos=new FileOutputStream(args[2]);
  Result result=new Result(fos);
  Serializer serializer=SerializerFactory.getSerializer("xml");
  serializer.setOutputStream(fos);
  transformer.setContentHandler(serializer.asContentHandler());
  org.xml.sax.ContentHandler chandler=transformer.getInputContentHandler();
  DC dc=new DC(chandler);
  reader.setContentHandler(dc);
  if (chandler instanceof LexicalHandler) {
    reader.setProperty("http://xml.org/sax/properties/lexical-handler",chandler);
  }
 else {
    reader.setProperty("http://xml.org/sax/properties/lexical-handler",null);
  }
  reader.parse(args[1]);
}
 

Example 72

From project logsaw-app, under directory /net.sf.logsaw.dialect.log4j/src/net/sf/logsaw/dialect/log4j/xml/.

Source file: Log4JXMLLayoutDialect.java

  17 
vote

@Override public void parse(final ILogResource log,final InputStream input,ILogEntryCollector collector) throws CoreException {
  Assert.isNotNull(log,"log");
  Assert.isNotNull(input,"input");
  Assert.isNotNull(collector,"collector");
  try {
    InputStream eventSetIS=getClass().getResourceAsStream(FILENAME_EVENTSET_XML);
    XMLReader reader=XMLReaderFactory.createXMLReader();
    XMLFilter filter=new Log4JXMLFilter(collector);
    filter.setParent(reader);
    filter.setEntityResolver(new EntityResolver(){
      @Override public InputSource resolveEntity(      String publicId,      String systemId) throws SAXException, IOException {
        if ((systemId != null) && systemId.toLowerCase().endsWith(FILENAME_LOG4J_DTD)) {
          InputStream is=getClass().getResourceAsStream(FILENAME_LOG4J_DTD);
          return new InputSource(is);
        }
        if ((systemId != null) && systemId.equals("%file%")) {
          InputSource src=new InputSource(input);
          IHasEncoding enc=(IHasEncoding)log.getAdapter(IHasEncoding.class);
          src.setEncoding(enc.getEncoding());
          return src;
        }
        return null;
      }
    }
);
    filter.parse(new InputSource(eventSetIS));
  }
 catch (  OperationCanceledException e) {
  }
catch (  Exception e) {
    throw new CoreException(new Status(IStatus.ERROR,Log4JDialectPlugin.PLUGIN_ID,NLS.bind(Messages.Log4JDialect_error_parsingFailed,new Object[]{log.getName(),e.getLocalizedMessage()}),e));
  }
}
 

Example 73

From project mediautilities, under directory /src/com/larvalabs/svgandroid/.

Source file: SVGParser.java

  17 
vote

private static SVG parse(InputStream in,Integer searchColor,Integer replaceColor,boolean whiteMode) throws SVGParseException {
  SVGHandler svgHandler=null;
  try {
    SAXParserFactory spf=SAXParserFactory.newInstance();
    SAXParser sp=spf.newSAXParser();
    XMLReader xr=sp.getXMLReader();
    final Picture picture=new Picture();
    svgHandler=new SVGHandler(picture);
    svgHandler.setColorSwap(searchColor,replaceColor);
    svgHandler.setWhiteMode(whiteMode);
    CopyInputStream cin=new CopyInputStream(in);
    IDHandler idHandler=new IDHandler();
    xr.setContentHandler(idHandler);
    xr.parse(new InputSource(cin.getCopy()));
    svgHandler.idXml=idHandler.idXml;
    xr.setContentHandler(svgHandler);
    xr.parse(new InputSource(cin.getCopy()));
    SVG result=new SVG(picture,svgHandler.bounds);
    if (!Float.isInfinite(svgHandler.limits.top)) {
      result.setLimits(svgHandler.limits);
    }
    return result;
  }
 catch (  Exception e) {
    throw new SVGParseException(e);
  }
}
 

Example 74

From project MEditor, under directory /editor-common/editor-common-server/src/main/java/cz/mzk/editor/server/fedora/utils/.

Source file: DocumentLoader.java

  17 
vote

public static Document loadDocument(InputStream in,boolean validate) throws DocumentException {
  try {
    SAXParserFactory saxParserFactory=SAXParserFactory.newInstance();
    SAXParser saxParser=saxParserFactory.newSAXParser();
    XMLReader parser=saxParser.getXMLReader();
    parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false);
    parser.setFeature("http://xml.org/sax/features/validation",false);
    SAXReader reader=new SAXReader(parser);
    return reader.read(in);
  }
 catch (  ParserConfigurationException ex) {
    Logger.getLogger(DocumentLoader.class.getName()).log(Level.SEVERE,null,ex);
    return null;
  }
catch (  SAXException ex) {
    Logger.getLogger(DocumentLoader.class.getName()).log(Level.SEVERE,null,ex);
    return null;
  }
}
 

Example 75

From project mwe, under directory /plugins/org.eclipse.emf.mwe.ui/src/org/eclipse/emf/mwe/internal/ui/debug/launching/ui/launchable/.

Source file: LaunchableTester.java

  17 
vote

private boolean checkFileCriteria(final IFile file){
  if (!file.exists())   return false;
  try {
    final InputStream stream=file.getContents();
    final XMLContentHandler contentHandler=new XMLContentHandler();
    final XMLReader reader=SAXParserFactory.newInstance().newSAXParser().getXMLReader();
    reader.setContentHandler(contentHandler);
    final InputSource inputSource=new InputSource(stream);
    reader.parse(inputSource);
    final String rootName=contentHandler.getRootName();
    return ROOT_ELEMENT_NAME.equals(rootName);
  }
 catch (  final CoreException e) {
    e.printStackTrace();
    return false;
  }
catch (  final SAXException e) {
    e.printStackTrace();
    return false;
  }
catch (  final ParserConfigurationException e) {
    e.printStackTrace();
    return false;
  }
catch (  final IOException e) {
    e.printStackTrace();
    return false;
  }
}
 

Example 76

From project mylyn.docs, under directory /org.eclipse.mylyn.wikitext.core/src/org/eclipse/mylyn/internal/wikitext/core/parser/builder/.

Source file: XHtmlParser.java

  17 
vote

@Override protected void parse(InputSource input,DocumentBuilder builder,ContentHandler contentHandler) throws IOException, SAXException {
  if (input == null) {
    throw new IllegalArgumentException();
  }
  if (builder == null) {
    throw new IllegalArgumentException();
  }
  XMLReader xmlReader=XMLReaderFactory.createXMLReader();
  xmlReader.setContentHandler(contentHandler);
  Reader reader=input.getCharacterStream();
  if (reader == null) {
    final InputStream in=input.getByteStream();
    if (in == null) {
      throw new IllegalArgumentException("input must provide a byte stream or a character stream");
    }
    reader=new InputStreamReader(in,input.getEncoding() == null ? "utf-8" : input.getEncoding());
  }
  reader=new ConcatenatingReader(new StringReader("<?xml version='1.0'?><!DOCTYPE html [ <!ENTITY nbsp \"&#160;\"> <!ENTITY copy \"&#169;\"> <!ENTITY reg \"&#174;\"> <!ENTITY euro \"&#8364;\"> ]>"),reader);
  input=new InputSource(reader);
  xmlReader.parse(input);
}
 

Example 77

From project mylyn.docs.intent.main, under directory /plugins/org.eclipse.mylyn.docs.intent.markup/src/org/eclipse/mylyn/docs/intent/markup/resource/.

Source file: WikimediaResource.java

  17 
vote

private void handleImagesData(URI eImgURI,String baseServer,InputStream input) throws ParserConfigurationException, SAXException, IOException {
  final SAXParserFactory parserFactory=SAXParserFactory.newInstance();
  parserFactory.setNamespaceAware(true);
  parserFactory.setValidating(false);
  SAXParser saxParser=parserFactory.newSAXParser();
  XMLReader xmlReader=saxParser.getXMLReader();
  xmlReader.setEntityResolver(IgnoreDtdEntityResolver.getInstance());
  ImageFetchingContentHandler contentHandler=new ImageFetchingContentHandler();
  xmlReader.setContentHandler(contentHandler);
  try {
    xmlReader.parse(new InputSource(input));
  }
 catch (  IOException e) {
    throw new RuntimeException(String.format("Unexpected exception retrieving data from %s",eImgURI),e);
  }
  if (contentHandler.imageTitleToUrl.size() > 0) {
    Iterator<Image> it=Iterators.filter(getAllContents(),Image.class);
    while (it.hasNext()) {
      Image cur=it.next();
      String completeURL=contentHandler.imageTitleToUrl.get("Image:" + cur.getUrl());
      if (completeURL != null) {
        cur.setUrl(baseServer + "/" + completeURL);
      }
    }
  }
}
 

Example 78

From project npr-android-app, under directory /src/org/npr/api/.

Source file: Client.java

  17 
vote

public void sax(ContentHandler handler){
  try {
    XMLReader xr=SAXParserFactory.newInstance().newSAXParser().getXMLReader();
    xr.setContentHandler(handler);
    xr.parse(new InputSource(download()));
  }
 catch (  SAXException e) {
    Log.e(LOG_TAG,"error creating parser",e);
  }
catch (  ParserConfigurationException e) {
    Log.e(LOG_TAG,"error creating parser",e);
  }
catch (  FactoryConfigurationError e) {
    Log.e(LOG_TAG,"error creating parser",e);
  }
catch (  IOException e) {
    Log.e(LOG_TAG,"error parsing",e);
  }
}
 

Example 79

From project nuxeo-platform-login, under directory /nuxeo-platform-login-cas2/src/main/java/edu/yale/its/tp/cas/client/.

Source file: ServiceTicketValidator.java

  17 
vote

public void validate() throws IOException, SAXException, ParserConfigurationException {
  if (casValidateUrl == null || st == null)   throw new IllegalStateException("must set validation URL and ticket");
  clear();
  attemptedAuthentication=true;
  Map<String,String> urlParameters=new HashMap<String,String>();
  urlParameters.put("service",service);
  urlParameters.put("ticket",st);
  if (proxyCallbackUrl != null) {
    urlParameters.put("pgtUrl",proxyCallbackUrl);
  }
  if (renew) {
    urlParameters.put("renew","true");
  }
  String url=URIUtils.addParametersToURIQuery(casValidateUrl,urlParameters);
  String response=SecureURL.retrieve(url,false);
  this.entireResponse=response;
  if (response != null) {
    XMLReader r=SAXParserFactory.newInstance().newSAXParser().getXMLReader();
    r.setFeature("http://xml.org/sax/features/namespaces",false);
    r.setContentHandler(newHandler());
    r.parse(new InputSource(new StringReader(response)));
  }
}
 

Example 80

From project org.openscada.external, under directory /org.openscada.external.jOpenDocument/src/org/jopendocument/model/.

Source file: OpenDocument.java

  17 
vote

public void loadFrom(final File f){
  final SaxContentUnmarshaller contentHandler=new SaxContentUnmarshaller(this);
  final SaxStylesUnmarshaller stylesHandler=new SaxStylesUnmarshaller();
  try {
    this.zipFile=new ZipFile(f);
    final XMLReader rdr=XMLReaderFactory.createXMLReader();
    rdr.setContentHandler(contentHandler);
    final ZipEntry contnetEntry=this.zipFile.getEntry("content.xml");
    final InputSource inputSource1=new InputSource(new InputStreamReader(this.zipFile.getInputStream(contnetEntry),"UTF-8"));
    rdr.parse(inputSource1);
    rdr.setContentHandler(stylesHandler);
    final ZipEntry stylesEntry=this.zipFile.getEntry("styles.xml");
    if (stylesEntry != null) {
      final InputSource inputSource2=new InputSource(new InputStreamReader(this.zipFile.getInputStream(stylesEntry),"UTF-8"));
      rdr.parse(inputSource2);
    }
  }
 catch (  final Exception e1) {
    e1.printStackTrace();
  }
  this.init(contentHandler.getBody(),contentHandler.getAutomaticstyles(),stylesHandler.getStyles(),stylesHandler.getAutomaticStyles(),stylesHandler.getMasterStyles());
}
 

Example 81

From project pepe, under directory /pepe/src/edu/stanford/pepe/org/objectweb/asm/xml/.

Source file: Processor.java

  17 
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 82

From project phonegap-simjs, under directory /src/org/apache/wink/json4j/utils/.

Source file: XML.java

  17 
vote

/** 
 * Method to do the transform from an XML input stream to a JSON stream. Neither input nor output streams are closed.  Closure is left up to the caller.
 * @param XMLStream The XML stream to convert to JSON
 * @param JSONStream The stream to write out JSON to.  The contents written to this stream are always in UTF-8 format.
 * @param verbose Flag to denote whether or not to render the JSON text in verbose (indented easy to read), or compact (not so easy to read, but smaller), format.
 * @throws SAXException Thrown if a parse error occurs.
 * @throws IOException Thrown if an IO error occurs.
 */
public static void toJson(InputStream XMLStream,OutputStream JSONStream,boolean verbose) throws SAXException, IOException {
  if (logger.isLoggable(Level.FINER)) {
    logger.entering(className,"toJson(InputStream, OutputStream)");
  }
  if (XMLStream == null) {
    throw new NullPointerException("XMLStream cannot be null");
  }
 else   if (JSONStream == null) {
    throw new NullPointerException("JSONStream cannot be null");
  }
 else {
    if (logger.isLoggable(Level.FINEST)) {
      logger.logp(Level.FINEST,className,"transform","Fetching a SAX parser for use with JSONSAXHandler");
    }
    try {
      SAXParserFactory factory=SAXParserFactory.newInstance();
      factory.setNamespaceAware(true);
      SAXParser sParser=factory.newSAXParser();
      XMLReader parser=sParser.getXMLReader();
      JSONSAXHandler jsonHandler=new JSONSAXHandler(JSONStream,verbose);
      parser.setContentHandler(jsonHandler);
      parser.setErrorHandler(jsonHandler);
      InputSource source=new InputSource(new BufferedInputStream(XMLStream));
      if (logger.isLoggable(Level.FINEST)) {
        logger.logp(Level.FINEST,className,"transform","Parsing the XML content to JSON");
      }
      source.setEncoding("UTF-8");
      parser.parse(source);
      jsonHandler.flushBuffer();
    }
 catch (    javax.xml.parsers.ParserConfigurationException pce) {
      throw new SAXException("Could not get a parser: " + pce.toString());
    }
  }
  if (logger.isLoggable(Level.FINER)) {
    logger.exiting(className,"toJson(InputStream, OutputStream)");
  }
}
 

Example 83

From project platform_external_doclava, under directory /src/com/google/doclava/apicheck/.

Source file: XmlApiFile.java

  17 
vote

public static ApiInfo parseApi(InputStream xmlStream) throws ApiParseException {
  try {
    XMLReader xmlreader=XMLReaderFactory.createXMLReader();
    XmlApiFile handler=new XmlApiFile();
    xmlreader.setContentHandler(handler);
    xmlreader.setErrorHandler(handler);
    xmlreader.parse(new InputSource(xmlStream));
    ApiInfo apiInfo=handler.getApi();
    apiInfo.resolveSuperclasses();
    apiInfo.resolveInterfaces();
    return apiInfo;
  }
 catch (  Exception e) {
    throw new ApiParseException("Error parsing API",e);
  }
}
 

Example 84

From project rest-assured, under directory /rest-assured/src/main/java/com/jayway/restassured/path/xml/.

Source file: XmlPath.java

  17 
vote

public GPathResult invoke(){
  try {
    final XmlSlurper slurper;
    if (mode == XML) {
      slurper=new XmlSlurper();
    }
 else {
      XMLReader p=new org.ccil.cowan.tagsoup.Parser();
      slurper=new XmlSlurper(p);
    }
    return method(slurper);
  }
 catch (  Exception e) {
    throw new ParsePathException("Failed to parse the XML document",e);
  }
}
 

Example 85

From project riftsaw-ode, under directory /bpel-compiler/src/main/java/org/apache/ode/bpel/compiler/bom/.

Source file: BpelObjectFactory.java

  17 
vote

/** 
 * Parse a BPEL process found at the input source.
 * @param isrc input source.
 * @return
 * @throws SAXException 
 */
public Process parse(InputSource isrc,URI systemURI) throws IOException, SAXException {
  XMLReader _xr=XMLParserUtils.getXMLReader();
  LocalEntityResolver resolver=new LocalEntityResolver();
  resolver.register(Bpel11QNames.NS_BPEL4WS_2003_03,getClass().getResource("/bpel4ws_1_1-fivesight.xsd"));
  resolver.register(Bpel20QNames.NS_WSBPEL2_0,getClass().getResource("/wsbpel_main-draft-Apr-29-2006.xsd"));
  resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_ABSTRACT,getClass().getResource("/ws-bpel_abstract_common_base.xsd"));
  resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_EXEC,getClass().getResource("/ws-bpel_executable.xsd"));
  resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_PLINK,getClass().getResource("/ws-bpel_plnktype.xsd"));
  resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_SERVREF,getClass().getResource("/ws-bpel_serviceref.xsd"));
  resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_VARPROP,getClass().getResource("/ws-bpel_varprop.xsd"));
  resolver.register(XML,getClass().getResource("/xml.xsd"));
  resolver.register(WSDL,getClass().getResource("/wsdl.xsd"));
  resolver.register(Bpel20QNames.NS_WSBPEL_PARTNERLINK_2004_03,getClass().getResource("/wsbpel_plinkType-draft-Apr-29-2006.xsd"));
  _xr.setEntityResolver(resolver);
  Document doc=DOMUtils.newDocument();
  _xr.setContentHandler(new DOMBuilderContentHandler(doc));
  _xr.setFeature("http://xml.org/sax/features/namespaces",true);
  _xr.setFeature("http://xml.org/sax/features/namespace-prefixes",true);
  _xr.parse(isrc);
  return (Process)createBpelObject(doc.getDocumentElement(),systemURI);
}
 

Example 86

From project SDMXHDataExport, under directory /omod/src/main/java/org/openmrs/module/sdmxhddataexport/web/controller/report/.

Source file: ReportDataElementController.java

  17 
vote

public String transform(String str) throws Exception {
  try {
    InputStream inpXsl=OpenmrsClassLoader.getInstance().getResourceAsStream("xml-to-string.xsl");
    XMLReader reader=XMLReaderFactory.createXMLReader();
    InputStream inp=new ByteArrayInputStream(str.getBytes());
    Source source=new SAXSource(reader,new InputSource(inp));
    StringWriter outWriter=new StringWriter();
    StreamResult result=new StreamResult(outWriter);
    Source style=new StreamSource(inpXsl);
    TransformerFactory transFactory=TransformerFactory.newInstance();
    Transformer trans=transFactory.newTransformer(style);
    trans.transform(source,result);
    String s=outWriter.getBuffer().toString();
    System.out.println(s);
    return s;
  }
 catch (  SAXException e) {
    System.out.println(e.getMessage());
    return e.getMessage();
  }
}
 

Example 87

From project seamless, under directory /xml/src/main/java/org/seamless/xml/.

Source file: SAXParser.java

  17 
vote

protected XMLReader create(){
  try {
    if (getSchemaSources() != null) {
      SAXParserFactory factory=SAXParserFactory.newInstance();
      factory.setNamespaceAware(true);
      factory.setSchema(createSchema(getSchemaSources()));
      XMLReader xmlReader=factory.newSAXParser().getXMLReader();
      xmlReader.setErrorHandler(getErrorHandler());
      return xmlReader;
    }
    return XMLReaderFactory.createXMLReader();
  }
 catch (  Exception ex) {
    throw new RuntimeException(ex);
  }
}
 

Example 88

From project servicemix-utils, under directory /src/main/java/org/apache/servicemix/jbi/jaxp/.

Source file: SourceTransformer.java

  17 
vote

public SAXSource toSAXSourceFromDOM(DOMSource source) throws TransformerException {
  if (DOM_2_SAX_CLASS != null) {
    try {
      Constructor cns=DOM_2_SAX_CLASS.getConstructor(new Class[]{Node.class});
      XMLReader converter=(XMLReader)cns.newInstance(new Object[]{source.getNode()});
      converter.setFeature("http://xml.org/sax/features/validation",defaultValidatingDtd);
      converter.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",defaultValidatingDtd);
      return new SAXSource(converter,new InputSource());
    }
 catch (    Exception e) {
      throw new TransformerException(e);
    }
  }
 else {
    String str=toString(source);
    StringReader reader=new StringReader(str);
    return new SAXSource(new InputSource(reader));
  }
}
 

Example 89

From project servicemix4-specs, under directory /jaxb-api-2.0/src/main/java/javax/xml/bind/helpers/.

Source file: AbstractUnmarshallerImpl.java

  17 
vote

public Object unmarshal(Source source) throws JAXBException {
  if (source == null) {
    throw new IllegalArgumentException("source must not be null");
  }
 else   if (source instanceof SAXSource) {
    SAXSource saxSource=(SAXSource)source;
    XMLReader reader=saxSource.getXMLReader();
    if (reader == null) {
      reader=getXMLReader();
    }
    return unmarshal(reader,saxSource.getInputSource());
  }
 else   if (source instanceof StreamSource) {
    StreamSource ss=(StreamSource)source;
    InputSource is=new InputSource();
    is.setSystemId(ss.getSystemId());
    is.setByteStream(ss.getInputStream());
    is.setCharacterStream(ss.getReader());
    return unmarshal(is);
  }
 else   if (source instanceof DOMSource)   return unmarshal(((DOMSource)source).getNode());
 else   throw new IllegalArgumentException();
}
 

Example 90

From project Sketchy-Truck, under directory /andengine/src/org/anddev/andengine/entity/layer/tiled/tmx/.

Source file: TMXLoader.java

  17 
vote

public TMXTiledMap load(final InputStream pInputStream) throws TMXLoadException {
  try {
    final SAXParserFactory spf=SAXParserFactory.newInstance();
    final SAXParser sp=spf.newSAXParser();
    final XMLReader xr=sp.getXMLReader();
    final TMXParser tmxParser=new TMXParser(this.mContext,this.mTextureManager,this.mTextureOptions,this.mTMXTilePropertyListener);
    xr.setContentHandler(tmxParser);
    xr.parse(new InputSource(new BufferedInputStream(pInputStream)));
    return tmxParser.getTMXTiledMap();
  }
 catch (  final SAXException e) {
    throw new TMXLoadException(e);
  }
catch (  final ParserConfigurationException pe) {
    return null;
  }
catch (  final IOException e) {
    throw new TMXLoadException(e);
  }
}
 

Example 91

From project sojo, under directory /src/main/java/net/sf/sojo/interchange/xmlrpc/.

Source file: XmlRpcParser.java

  17 
vote

public Object parse(final String pvXmlRpcString) throws XmlRpcException {
  Object lvReturn=null;
  boolean lvIsFault=false;
  try {
    if (pvXmlRpcString != null) {
      SAXParserFactory lvFactory=SAXParserFactory.newInstance();
      SAXParser lvParser=lvFactory.newSAXParser();
      XMLReader lvReader=lvParser.getXMLReader();
      XmlRpcContentHandler lvContentHandler=new XmlRpcContentHandler();
      lvContentHandler.setReturnValueAsList(getReturnValueAsList());
      lvReader.setContentHandler(lvContentHandler);
      ByteArrayInputStream lvArrayInputStream=new ByteArrayInputStream(pvXmlRpcString.getBytes());
      lvReader.parse(new InputSource(lvArrayInputStream));
      lvReturn=lvContentHandler.getResults();
      methodName=lvContentHandler.getMethodName();
      lvIsFault=lvContentHandler.isFault();
    }
  }
 catch (  SAXParseException e) {
    throw new XmlRpcException(e.getMessage(),e);
  }
catch (  Exception e) {
    throw new XmlRpcException("Exception by parse XML-RPC-String: " + pvXmlRpcString,e);
  }
  if (lvIsFault == true && getConvertResult2XmlRpcExceptionAndThrow()) {
    Map<?,?> lvMap=(Map<?,?>)lvReturn;
    Object lvFaultCode=lvMap.get("faultCode");
    Object lvMessage=lvMap.get("faultString");
    throw new XmlRpcException(lvFaultCode + ": " + lvMessage);
  }
  return lvReturn;
}
 

Example 92

From project solder, under directory /impl/src/main/java/org/jboss/solder/config/xml/parser/.

Source file: ParserMain.java

  17 
vote

public SaxNode parse(InputSource inputSource,String fileUrl,List<Exception> errors){
  this.errors=errors;
  document=fileUrl;
  try {
    XMLReader xr=XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);
    xr.setErrorHandler(this);
    xr.parse(inputSource);
    return parentNode;
  }
 catch (  SAXException e) {
    throw new RuntimeException(e);
  }
catch (  IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 93

From project SouthamptonUniversityMap, under directory /src/net/cbaines/suma/.

Source file: DataManager.java

  17 
vote

static PathOverlay getRoutePath(InputStream routeResource,int colour,ResourceProxy resProxy){
  PathOverlay data=null;
  try {
    SAXParserFactory spf=SAXParserFactory.newInstance();
    SAXParser sp=spf.newSAXParser();
    XMLReader xr=sp.getXMLReader();
    DataHandler dataHandler=new DataHandler(colour,resProxy);
    xr.setContentHandler(dataHandler);
    xr.parse(new InputSource(routeResource));
    data=dataHandler.getData();
  }
 catch (  ParserConfigurationException pce) {
    Log.e("SAX XML","sax parse error",pce);
  }
catch (  SAXException se) {
    Log.e("SAX XML","sax error",se);
  }
catch (  IOException ioe) {
    Log.e("SAX XML","sax parse io error",ioe);
  }
  return data;
}
 

Example 94

From project sparsemapcontent, under directory /extensions/milton/src/main/java/ignore/com/bradmcevoy/http/webdav/.

Source file: DefaultPropFindRequestFieldParser.java

  17 
vote

@Override public PropertiesRequest getRequestedFields(InputStream in){
  try {
    final Set<QName> set=new LinkedHashSet<QName>();
    ByteArrayOutputStream bout=new ByteArrayOutputStream();
    StreamUtils.readTo(in,bout,false,true);
    byte[] arr=bout.toByteArray();
    if (arr.length > 1) {
      ByteArrayInputStream bin=new ByteArrayInputStream(arr);
      XMLReader reader=XMLReaderFactory.createXMLReader();
      PropFindSaxHandler handler=new PropFindSaxHandler();
      reader.setContentHandler(handler);
      try {
        reader.parse(new InputSource(bin));
        if (handler.isAllProp()) {
          return new PropertiesRequest();
        }
 else {
          set.addAll(handler.getAttributes().keySet());
        }
      }
 catch (      IOException e) {
        log.warn("exception parsing request body",e);
      }
catch (      SAXException e) {
        log.warn("exception parsing request body",e);
        throw new RuntimeBadRequestException(e.getMessage(),e);
      }
    }
    return PropertiesRequest.toProperties(set);
  }
 catch (  Exception ex) {
    throw new RuntimeException(ex);
  }
}
 

Example 95

From project spring-dbunit, under directory /spring-dbunit-core/src/main/java/com/excilys/ebi/spring/dbunit/dataset/xml/flyweight/.

Source file: FlyWeightFlatXmlProducer.java

  17 
vote

public void produce() throws DataSetException {
  logger.debug("produce() - start");
  try {
    SAXParserFactory saxParserFactory=SAXParserFactory.newInstance();
    saxParserFactory.setValidating(_validating);
    XMLReader xmlReader=saxParserFactory.newSAXParser().getXMLReader();
    if (_dtdHandler != null) {
      FlatDtdHandler.setLexicalHandler(xmlReader,_dtdHandler);
      FlatDtdHandler.setDeclHandler(xmlReader,_dtdHandler);
    }
    xmlReader.setContentHandler(this);
    xmlReader.setErrorHandler(this);
    xmlReader.setEntityResolver(_resolver);
    xmlReader.parse(_inputSource);
  }
 catch (  ParserConfigurationException e) {
    throw new DataSetException(e);
  }
catch (  SAXException e) {
    DataSetException exceptionToRethrow=buildException(e);
    throw exceptionToRethrow;
  }
catch (  IOException e) {
    throw new DataSetException(e);
  }
}
 

Example 96

From project TABuss, under directory /src/org/ubicompforall/BusTUC/Main/.

Source file: BusTUCApp.java

  17 
vote

public void drivingPath(double[] dest,Location loc){
  System.out.println("dest: " + dest[0] + "  "+ dest[1]);
  Location lastKnownLocation=loc;
  StringBuilder urlString=new StringBuilder();
  urlString.append("http://maps.google.com/maps?f=d&hl=en");
  urlString.append("&saddr=");
  urlString.append(Double.toString(lastKnownLocation.getLatitude()));
  urlString.append(",");
  urlString.append(Double.toString(lastKnownLocation.getLongitude()));
  urlString.append("&daddr=");
  urlString.append(Double.toString(dest[0] / 1.0E6));
  urlString.append(",");
  urlString.append(Double.toString(dest[1] / 1.0E6));
  urlString.append("&dirflg=w&hl=en&ie=UTF8&z=14&output=kml");
  try {
    URL url=new URL(urlString.toString());
    SAXParserFactory factory=SAXParserFactory.newInstance();
    SAXParser parser=factory.newSAXParser();
    XMLReader xmlreader=parser.getXMLReader();
    NavigationSaxHandler navSaxHandler=new NavigationSaxHandler();
    xmlreader.setContentHandler(navSaxHandler);
    InputSource is=new InputSource(url.openStream());
    xmlreader.parse(is);
    NavigationDataSet ds=navSaxHandler.getParsedData();
    Log.d("MAPAPP",urlString.toString());
    drawPath(ds,Color.parseColor("#add331"),mapView);
  }
 catch (  Exception e) {
  }
}
 

Example 97

From project tempo, under directory /wds-service/src/main/java/org/intalio/tempo/workflow/wds/core/xforms/.

Source file: XFormsProcessor.java

  17 
vote

/** 
 * Process an XForms document. <ul> <li>If the model schema is specified as a relative URI, it is changed to comply to the form URI,  e.g. if a form is stored at (oxf:/)my/uri/form1.xform and it specified "form1.xsd"  as its model schema, then the value of the "schema" attribute of the "xforms:model"  element will be rewritten as: "oxf:/my/uri/form1.xsd"</li> <li>The XForms document is reformatted in a "pretty-print" way.</li> </ul>
 */
@SuppressWarnings("deprecation") public static Item processXForm(final String itemUri,InputStream inputStream) throws IOException, ParserConfigurationException, SAXException {
  if (LOG.isDebugEnabled())   LOG.debug("Processing " + itemUri);
  StringWriter out=new StringWriter();
  SAXParser parser=SAXParserFactory.newInstance().newSAXParser();
  OutputFormat format=new OutputFormat();
  format.setEncoding(CharEncoding.UTF_8);
  format.setOmitXMLDeclaration(false);
  format.setOmitComments(false);
  format.setPreserveSpace(true);
  SchemaURLRewriter ser=new SchemaURLRewriter(out,format,itemUri);
  XMLReader reader=parser.getXMLReader();
  reader.setContentHandler(ser);
  reader.parse(new InputSource(inputStream));
  return new Item(itemUri,XFORMS_CONTENT_TYPE,out.toString().getBytes(CharEncoding.UTF_8));
}
 

Example 98

From project tika, under directory /tika-parsers/src/main/java/org/apache/tika/parser/microsoft/ooxml/.

Source file: XSSFExcelExtractorDecorator.java

  17 
vote

public void processSheet(SheetContentsHandler sheetContentsExtractor,StylesTable styles,ReadOnlySharedStringsTable strings,InputStream sheetInputStream) throws IOException, SAXException {
  InputSource sheetSource=new InputSource(sheetInputStream);
  SAXParserFactory saxFactory=SAXParserFactory.newInstance();
  try {
    SAXParser saxParser=saxFactory.newSAXParser();
    XMLReader sheetParser=saxParser.getXMLReader();
    XSSFSheetInterestingPartsCapturer handler=new XSSFSheetInterestingPartsCapturer(new XSSFSheetXMLHandler(styles,strings,sheetContentsExtractor,formatter,false));
    sheetParser.setContentHandler(handler);
    sheetParser.parse(sheetSource);
    sheetInputStream.close();
    sheetProtected.add(handler.hasProtection);
  }
 catch (  ParserConfigurationException e) {
    throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
  }
}
 

Example 99

From project wip, under directory /src/main/java/fr/ippon/wip/transformers/pool/.

Source file: XMLReaderPool.java

  17 
vote

@Override protected CloseableXmlReader buildResource(){
  try {
    XMLReader parser=XMLReaderFactory.createXMLReader(parserClassName);
    parser.setFeature("http://cyberneko.org/html/features/override-namespaces",true);
    parser.setFeature("http://cyberneko.org/html/features/insert-namespaces",true);
    parser.setFeature("http://cyberneko.org/html/features/scanner/ignore-specified-charset",true);
    parser.setProperty("http://cyberneko.org/html/properties/default-encoding","UTF-8");
    parser.setProperty("http://cyberneko.org/html/properties/doctype/pubid","-//W3C//DTD XHTML 1.0 Transitional//EN");
    parser.setProperty("http://cyberneko.org/html/properties/doctype/sysid","http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd");
    parser.setFeature("http://cyberneko.org/html/features/insert-doctype",true);
    parser.setFeature("http://apache.org/xml/features/scanner/notify-builtin-refs",true);
    parser.setFeature("http://cyberneko.org/html/features/scanner/notify-builtin-refs",true);
    return new CloseableXmlReader(this,parser);
  }
 catch (  SAXException e) {
    e.printStackTrace();
    return null;
  }
}
 

Example 100

From project xmlcalabash1, under directory /src/com/xmlcalabash/model/.

Source file: Parser.java

  17 
vote

private XdmNode parse(InputStream instream,URI baseURI) throws SaxonApiException {
  try {
    XMLReader reader=XMLReaderFactory.createXMLReader();
    reader.setEntityResolver(runtime.getResolver());
    SAXSource source=new SAXSource(reader,new InputSource(instream));
    DocumentBuilder builder=runtime.getProcessor().newDocumentBuilder();
    builder.setLineNumbering(true);
    builder.setDTDValidation(false);
    builder.setBaseURI(baseURI);
    return builder.build(source);
  }
 catch (  SAXException se) {
    throw new XProcException(se);
  }
}
 

Example 101

From project xwiki-commons, under directory /xwiki-commons-core/xwiki-commons-xml/src/main/java/org/xwiki/xml/internal/.

Source file: DefaultXMLReaderFactory.java

  17 
vote

@Override public XMLReader createXMLReader() throws SAXException, ParserConfigurationException {
  XMLReader xmlReader;
  try {
    Object xercesConfiguration=Class.forName("org.apache.xerces.parsers.XML11NonValidatingConfiguration").newInstance();
    Method setPropertyMethod=xercesConfiguration.getClass().getMethod("setProperty",String.class,Object.class);
    setPropertyMethod.invoke(xercesConfiguration,"http://apache.org/xml/properties/internal/grammar-pool",this.xercesGrammarPool);
    xmlReader=(XMLReader)Class.forName("org.apache.xerces.parsers.SAXParser").getConstructor(Class.forName("org.apache.xerces.xni.parser.XMLParserConfiguration")).newInstance(xercesConfiguration);
  }
 catch (  Exception e) {
    SAXParserFactory parserFactory=SAXParserFactory.newInstance();
    SAXParser parser=parserFactory.newSAXParser();
    xmlReader=parser.getXMLReader();
  }
  return xmlReader;
}
 

Example 102

From project androidquery, under directory /src/com/androidquery/service/.

Source file: MarketService.java

  15 
vote

@Override public void handleTag(boolean opening,String tag,Editable output,XMLReader xmlReader){
  if ("li".equals(tag)) {
    if (opening) {
      output.append("  ");
      output.append(BULLET);
      output.append("  ");
    }
 else {
      output.append("\n");
    }
  }
}
 

Example 103

From project jsword, under directory /src/main/java/org/crosswire/common/xml/.

Source file: XMLFeatureSet.java

  15 
vote

/** 
 * Set the control state on the parser.
 * @param parser
 */
public void setFeature(XMLReader parser){
  String control=feature.getControl();
  try {
    parser.setFeature(control,state);
  }
 catch (  SAXNotRecognizedException e) {
    System.err.println("warning: Parser does not recognize feature (" + control + ")");
  }
catch (  SAXNotSupportedException e) {
    System.err.println("warning: Parser does not support feature (" + control + ")");
  }
}
 

Example 104

From project k-9, under directory /src/com/fsck/k9/helper/.

Source file: HtmlConverter.java

  15 
vote

@Override public void handleTag(boolean opening,String tag,Editable output,XMLReader xmlReader){
  tag=tag.toLowerCase(Locale.US);
  if (tag.equals("hr") && opening) {
    output.append("_____________________________________________\n");
  }
 else   if (TAGS_WITH_IGNORED_CONTENT.contains(tag)) {
    handleIgnoredTag(opening,output);
  }
}
 

Example 105

From project maven-doxia, under directory /doxia-core/src/main/java/org/apache/maven/doxia/util/.

Source file: XmlValidator.java

  15 
vote

/** 
 * @param hasDtdAndXsd to flag the <code>ErrorHandler</code>.
 * @return an xmlReader instance.
 * @throws SAXException if any
 */
private XMLReader getXmlReader(boolean hasDtdAndXsd) throws SAXException {
  if (xmlReader == null) {
    MessagesErrorHandler errorHandler=new MessagesErrorHandler(getLog());
    xmlReader=XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    xmlReader.setFeature("http://xml.org/sax/features/validation",true);
    xmlReader.setFeature("http://apache.org/xml/features/validation/schema",true);
    xmlReader.setErrorHandler(errorHandler);
    xmlReader.setEntityResolver(new CachedFileEntityResolver());
  }
  ((MessagesErrorHandler)xmlReader.getErrorHandler()).setHasDtdAndXsd(hasDtdAndXsd);
  return xmlReader;
}
 

Example 106

From project SPDX-Tools, under directory /lib-source/grddl-src/com/hp/hpl/jena/grddl/impl/.

Source file: GRDDLReaderBase.java

  15 
vote

private Object setSAXFeatureOrProperty(String propName,Object propValue,XMLReader parser) throws SAXNotRecognizedException, SAXNotSupportedException {
  int b=toBoolean(propValue);
switch (b) {
case 0:
case 1:
    boolean oldb=parser.getFeature(propName);
  parser.setFeature(propName,b == 1);
return new Boolean(oldb);
case -1:
Object old=parser.getProperty(propName);
parser.setProperty(propName,propValue);
return old;
}
throw new BrokenException("impossible");
}
 

Example 107

From project WebproxyPortlet, under directory /src/main/java/edu/wisc/my/webproxy/beans/filtering/.

Source file: NekoHtmlParser.java

  15 
vote

public XMLReader getReader(LexicalHandler myHandler){
  SAXParser defaultParser=new SAXParser();
  try {
    defaultParser.setProperty("http://xml.org/sax/properties/lexical-handler",myHandler);
    defaultParser.setProperty("http://cyberneko.org/html/properties/default-encoding","UTF-8");
    defaultParser.setProperty("http://cyberneko.org/html/properties/names/elems","match");
    defaultParser.setProperty("http://cyberneko.org/html/properties/names/attrs","no-change");
    defaultParser.setFeature("http://cyberneko.org/html/features/report-errors",reportErrors);
    defaultParser.setFeature("http://cyberneko.org/html/features/insert-doctype",insertDoctype);
    defaultParser.setFeature("http://cyberneko.org/html/features/balance-tags",balanceTags);
    defaultParser.setFeature("http://cyberneko.org/html/features/scanner/script/strip-comment-delims",scriptStripComment);
    defaultParser.setFeature("http://cyberneko.org/html/features/scanner/style/strip-comment-delims",stripComments);
    defaultParser.setFeature("http://cyberneko.org/html/features/scanner/script/strip-cdata-delims",true);
    defaultParser.setFeature("http://cyberneko.org/html/features/scanner/notify-builtin-refs",true);
    defaultParser.setFeature("http://apache.org/xml/features/scanner/notify-char-refs",true);
  }
 catch (  SAXNotRecognizedException e) {
    log.debug("SaxParser not recognized:  ",e);
  }
catch (  SAXNotSupportedException e) {
    log.debug("SaxParser not supported:  ",e);
  }
  return defaultParser;
}