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:de.mpg.escidoc.services.edoc.PubManImport.java

public void run() {

    XmlTransforming xmlTransforming = new XmlTransformingBean();

    try {/*w  ww . ja v a 2  s .  co  m*/
        File file = new File(fileName);
        if (!file.exists()) {
            System.err.println("File \"" + file.getAbsolutePath() + "\" not found!");
            System.exit(1);
        }

        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        ImportHandler importHandler = new ImportHandler();
        parser.parse(new InputSource(new InputStreamReader(new FileInputStream(file))), importHandler);

        List<String> itemXmls = importHandler.getItems();

        for (String itemXml : itemXmls) {
            validateItem(itemXml);
            ItemVO itemVO = xmlTransforming.transformToItem(itemXml);
            System.out.println(itemVO);
        }

        // System.exit(0);

        for (String itemXml : itemXmls) {
            importItem(itemXml);
            //sleep(5000);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.entertailion.java.caster.DeviceFinder.java

public void onBroadcastFound(final BroadcastAdvertisement advert) {
    if (advert.getLocation() != null) {
        new Thread(new Runnable() {
            public void run() {
                Log.d(LOG_TAG, "location=" + advert.getLocation());
                HttpResponse response = new HttpRequestHelper().sendHttpGet(advert.getLocation());
                if (response != null) {
                    String appsUrl = null;
                    Header header = response.getLastHeader(HEADER_APPLICATION_URL);
                    if (header != null) {
                        appsUrl = header.getValue();
                        if (!appsUrl.endsWith("/")) {
                            appsUrl = appsUrl + "/";
                        }/*from   w  w  w  .  j  a v  a  2  s . c  o m*/
                        Log.d(LOG_TAG, "appsUrl=" + appsUrl);
                    }
                    try {
                        InputStream inputStream = response.getEntity().getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

                        InputSource inStream = new org.xml.sax.InputSource();
                        inStream.setCharacterStream(reader);
                        SAXParserFactory spf = SAXParserFactory.newInstance();
                        SAXParser sp = spf.newSAXParser();
                        XMLReader xr = sp.getXMLReader();
                        BroadcastHandler broadcastHandler = new BroadcastHandler();
                        xr.setContentHandler(broadcastHandler);
                        xr.parse(inStream);
                        Log.d(LOG_TAG, "modelName=" + broadcastHandler.getDialServer().getModelName());
                        // Only handle ChromeCast devices; not other DIAL
                        // devices like ChromeCast devices
                        if (broadcastHandler.getDialServer().getModelName().equals(CHROME_CAST_MODEL_NAME)) {
                            Log.d(LOG_TAG,
                                    "ChromeCast device found: " + advert.getIpAddress().getHostAddress());
                            DialServer dialServer = new DialServer(advert.getLocation(), advert.getIpAddress(),
                                    advert.getPort(), appsUrl,
                                    broadcastHandler.getDialServer().getFriendlyName(),
                                    broadcastHandler.getDialServer().getUuid(),
                                    broadcastHandler.getDialServer().getManufacturer(),
                                    broadcastHandler.getDialServer().getModelName());
                            trackedDialServers.add(dialServer);
                        }
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "parse device description", e);
                    }
                }
            }
        }).start();
    }
}

From source file:com.mirth.connect.model.converters.DICOMSerializer.java

@Override
public String fromXML(String source) throws SerializerException {
    if (source == null || source.length() == 0) {
        return StringUtils.EMPTY;
    }//from   w  ww.j  a  v a2  s.  c o  m

    try {
        // re-parse the xml to Mirth format
        Document document = documentSerializer.fromXML(source);
        Element element = document.getDocumentElement();
        Node node = element.getChildNodes().item(0);

        // change back to <attr> tag for all tags under <dicom> tag
        while (node != null) {
            renameTagToAttr(document, node);
            node = node.getNextSibling();
        }

        NodeList items = document.getElementsByTagName("item");

        // change back to <attr> tag for all tags under <item> tags
        if (items != null) {
            for (int i = 0; i < items.getLength(); i++) {
                Node itemNode = items.item(i);

                if (itemNode.getChildNodes() != null) {
                    NodeList itemNodes = itemNode.getChildNodes();

                    for (int j = 0; j < itemNodes.getLength(); j++) {
                        Node nodeItem = itemNodes.item(j);
                        renameTagToAttr(document, nodeItem);
                    }
                }
            }
        }

        // find the charset
        String charset = null;
        Element charsetElement = (Element) document.getElementsByTagName("tag00080005").item(0);

        if (charsetElement != null) {
            charset = charsetElement.getNodeValue();
        } else {
            charset = "utf-8";
        }

        // parse the Document into a DicomObject
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        DicomObject dicomObject = new BasicDicomObject();
        ContentHandlerAdapter contentHandler = new ContentHandlerAdapter(dicomObject);
        byte[] documentBytes = documentSerializer.toXML(document).trim().getBytes(charset);
        parser.parse(new InputSource(new ByteArrayInputStream(documentBytes)), contentHandler);
        return new String(Base64.encodeBase64Chunked(DICOMUtil.dicomObjectToByteArray(dicomObject)));
    } catch (Exception e) {
        throw new SerializerException(e);
    }
}

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

@Transactional
public void load() {
    // 1. Check wether we are allowed to load default content into the DB
    final List<SyncopeConf> res = confDAO.findAll();

    if (res == null || res.size() > 0) {
        LOG.info("Data found in the database, leaving untouched");
        return;//from   w ww  .java2  s.co  m
    }

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

            final String updateViews = views.get(idx).toString().replaceAll("\\n", " ");
            entityManager.createNativeQuery(updateViews).executeUpdate();
        }

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

    // 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());

            final String updateIndexed = indexes.get(idx).toString();
            entityManager.createNativeQuery(updateIndexed).executeUpdate();
        }

        LOG.debug("Indexes created, go for default content");
    } catch (Exception e) {
        LOG.error("While creating indexes", e);
    }

    // noop workflow
    //        entityManager.createNativeQuery("DELETE FROM ACT_GE_PROPERTY").executeUpdate();

    // 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 (Exception e) {
        LOG.error("While loading default content", e);
    }
}

From source file:com.aurel.track.exchange.track.importer.ImporterDataParser.java

public List<ExchangeWorkItem> parse(File xml, Map<Integer, Integer> fieldMatcher) {
    this.fieldMatcher = fieldMatcher;
    //get a factory
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    try {/*from ww  w . j a  va  2  s  . co  m*/
        SAXParser saxParser = saxParserFactory.newSAXParser();
        LOGGER.debug("Data parser started...");
        saxParser.parse(xml, this);
        LOGGER.debug("Data parser done");
        return exchangeWorkItemsList;
    } catch (SAXException se) {
        LOGGER.error(ExceptionUtils.getStackTrace(se));
    } catch (ParserConfigurationException pce) {
        LOGGER.error(ExceptionUtils.getStackTrace(pce));
    } catch (IOException ie) {
        LOGGER.error(ExceptionUtils.getStackTrace(ie));
    }
    return null;
}

From source file:com.travelguide.GuideActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    final String TAG = "Activity2";

    String ln = getIntent().getExtras().getString("tag");
    if ((ln.equals("Espaol")) || (ln.equals("Spanish"))) {
        TextView t1 = (TextView) findViewById(R.id.thanks);
        t1.setText("Gracias por usar mi aplicacin.");

        TextView t2 = (TextView) findViewById(R.id.link);
        t2.setText("Las ubicaciones de visitantes en el interior "
                + getIntent().getExtras().getString("com.travelguide.radius") + " millas para "
                + getIntent().getExtras().getString("com.travelguide.location"));

    } else {/* ww  w.  j a v a  2s.  c om*/
        TextView t1 = (TextView) findViewById(R.id.thanks);
        t1.setText("Thanks for using my App.");

        TextView t2 = (TextView) findViewById(R.id.link);
        t2.setText(
                "Visitor locations found within " + getIntent().getExtras().getString("com.travelguide.radius")
                        + " miles for " + getIntent().getExtras().getString("com.travelguide.location"));

    }

    String url = getIntent().getExtras().getString("com.travelguide.link");
    Log.i(TAG, url);

    try {
        //***** Parsing the xml file*****
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        tgparse myXML_parser = new tgparse();
        xr.setContentHandler(myXML_parser);

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url.replace(" ", "%20"));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);
        Log.i(TAG, "responseBody: " + responseBody);
        ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes());
        xr.parse(new InputSource(is));

        Log.i(TAG, "parse complete");

        TextView placename[];
        TextView placeaddress[];
        TextView placerating[];

        tgxml data;
        data = tgparse.getXMLData();
        placename = new TextView[data.getName().size()];
        placeaddress = new TextView[data.getName().size()];
        placerating = new TextView[data.getName().size()];

        webview = (WebView) findViewById(R.id.myWebView);

        //    webview.setBackgroundColor(0);
        //    webview.setBackgroundResource(R.drawable.openbook);

        String stg1 = new String();
        stg1 = "<html>";
        for (int i = 1; i < (data.getName().size()); i++) {
            Log.i(TAG, " " + i);
            Log.i(TAG, "Name= " + data.getName().get(i));
            Log.i(TAG, "Address= " + data.getAddress().get(i));
            Log.i(TAG, "Rating= " + data.getRating().get(i));

            placename[i] = new TextView(this);
            placename[i].setText("Name= " + data.getName().get(i));

            placeaddress[i] = new TextView(this);
            placeaddress[i].setText("Address= " + data.getAddress().get(i));

            placerating[i] = new TextView(this);
            placerating[i].setText("Rating= " + data.getRating().get(i));

            if ((ln.equals("Espaol")) || (ln.equals("Spanish"))) {
                stg1 = stg1 + "Nombre: " + data.getName().get(i) + "<br>" + " Direccin: "
                        + data.getAddress().get(i) + "<br>" + " clasificacin= " + data.getRating().get(i)
                        + "<br>" + "<br>";
            } else {
                stg1 = stg1 + "Name: " + data.getName().get(i) + "<br>" + " Address: "
                        + data.getAddress().get(i) + "<br>" + " Rating= " + data.getRating().get(i) + "<br>"
                        + "<br>";
            }

        }
        stg1 = stg1 + "</html>";
        webview.loadDataWithBaseURL(null, stg1, "text/html", "utf-8", "about:blank");

    } catch (Exception e) {
        Log.i(TAG, "Exception caught", e);

    }

}

From source file:com.textocat.textokit.morph.ruscorpora.RusCorporaCollectionReader.java

@Override
public void initialize(UimaContext ctx) throws ResourceInitializationException {
    super.initialize(ctx);
    tagMapper = InitializableFactory.create(ctx, tagMapperClassName, RusCorporaTagMapper.class);
    if (!inputDir.isDirectory()) {
        throw new IllegalArgumentException(String.format("%s is not existing directory", inputDir));
    }//ww w.  j  a v  a 2  s  .co  m
    relativeURIFunc = CorpusUtils.relativeURIFunction(inputDir);
    relativePathFunc = CorpusUtils.relativePathFunction(inputDir);
    String inputFileExt = DEFAULT_INPUT_FILE_EXT;
    inputFiles = ImmutableList
            .copyOf(FileUtils.listFiles(inputDir, suffixFileFilter(inputFileExt), TrueFileFilter.INSTANCE));
    getLogger().info(String.format("Detected *%s files in %s: %s", inputFileExt, inputDir, inputFiles.size()));
    try {
        SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
        xmlReader = saxParser.getXMLReader();
    } catch (Exception e) {
        throw new ResourceInitializationException(e);
    }
}

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 {//w w w  .j a va2s .co  m
        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:es.ehu.si.ixa.pipe.convert.Convert.java

/**
 * Process the ancora constituent XML annotation into Penn Treebank bracketing
 * style.//  w  ww  .  j  ava  2s  .c  om
 * 
 * @param inXML
 *          the ancora xml constituent document
 * @return the ancora trees in penn treebank one line format
 * @throws IOException
 *           if io exception
 */
public String ancora2treebank(File inXML) throws IOException {
    String filteredTrees = null;
    if (inXML.isFile()) {

        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser;
        try {
            saxParser = saxParserFactory.newSAXParser();
            AncoraTreebank ancoraParser = new AncoraTreebank();
            saxParser.parse(inXML, ancoraParser);
            String trees = ancoraParser.getTrees();
            // remove empty trees created by "missing" and "elliptic" attributes
            filteredTrees = trees.replaceAll("\\(\\SN\\)", "");
            // format correctly closing brackets
            filteredTrees = filteredTrees.replace(") )", "))");
            // remove double spaces
            filteredTrees = filteredTrees.replaceAll("  ", " ");
            // remove empty sentences created by <sentence title="yes"> elements
            filteredTrees = filteredTrees.replaceAll("\\(SENTENCE \\)\n", "");
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        System.out.println("Please choose a valid file as input");
    }
    return filteredTrees;
}

From source file:net.lightbody.bmp.proxy.jetty.xml.XmlParser.java

/**
 * Constructor.//from w ww.j  a va2 s.  com
 */
public XmlParser(boolean validating) {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(validating);
        _parser = factory.newSAXParser();
        try {
            if (validating)
                _parser.getXMLReader().setFeature("http://apache.org/xml/features/validation/schema",
                        validating);
        } catch (Exception e) {
            if (validating)
                log.warn("Schema validation may not be supported: ", e);
            else
                LogSupport.ignore(log, e);
        }
        _parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", validating);
        _parser.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", validating);
        _parser.getXMLReader().setFeature("http://xml.org/sax/features/namespace-prefixes", validating);
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
        throw new Error(e.toString());
    }
}