Example usage for javax.xml.parsers SAXParserFactory newInstance

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

Introduction

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

Prototype


public static SAXParserFactory newInstance() 

Source Link

Document

Obtain a new instance of a SAXParserFactory .

Usage

From source file:net.sf.jasperreports.engine.xml.BaseSaxParserFactory.java

protected SAXParserFactory createSAXParserFactory() throws ParserConfigurationException, SAXException {
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();

    if (log.isDebugEnabled()) {
        log.debug("Instantiated SAX parser factory of type " + parserFactory.getClass().getName());
    }// w  w  w.  ja v a  2s  . c  o  m

    parserFactory.setNamespaceAware(true);

    boolean validating = isValidating();
    parserFactory.setValidating(validating);
    parserFactory.setFeature("http://xml.org/sax/features/validation", validating);
    return parserFactory;
}

From source file:com.determinato.feeddroid.parser.RssParser.java

/**
 * Persists RSS item to the database.//from  ww  w  .  j av a 2 s.  c o  m
 * @param id item ID
 * @param folderId ID of containing folder
 * @param rssurl URL of RSS feed
 * @return long containing ID of inserted item
 * @throws Exception
 */
public long syncDb(long id, long folderId, String rssurl) throws Exception {
    mId = id;
    mFolderId = folderId;
    mRssUrl = rssurl;

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    XMLReader reader = parser.getXMLReader();

    reader.setContentHandler(this);
    reader.setErrorHandler(this);

    URL url = new URL(mRssUrl);

    URLConnection c = url.openConnection();
    // TODO: Is this a known user agent, or do I need to come up with my own?
    c.setRequestProperty("User-Agent", "Android/m3-rc37a");

    try {
        BufferedReader bufReader = new BufferedReader(new InputStreamReader(c.getInputStream()), 65535);
        reader.parse(new InputSource(bufReader));
    } catch (NullPointerException e) {
        Log.e(TAG, Log.getStackTraceString(e));
        Log.e(TAG, "Failed to load URL" + url.toString());
    }

    return mId;
}

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 .  java 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.esri.gpt.server.csw.client.CswCatalog.java

/**
 * Execute GetCapabilities using SAX objects. Send GetCapabilities request,
 * receive the response from a service, and parse the response to get URLs for
 * "GetRecords" and "GetRecordsById".//from   w  ww.  j  a  va2s .c  o m
 * 
 * @return the csw catalog capabilities
 * @throws SAXException the sAX exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ParserConfigurationException the parser configuration exception
 * @return Csw Capabilities object
 */
private CswCatalogCapabilities executeGetCapabilitiesWithSAX()
        throws SAXException, IOException, ParserConfigurationException {
    CswCatalogCapabilities capabilities = new CswCatalogCapabilities();

    CswClient client = new CswClient();
    client.setConnectTimeout(this.getConnectionTimeoutMs());
    client.setReadTimeout(this.getResponseTimeoutMs());
    client.setBatchHttpClient(getBatchHttpClient());
    // Execute submission and parsing into response element
    InputStream responseStream = client.submitHttpRequest("GET", url, "");

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    CapabilitiesParse cParse = new CapabilitiesParse(capabilities);
    factory.newSAXParser().parse(new InputSource(responseStream), cParse);

    this.capabilities = capabilities;
    Utils.close(responseStream);
    return capabilities;
}

From source file:net.sf.ehcache.config.Configurator.java

/**
 * Configures a bean from an XML input stream
 *///from   w ww .ja v  a 2 s  . co m
public void configure(final Object bean, final InputStream inputStream) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Configuring ehcache from InputStream");
    }
    final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    final BeanHandler handler = new BeanHandler(bean);
    parser.parse(inputStream, handler);
}

From source file:org.syncope.core.init.ContentLoader.java

@Transactional
public void load() {
    // 0. DB connection, to be used below
    Connection conn = DataSourceUtils.getConnection(dataSource);

    // 1. Check wether we are allowed to load default content into the DB
    Statement statement = null;//from   w  ww.  j av  a2s .  com
    ResultSet resultSet = null;
    boolean existingData = false;
    try {
        statement = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

        resultSet = statement.executeQuery("SELECT * FROM " + SyncopeConf.class.getSimpleName());
        resultSet.last();

        existingData = resultSet.getRow() > 0;
    } catch (SQLException e) {
        LOG.error("Could not access to table " + SyncopeConf.class.getSimpleName(), e);

        // Setting this to true make nothing to be done below
        existingData = true;
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            LOG.error("While closing SQL result set", e);
        }
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            LOG.error("While closing SQL statement", e);
        }
    }

    if (existingData) {
        LOG.info("Data found in the database, leaving untouched");
        return;
    }

    LOG.info("Empty database found, loading default content");

    // 2. Create views
    LOG.debug("Creating views");
    try {
        InputStream viewsStream = getClass().getResourceAsStream("/views.xml");
        Properties views = new Properties();
        views.loadFromXML(viewsStream);

        for (String idx : views.stringPropertyNames()) {
            LOG.debug("Creating view {}", views.get(idx).toString());

            try {
                statement = conn.createStatement();
                statement.executeUpdate(views.get(idx).toString().replaceAll("\\n", " "));
                statement.close();
            } catch (SQLException e) {
                LOG.error("Could not create view ", e);
            }
        }

        LOG.debug("Views created, go for indexes");
    } catch (Throwable t) {
        LOG.error("While creating views", t);
    }

    // 3. Create indexes
    LOG.debug("Creating indexes");
    try {
        InputStream indexesStream = getClass().getResourceAsStream("/indexes.xml");
        Properties indexes = new Properties();
        indexes.loadFromXML(indexesStream);

        for (String idx : indexes.stringPropertyNames()) {
            LOG.debug("Creating index {}", indexes.get(idx).toString());

            try {
                statement = conn.createStatement();
                statement.executeUpdate(indexes.get(idx).toString());
                statement.close();
            } catch (SQLException e) {
                LOG.error("Could not create index ", e);
            }
        }

        LOG.debug("Indexes created, go for default content");
    } catch (Throwable t) {
        LOG.error("While creating indexes", t);
    } finally {
        DataSourceUtils.releaseConnection(conn, dataSource);
    }

    try {
        conn.close();
    } catch (SQLException e) {
        LOG.error("While closing SQL connection", e);
    }

    // 4. Load default content
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
        SAXParser parser = factory.newSAXParser();
        parser.parse(getClass().getResourceAsStream("/content.xml"), importExport);
        LOG.debug("Default content successfully loaded");
    } catch (Throwable t) {
        LOG.error("While loading default content", t);
    }
}

From source file:com.npower.cp.xmlinventory.OTAInventoryImpl.java

/**
 * Create Digester to parsing Template index file.
 * @return//from   w  w w.j av a2 s .  com
 * @throws SAXException 
 * @throws ParserConfigurationException 
 */
private Digester createDigester() throws ParserConfigurationException, SAXException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    //spf.setNamespaceAware(true);
    //spf.setXIncludeAware(true);

    // Initialize the digester
    Digester currentDigester = new Digester(spf.newSAXParser());
    currentDigester.setValidating(false);

    // Parsing template
    currentDigester.addSetProperties("ota-templates/import", "filename", "include");

    // Parsing manufacturer
    currentDigester.addObjectCreate("ota-templates/manufacturer", ManufacturerItem.class);
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/id", "ID");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/name", "name");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/description", "description");
    currentDigester.addSetNext("ota-templates/manufacturer", "add");

    // Parsing model
    currentDigester.addObjectCreate("ota-templates/manufacturer/model", ModelItem.class);
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/id", "ID");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/name", "name");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/description", "description");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/compatible", "compatible");
    currentDigester.addSetNext("ota-templates/manufacturer/model", "addModel");

    // Parsing template
    currentDigester.addObjectCreate("ota-templates/manufacturer/model/template", OTATemplateItem.class);
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/template/id", "externalID");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/template/name", "name");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/template/description",
            "description");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/template/content", "contentString");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/template/category",
            "categoryByName");
    currentDigester.addSetProperties("ota-templates/manufacturer/model/template/content", "filename",
            "filename");
    currentDigester.addSetNext("ota-templates/manufacturer/model/template", "addTemplate");

    return currentDigester;
}

From source file:egat.cli.AbstractGameCommandHandler.java

protected void processCommand(InputStream inputStream, boolean symmetric) throws CommandProcessingException {

    try {/*from  w ww  .ja v  a  2s. c  o m*/
        if (symmetric) {
            SAXParserFactory factory = SAXParserFactory.newInstance();

            SAXParser parser = factory.newSAXParser();

            SymmetricGameHandler handler = new SymmetricGameHandler();

            parser.parse(inputStream, handler);

            MutableSymmetricGame game = handler.getGame();

            processSymmetricGame(game);
        } else {

            SAXParserFactory factory = SAXParserFactory.newInstance();

            SAXParser parser = factory.newSAXParser();

            StrategicGameHandler handler = new StrategicGameHandler();

            parser.parse(inputStream, handler);

            MutableStrategicGame game = handler.getGame();

            processStrategicGame(game);

        }
    } catch (ParserConfigurationException e) {
        throw new CommandProcessingException(e);
    } catch (SAXException e) {
        throw new CommandProcessingException(e);
    } catch (IOException e) {
        throw new CommandProcessingException(e);
    }

}

From source file:com.connectsdk.device.netcast.NetcastHttpServer.java

public void start() {
    if (running)/*  ww  w . jav  a  2 s  .c om*/
        return;

    running = true;

    try {
        welcomeSocket = new ServerSocket(this.port);
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    while (running) {
        if (welcomeSocket == null || welcomeSocket.isClosed()) {
            stop();
            break;
        }

        Socket connectionSocket = null;
        BufferedReader inFromClient = null;
        DataOutputStream outToClient = null;

        try {
            connectionSocket = welcomeSocket.accept();
        } catch (IOException ex) {
            ex.printStackTrace();
            // this socket may have been closed, so we'll stop
            stop();
            return;
        }

        String str = null;
        int c;
        StringBuilder sb = new StringBuilder();

        try {
            inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

            while ((str = inFromClient.readLine()) != null) {
                if (str.equals("")) {
                    break;
                }
            }

            while ((c = inFromClient.read()) != -1) {
                sb.append((char) c);
                String temp = sb.toString();

                if (temp.endsWith("</envelope>"))
                    break;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        String body = sb.toString();

        Log.d("Connect SDK", "got message body: " + body);

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = dateFormat.format(calendar.getTime());
        String androidOSVersion = android.os.Build.VERSION.RELEASE;

        PrintWriter out = null;

        try {
            outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            out = new PrintWriter(outToClient);
            out.println("HTTP/1.1 200 OK");
            out.println("Server: Android/" + androidOSVersion + " UDAP/2.0 ConnectSDK/1.2.1");
            out.println("Cache-Control: no-store, no-cache, must-revalidate");
            out.println("Date: " + date);
            out.println("Connection: Close");
            out.println("Content-Length: 0");
            out.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                inFromClient.close();
                out.close();
                outToClient.close();
                connectionSocket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        InputStream stream = null;

        try {
            stream = new ByteArrayInputStream(body.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }

        NetcastPOSTRequestParser handler = new NetcastPOSTRequestParser();

        SAXParser saxParser;
        try {
            saxParser = saxParserFactory.newSAXParser();
            saxParser.parse(stream, handler);
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }

        if (body.contains("ChannelChanged")) {
            ChannelInfo channel = NetcastChannelParser.parseRawChannelData(handler.getJSONObject());

            Log.d("Connect SDK", "Channel Changed: " + channel.getNumber());

            for (URLServiceSubscription<?> sub : subscriptions) {
                if (sub.getTarget().equalsIgnoreCase("ChannelChanged")) {
                    for (int i = 0; i < sub.getListeners().size(); i++) {
                        @SuppressWarnings("unchecked")
                        ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners()
                                .get(i);
                        Util.postSuccess(listener, channel);
                    }
                }
            }
        } else if (body.contains("KeyboardVisible")) {
            boolean focused = false;

            TextInputStatusInfo keyboard = new TextInputStatusInfo();
            keyboard.setRawData(handler.getJSONObject());

            try {
                JSONObject currentWidget = (JSONObject) handler.getJSONObject().get("currentWidget");
                focused = (Boolean) currentWidget.get("focus");
                keyboard.setFocused(focused);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Log.d("Connect SDK", "KeyboardFocused?: " + focused);

            for (URLServiceSubscription<?> sub : subscriptions) {
                if (sub.getTarget().equalsIgnoreCase("KeyboardVisible")) {
                    for (int i = 0; i < sub.getListeners().size(); i++) {
                        @SuppressWarnings("unchecked")
                        ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners()
                                .get(i);
                        Util.postSuccess(listener, keyboard);
                    }
                }
            }
        } else if (body.contains("TextEdited")) {
            System.out.println("TextEdited");

            String newValue = "";

            try {
                newValue = handler.getJSONObject().getString("value");
            } catch (JSONException ex) {
                ex.printStackTrace();
            }

            Util.postSuccess(textChangedListener, newValue);
        } else if (body.contains("3DMode")) {
            try {
                String enabled = (String) handler.getJSONObject().get("value");
                boolean bEnabled;

                if (enabled.equalsIgnoreCase("true"))
                    bEnabled = true;
                else
                    bEnabled = false;

                for (URLServiceSubscription<?> sub : subscriptions) {
                    if (sub.getTarget().equalsIgnoreCase("3DMode")) {
                        for (int i = 0; i < sub.getListeners().size(); i++) {
                            @SuppressWarnings("unchecked")
                            ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners()
                                    .get(i);
                            Util.postSuccess(listener, bEnabled);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}