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:ee.ria.xroad.common.message.SaxSoapParserImpl.java

@SneakyThrows
private static SAXParserFactory createSaxParserFactory() {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);/*from  w w w .j  a  va  2 s  .  co m*/
    factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    // disable external entity parsing to avoid DOS attacks
    factory.setValidating(false);
    factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
    factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    return factory;
}

From source file:com.cyberway.issue.crawler.settings.XMLSettingsHandler.java

/** Read the CrawlerSettings object from a specific file.
 *
 * @param settings the settings object to be updated with data from the
 *                 persistent storage./*from w w  w  . j  av a2 s .  c  om*/
 * @param f the file to read from.
 * @return the updated settings object or null if there was no data for this
 *         in the persistent storage.
 */
protected final CrawlerSettings readSettingsObject(CrawlerSettings settings, File f) {
    CrawlerSettings result = null;
    try {
        InputStream is = null;
        if (!f.exists()) {
            // Perhaps the file we're looking for is on the CLASSPATH.
            // DON'T look on the CLASSPATH for 'settings.xml' files.  The
            // look for 'settings.xml' files happens frequently. Not looking
            // on classpath for 'settings.xml' is an optimization based on
            // ASSUMPTION that there will never be a 'settings.xml' saved
            // on classpath.
            if (!f.getName().startsWith(settingsFilename)) {
                is = XMLSettingsHandler.class.getResourceAsStream(f.getPath());
            }
        } else {
            is = new FileInputStream(f);
        }
        if (is != null) {
            XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
            InputStream file = new BufferedInputStream(is);
            parser.setContentHandler(new CrawlSettingsSAXHandler(settings));
            InputSource source = new InputSource(file);
            source.setSystemId(f.toURL().toExternalForm());
            parser.parse(source);
            result = settings;
        }
    } catch (SAXParseException e) {
        logger.warning(e.getMessage() + " in '" + e.getSystemId() + "', line: " + e.getLineNumber()
                + ", column: " + e.getColumnNumber());
    } catch (SAXException e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (ParserConfigurationException e) {
        logger.warning(e.getMessage() + ": " + e.getCause().getMessage());
    } catch (FactoryConfigurationError e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (IOException e) {
        logger.warning("Could not access file '" + f.getAbsolutePath() + "': " + e.getMessage());
    }
    return result;
}

From source file:cm.aptoide.pt.RemoteInTab.java

private void xmlPass(String srv, boolean type) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {//w w  w.  ja v a  2s .c  om
        File xml_file = null;
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        if (type) {
            RssHandler handler = new RssHandler(this, srv);
            xr.setContentHandler(handler);
            xml_file = new File(XML_PATH);
        } else {
            ExtrasRssHandler handler = new ExtrasRssHandler(this, srv);
            xr.setContentHandler(handler);
            xml_file = new File(EXTRAS_XML_PATH);
        }

        InputStreamReader isr = new FileReader(xml_file);
        InputSource is = new InputSource(isr);
        xr.parse(is);
        xml_file.delete();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}

From source file:se.lu.nateko.edca.svc.GetCapabilities.java

/**
 * Parses an XML response from a GetCapabilities request and stores available Layers
 * and options in the local SQLite database.
 * @param xmlResponse A reader wrapped around an InputStream containing the XML response from a GetCapabilities request.
 *//* www  . j a  v  a  2  s  .  c om*/
protected boolean parseXMLResponse(BufferedReader xmlResponse) {
    Log.d(TAG, "parseXMLResponse(Reader) called.");

    try {
        SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Make a SAXParser factory.
        spfactory.setValidating(false); // Tell the factory not to make validating parsers.
        SAXParser saxParser = spfactory.newSAXParser(); // Use the factory to make a SAXParser.
        XMLReader xmlReader = saxParser.getXMLReader(); // Get an XML reader from the parser, which will send event calls to its specified event handler.
        XMLEventHandler xmlEventHandler = new XMLEventHandler();
        xmlReader.setContentHandler(xmlEventHandler); // Set which event handler to use.
        xmlReader.setErrorHandler(xmlEventHandler); // Also set where to send error calls.
        InputSource source = new InputSource(xmlResponse); // Make an InputSource from the XML input to give to the reader.
        xmlReader.parse(source); // Start parsing the XML.
    } catch (Exception e) {
        Log.e(TAG, "XML parsing error: " + e.toString() + " - " + e.getMessage());
        return false;
    }
    return true;
}

From source file:cm.aptoide.pt.MainActivity.java

private void loadRecommended() {

    if (Login.isLoggedIn(mContext)) {
        ((TextView) featuredView.findViewById(R.id.recommended_text)).setVisibility(View.GONE);
    } else {/*from   w w  w  .j  a v  a  2s.  c o  m*/
        ((TextView) featuredView.findViewById(R.id.recommended_text)).setVisibility(View.VISIBLE);
    }

    new Thread(new Runnable() {

        private ArrayList<HashMap<String, String>> valuesRecommended;

        public void run() {
            loadUIRecommendedApps();
            File f = null;
            try {
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                NetworkUtils utils = new NetworkUtils();
                BufferedInputStream bis = new BufferedInputStream(
                        utils.getInputStream("http://webservices.aptoide.com/webservices/listUserBasedApks/"
                                + Login.getToken(mContext) + "/10/xml", null, null, mContext),
                        8 * 1024);
                f = File.createTempFile("abc", "abc");
                OutputStream out = new FileOutputStream(f);
                byte buf[] = new byte[1024];
                int len;
                while ((len = bis.read(buf)) > 0)
                    out.write(buf, 0, len);
                out.close();
                bis.close();
                String hash = Md5Handler.md5Calc(f);
                ViewApk parent_apk = new ViewApk();
                parent_apk.setApkid("recommended");
                if (!hash.equals(db.getItemBasedApksHash(parent_apk.getApkid()))) {
                    // Database.database.beginTransaction();
                    db.deleteItemBasedApks(parent_apk);
                    sp.parse(f, new HandlerItemBased(parent_apk));
                    db.insertItemBasedApkHash(hash, parent_apk.getApkid());
                    // Database.database.setTransactionSuccessful();
                    // Database.database.endTransaction();
                    loadUIRecommendedApps();
                }

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

            if (f != null)
                f.delete();

        }

        private void loadUIRecommendedApps() {

            valuesRecommended = db.getItemBasedApksRecommended("recommended");

            runOnUiThread(new Runnable() {

                public void run() {

                    LinearLayout ll = (LinearLayout) featuredView.findViewById(R.id.recommended_container);
                    ll.removeAllViews();
                    LinearLayout llAlso = new LinearLayout(MainActivity.this);
                    llAlso.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT));
                    llAlso.setOrientation(LinearLayout.HORIZONTAL);
                    if (valuesRecommended.isEmpty()) {
                        if (Login.isLoggedIn(mContext)) {
                            TextView tv = new TextView(mContext);
                            tv.setText(R.string.no_recommended_apps);
                            tv.setTextAppearance(mContext, android.R.attr.textAppearanceMedium);
                            tv.setPadding(10, 10, 10, 10);
                            ll.addView(tv);
                        }
                    } else {

                        for (int i = 0; i != valuesRecommended.size(); i++) {
                            LinearLayout txtSamItem = (LinearLayout) getLayoutInflater()
                                    .inflate(R.layout.row_grid_item, null);
                            ((TextView) txtSamItem.findViewById(R.id.name))
                                    .setText(valuesRecommended.get(i).get("name"));
                            ImageLoader.getInstance().displayImage(valuesRecommended.get(i).get("icon"),
                                    (ImageView) txtSamItem.findViewById(R.id.icon));
                            float stars = 0f;
                            try {
                                stars = Float.parseFloat(valuesRecommended.get(i).get("rating"));
                            } catch (Exception e) {
                                stars = 0f;
                            }
                            ((RatingBar) txtSamItem.findViewById(R.id.rating)).setIsIndicator(true);
                            ((RatingBar) txtSamItem.findViewById(R.id.rating)).setRating(stars);
                            txtSamItem.setPadding(10, 0, 0, 0);
                            // ((TextView)
                            // txtSamItem.findViewById(R.id.version))
                            // .setText(getString(R.string.version) +" "+
                            // valuesRecommended.get(i).get("vername"));
                            ((TextView) txtSamItem.findViewById(R.id.downloads))
                                    .setText("(" + valuesRecommended.get(i).get("downloads") + " "
                                            + getString(R.string.downloads) + ")");
                            txtSamItem.setTag(valuesRecommended.get(i).get("_id"));
                            txtSamItem.setLayoutParams(new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.MATCH_PARENT, 100, 1));
                            // txtSamItem.setOnClickListener(featuredListener);
                            txtSamItem.setOnClickListener(new OnClickListener() {

                                @Override
                                public void onClick(View arg0) {
                                    Intent i = new Intent(MainActivity.this, ApkInfo.class);
                                    long id = Long.parseLong((String) arg0.getTag());
                                    i.putExtra("_id", id);
                                    i.putExtra("top", true);
                                    i.putExtra("category", Category.ITEMBASED.ordinal());
                                    startActivity(i);
                                }
                            });

                            txtSamItem.measure(0, 0);

                            if (i % 2 == 0) {
                                ll.addView(llAlso);

                                llAlso = new LinearLayout(MainActivity.this);
                                llAlso.setLayoutParams(new LinearLayout.LayoutParams(
                                        LinearLayout.LayoutParams.MATCH_PARENT, 100));
                                llAlso.setOrientation(LinearLayout.HORIZONTAL);
                                llAlso.addView(txtSamItem);
                            } else {
                                llAlso.addView(txtSamItem);
                            }
                        }

                        ll.addView(llAlso);
                    }
                }
            });
        }
    }).start();

}

From source file:edu.virginia.speclab.juxta.author.model.JuxtaXMLParser.java

public void parse() throws ReportedException {
    firstPassReadFile();/*from  w ww .ja  v a  2s  .c om*/
    offsetMap = new OffsetMap(rawXMLText.length());

    // Setup special tag handling to cover behavior for
    // add, del, note and pb tags
    setupCustomTagHandling();

    try {
        if (file.getName().endsWith("xml")) {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            parser = factory.newSAXParser();

            XMLReader xmlReader = parser.getXMLReader();
            xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", this);

            // ignore external DTDs
            xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

            parser.parse(new InputSource(new StringReader(rawXMLText)), this);
            if (getDocumentType() == DocumentType.UNKNOWN) {
                // If we made it here and we don't know what the document type is,
                // it's just an XML document
                setDocumentType(DocumentType.XML);
            }
            // Uncomment these lines for some verbose debugging of the XML parsing
            // and the resulting processed output.
            //                getRootNode().debugPrint();
            //                try {
            //                    printDebuggingInfo();
            //                } catch (ReportedException ex) {
            //Logger.getLogger(JuxtaXMLParser.class.getName()).log(Level.SEVERE, null, ex);
            //                }
        } else {
            processAsPlaintext();
        }
    } catch (ParserConfigurationException ex) {
        throw new ReportedException(ex, "Problem with our parser configuration.");
    } catch (SAXParseException ex) {
        throw new ReportedException(ex, "XML Parsing Error at column " + ex.getColumnNumber() + ", line "
                + ex.getLineNumber() + " :\n" + ex.getLocalizedMessage());
    } catch (SAXException ex) {
        throw new ReportedException(ex, "SAX Exception: " + ex.getLocalizedMessage());
    } catch (IOException ex) {
        throw new ReportedException(ex, ex.getLocalizedMessage());
    }
}

From source file:cm.aptoide.pt.Aptoide.java

private void getRemoteServLst(String file) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {/*  ww w .  j av a2  s. c  om*/
        keepScreenOn.acquire();

        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        NewServerRssHandler handler = new NewServerRssHandler(this);
        xr.setContentHandler(handler);

        InputStreamReader isr = new FileReader(new File(file));
        InputSource is = new InputSource(isr);
        xr.parse(is);
        File xml_file = new File(file);
        xml_file.delete();
        server_lst = handler.getNewSrvs();
        get_apks = handler.getNewApks();

        keepScreenOn.release();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}

From source file:captureplugin.drivers.dreambox.connector.DreamboxConnector.java

/**
 * Add a recording to the Dreambox//  w  w w .j a  v  a  2 s  . c  om
 * 
 * @param dreamboxChannel
 *          the DreamboxChannel for the Program
 * @param prgTime
 *          add this ProgramTime
 * @param afterEvent
 *          0=nothing, 1=standby, 2=deepstandby, 3=auto
 * @param timezone
 *          TimeZone to use for recording
 * @return True, if successful
 */
public boolean addRecording(DreamboxChannel dreamboxChannel, ProgramTime prgTime, int afterEvent,
        TimeZone timezone) {
    if (!mConfig.hasValidAddress()) {
        return false;
    }
    try {
        Calendar start = prgTime.getStartAsCalendar();
        start.setTimeZone(timezone);

        Calendar end = prgTime.getEndAsCalendar();
        end.setTimeZone(timezone);

        String shortInfo = prgTime.getProgram().getShortInfo();
        if (shortInfo == null) {
            shortInfo = "";
        }

        InputStream stream = openStreamForLocalUrl(
                "/web/tvbrowser?&command=add&action=0" + "&syear=" + start.get(Calendar.YEAR) + "&smonth="
                        + (start.get(Calendar.MONTH) + 1) + "&sday=" + start.get(Calendar.DAY_OF_MONTH)
                        + "&shour=" + start.get(Calendar.HOUR_OF_DAY) + "&smin=" + start.get(Calendar.MINUTE) +

                        "&eyear=" + end.get(Calendar.YEAR) + "&emonth=" + (end.get(Calendar.MONTH) + 1)
                        + "&eday=" + end.get(Calendar.DAY_OF_MONTH) + "&ehour=" + end.get(Calendar.HOUR_OF_DAY)
                        + "&emin=" + end.get(Calendar.MINUTE) +

                        "&sRef="
                        + URLEncoder.encode(dreamboxChannel.getName() + "|" + dreamboxChannel.getReference(),
                                "UTF8")
                        + "&name=" + URLEncoder.encode(prgTime.getProgram().getTitle(), "UTF8")
                        + "&description=" + URLEncoder.encode(shortInfo, "UTF8") +

                        "&afterevent=" + afterEvent + "&eit=&disabled=0&justplay=0&repeated=0");

        SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
        DreamboxStateHandler handler = new DreamboxStateHandler();
        saxParser.parse(stream, handler);
        return (Boolean.valueOf(handler.getState()));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    return false;
}

From source file:cm.aptoide.pt.Aptoide.java

private void parseXmlString(String file) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {//from  w ww .  j a  v a2 s.  c o  m
        keepScreenOn.acquire();

        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        NewServerRssHandler handler = new NewServerRssHandler(this);
        xr.setContentHandler(handler);

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(file));
        xr.parse(is);
        server_lst = handler.getNewSrvs();
        get_apks = handler.getNewApks();

        keepScreenOn.release();

    } catch (IOException e) {
    } catch (SAXException e) {
    } catch (ParserConfigurationException e) {
    }
}

From source file:com.wooki.test.unit.ConversionsTest.java

@Test(enabled = true)
public void testAptConversion() {
    String result = "   ------\n            Title\n            ------\n            Author\n            ------\n             Date\n\n  Paragraph 1, line 1.\n  Paragraph 1, line 2.\n\n  Paragraph 2, line 1.\n  Paragraph 2, line 2.\n\nSection title\n\n* Sub-section title\n\n** Sub-sub-section title\n\n*** Sub-sub-sub-section title\n\n**** Sub-sub-sub-sub-section title\n\n      * List item 1.\n\n      * List item 2.\n\n        Paragraph contained in list item 2.\n\n            * Sub-list item 1.\n\n            * Sub-list item 2.\n\n      * List item 3.\n        Force end of list:\n\n      []\n\n+------------------------------------------+\nVerbatim text not contained in list item 3\n+------------------------------------------+\n\n      [[1]] Numbered item 1.\n\n                [[A]] Numbered item A.\n\n                [[B]] Numbered item B.\n\n      [[2]] Numbered item 2.\n\n  List numbering schemes: [[1]], [[a]], [[A]], [[i]], [[I]].\n\n      [Defined term 1] of definition list.\n\n      [Defined term 2] of definition list.\n\n+-------------------------------+\nVerbatim text\n                        in a box\n+-------------------------------+\n\n  --- instead of +-- suppresses the box around verbatim text.\n\n[Figure name] Figure caption\n\n*----------*--------------+----------------:\n| Centered | Left-aligned | Right-aligned  |\n| cell 1,1 | cell 1,2     | cell 1,3       |\n*----------*--------------+----------------:\n| cell 2,1 | cell 2,2     | cell 2,3       |\n*----------*--------------+----------------:\nTable caption\n\n  No grid, no caption:\n\n*-----*------*\n cell | cell\n*-----*------*\n cell | cell\n*-----*------*\n\n  Horizontal line:\n\n=======================================================================\n\n^L\n  New page.\n\n  <Italic> font. <<Bold>> font. <<<Monospaced>>> font.\n\n  {Anchor}. Link to {{anchor}}. Link to {{http://www.pixware.fr}}.\n  Link to {{{anchor}showing alternate text}}.\n  Link to {{{http://www.pixware.fr}Pixware home page}}.\n\n  Force line\\\n  break.\n\n  Non\\ breaking\\ space.\n\n  Escaped special characters: \\~, \\=, \\-, \\+, \\*, \\[, \\], \\<, \\>, \\{, \\}, \\\\.\n\n  Copyright symbol: \\251, \\xA9, \\u00a9.\n\n~~Commented out.";
    File aptFile = null;/*from  w w w.j  a  va2s .  com*/
    String from = "apt";
    File out = null;

    try {
        out = File.createTempFile("fromAptToXHTML", ".html");
        InputStream apt = new ByteArrayInputStream(result.getBytes());
        try {
            aptFile = File.createTempFile("wooki", ".apt");
            FileOutputStream fos = new FileOutputStream(aptFile);
            logger.debug("APT File is " + aptFile.getAbsolutePath());
            byte[] content = null;
            int available = 0;
            while ((available = apt.available()) > 0) {
                content = new byte[available];
                apt.read(content);
                fos.write(content);
            }
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String to = "xhtml";
        Converter converter = new DefaultConverter();
        InputFileWrapper input = InputFileWrapper.valueOf(aptFile.getAbsolutePath(), from, "ISO-8859-1",
                converter.getInputFormats());

        OutputFileWrapper output = OutputFileWrapper.valueOf(out.getAbsolutePath(), to, "UTF-8",
                converter.getOutputFormats());

        converter.convert(input, output);
    } catch (UnsupportedFormatException e) {
        e.printStackTrace();
    } catch (ConverterException e) {
        e.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    InputStream newHTML = fromAptToDocbook.performTransformation(new FileSystemResource(out));
    SAXParserFactory factory = SAXParserFactory.newInstance();

    // cration d'un parseur SAX
    SAXParser parser;
    try {
        parser = factory.newSAXParser();
        parser.parse(new InputSource(newHTML), htmlParser);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        logger.error(e.getLocalizedMessage());
    } catch (SAXException e) {
        e.printStackTrace();
        logger.error(e.getLocalizedMessage());
    } catch (IOException e) {
        e.printStackTrace();
        logger.error(e.getLocalizedMessage());
    }

    Book book = htmlParser.getBook();
    logger.debug("The book title is " + book.getTitle());
}