private boolean loadParticleXML() {
    InputStream is = null;
    try {
      SAXParserFactory spf = SAXParserFactory.newInstance();
      SAXParser sp = spf.newSAXParser();

      QuickTiGame2dParticleParser handler = new QuickTiGame2dParticleParser(this);

      XMLReader xr = sp.getXMLReader();
      xr.setContentHandler(handler);

      is = QuickTiGame2dUtil.getFileInputStream(image);
      xr.parse(new InputSource(new BufferedInputStream(is)));

      emissionRate = maxParticles / particleLifespan;

      sourcePosition.x = x;
      sourcePosition.y = y;

    } catch (Exception e) {
      if (debug)
        Log.w(Quicktigame2dModule.LOG_TAG, String.format("failed to load particle: %s", image), e);
      return false;
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (IOException e) {
          // nothing to do
        }
      }
    }

    return true;
  }
 private static SVG parse(
     InputStream in, Integer searchColor, Integer replaceColor, boolean whiteMode)
     throws SVGParseException {
   //        Util.debug("Parsing SVG...");
   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));
     //        Util.debug("Parsing complete in " + (System.currentTimeMillis() - start) + "
     // millis.");
     SVG result = new SVG(picture, handler.bounds);
     // Skip bounds if it was an empty pic
     if (!Float.isInfinite(handler.limits.top)) {
       result.setLimits(handler.limits);
     }
     return result;
   } catch (Exception e) {
     throw new SVGParseException(e);
   }
 }
 @Test
 public void test1() throws Exception {
   SAXParser parser = createParser();
   parser.parse(
       Bug4991020.class.getResource("Bug4991020.xml").toExternalForm(),
       new util.DraconianErrorHandler());
 }
 private void processCommentLines(File file) throws SAXException, IOException {
   SAXParser parser = newSaxParser(false);
   XMLReader xmlReader = parser.getXMLReader();
   commentHandler = new CommentHandler();
   xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", commentHandler);
   parser.parse(FileUtils.openInputStream(file), commentHandler);
 }
 private CloudServersException parseCloudServersException(HttpResponse response) {
   CloudServersException cse = new CloudServersException();
   try {
     BasicResponseHandler responseHandler = new BasicResponseHandler();
     String body = responseHandler.handleResponse(response);
     CloudServersFaultXMLParser parser = new CloudServersFaultXMLParser();
     SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
     XMLReader xmlReader = saxParser.getXMLReader();
     xmlReader.setContentHandler(parser);
     xmlReader.parse(new InputSource(new StringReader(body)));
     cse = parser.getException();
   } catch (ClientProtocolException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (IOException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (ParserConfigurationException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (SAXException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (FactoryConfigurationError e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   }
   return cse;
 }
 public List<Customer> readDataFromXML(String filename)
     throws ParserConfigurationException, SAXException, IOException {
   SAXParserFactory factory = SAXParserFactory.newInstance();
   SAXParser parser = factory.newSAXParser();
   parser.parse(new File(filename), this);
   return data;
 }
  public boolean updataFeedFromServer(final int page, final int topicId, final int size) {
    Log.d(
        TAG,
        String.format("::updataFeedFromServer(page=%s,topicID=%s,size%s)", page, topicId, size));
    try {
      List<JokeBean> jokeItems = new ArrayList<JokeBean>();
      JokeClient client = new JokeClient();
      ResponseData responseData = client.getJokes(page, size, topicId);

      if (responseData.getStatus()) {
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        JokeBeanHandler handler = new JokeBeanHandler();
        InputSource is = new InputSource(new StringReader(responseData.toString()));
        parser.parse(is, handler);

        jokeItems.addAll(handler.getJokeItems());

        /* Set topic id */
        for (JokeBean item : jokeItems) {
          item.setTopic(topicId);
        }

        /* Now write the joke to cache */
        return db.addAll(jokeItems);
      }
    } catch (Exception e) {
      Log.e(TAG, "" + e.getMessage());
      e.printStackTrace();
    }
    return false;
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.flash_card_activity);

    // Initialize fields
    initialize();

    try {
      SAXParserFactory spf = SAXParserFactory.newInstance();
      SAXParser sp = spf.newSAXParser();
      XMLReader xr = sp.getXMLReader();
      myParser = new XMLParser();
      xr.setContentHandler(myParser);
      xr.parse(new InputSource(this.getResources().openRawResource(R.raw.words)));
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      words = myParser.getWordsList();
      // db = dbh.getWritableDatabase();
      // myWords = dbh.getMyWordsList();
      displayWord(words.get(index));
    }

    pbProgress.setMax(words.size());
  }
  public void testWithDummyExtSubset() throws Exception {
    final String XML =
        "<!DOCTYPE root PUBLIC '//some//public//id' 'no-such-thing.dtd'>\n" + "<root />";

    SAXParserFactoryImpl spf = new SAXParserFactoryImpl();
    spf.setNamespaceAware(true);
    SAXParser sp = spf.newSAXParser();
    DefaultHandler h = new DefaultHandler();

    /* First: let's verify that we get an exception for
     * unresolved reference...
     */
    try {
      sp.parse(new InputSource(new StringReader(XML)), h);
    } catch (SAXException e) {
      verifyException(e, "No such file or directory");
    }

    // And then with dummy resolver; should work ok now
    sp = spf.newSAXParser();
    sp.getXMLReader().setEntityResolver(new MyResolver("   "));
    h = new DefaultHandler();
    try {
      sp.parse(new InputSource(new StringReader(XML)), h);
    } catch (SAXException e) {
      fail(
          "Should not have failed with entity resolver, got ("
              + e.getClass()
              + "): "
              + e.getMessage());
    }
  }
 /**
  * Deconstructs response into given content handler
  *
  * @param entity returned HttpEntity
  * @return deconstructed response
  * @throws java.io.IOException
  * @see org.apache.http.HttpEntity
  */
 @Override
 protected byte[] getResponseData(HttpEntity entity) throws IOException {
   if (entity != null) {
     InputStream instream = entity.getContent();
     InputStreamReader inputStreamReader = null;
     if (instream != null) {
       try {
         SAXParserFactory sfactory = SAXParserFactory.newInstance();
         SAXParser sparser = sfactory.newSAXParser();
         XMLReader rssReader = sparser.getXMLReader();
         rssReader.setContentHandler(handler);
         inputStreamReader = new InputStreamReader(instream, DEFAULT_CHARSET);
         rssReader.parse(new InputSource(inputStreamReader));
       } catch (SAXException e) {
         Log.e(LOG_TAG, "getResponseData exception", e);
       } catch (ParserConfigurationException e) {
         Log.e(LOG_TAG, "getResponseData exception", e);
       } finally {
         AsyncHttpClient.silentCloseInputStream(instream);
         if (inputStreamReader != null) {
           try {
             inputStreamReader.close();
           } catch (IOException e) {
             /*ignore*/
           }
         }
       }
     }
   }
   return null;
 }
  public void loadIdea() {

    try {

      URL url = new URL(idea_url);

      SAXParserFactory spf = SAXParserFactory.newInstance();
      SAXParser sp = spf.newSAXParser();

      XMLReader xr = sp.getXMLReader();
      IdeaDetailHandler myExampleHandler = new IdeaDetailHandler();
      xr.setContentHandler(myExampleHandler);

      InputSource is = new InputSource(url.openStream());
      is.setEncoding("UTF-8");
      xr.parse(is);

      idea = myExampleHandler.getParsedData();

      Message myMessage = new Message();
      myMessage.obj = "SUCCESS";
      handler.sendMessage(myMessage);

    } catch (Exception e) {
      // Log.e("Ideas4All", "Error", e);
    }
  }
 public VersionInfo getNewestVersionInfo() {
   VersionInfo versionInfo = new VersionInfo();
   HttpClient hc = new DefaultHttpClient();
   HttpGet get = new HttpGet(server_address + "/VersionInfo.xml");
   try {
     HttpResponse response = hc.execute(get);
     if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
       HttpEntity he = response.getEntity();
       try {
         SAXParserFactory factory = SAXParserFactory.newInstance();
         SAXParser parser = factory.newSAXParser();
         parser.parse(he.getContent(), new VersionSaxHandler(versionInfo));
       } catch (Exception e) {
         Log.e(tag, "xml解析错误");
         return null;
       }
       he.consumeContent();
     }
   } catch (ClientProtocolException e) {
     Log.e(tag, "协议错误");
     return null;
   } catch (IOException e) {
     Log.e(tag, "读写错误");
     return null;
   }
   return versionInfo;
 }
Beispiel #13
0
 public void update() throws IOException, SAXException, ParserConfigurationException {
   MibewResponse response = fConnection.request("operator/update.php", "since=" + fSince);
   SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
   UpdateHandler handler = new UpdateHandler();
   sp.parse(new ByteArrayInputStream(response.getResponse()), handler);
   handleResponse(response, handler);
 }
Beispiel #14
0
  /** Responsible for parsing the document */
  public ArrayList<String> parseDocument(URL url) {

    snippets.clear();

    // Adds a factory
    SAXParserFactory factory = SAXParserFactory.newInstance();

    try {

      // adds a new instance of parser
      SAXParser parser = factory.newSAXParser();

      // TODO SHOULD THIS BE MOVED TO MORE PROPER PLACE?
      // Sets user Agent
      System.setProperty("http.agent", "ChaosPoemSearch");

      // Stream xml to parser
      parser.parse(new InputSource(url.openStream()), this);

    } catch (SAXException se) {

    } catch (ParserConfigurationException pce) {

    } catch (ConnectException e) {

    } catch (IOException ie) {

    }

    return snippets;
  }
Beispiel #15
0
  public ArrayList<IProject> getProjects() {
    final ArrayList<IProject> result = new ArrayList<IProject>();
    try {
      IProject featureProject = getFeatureProject();
      IFile featureXMLFile = featureProject.getFile("feature.xml");
      SAXParser parser = SAXParserFactory.newInstance().newSAXParser();

      DefaultHandler handler =
          new DefaultHandler() {
            @Override
            public void startElement(
                String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
              if ("plugin".equals(qName)) {
                String id = attributes.getValue("id");
                IProject eachProject = ResourcesPlugin.getWorkspace().getRoot().getProject(id);
                if (!eachProject.exists()) {
                  throw new BuildException(
                      MessageFormat.format(
                          "아이디가 {0}인 프로젝틀르 찾지 못했습니다. 프로젝트 아이디와 프로젝트 명은 동일한 것으로 간주합니다.", id));
                }
                result.add(eachProject);
              }
            }
          };
      parser.parse(featureXMLFile.getContents(), handler);
    } catch (Exception e) {
      throw new BuildException(e.getMessage(), e);
    }

    return result;
  }
  @NotNull
  private MostlySingularMultiMap<String, AnnotationData> getDataFromFile(
      @NotNull final PsiFile file) {
    Pair<MostlySingularMultiMap<String, AnnotationData>, Long> cached =
        annotationFileToDataAndModStamp.get(file);
    final long fileModificationStamp = file.getModificationStamp();
    if (cached != null && cached.getSecond() == fileModificationStamp) {
      return cached.getFirst();
    }
    DataParsingSaxHandler handler = new DataParsingSaxHandler(file);
    try {
      SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
      saxParser.parse(new InputSource(new StringReader(escapeAttributes(file.getText()))), handler);
    } catch (IOException e) {
      LOG.error(e);
    } catch (ParserConfigurationException e) {
      LOG.error(e);
    } catch (SAXException e) {
      LOG.error(e);
    }

    Pair<MostlySingularMultiMap<String, AnnotationData>, Long> pair =
        Pair.create(handler.getResult(), file.getModificationStamp());
    annotationFileToDataAndModStamp.put(file, pair);

    return pair.first;
  }
Beispiel #17
0
  /**
   * @param filename
   * @param docs
   */
  public void parse(String filename, Collection<WikipediaDocument> docs) {
    // System.out.println("::Parser::parse\nFilename=" + filename+ " Docs_size=" + docs.size());
    if (filename == null || filename.isEmpty()) {
      return;
    }
    try {

      InputStreamReader inReader = new InputStreamReader(new FileInputStream(filename), "UTF-8");
      BufferedReader reader = new BufferedReader(inReader);
      InputSource is = new InputSource(reader);
      is.setEncoding("UTF-8");

      SAXParserFactory spf = SAXParserFactory.newInstance();
      SAXParser saxParser = spf.newSAXParser();
      DefaultHandler handler = new XMLParser(docs);

      saxParser.parse(is, handler);

    } catch (IOException x) {
      System.err.println(x);
    } catch (ParserConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SAXException e) {
      // TODO Auto-generated catch block
      System.out.println("Parsing Terminated");
      e.printStackTrace();
    } finally {
    }
  }
Beispiel #18
0
  @Override
  protected RssItem doInBackground(RssParser... params) {

    RssParser parser = params[0];
    RssItem item = null;

    try {
      SAXParserFactory spf = SAXParserFactory.newInstance();
      SAXParser sp = spf.newSAXParser();
      XMLReader xr = sp.getXMLReader();
      xr.setContentHandler(parser);

      // chamar arquivo xml
      // xr.parse(new InputSource(activity.getAssets().open("image_of_the_day.xml")));

      // chamar link na internet
      URL url = new URL("http://www.nasa.gov/rss/dyn/image_of_the_day.rss");
      xr.parse(new InputSource(url.openConnection().getInputStream()));

      item = parser.getFirstItem();
      if (item != null) {
        /*item.setImagem(
        BitmapFactory.decodeResource(
        		activity.getResources(), R.drawable.image_of_the_day));*/
        item.setImagem(getBitmap(item.getImagemUrl()));
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    return item;
  }
  /**
   * Does the actual parsing of a devices.xml file.
   *
   * @param deviceXml the {@link File} to load/parse. This must be an existing file.
   * @param list the list in which to write the parsed {@link LayoutDevice}.
   */
  private void parseLayoutDevices(File deviceXml, List<LayoutDevice> list) {
    // first we validate the XML
    try {
      Source source = new StreamSource(new FileReader(deviceXml));

      CaptureErrorHandler errorHandler = new CaptureErrorHandler(deviceXml.getAbsolutePath());

      Validator validator = LayoutDevicesXsd.getValidator(errorHandler);
      validator.validate(source);

      if (errorHandler.foundError() == false) {
        // do the actual parsing
        LayoutDeviceHandler handler = new LayoutDeviceHandler();

        SAXParser parser = mParserFactory.newSAXParser();
        parser.parse(new InputSource(new FileInputStream(deviceXml)), handler);

        // get the parsed devices
        list.addAll(handler.getDevices());
      }
    } catch (SAXException e) {
      AdtPlugin.log(e, "Error parsing %1$s", deviceXml.getAbsoluteFile());
    } catch (FileNotFoundException e) {
      // this shouldn't happen as we check above.
    } catch (IOException e) {
      AdtPlugin.log(e, "Error reading %1$s", deviceXml.getAbsoluteFile());
    } catch (ParserConfigurationException e) {
      AdtPlugin.log(e, "Error parsing %1$s", deviceXml.getAbsoluteFile());
    }
  }
Beispiel #20
0
  private RSSFeed getFeed(String urlToRssFeed) {
    try {
      // setup the url
      URL url = new URL(urlToRssFeed);

      // create the factory
      SAXParserFactory factory = SAXParserFactory.newInstance();
      // create a parser
      SAXParser parser = factory.newSAXParser();

      // create the reader (scanner)
      XMLReader xmlreader = parser.getXMLReader();
      // instantiate our handler
      RSSHandler theRssHandler = new RSSHandler();
      // assign our handler
      xmlreader.setContentHandler(theRssHandler);
      // get our data via the url class
      InputSource is = new InputSource(url.openStream());
      // perform the synchronous parse
      xmlreader.parse(is);
      // get the results - should be a fully populated RSSFeed instance,
      // or null on error
      return theRssHandler.getFeed();
    } catch (Exception ee) {
      // if we have a problem, simply return null
      return null;
    }
  }
  private void fetchComments() {
    try {
      final URL newUrl = new URL(book.get().getCommentsUrl());

      // sax stuff
      final SAXParserFactory factory = SAXParserFactory.newInstance();
      final SAXParser parser = factory.newSAXParser();

      final XMLReader reader = parser.getXMLReader();

      // initialize our parser logic
      final CommentsHandler commentsHandler = new CommentsHandler(book.get().getComments());
      reader.setContentHandler(commentsHandler);

      // get the xml feed
      reader.parse(new InputSource(newUrl.openStream()));
    } catch (MalformedURLException e) {
      COMMENTS_ERROR = MALFORMED_URL;
      Log.e(TAG, "MalformedURLException: " + e + "\nIn fetchComments()");
    } catch (ParserConfigurationException pce) {
      COMMENTS_ERROR = PARSER_CONFIG_ERROR;
      Log.e(TAG, "ParserConfigurationException: " + pce + "\nIn fetchComments()");
    } catch (SAXException se) {
      COMMENTS_ERROR = SAX_ERROR;
      Log.e(TAG, "SAXException: " + se + "\nIn fetchComments()");
    } catch (IOException ioe) {
      COMMENTS_ERROR = IO_ERROR;
      Log.e(TAG, "IOException: " + ioe + "\nIn fetchComments()");
    }
  }
  /**
   * 根据 xml 文件初始化配置信息,使用 AnalyzeHandler 进行 xml 解析
   *
   * <p>{@link AnalyzeHandler}
   *
   * @param context 上下文
   * @param xmlId xmlId(必须要在 res/raw 文件夹下)
   */
  void initVirtualLightningConfig(Context context, int xmlId) {
    String name = context.getResources().getResourceName(xmlId);

    if (!name.substring(name.indexOf(":") + 1, name.indexOf("/")).equals("raw")) {
      throw new VLInitException("资源文件后缀名不正确!必须为\".xml\"结尾放在\"res/raw\"的XML文件");
    }

    InputStream source = context.getResources().openRawResource(xmlId);

    try {
      SAXParser parser = SAXParserFactory.newInstance().newSAXParser();

      parser.parse(source, new AnalyzeHandler(this));

    } catch (ParserConfigurationException | SAXException | IOException e) {
      throw new VLInitException("解析 XML 文件发生错误:" + e.getMessage());
    } finally {
      try {
        source.close();
      } catch (IOException ignored) {
      }
    }

    initDatabase(context);
  }
Beispiel #23
0
 /**
  * Uses PackInHandler to update AD.
  *
  * @param fileName xml file to read
  * @return status message
  */
 public String importXML(String fileName, Properties ctx, String trxName) throws Exception {
   log.info("importXML:" + fileName);
   File in = new File(fileName);
   if (!in.exists()) {
     String msg = "File does not exist: " + fileName;
     log.info("importXML:" + msg);
     return msg;
   }
   try {
     log.info("starting");
     System.setProperty(
         "javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl");
     PackInHandler handler = new PackInHandler();
     handler.set_TrxName(trxName);
     handler.setCtx(ctx);
     handler.setProcess(this);
     SAXParserFactory factory = SAXParserFactory.newInstance();
     SAXParser parser = factory.newSAXParser();
     String msg = "Start Parser";
     log.info(msg);
     parser.parse(in, handler);
     msg = "End Parser";
     log.info(msg);
     return "OK.";
   } catch (Exception e) {
     log.log(Level.SEVERE, "importXML:", e);
     throw e;
   }
 }
  public static ParentalControlConcern parse(File file) {

    try {

      log.info("Parsing '" + file.getCanonicalPath() + "'...");
      SAXParserFactory factory = SAXParserFactory.newInstance();
      factory.setNamespaceAware(true);
      factory.setValidating(true);
      SAXParser parser = factory.newSAXParser();
      parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
      ParentalControlConcernHandler handler = new ParentalControlConcernHandler();
      parser.parse(file, handler);
      log.info("Parsed '" + file.getCanonicalPath() + "'");
      return handler.result;

    } catch (SAXParseException ex) {

      log.error(
          "Could not validate the parental control concern XML file!  Validation error follows.");
      log.error(ex.getMessage());
      ex.printStackTrace();
      return null;

    } catch (Exception ex) {

      log.error(ex);
      return null;
    }
  }
 // This method is executed in the background thread on our Survey object
 private String uploadSurveyData(String myXML) {
   // Set up communication with the server
   DefaultHttpClient client = new DefaultHttpClient();
   String result = null;
   //
   HttpPost httpPost;
   httpPost =
       new HttpPost(
           "http://YOUR DOMAIN HERE/survey-webApp/index.php/webUser_Controllers/android_controller/save_survey_xml");
   try {
     // Encode the xml, add header and set it to POST request
     StringEntity entity = new StringEntity(myXML, HTTP.UTF_8);
     // entity.setContentType("text/xml");
     httpPost.setEntity(entity);
     // Execute POST request and get response
     HttpResponse response = client.execute(httpPost);
     HttpEntity responseEntity = response.getEntity();
     // System.out.print(EntityUtils.toString(responseEntity));
     // Set up XML parsing objects
     SAXParserFactory spf = SAXParserFactory.newInstance();
     SAXParser sp = spf.newSAXParser();
     XMLReader xr = sp.getXMLReader();
     // Set up an instance of our class to parse the status response
     HttpResponseHandler myResponseHandler = new HttpResponseHandler();
     xr.setContentHandler(myResponseHandler);
     xr.parse(retrieveInputStream(responseEntity));
     // check myResponseHandler for response
     result = myResponseHandler.getStatus();
   } catch (Exception e) {
     result = "Exception - " + e.getMessage();
   }
   return result;
 }
  /**
   * {@link SAXParserFactoryUtil#setXIncludeAware}のテストです。
   *
   * @throws Exception
   */
  public void testSetXIncludeAware() throws Exception {
    SAXParserFactory spf = SAXParserFactoryUtil.newInstance();
    SAXParserFactoryUtil.setXIncludeAware(spf, true);
    spf.setNamespaceAware(true);
    SAXParser parser = SAXParserFactoryUtil.newSAXParser(spf);

    InputSource is =
        new InputSource(ResourceUtil.getResourceAsStream("org/seasar/framework/util/include.xml"));
    is.setSystemId("include.xml");
    parser.parse(
        is,
        new DefaultHandler() {

          @Override
          public void startElement(
              String uri, String localName, String qName, Attributes attributes)
              throws SAXException {
            if ("bar".equals(qName)) {
              included = true;
            }
          }

          @Override
          public InputSource resolveEntity(String publicId, String systemId)
              throws IOException, SAXException {
            InputSource is =
                new InputSource(
                    ResourceUtil.getResourceAsStream("org/seasar/framework/util/included.xml"));
            is.setSystemId("included.xml");
            return is;
          }
        });
    assertTrue(included);
  }
Beispiel #27
0
  // ---- main ----
  public static void main(final String[] argv) {
    if (argv.length != 1) {
      System.err.println(
          "Usage: java "
              + GpxReader.class.getSimpleName()
              + " <file>"); //$NON-NLS-1$ //$NON-NLS-2$
      System.exit(1);
    }

    final long startMillis = System.currentTimeMillis();

    try {
      final File f = new File(argv[0]);
      System.out.println("File size: " + f.length() + " bytes"); // $NON-NLS-1$ //$NON-NLS-2$

      // Use an instance of ourselves as the SAX event handler
      final DefaultHandler handler = new GpxReader();

      // Parse the input with the default (non-validating) parser
      final SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
      saxParser.parse(f, handler);
    } catch (final Exception t) {
      t.printStackTrace();
      System.exit(2);
    }

    final long millis = System.currentTimeMillis() - startMillis;
    System.out.println("Time consumed: " + millis + " ms"); // $NON-NLS-1$ //$NON-NLS-2$
  }
  /** {@inheritDoc} */
  public ParseResult parse(RSyntaxDocument doc, String style) {

    result.clearNotices();
    Element root = doc.getDefaultRootElement();
    result.setParsedLines(0, root.getElementCount() - 1);

    if (spf == null || doc.getLength() == 0) {
      return result;
    }

    try {
      SAXParser sp = spf.newSAXParser();
      Handler handler = new Handler(doc);
      DocumentReader r = new DocumentReader(doc);
      InputSource input = new InputSource(r);
      sp.parse(input, handler);
      r.close();
    } catch (SAXParseException spe) {
      // A fatal parse error - ignore; a ParserNotice was already created.
    } catch (Exception e) {
      // e.printStackTrace(); // Will print if DTD specified and can't be found
      result.addNotice(
          new DefaultParserNotice(this, "Error parsing XML: " + e.getMessage(), 0, -1, -1));
    }

    return result;
  }
 Parser(String uri) {
   try {
     SAXParserFactory parserFactory = SAXParserFactory.newInstance();
     SAXParser parser = parserFactory.newSAXParser();
     ConfigHandler handler = new ConfigHandler();
     parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", true);
     parser.parse(new File(uri), handler);
   } catch (IOException e) {
     System.out.println("Error reading URI: " + e.getMessage());
   } catch (SAXException e) {
     System.out.println("Error in parsing: " + e.getMessage());
   } catch (ParserConfigurationException e) {
     System.out.println("Error in XML parser configuration: " + e.getMessage());
   }
   // System.out.println("Number of Persons : " + Person.numberOfPersons());
   // nameLengthStatistics();
   // System.out.println("Number of Publications with authors/editors: " +
   //                   Publication.getNumberOfPublications());
   // System.out.println("Maximum number of authors/editors in a publication: " +
   //                           Publication.getMaxNumberOfAuthors());
   // publicationCountStatistics();
   // Person.enterPublications();
   // Person.printCoauthorTable();
   // Person.printNamePartTable();
   // Person.findSimilarNames();
 }
Beispiel #30
0
  private static Service parseServicePayload(String payload) throws ResponseParseException {

    JAXBContext jaxbContext;
    Service service = null;

    try {
      jaxbContext = JAXBContext.newInstance(Service.class);
      Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

      InputStream inputStream =
          new ByteArrayInputStream(payload.getBytes(Charset.forName("UTF-8")));

      SAXParserFactory spf = SAXParserFactory.newInstance();
      spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
      SAXParser sp = spf.newSAXParser();
      XMLReader xmlReader = sp.getXMLReader();
      InputSource inputSource = new InputSource(inputStream);
      SAXSource saxSource = new SAXSource(xmlReader, inputSource);

      service = (Service) jaxbUnmarshaller.unmarshal(saxSource);

    } catch (JAXBException
        | FactoryConfigurationError
        | ParserConfigurationException
        | SAXException e) {
      throw new ResponseParseException(e);
    }

    return service;
  }