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:egat.cli.strategyregret.StrategyRegretCommandHandler.java

protected void processSymmetricGame(MutableSymmetricGame game) throws CommandProcessingException {

    try {/*from ww  w .j  a v a2 s  .c om*/
        Profile profile = null;

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

            Action[] actions = ((Set<Action>) game.getActions()).toArray(new Action[0]);
            Number[] distribution = new Number[actions.length];

            Arrays.fill(distribution, 1.0 / distribution.length);

            Strategy strategy = Games.createStrategy(actions, distribution);
            Arrays.fill(strategies, strategy);

            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);
    }
}

From source file:fr.lemet.application.keolis.Keolis.java

/**
 * @param <ObjetKeolis> type d'objet Keolis.
 * @param url           url.//from   w  w  w  .j a  va 2  s .com
 * @param handler       handler.
 * @return liste d'objets Keolis.
 * @throws fr.lemet.transportscommun.util.ErreurReseau    en cas d'erreur rseau.
 * @throws KeolisException en cas d'erreur lors de l'appel aux API Keolis.
 */
@SuppressWarnings("unchecked")
private <ObjetKeolis> List<ObjetKeolis> appelKeolis(String url, KeolisHandler<ObjetKeolis> handler)
        throws ErreurReseau {
    LOG_YBO.debug("Appel d'une API Keolis sur l'url '" + url + '\'');
    long startTime = System.nanoTime() / 1000;
    HttpClient httpClient = HttpUtils.getHttpClient();
    HttpUriRequest httpPost = new HttpPost(url);
    Answer<?> answer;
    try {
        HttpResponse reponse = httpClient.execute(httpPost);
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        reponse.getEntity().writeTo(ostream);
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        parser.parse(new ByteArrayInputStream(ostream.toByteArray()), handler);
        answer = handler.getAnswer();
    } catch (IOException socketException) {
        throw new ErreurReseau(socketException);
    } catch (SAXException saxException) {
        throw new ErreurReseau(saxException);
    } catch (ParserConfigurationException exception) {
        throw new KeolisException("Erreur lors de l'appel  l'API keolis", exception);
    }
    if (answer == null || answer.getStatus() == null || !"0".equals(answer.getStatus().getCode())) {
        throw new ErreurReseau();
    }
    long elapsedTime = System.nanoTime() / 1000 - startTime;
    LOG_YBO.debug("Rponse de Keolis en " + elapsedTime + "s");
    return (List<ObjetKeolis>) answer.getData();
}

From source file:io.onedecision.engine.decisions.model.dmn.validators.SchemaValidator.java

public void validate(InputStream obj, Errors errors) {
    InputStream is = (InputStream) obj;

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(new LocalResourceResolver());

    try {//from   www . java 2  s.  c  o m
        schemaFactory.newSchema(new StreamSource(getResourceAsStreamWrapper("schema/dmn.xsd")));
    } catch (SAXException e1) {
        errors.reject("Cannot find / read schema", "Exception: " + e1.getMessage());
    }

    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    // parserFactory.setValidating(true);
    parserFactory.setNamespaceAware(true);
    // parserFactory.setSchema(schema);

    SAXParser parser = null;
    try {
        parser = parserFactory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setErrorHandler(this);

        try {
            parser.parse(new InputSource(is), (DefaultHandler) null);
        } catch (Exception e) {
            String msg = "Schema validation failed";
            LOGGER.error(msg, e);
            errors.reject(msg, "Exception: " + e.getMessage());
        }
        if (this.errors.size() > 0) {
            errors.reject("Schema validation failed", this.errors.toString());
        }
    } catch (ParserConfigurationException e1) {
        errors.reject("Cannot create parser", "Exception: " + e1.getMessage());
    } catch (SAXException e1) {
        errors.reject("Parser cannot be created", "Exception: " + e1.getMessage());
    }
}

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

public Collection<Long> getIds(String query, String db, Collection<Long> ids, int chunkSize) throws Exception {
    int retStart = 0;
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    ESearchHandler handler = new ESearchHandler(ids);
    InputStream is = getInputStream("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi", "db", db,
            "term", query, "retstart", retStart, "retmax", chunkSize, "usehistory", "y", "version", "2.0")
                    .call();//  w ww  .  jav a 2 s .  c  o m
    while (true) {
        saxParser.parse(is, handler);
        if ((handler.retStart + handler.retMax) < (handler.count - 1)) {
            retStart += handler.retMax;
            is = getInputStream("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi", "db", db, "term",
                    query, "retstart", retStart, "retmax", "" + chunkSize, "usehistory", "y", "QueryKey",
                    handler.queryKey, "WebEnv", handler.webEnv, "version", "2.0").call();
        } else
            break;
    }
    return ids;
}

From source file:fr.paris.lutece.plugins.dila.modules.solr.utils.parsers.DilaSolrLocalParser.java

/**
 * Initializes and launches the parsing of the local cards (public
 * constructor)//from   w ww .  ja v  a  2  s  . com
 */
public DilaSolrLocalParser() {
    // Gets the local cards
    List<LocalDTO> localCardsList = _dilaLocalService.findAll();

    // Initializes the SolrItem list
    _listSolrItems = new ArrayList<SolrItem>();

    // Initializes the indexing type
    _strType = AppPropertiesService.getProperty(PROPERTY_INDEXING_TYPE);

    // Initializes the site
    _strSite = SolrIndexerService.getWebAppName();

    // Initializes the prod url
    _strProdUrl = SolrIndexerService.getBaseUrl();

    try {
        // Initializes the SAX parser
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();

        // Launches the parsing on each local card
        parseAllLocalCards(localCardsList, parser);
    } catch (ParserConfigurationException e) {
        AppLogService.error(e.getMessage(), e);
    } catch (SAXException e) {
        AppLogService.error(e.getMessage(), e);
    }
}

From source file:com.gc.iotools.fmt.detect.droid.DroidDetectorImpl.java

private XMLReader getXMLReader(final SAXModelBuilder mb) throws Exception {
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);/*from   w w w . ja  va  2s .  c  o m*/
    // factory.setValidating(true);
    final SAXParser saxParser = factory.newSAXParser();
    final XMLReader parser = saxParser.getXMLReader();
    // URL url = DroidDetectorImpl.class
    // .getResource("DROID_SignatureFile.xsd");
    // parser.setProperty(
    // "http://java.sun.com/xml/jaxp/properties/schemaSource", url);
    mb.setupNamespace(SIGNATURE_FILE_NS, true);
    parser.setContentHandler(mb);
    return parser;
}

From source file:jp.gr.java_conf.petit_lycee.subsonico.MethodConstants.java

SubsonicResponse parseResponseXML(InputStream is)
        throws SubsonicException, IOException, SAXException, ParserConfigurationException {

    SubsonicXMLHandler handler = new SubsonicXMLHandler();
    SAXParserFactory factory = SAXParserFactory.newInstance();

    SAXParser parser = factory.newSAXParser();
    parser.parse(is, handler);/*from w w  w  . j  av a 2 s  . co  m*/
    if (handler.isError()) {
        throw handler.getException();
    }
    return handler.getResponse();
}

From source file:edu.scripps.fl.pubchem.promiscuity.PCPromiscuityFactory.java

public Map<Long, CompoundPromiscuityInfo> getCompoundsWithDescriptors(List<Long> ids, String db)
        throws Exception {
    log.info("Number of compounds in eSummary request: " + ids.size());
    log.info("Memory usage before getting compound eSummary document: " + memUsage());

    InputStream is = EUtilsFactory.getInstance().getSummaries(ids, db);
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    CompoundESummaryHandler handler = new CompoundESummaryHandler();
    saxParser.parse(is, handler);/*from  w  w  w. j  a  v a 2s . com*/

    log.info("Memory usage after getting compound eSummary document: " + memUsage());

    return handler.getCompoundIdMap();
}

From source file:importer.handler.post.stages.SAXSplitter.java

/**
 * Split a TEI-XML file into versions of XML
 * @param tei the TEI content containing versions
 * @return an analysis of the variant markup in a file
 * @throws ImportException if something went wrong
 *//*from  ww w  . j a  v a  2 s. c  o  m*/
public JSONArray scan(String tei) throws ImporterException {
    this.layers = new HashMap<String, Integer>();
    this.lineNo = 1;
    this.splits = new HashSet<String>();
    this.attributes = new HashMap<String, String>();
    this.siblings = new HashMap<String, String>();
    this.states = new Stack<Integer>();
    this.states.push(0);
    this.siblingCount = 0;
    this.path = new StringBuilder();
    // hard-wire config for now
    attributes.put("add", "n");
    attributes.put("rdg", "wit");
    attributes.put("lem", "wit");
    siblings.put("add", "del");
    siblings.put("del", "add");
    siblings.put("lem", "rdg");
    siblings.put("rdg", "lem");
    splits.add("add");
    splits.add("del");
    splits.add("sic");
    splits.add("corr");
    splits.add("abbrev");
    splits.add("expan");
    splits.add("rdg");
    splits.add("lem");
    splits.add("app");
    splits.add("mod");
    splits.add("choice");
    splits.add("subst");
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        parser = spf.newSAXParser();
        xmlReader = parser.getXMLReader();
        xmlReader.setContentHandler(this);
        xmlReader.setErrorHandler(new MyErrorHandler(System.err));
        CharArrayReader car = new CharArrayReader(tei.toCharArray());
        xmlReader.parse(new InputSource(car));
        return layersToJson();
    } catch (Exception e) {
        throw new ImporterException(e);
    }
}

From source file:com.ibm.jaql.lang.expr.xml.TypedXmlToJsonFn.java

@Override
public JsonValue eval(Context context) throws Exception {
    if (parser == null) {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        parser = factory.newSAXParser().getXMLReader();
        handler = new TypedXmlToJsonHandler2();
        parser.setContentHandler(handler);
    }/*www.jav a 2 s.  c o  m*/

    JsonString s = (JsonString) exprs[0].eval(context);
    parser.parse(new InputSource(new StringReader(s.toString())));
    return handler.result;
}