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:fr.paris.lutece.plugins.dila.modules.solr.utils.parsers.DilaSolrPublicParser.java

/**
 * Initializes and launches the parsing of the public cards (public
 * constructor)/*  www.  j a  va 2  s. c  o m*/
 */
public DilaSolrPublicParser() {
    // Gets the list of CDC index keys
    String strIndexKeys = AppPropertiesService
            .getProperty(PROPERTY_INDEXING_FRAGMENT + PROPERTY_LIST_INDEX_KEYS_FRAGMENT);

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

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

    // Initializes the site
    _strSite = AppPropertiesService.getProperty(PROPERTY_SITE);

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

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

        // Splits the list of CDC index keys
        String[] splitKeys = strIndexKeys.split(",");

        for (int i = 0; i < splitKeys.length; i++) {
            // Gets the XML index file path
            String strXmlDirectory = AppPropertiesService
                    .getProperty(splitKeys[i] + STRING_POINT + PROPERTY_INDEXING_XML_BASE_VAR);
            File xmlPath = new File(strXmlDirectory);
            // Launches the parsing of all files in this directory
            parseAllPublicCards(xmlPath, parser);
        }
    } catch (ParserConfigurationException e) {
        AppLogService.error(e.getMessage(), e);
    } catch (SAXException e) {
        AppLogService.error(e.getMessage(), e);
    }
}

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

public void start() {
    //TODO: this method is too complex and should be refactored
    if (running)//from w ww .j a v a2  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(Util.T, "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.println();
            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(Util.T, "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(Util.T, "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;

                bEnabled = enabled.equalsIgnoreCase("true");

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

From source file:org.gege.caldavsyncadapter.caldav.entities.CalendarEvent.java

public boolean setICSasMultiStatus(String stringMultiStatus) {
    boolean Result = false;
    String ics = "";
    MultiStatus multistatus;//from w  w w  . j  av a 2 s. co m
    ArrayList<Response> responselist;
    Response response;
    PropStat propstat;
    Prop prop;
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        MultiStatusHandler contentHandler = new MultiStatusHandler();
        reader.setContentHandler(contentHandler);
        reader.parse(new InputSource(new StringReader(stringMultiStatus)));

        multistatus = contentHandler.mMultiStatus;
        if (multistatus != null) {
            responselist = multistatus.ResponseList;
            if (responselist.size() == 1) {
                response = responselist.get(0);
                //HINT: bugfix for google calendar
                if (response.href.equals(this.getUri().getPath().replace("@", "%40"))) {
                    propstat = response.propstat;
                    if (propstat.status.contains("200 OK")) {
                        prop = propstat.prop;
                        ics = prop.calendardata;
                        this.setETag(prop.getetag);
                        Result = true;
                    }
                }
            }
        }
    } catch (ParserConfigurationException e1) {
        e1.printStackTrace();
    } catch (SAXException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    this.stringIcs = ics;
    return Result;
}

From source file:eu.apenet.dpt.utils.util.Ead2EdmInformation.java

private void determineDaoInformation(File fileToRead)
        throws IOException, SAXException, ParserConfigurationException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();
    EadContentHandler myContentHandler = new EadContentHandler();
    xr.setContentHandler(myContentHandler);
    xr.parse(new InputSource(new InputStreamReader(new BOMInputStream(new FileInputStream(fileToRead)))));

    if (this.roleType == null) {
        this.roleType = "UNSPECIFIED";
    }//from  w  ww.j  a  va2s . c o  m
}

From source file:com.binomed.showtime.android.util.CineShowtimeFactory.java

private XMLReader getReader() throws Exception {
    if (reader == null) {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        reader = sp.getXMLReader();// ww w.  j  ava2  s . co m
    }
    return reader;
}

From source file:eionet.gdem.validation.ValidationService.java

/**
/**//ww w. j  a v  a  2  s  . c  o m
 * Validate XML. If schema is null, then read the schema or DTD from the header of XML. If schema or DTD is defined, then ignore
 * the defined schema or DTD.
 *
 * @param srcStream XML file as InputStream to be validated.
 * @param schema XML Schema URL.
 * @return Validation result as HTML snippet.
 * @throws DCMException in case of unknnown system error.
 */
public String validateSchema(InputStream srcStream, String schema) throws DCMException {

    String result = "";
    boolean isDTD = false;
    boolean isBlocker = false;

    if (Utils.isNullStr(schema)) {
        schema = null;
    }

    try {

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

        reader.setErrorHandler(errHandler);
        XmlconvCatalogResolver catalogResolver = new XmlconvCatalogResolver();
        reader.setEntityResolver(catalogResolver);

        // make parser to validate
        reader.setFeature("http://xml.org/sax/features/validation", true);
        reader.setFeature("http://apache.org/xml/features/validation/schema", true);
        reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);

        reader.setFeature("http://xml.org/sax/features/namespaces", true);
        reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
        reader.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false);

        InputAnalyser inputAnalyser = new InputAnalyser();
        inputAnalyser.parseXML(uriXml);
        String namespace = inputAnalyser.getSchemaNamespace();

        // if schema is not in the parameter, then sniff it from the header of xml
        if (schema == null) {
            schema = inputAnalyser.getSchemaOrDTD();
            isDTD = inputAnalyser.isDTD();
        } else {
            // if the given schema ends with dtd, then don't do schema validation
            isDTD = schema.endsWith("dtd");
        }

        // schema is already given as a parameter. Read the default namespace from XML file and set external schema.
        if (schema != null) {
            if (!isDTD) {
                if (Utils.isNullStr(namespace)) {
                    // XML file does not have default namespace
                    setNoNamespaceSchemaProperty(reader, schema);
                } else {
                    setNamespaceSchemaProperty(reader, namespace, schema);
                }
            } else {
                // validate against DTD
                setLocalSchemaUrl(schema);
                LocalEntityResolver localResolver = new LocalEntityResolver(schema, getValidatedSchema());
                reader.setEntityResolver(localResolver);
            }
        } else {
            return validationFeedback.formatFeedbackText(
                    "Could not validate XML file. Unable to locate XML Schema reference.",
                    QAFeedbackType.WARNING, isBlocker);
        }
        // if schema is not available, then do not parse the XML and throw error
        if (!Utils.resourceExists(getValidatedSchema())) {
            return validationFeedback.formatFeedbackText(
                    "Failed to read schema document from the following URL: " + getValidatedSchema(),
                    QAFeedbackType.ERROR, isBlocker);
        }
        Schema schemaObj = schemaManager.getSchema(getOriginalSchema());
        if (schemaObj != null) {
            isBlocker = schemaObj.isBlocker();
        }
        validationFeedback.setSchema(getOriginalSchema());
        InputSource is = new InputSource(srcStream);
        reader.parse(is);

    } catch (SAXParseException se) {
        return validationFeedback.formatFeedbackText("Document is not well-formed. Column: "
                + se.getColumnNumber() + "; line:" + se.getLineNumber() + "; " + se.getMessage(),
                QAFeedbackType.ERROR, isBlocker);
    } catch (IOException ioe) {
        return validationFeedback.formatFeedbackText(
                "Due to an IOException, the parser could not check the document. " + ioe.getMessage(),
                QAFeedbackType.ERROR, isBlocker);
    } catch (Exception e) {
        Exception se = e;
        if (e instanceof SAXException) {
            se = ((SAXException) e).getException();
        }
        if (se != null) {
            se.printStackTrace(System.err);
        } else {
            e.printStackTrace(System.err);
        }
        return validationFeedback.formatFeedbackText(
                "The parser could not check the document. " + e.getMessage(), QAFeedbackType.ERROR, isBlocker);
    }

    validationFeedback.setValidationErrors(getErrorList());
    result = validationFeedback.formatFeedbackText(isBlocker);

    // validation post-processor
    QAResultPostProcessor postProcessor = new QAResultPostProcessor();
    result = postProcessor.processQAResult(result, schema);
    warningMessage = postProcessor.getWarningMessage(schema);

    return result;
}

From source file:com.ewhoxford.android.bloodpressure.ghealth.gdata.GDataHealthClient.java

@Override
public List<Result> retrieveResults()
        throws AuthenticationException, InvalidProfileException, ServiceException {

    if (authToken == null) {
        throw new IllegalStateException("authToken must not be null");
    }/* www  . j  av  a  2  s .  c o m*/

    if (profileId == null) {
        throw new IllegalStateException("profileId must not be null.");
    }

    String url = service.getBaseURL() + "/profile/ui/" + profileId + "/-/labtest";
    InputStream istream = retreiveData(url);

    HealthGDataContentHandler ccrHandler = new HealthGDataContentHandler();
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        XMLReader xr = sp.getXMLReader();
        xr.setContentHandler(ccrHandler);
        xr.parse(new InputSource(istream));
    } catch (ParserConfigurationException e) {
        throw new ServiceException(e);
    } catch (SAXException e) {
        throw new ServiceException(e);
    } catch (IOException e) {
        throw new ServiceException(e);
    } finally {
        if (istream != null) {
            try {
                istream.close();
            } catch (IOException e) {
                throw new ServiceException(e);
            }
        }
    }

    return ccrHandler.getResults();
}

From source file:net.smart_json_database.JSONDatabase.java

private JSONDatabase(Context context, String configurationName) throws InitJSONDatabaseExcepiton {

    AssetManager assetManager = context.getAssets();
    InputStream stream = null;//w w  w .j  a v a2 s  .com

    String configXML = null;
    try {
        configXML = configurationName + ".xml";
        stream = assetManager.open(configXML);

    } catch (IOException e) {
        throw new InitJSONDatabaseExcepiton("Could not load asset " + configXML);
    } finally {
        if (stream != null) {

            SAXParserFactory factory = SAXParserFactory.newInstance();
            XMLConfigHandler handler = new XMLConfigHandler();
            SAXParser saxparser;
            try {
                saxparser = factory.newSAXParser();
                saxparser.parse(stream, handler);
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                throw new InitJSONDatabaseExcepiton("Parser-Error while reading the " + configXML, e);
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                throw new InitJSONDatabaseExcepiton("SAX-Error while reading the " + configXML, e);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                throw new InitJSONDatabaseExcepiton("IO-Error while reading the " + configXML, e);
            }

            mDbName = handler.getDbName();

            if (Util.IsNullOrEmpty(mDbName))
                throw new InitJSONDatabaseExcepiton("db name is empty check the xml configuration");

            mDbVersion = handler.getDbVersion();

            if (mDbVersion < 1)
                throw new InitJSONDatabaseExcepiton(
                        "db version must be 1 or greater -  check the xml configuration");

            mUpgradeClassPath = handler.getUpgradeClass();

            if (!Util.IsNullOrEmpty(mUpgradeClassPath)) {
                try {
                    Class<?> x = Class.forName(mUpgradeClassPath);
                    dbUpgrade = (IUpgrade) x.newInstance();
                } catch (Exception e) {
                }
            }

            dbHelper = new DBHelper(context, mDbName, mDbVersion);
            listeners = new ArrayList<IDatabaseChangeListener>();
            tags = new HashMap<String, Integer>();
            invertedTags = new HashMap<Integer, String>();
            updateTagMap();

        } else {
            throw new InitJSONDatabaseExcepiton(configXML + " is empty");
        }
    }
}

From source file:com.epam.wilma.test.client.HttpRequestSender.java

private InputStream compress(final InputStream source) {
    try {/*from   w  ww  . j ava  2 s  .  c  om*/
        OutputStream fis = new ByteArrayOutputStream();
        SAXDocumentSerializer saxDocumentSerializer = new SAXDocumentSerializer();
        saxDocumentSerializer.setOutputStream(fis);
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setNamespaceAware(true);
        SAXParser saxParser = saxParserFactory.newSAXParser();
        saxParser.parse(source, saxDocumentSerializer);
        return new ByteArrayInputStream(((ByteArrayOutputStream) fis).toByteArray());
    } catch (ParserConfigurationException e) {
        throw new SystemException("error", e);
    } catch (SAXException e) {
        throw new SystemException("error", e);
    } catch (IOException e) {
        throw new SystemException("error", e);
    }
}