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: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  va  2s.  c om

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

    return handler.getCompoundIdMap();
}

From source file:com.openbravo.pos.admin.RolesViewTree.java

public void getPermissions() throws BasicException {
    try {/*w  w  w.  j  ava 2s.  c o m*/
        String m_roles = m_dlAdmin.getRoleID(m_jName.getText());
        String sRolePermisions = m_dlAdmin.findRolePermissions(m_roles);
        m_apermissions = new HashSet<>();
        if (m_sp == null) {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            m_sp = spf.newSAXParser();
        }
        m_sp.parse(new InputSource(new StringReader(sRolePermisions)),
                new RolesViewTree.ConfigurationHandler());
    } catch (ParserConfigurationException | SAXException ex) {
        Logger.getLogger(JRootApp.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(RolesViewTree.class.getName()).log(Level.SEVERE, null, ex);
    }
    ;
}

From source file:hu.sztaki.lpds.pgportal.services.dspace.LNIclient.java

/**
 * Completes the two-part operation started by startPut(), by
 * collecting status of the PUT operation and converting the
 * WebDAV URI of the newly-created resource back to a Handle,
 * which it returns.//from w  w w  .  ja v  a 2  s.  com
 * <p>
 * Any failure results in an exception.
 *
 * @return Handle of the newly-created DSpace resource.
 */
public String finishPut() throws InterruptedException, IOException, SAXException, SAXNotRecognizedException,
        ParserConfigurationException {
    if (lastPutThread != null) {
        lastPutThread.join();
        lastPutThread = null;
    }

    Header loc = lastPut.getResponseHeader("Location");
    lastStatus = lastPut.getStatusCode();
    if (lastStatus < 100 || lastStatus >= 400)
        throw new IOException("PUT returned status = " + lastStatus + "; text=" + lastPut.getStatusText());

    lastPut = null;
    if (loc != null) {
        String newURL = loc.getValue();

        // do a quick PROPFIND to get the handle
        PropfindMethod pf = new PropfindMethod(newURL, propfindBody);
        pf.setDoAuthentication(true);
        client.executeMethod(pf);

        int pfStatus = pf.getStatusCode();
        if (pfStatus < 200 || pfStatus >= 300)
            throw new IOException(
                    "finishPut.propfind got status = " + pfStatus + "; text=" + pf.getStatusText());

        // Maybe move all this crap to within Propfind class??
        // so it can get the inputstream directly?
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        PropfindHandler handler = new PropfindHandler();

        // XXX FIXME: should turn off validation here explicitly, but
        //  it seems to be off by default.
        xr.setFeature("http://xml.org/sax/features/namespaces", true);
        xr.setContentHandler(handler);
        xr.setErrorHandler(handler);
        xr.parse(new InputSource(pf.getResponseBodyAsStream()));

        return handler.handle;
    } else
        throw new IOException("PUT response was missing a Location: header.");
}

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

/**
 * Remove a recording from the Dreambox//from  w  w w . jav  a 2 s . c o  m
 * 
 * @param dreamboxChannel
 *          the DreamboxChannel for the Program
 * @param prgTime
 *          ProgramTime to remove @return true, if successful
 * @param timezone
 *          Timezone to use for recording
 * @return True, if successful
 */
public boolean removeRecording(DreamboxChannel dreamboxChannel, ProgramTime prgTime, 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=del&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=0&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:com.datatorrent.stram.webapp.OperatorDiscoverer.java

private void processJavadocXml(InputStream is) throws ParserConfigurationException, SAXException, IOException {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.newSAXParser().parse(is, new JavadocSAXHandler());
}

From source file:com.abstratt.mdd.core.util.MDDUtil.java

public static boolean isGenerated(java.net.URI uri) {
    if (cachedParserFactory == null) {
        cachedParserFactory = SAXParserFactory.newInstance();
    }//from   w w w . j a  va2s.co  m
    SAXParser xmlParser;
    try {
        xmlParser = cachedParserFactory.newSAXParser();
    } catch (ParserConfigurationException e) {
        if (Platform.inDebugMode())
            LogUtils.logError(MDDCore.PLUGIN_ID, "Error creating XML parser", e);
        return false;
    } catch (SAXException e) {
        if (Platform.inDebugMode())
            LogUtils.logError(MDDCore.PLUGIN_ID, "Error creating XML parser", e);
        return false;
    }
    final boolean[] generated = { false };
    final boolean[] aborted = { false };
    InputStream stream = null;
    try {
        stream = new BufferedInputStream(uri.toURL().openStream());
        xmlParser.parse(stream, new DefaultHandler() {
            private boolean skipping = true;

            @Override
            public void startElement(String uri, String localName, String name, Attributes attributes)
                    throws SAXException {
                if (name.equalsIgnoreCase("eAnnotations"))
                    if (GENERATED.equals(attributes.getValue("source"))) {
                        generated[0] = true;
                        aborted[0] = true;
                        throw new SAXParseException("", null);
                    } else
                        return;
                if (!skipping) {
                    // should have seen the annotation by now
                    aborted[0] = true;
                    throw new SAXParseException("", null);
                }
                if (name.startsWith("uml"))
                    skipping = false;
            }
        });
    } catch (SAXException e) {
        if (!aborted[0] && Platform.inDebugMode())
            LogUtils.logError(MDDCore.PLUGIN_ID, "Error parsing " + uri, e);
    } catch (IOException e) {
        if (Platform.inDebugMode())
            LogUtils.logError(MDDCore.PLUGIN_ID, "Error parsing " + uri, e);
    } finally {
        if (stream != null)
            try {
                stream.close();
            } catch (IOException e) {
                // no biggie
            }
    }
    return generated[0];
}

From source file:ee.sk.digidoc.factory.SAXDigiDocFactory.java

/**
 * Reads in a DigiDoc file. One of fname or isSdoc must be given.
 * @param fname signed doc filename/* ww w .ja v a  2 s  . c  o m*/
 * @param isSdoc opened stream with DigiDoc data
 * The user must open and close it.
 * @param errs list of errors to fill with parsing errors. If given
 * then attempt is made to continue parsing on errors and return them in this list.
 * If not given (null) then the first error found will be thrown.
 * @return signed document object if successfully parsed
 */
private SignedDoc readSignedDocOfType(String fname, InputStream isSdoc, boolean isBdoc, List errs)
        throws DigiDocException {
    // Use an instance of ourselves as the SAX event handler
    SAXDigiDocFactory handler = this;
    m_errs = errs;
    DigiDocVerifyFactory.initProvider();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    if (m_logger.isDebugEnabled())
        m_logger.debug("Start reading ddoc/bdoc " + ((fname != null) ? "from file: " + fname : "from stream")
                + " bdoc: " + isBdoc);
    if (fname == null && isSdoc == null) {
        throw new DigiDocException(DigiDocException.ERR_READ_FILE, "No input file", null);
    }
    if (fname != null) {
        File inFile = new File(fname);
        if (!inFile.canRead() || inFile.length() == 0) {
            throw new DigiDocException(DigiDocException.ERR_READ_FILE, "Empty or unreadable input file", null);
        }
    }
    ZipFile zf = null;
    ZipArchiveInputStream zis = null;
    ZipArchiveEntry ze = null;
    InputStream isEntry = null;
    File fTmp = null;
    try {
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        if (isBdoc) { // bdoc parsing
            // must be a bdoc document ?
            m_doc = new SignedDoc();
            m_doc.setVersion(SignedDoc.BDOC_VERSION_1_0);
            m_doc.setFormat(SignedDoc.FORMAT_BDOC);
            Enumeration eFiles = null;
            if (fname != null) {
                zf = new ZipFile(fname, "UTF-8");
                eFiles = zf.getEntries();
            } else if (isSdoc != null) {
                zis = new ZipArchiveInputStream(isSdoc, "UTF-8", true, true);
            }
            ArrayList lSigFnames = new ArrayList();
            ArrayList lDataFnames = new ArrayList();
            // read all entries
            boolean bHasMimetype = false, bManifest1 = false;
            int nFil = 0;
            while ((zf != null && eFiles.hasMoreElements())
                    || (zis != null && ((ze = zis.getNextZipEntry()) != null))) {
                nFil++;

                // read entry
                if (zf != null) { // ZipFile
                    ze = (ZipArchiveEntry) eFiles.nextElement();
                    isEntry = zf.getInputStream(ze);
                } else { // ZipArchiveInputStream
                    int n = 0, nTot = 0;
                    if ((ze.getName().equals(FILE_MIMETYPE) || ze.getName().equals(FILE_MANIFEST)
                            || (ze.getName().startsWith(FILE_SIGNATURES) && ze.getName().endsWith(".xml")))
                            || (nMaxBdocFilCached <= 0
                                    || (ze.getSize() < nMaxBdocFilCached && ze.getSize() >= 0))) {
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        byte[] data = new byte[2048];
                        while ((n = zis.read(data)) > 0) {
                            bos.write(data, 0, n);
                            nTot += n;
                        }
                        if (m_logger.isDebugEnabled())
                            m_logger.debug("Read: " + nTot + " bytes from zip");
                        data = bos.toByteArray();
                        bos = null;
                        isEntry = new ByteArrayInputStream(data);
                    } else {
                        File fCacheDir = new File(ConfigManager.instance().getStringProperty(
                                "DIGIDOC_DF_CACHE_DIR", System.getProperty("java.io.tmpdir")));
                        fTmp = File.createTempFile("bdoc-data", ".tmp", fCacheDir);
                        FileOutputStream fos = new FileOutputStream(fTmp);
                        byte[] data = new byte[2048];
                        while ((n = zis.read(data)) > 0) {
                            fos.write(data, 0, n);
                            nTot += n;
                        }
                        if (m_logger.isDebugEnabled())
                            m_logger.debug("Read: " + nTot + " bytes from zip to: " + fTmp.getAbsolutePath());
                        fos.close();
                        isEntry = new FileInputStream(fTmp);
                    }
                }
                if (m_logger.isDebugEnabled())
                    m_logger.debug("Entry: " + ze.getName() + " nlen: " + ze.getName().length() + " size: "
                            + ze.getSize() + " dir: " + ze.isDirectory() + " comp-size: "
                            + ze.getCompressedSize());
                // mimetype file
                if (ze.getName().equals(FILE_MIMETYPE)) {
                    if (m_logger.isDebugEnabled())
                        m_logger.debug("Check mimetype!");
                    checkBdocMimetype(isEntry);
                    bHasMimetype = true;
                    m_doc.setComment(ze.getComment());
                    if (nFil != 1) {
                        m_logger.error("mimetype file is " + nFil + " file but must be first");
                        handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML,
                                "mimetype file is not first zip entry", null));
                    }
                } else if (ze.getName().equals(FILE_MANIFEST)) { // manifest.xml file
                    if (m_logger.isDebugEnabled())
                        m_logger.debug("Read manifest");
                    if (!bManifest1 && isEntry != null) {
                        bManifest1 = true;
                        BdocManifestParser mfparser = new BdocManifestParser(m_doc);
                        mfparser.readManifest(isEntry);
                    } else {
                        m_logger.error("Found multiple manifest.xml files!");
                        throw new DigiDocException(DigiDocException.ERR_MULTIPLE_MANIFEST_FILES,
                                "Found multiple manifest.xml files!", null);
                    }
                } else if (ze.getName().startsWith(FILE_SIGNATURES) && ze.getName().endsWith(".xml")) { // some signature
                    m_fileName = ze.getName();
                    if (m_logger.isDebugEnabled())
                        m_logger.debug("Reading bdoc siganture: " + m_fileName);
                    boolean bExists = false;
                    for (int j = 0; j < lSigFnames.size(); j++) {
                        String s1 = (String) lSigFnames.get(j);
                        if (s1.equals(m_fileName))
                            bExists = true;
                    }
                    if (bExists) {
                        m_logger.error("Duplicate signature filename: " + m_fileName);
                        handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML,
                                "Duplicate signature filename: " + m_fileName, null));
                    } else
                        lSigFnames.add(m_fileName);
                    SAXParser saxParser = factory.newSAXParser();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    int n = 0;
                    byte[] data = new byte[2048];
                    while ((n = isEntry.read(data)) > 0)
                        bos.write(data, 0, n);
                    data = bos.toByteArray();
                    bos = null;
                    if (m_logger.isDebugEnabled())
                        m_logger.debug(
                                "Parsing bdoc: " + m_fileName + " size: " + ((data != null) ? data.length : 0));
                    saxParser.parse(new SignatureInputStream(new ByteArrayInputStream(data)), this);
                    if (m_logger.isDebugEnabled())
                        m_logger.debug("Parsed bdoc: " + m_fileName);
                    Signature sig1 = m_doc.getLastSignature();
                    m_sigComment = ze.getComment();
                    if (sig1 != null) {
                        sig1.setPath(m_fileName);
                        sig1.setComment(ze.getComment());
                    }
                } else { // probably a data file
                    if (m_logger.isDebugEnabled())
                        m_logger.debug("Read data file: " + ze.getName());
                    if (!ze.isDirectory()) {
                        boolean bExists = false;
                        for (int j = 0; j < lDataFnames.size(); j++) {
                            String s1 = (String) lDataFnames.get(j);
                            if (s1.equals(ze.getName()))
                                bExists = true;
                        }
                        if (bExists) {
                            m_logger.error("Duplicate datafile filename: " + ze.getName());
                            handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML,
                                    "Duplicate datafile filename: " + ze.getName(), null));
                        } else
                            lDataFnames.add(ze.getName());
                        DataFile df = m_doc.findDataFileById(ze.getName());
                        if (df != null) {
                            if (ze.getSize() > 0)
                                df.setSize(ze.getSize());
                            df.setContentType(DataFile.CONTENT_BINARY);
                            df.setFileName(ze.getName());
                        } else {
                            df = new DataFile(ze.getName(), DataFile.CONTENT_BINARY, ze.getName(),
                                    "application/binary", m_doc);
                            if (m_doc.getDataFiles() == null)
                                m_doc.setDataFiles(new ArrayList());
                            m_doc.getDataFiles().add(df);
                            //m_doc.addDataFile(df); // this does some intiailization work unnecessary here
                        }
                        // enable caching if requested
                        if (isEntry != null)
                            df.setOrCacheBodyAndCalcHashes(isEntry);
                        df.setComment(ze.getComment());
                        df.setLastModDt(new Date(ze.getTime()));
                        // fix mime type according to DataObjectFormat
                        Signature sig1 = m_doc.getLastSignature();
                        if (sig1 != null) {
                            Reference dRef = sig1.getSignedInfo().getReferenceForDataFile(df);
                            if (dRef != null) {
                                DataObjectFormat dof = sig1.getSignedInfo()
                                        .getDataObjectFormatForReference(dRef);
                                if (dof != null) {
                                    df.setMimeType(dof.getMimeType());
                                }
                            }
                        }
                    }
                }
                if (fTmp != null) {
                    fTmp.delete();
                    fTmp = null;
                }
            } // while zip entries
            if (!bHasMimetype) {
                m_logger.error("No mimetype file");
                handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML,
                        "Not a BDOC format file! No mimetype file!", null));
            }
            // if no signatures exist then copy mime-type from manifest.xml to DataFile -s
            if (m_doc.countSignatures() == 0) {
                for (int i = 0; i < m_doc.countDataFiles(); i++) {
                    DataFile df = m_doc.getDataFile(i);
                    if (m_doc.getManifest() != null) {
                        for (int j = 0; j < m_doc.getManifest().getNumFileEntries(); j++) {
                            ManifestFileEntry mfe = m_doc.getManifest().getFileEntry(j);
                            if (mfe.getFullPath() != null && mfe.getFullPath().equals(df.getFileName())) {
                                df.setMimeType(mfe.getMediaType());
                            } // if fullpath
                        } // for
                    } // if
                } // for i
            }
        } else { // ddoc parsing
            if (m_logger.isDebugEnabled())
                m_logger.debug("Reading ddoc: " + fname + " file: " + m_fileName);
            m_fileName = fname;
            SAXParser saxParser = factory.newSAXParser();
            if (fname != null)
                saxParser.parse(new SignatureInputStream(new FileInputStream(fname)), this);
            else if (isSdoc != null)
                saxParser.parse(isSdoc, this);
        }
    } catch (org.xml.sax.SAXParseException ex) {
        m_logger.error("SAX Error: " + ex);
        handleError(ex);

    } catch (Exception ex) {
        m_logger.error("Error reading3: " + ex);
        ex.printStackTrace();
        /*if(ex instanceof DigiDocException){
           DigiDocException dex = (DigiDocException)ex;
           m_logger.error("Dex: " + ex);
           if(dex.getNestedException() != null) {
              dex.getNestedException().printStackTrace();
              m_logger.error("Trace: "); 
           }
        }*/
        handleError(ex);
    } finally { // cleanup
        try {
            if (isEntry != null) {
                isEntry.close();
                isEntry = null;
            }
            if (zis != null)
                zis.close();
            if (zf != null)
                zf.close();
            if (fTmp != null) {
                fTmp.delete();
                fTmp = null;
            }
        } catch (Exception ex) {
            m_logger.error("Error closing streams and files: " + ex);
        }
    }
    // compare Manifest and DataFiles
    boolean bErrList = (errs != null);
    if (errs == null)
        errs = new ArrayList();
    boolean bOk = DigiDocVerifyFactory.verifyManifestEntries(m_doc, errs);
    if (m_doc == null) {
        m_logger.error("Error reading4: doc == null");
        handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML,
                "This document is not in ddoc or bdoc format", null));
    }
    if (!bErrList && errs.size() > 0) { // if error list was not used then we have to throw exception. So we will throw the first one since we can only do it once
        DigiDocException ex = (DigiDocException) errs.get(0);
        throw ex;
    }
    return m_doc;
}

From source file:br.org.indt.ndg.server.client.TemporaryOpenRosaBussinessDelegate.java

public boolean parseAndPersistResult(InputStreamReader inputStreamReader, String contentType)
        throws IOException {
    String resultString = parseMultipartEncodedFile(inputStreamReader, contentType, "filename");
    SAXParserFactory factory = SAXParserFactory.newInstance();
    OpenRosaResultsHandler handler = new OpenRosaResultsHandler();
    try {/*from   w  ww  .ja va2 s  . c om*/
        ByteArrayInputStream streamToParse = new ByteArrayInputStream(resultString.getBytes());
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(streamToParse, handler);
        streamToParse.close();
    } catch (Throwable err) {
        err.printStackTrace();
    }
    String resultId = handler.getResultId();
    String deviceId = handler.getDeviceId();
    String surveyId = handler.getSurveyId();
    if (resultId == null || deviceId == null || surveyId == null) {
        return false;
    } else {
        return persistResult(resultString, surveyId, resultId, deviceId);
    }
}

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

private Vector<String> getRemoteServLst(String file) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    Vector<String> out = new Vector<String>();
    try {/*from   w w  w  .jav a  2  s. com*/
        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();
        out = handler.getNewSrvs();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    return out;
}

From source file:org.springsource.ide.eclipse.commons.core.SpringCoreUtils.java

public static SAXParser getSaxParser() {
    if (!SAX_PARSER_ERROR) {
        try {/*from   www.  ja v a2  s. c o  m*/
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            SAXParser parser = factory.newSAXParser();
            return parser;
        } catch (Exception e) {
            StatusHandler.log(new Status(IStatus.INFO, CorePlugin.PLUGIN_ID,
                    "Error creating SaxParserFactory. Switching to OSGI service reference."));
            SAX_PARSER_ERROR = true;
        }
    }

    BundleContext bundleContext = CorePlugin.getDefault().getBundle().getBundleContext();
    ServiceReference reference = bundleContext.getServiceReference(SAXParserFactory.class.getName());
    if (reference != null) {
        try {
            synchronized (SAX_PARSER_LOCK) {
                SAXParserFactory factory = (SAXParserFactory) bundleContext.getService(reference);
                return factory.newSAXParser();
            }
        } catch (Exception e) {
            StatusHandler
                    .log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Error creating SaxParserFactory", e));
        } finally {
            bundleContext.ungetService(reference);
        }
    }

    return null;
}