Example usage for javax.xml.parsers SAXParserFactory newSAXParser

List of usage examples for javax.xml.parsers SAXParserFactory newSAXParser

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory newSAXParser.

Prototype


public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;

Source Link

Document

Creates a new instance of a SAXParser using the currently configured factory parameters.

Usage

From source file:es.prodevelop.gvsig.mini.tasks.weather.WeatherFunctionality.java

@Override
public boolean execute() {
    URL url;//from ww w .  j  a v a2 s.  c  o m
    try {
        String queryString = "http://ws.geonames.org/findNearbyPlaceName?lat=" + lat + "&lng=" + lon;
        InputStream is = Utils.openConnection(queryString);
        BufferedInputStream bis = new BufferedInputStream(is);

        /* Read bytes to the Buffer until there is nothing more to read(-1). */
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            if (isCanceled()) {
                res = TaskHandler.CANCELED;
                return true;
            }
            baf.append((byte) current);

        }

        place = this.parseGeoNames(baf.toByteArray());

        queryString = "http://www.google.com/ig/api?weather=" + place;
        /* Replace blanks with HTML-Equivalent. */
        url = new URL(queryString.replace(" ", "%20"));

        /* Get a SAXParser from the SAXPArserFactory. */
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        /* Get the XMLReader of the SAXParser we created. */
        XMLReader xr = sp.getXMLReader();

        /*
         * Create a new ContentHandler and apply it to the XML-Reader
         */
        GoogleWeatherHandler gwh = new GoogleWeatherHandler();
        xr.setContentHandler(gwh);

        if (isCanceled()) {
            res = TaskHandler.CANCELED;
            return true;
        }
        /* Parse the xml-data our URL-call returned. */
        xr.parse(new InputSource(url.openStream()));

        if (isCanceled()) {
            res = TaskHandler.CANCELED;
            return true;
        }
        /* Our Handler now provides the parsed weather-data to us. */
        ws = gwh.getWeatherSet();

        ws.place = place;
        res = TaskHandler.FINISHED;
        // map.showWeather(ws);
    } catch (IOException e) {
        if (e instanceof UnknownHostException) {
            res = TaskHandler.NO_RESPONSE;
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "", e);
        res = TaskHandler.ERROR;
    } finally {
        //         super.stop();
        return true;
    }
}

From source file:Validate.java

void parse(String dir, String filename)
        throws FileNotFoundException, IOException, ParserConfigurationException, SAXException {
    try {/*from   w w w  .  j a  v  a2  s .  co m*/
        File f = new File(dir, filename);
        StringBuffer errorBuff = new StringBuffer();
        InputSource input = new InputSource(new FileInputStream(f));
        // Set systemID so parser can find the dtd with a relative URL in the source document.
        input.setSystemId(f.toString());
        SAXParserFactory spfact = SAXParserFactory.newInstance();

        spfact.setValidating(true);
        spfact.setNamespaceAware(true);

        SAXParser parser = spfact.newSAXParser();
        XMLReader reader = parser.getXMLReader();

        //Instantiate inner-class error and lexical handler.
        Handler handler = new Handler(filename, errorBuff);
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
        parser.parse(input, handler);

        if (handler.containsDTD && !handler.errorOrWarning) // valid
        {
            buff.append("VALID " + filename + "\n");
            numValidFiles++;
        } else if (handler.containsDTD) // not valid
        {
            buff.append("NOT VALID " + filename + "\n");
            buff.append(errorBuff.toString());
            numInvalidFiles++;
        } else // no DOCTYPE to use for validation
        {
            buff.append("NO DOCTYPE DECLARATION " + filename + "\n");
            numFilesMissingDoctype++;
        }
    } catch (Exception e) // Serious problem!
    {
        buff.append("NOT WELL-FORMED " + filename + ". " + e.getMessage() + "\n");
        numMalformedFiles++;
    } finally {
        numXMLFiles++;
    }
}

From source file:my.mavenproject10.FileuploadController.java

@RequestMapping(method = RequestMethod.POST)
ModelAndView upload(HttpServletRequest request, HttpServletResponse response) {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    String fileName = "";
    int size = 0;
    ArrayList<String> result = new ArrayList<String>();
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {/*w  ww  .  j  a v  a 2  s .  co  m*/
            List items = upload.parseRequest(request);
            Iterator iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
                fileName = item.getName();
                System.out.println("file name " + item.getName());
                JAXBContext jc = JAXBContext.newInstance(CustomersType.class);
                SAXParserFactory spf = SAXParserFactory.newInstance();
                XMLReader xmlReader = spf.newSAXParser().getXMLReader();
                InputSource inputSource = new InputSource(
                        new InputStreamReader(item.getInputStream(), "UTF-8"));
                SAXSource source = new SAXSource(xmlReader, inputSource);
                Unmarshaller unmarshaller = jc.createUnmarshaller();
                CustomersType data2 = (CustomersType) unmarshaller.unmarshal(source);
                //System.out.println("size " + data2.getCustomer().size());
                size = data2.getCustomer().size();
                for (CustomerType customer : data2.getCustomer()) {
                    System.out.println(customer.toString());
                }
                //  
                double summ = 0.0;
                HashMap<Integer, Float> ordersMap = new HashMap<Integer, Float>();
                for (CustomerType customer : data2.getCustomer()) {
                    for (OrderType orderType : customer.getOrders().getOrder()) {
                        Float summPerOrder = 0.0f;
                        //System.out.println(orderType);
                        for (PositionType positionType : orderType.getPositions().getPosition()) {
                            //System.out.println(positionType);
                            summPerOrder += positionType.getCount() * positionType.getPrice();
                            summ += positionType.getCount() * positionType.getPrice();
                        }
                        ordersMap.put(orderType.getId(), summPerOrder);
                    }
                }
                summ = new BigDecimal(summ).setScale(2, RoundingMode.UP).doubleValue();
                System.out.println("   " + summ);
                result.add("   " + summ);

                //    
                HashMap<Integer, Float> customersMap = new HashMap<Integer, Float>();
                for (CustomerType customer : data2.getCustomer()) {
                    Float summPerCust = 0.0f;
                    customersMap.put(customer.getId(), summPerCust);
                    for (OrderType orderType : customer.getOrders().getOrder()) {
                        for (PositionType positionType : orderType.getPositions().getPosition()) {
                            summPerCust += positionType.getCount() * positionType.getPrice();
                        }
                    }
                    //System.out.println(customer.getId() + " orders " + summPerCust);
                    customersMap.put(customer.getId(), summPerCust);
                }
                TreeMap sortedMap = sortByValue(customersMap);
                System.out.println(" " + sortedMap.keySet().toArray()[0]
                        + "    : " + sortedMap.get(sortedMap.firstKey()));
                result.add(" " + sortedMap.keySet().toArray()[0] + "    : "
                        + sortedMap.get(sortedMap.firstKey()));

                //  
                TreeMap sortedMapOrders = sortByValue(ordersMap);
                System.out.println("   " + sortedMapOrders.keySet().toArray()[0]
                        + " : " + sortedMapOrders.get(sortedMapOrders.firstKey()));
                result.add("   " + sortedMapOrders.keySet().toArray()[0] + " : "
                        + sortedMapOrders.get(sortedMapOrders.firstKey()));

                //  
                System.out.println("   "
                        + sortedMapOrders.keySet().toArray()[sortedMapOrders.keySet().toArray().length - 1]
                        + " : " + sortedMapOrders.get(sortedMapOrders.lastKey()));
                result.add("   "
                        + sortedMapOrders.keySet().toArray()[sortedMapOrders.keySet().toArray().length - 1]
                        + " : " + sortedMapOrders.get(sortedMapOrders.lastKey()));

                // 
                System.out.println("  " + sortedMapOrders.size());
                result.add("  " + sortedMapOrders.size());

                //  
                ArrayList<Float> floats = new ArrayList<Float>(sortedMapOrders.values());
                Float summAvg = 0.0f;
                Float avg = 0.0f;
                for (Float f : floats) {
                    summAvg += f;
                }
                avg = new BigDecimal(summAvg / floats.size()).setScale(2, RoundingMode.UP).floatValue();
                System.out.println("   " + avg);
                result.add("   " + avg);

            }
        } catch (FileUploadException e) {
            System.out.println("FileUploadException:- " + e.getMessage());
        } catch (JAXBException ex) {
            //Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    ModelAndView modelAndView = new ModelAndView("fileuploadsuccess");
    modelAndView.addObject("files", result);
    modelAndView.addObject("name", fileName);
    modelAndView.addObject("size", size);
    return modelAndView;

}

From source file:cauchy.android.tracker.PicasaWSUtils.java

public Map<String, String> getAlbumsIdsByAlbumTitles() {
    String url_string = "http://picasaweb.google.com/data/feed/api/user/" + userID;
    try {/*from w w  w. j  a v  a 2s .c om*/
        URL url = new URL(url_string);
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        xr.setContentHandler(this);
        InputStream openStream = url.openStream();
        xr.parse(new InputSource(openStream));
        openStream.close();
        return albumsIdsByAlbumTitles;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:Main.java

public void process() {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);//  w  w  w.  j ava2  s . c o m
    spf.setValidating(true);
    System.out.println("Parser will " + (spf.isNamespaceAware() ? "" : "not ") + "be namespace aware");
    System.out.println("Parser will " + (spf.isValidating() ? "" : "not ") + "validate XML");
    try {
        parser = spf.newSAXParser();
        System.out.println("Parser object is: " + parser);
    } catch (SAXException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    } catch (ParserConfigurationException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
    try {
        parser.parse(new InputSource(new StringReader(getXMLData())), this);
    } catch (IOException e) {
        e.printStackTrace(System.err);
    } catch (SAXException e) {
        e.printStackTrace(System.err);
    }
}

From source file:TrySAX.java

private void process(File file) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);/*from  www.ja  va2  s.c  o  m*/
    spf.setValidating(true);
    System.out.println("Parser will " + (spf.isNamespaceAware() ? "" : "not ") + "be namespace aware");
    System.out.println("Parser will " + (spf.isValidating() ? "" : "not ") + "validate XML");
    try {
        parser = spf.newSAXParser();
        System.out.println("Parser object is: " + parser);
    } catch (SAXException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    } catch (ParserConfigurationException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
    System.out.println("\nStarting parsing of " + file + "\n");
    try {
        parser.parse(file, this);
    } catch (IOException e) {
        e.printStackTrace(System.err);
    } catch (SAXException e) {
        e.printStackTrace(System.err);
    }
}

From source file:com.zazuko.wikidata.municipalities.SparqlClient.java

List<Map<String, RDFTerm>> queryResultSet(final String query) throws IOException, URISyntaxException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    URIBuilder builder = new URIBuilder(endpoint);
    builder.addParameter("query", query);
    HttpGet httpGet = new HttpGet(builder.build());
    /*List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("query", query));
    httpGet.setEntity(new UrlEncodedFormEntity(nvps));*/
    CloseableHttpResponse response2 = httpclient.execute(httpGet);

    try {//from w w  w  . j  ava 2  s .com
        HttpEntity entity2 = response2.getEntity();
        InputStream in = entity2.getContent();
        if (debug) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            for (int ch = in.read(); ch != -1; ch = in.read()) {
                System.out.print((char) ch);
                baos.write(ch);
            }
            in = new ByteArrayInputStream(baos.toByteArray());
        }
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        final SparqlsResultsHandler sparqlsResultsHandler = new SparqlsResultsHandler();
        xmlReader.setContentHandler(sparqlsResultsHandler);
        xmlReader.parse(new InputSource(in));
        /*
         for (int ch = in.read(); ch != -1; ch = in.read()) {
         System.out.print((char)ch);
         }
         */
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
        return sparqlsResultsHandler.getResults();
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException ex) {
        throw new RuntimeException(ex);
    } finally {
        response2.close();
    }

}

From source file:edu.scripps.fl.pubchem.web.entrez.ELinkWebSession.java

@SuppressWarnings("unchecked")
protected Collection<ELinkResult> getELinkResultsSAX(final Collection<ELinkResult> relations) throws Exception {
    log.info("Memory in use before inputstream: " + memUsage());
    InputStream is = EUtilsWebSession.getInstance()
            .getInputStream("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi", getParams()).call();
    log.info("Memory in use after inputstream: " + memUsage());
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    DefaultHandler handler = new DefaultHandler() {
        private ELinkResult result;
        private List<Long> idList;
        private StringBuffer buf;
        private int depth;
        private String linkName;
        private String dbTo;

        public void characters(char ch[], int start, int length) throws SAXException {
            buf.append(ch, start, length);
        }//from   w ww .  ja v  a  2 s. co  m

        public void endElement(String uri, String localName, String qName) throws SAXException {
            if (qName.equalsIgnoreCase("LinkSet"))
                relations.add(result);
            else if (qName.equalsIgnoreCase("LinkSetDb")) {
                if (idList.size() > 0)
                    result.setIds(dbTo, linkName, idList);
            } else if (qName.equalsIgnoreCase("LinkName"))
                linkName = buf.toString();
            else if (qName.equalsIgnoreCase("dbTo"))
                dbTo = buf.toString();
            else if (qName.equalsIgnoreCase("DbFrom"))
                result.setDbFrom(buf.toString());
            else if (qName.equalsIgnoreCase("Id")) {
                Long id = Long.parseLong(buf.toString());
                if (depth == 4)
                    result.setId(id);
                else if (depth == 5)
                    idList.add(id);
            }
            depth--;
        }

        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            depth++;
            buf = new StringBuffer();
            if (qName.equalsIgnoreCase("LinkSet"))
                result = new ELinkResult();
            else if (qName.equalsIgnoreCase("LinkSetDb"))
                idList = new ArrayList();
        }
    };
    log.info("Memory in use before parsing: " + memUsage());
    log.info("Parsing elink results using SAX.");
    try {
        saxParser.parse(is, handler);
    } catch (SAXParseException ex) {
        throw new Exception("Error parsing ELink output: " + ex.getMessage());
    }
    log.info("Finished parsing elink results.");
    log.info("Memory in use after parsing: " + memUsage());
    return relations;
}

From source file:net.sf.jabref.importer.fetcher.OAI2Fetcher.java

/**
 *
 *
 * @param oai2Host/*from ww w  .  ja  v a2s.  c o m*/
 *            the host to query without leading http:// and without trailing /
 * @param oai2Script
 *            the relative location of the oai2 interface without leading
 *            and trailing /
 * @param oai2Metadataprefix
 *            the urlencoded metadataprefix
 * @param oai2Prefixidentifier
 *            the urlencoded prefix identifier
 * @param waitTimeMs
 *            Time to wait in milliseconds between query-requests.
 */
public OAI2Fetcher(String oai2Host, String oai2Script, String oai2Metadataprefix, String oai2Prefixidentifier,
        String oai2ArchiveName, long waitTimeMs) {
    this.oai2Host = oai2Host;
    this.oai2Script = oai2Script;
    this.oai2MetaDataPrefix = oai2Metadataprefix;
    this.oai2PrefixIdentifier = oai2Prefixidentifier;
    this.oai2ArchiveName = oai2ArchiveName;
    this.waitTime = waitTimeMs;
    try {
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        saxParser = parserFactory.newSAXParser();
    } catch (ParserConfigurationException | SAXException e) {
        LOGGER.error("Error creating SAXParser for OAI2Fetcher", e);
    }
}

From source file:egat.cli.strategyregret.StrategyRegretCommandHandler.java

protected void processStrategicGame(MutableStrategicGame game) throws CommandProcessingException {
    try {//from   w  w  w .jav a  2s . c o  m
        Profile profile = null;

        if (uniform) {
            Player[] players = game.players().toArray(new Player[0]);
            Strategy[] strategies = new Strategy[players.length];

            for (int i = 0; i < players.length; i++) {
                Action[] actions = ((Set<Action>) game.getActions(players[i])).toArray(new Action[0]);
                Number[] distribution = new Number[actions.length];
                Arrays.fill(distribution, 1.0 / distribution.length);
                strategies[i] = Games.createStrategy(actions, distribution);
            }

            profile = Games.createProfile(players, strategies);

        } else {
            InputStream inputStream = null;

            inputStream = new FileInputStream(profilePath);

            SAXParserFactory factory = SAXParserFactory.newInstance();

            SAXParser parser = factory.newSAXParser();

            ProfileHandler handler = new ProfileHandler();

            parser.parse(inputStream, handler);

            profile = handler.getProfile();
        }

        findRegret(profile, game);
    } catch (NonexistentPayoffException e) {
        System.err.println(String.format("Could not calculate regret. %s", e.getMessage()));
    } catch (FileNotFoundException e) {
        throw new CommandProcessingException(e);
    } catch (ParserConfigurationException e) {
        throw new CommandProcessingException(e);
    } catch (SAXException e) {
        throw new CommandProcessingException(e);
    } catch (IOException e) {
        throw new CommandProcessingException(e);
    }
}