Example usage for javax.xml.parsers SAXParserFactory newSAXParser

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

Introduction

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

Prototype


public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;

Source Link

Document

Creates a new instance of a SAXParser using the currently configured factory parameters.

Usage

From source file:de.uzk.hki.da.sb.Cli.java

/**
 * Copies the files listed in a SIP list to a single directory
 * /*w w  w.  j av  a2s.co  m*/
 * @param fileListFile The SIP list file
 * @return The path to the directory containing the files
 */
private String copySipListContentToFolder(File sipListFile) {

    CliProgressManager progressManager = new CliProgressManager();

    String tempFolderName = getTempFolderName();

    XMLReader xmlReader = null;
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        xmlReader = spf.newSAXParser().getXMLReader();
    } catch (Exception e) {
        logger.log("ERROR: Failed to create SAX parser", e);
        System.out.println("Fehler beim Einlesen der SIP-Liste: SAX-Parser konnte nicht erstellt werden.");
        return "";
    }
    xmlReader.setErrorHandler(new ErrorHandler() {

        @Override
        public void error(SAXParseException e) throws SAXException {
            throw new SAXException("Beim Einlesen der SIP-Liste ist ein Fehler aufgetreten.", e);
        }

        @Override
        public void fatalError(SAXParseException e) throws SAXException {
            throw new SAXException("Beim Einlesen der SIP-Liste ist ein schwerer Fehler aufgetreten.", e);
        }

        @Override
        public void warning(SAXParseException e) throws SAXException {
            logger.log("WARNING: Warning while parsing siplist", e);
            System.out.println("\nWarnung:\n" + e.getMessage());
        }
    });

    InputStream inputStream;
    try {
        inputStream = new FileInputStream(sipListFile);

        Reader reader = new InputStreamReader(inputStream, "UTF-8");
        Builder parser = new Builder(xmlReader);
        Document doc = parser.build(reader);
        reader.close();

        Element root = doc.getRootElement();
        Elements sipElements = root.getChildElements("sip");

        long files = 0;
        for (int i = 0; i < sipElements.size(); i++) {
            Elements fileElements = sipElements.get(i).getChildElements("file");
            if (fileElements != null)
                files += fileElements.size();
        }
        progressManager.setTotalSize(files);

        for (int i = 0; i < sipElements.size(); i++) {
            Element sipElement = sipElements.get(i);
            String sipName = sipElement.getAttributeValue("name");

            File tempDirectory = new File(tempFolderName + File.separator + sipName);
            if (tempDirectory.exists()) {
                FileUtils.deleteQuietly(new File(tempFolderName));
                System.out.println("\nDie SIP-Liste enthlt mehrere SIPs mit dem Namen " + sipName + ". "
                        + "Bitte vergeben Sie fr jedes SIP einen eigenen Namen.");
                return "";
            }
            tempDirectory.mkdirs();

            Elements fileElements = sipElement.getChildElements("file");

            for (int j = 0; j < fileElements.size(); j++) {
                Element fileElement = fileElements.get(j);
                String filepath = fileElement.getValue();

                File file = new File(filepath);
                if (!file.exists()) {
                    logger.log("ERROR: File " + file.getAbsolutePath() + " is referenced in siplist, "
                            + "but does not exist");
                    System.out.println("\nDie in der SIP-Liste angegebene Datei " + file.getAbsolutePath()
                            + " existiert nicht.");
                    FileUtils.deleteQuietly(new File(tempFolderName));
                    return "";
                }

                try {
                    if (file.isDirectory())
                        FileUtils.copyDirectoryToDirectory(file, tempDirectory);
                    else
                        FileUtils.copyFileToDirectory(file, tempDirectory);
                    progressManager.copyFilesFromListProgress();
                } catch (IOException e) {
                    logger.log("ERROR: Failed to copy file " + file.getAbsolutePath() + " to folder "
                            + tempDirectory.getAbsolutePath(), e);
                    System.out.println("\nDie in der SIP-Liste angegebene Datei " + file.getAbsolutePath()
                            + " konnte nicht kopiert werden.");
                    FileUtils.deleteQuietly(new File(tempFolderName));
                    return "";
                }
            }
        }
    } catch (Exception e) {
        logger.log("ERROR: Failed to read siplist " + sipListFile.getAbsolutePath(), e);
        System.out.println("\nBeim Lesen der SIP-Liste ist ein Fehler aufgetreten. ");
        return "";
    }

    return (new File(tempFolderName).getAbsolutePath());
}

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:net.lightbody.bmp.proxy.jetty.xml.XmlParser.java

/**
 * Construct/*from w w  w. j a  v  a 2s .  c o m*/
 */
public XmlParser() {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        boolean notValidating = Boolean.getBoolean("net.lightbody.bmp.proxy.jetty.xml.XmlParser.NotValidating");
        factory.setValidating(!notValidating);
        _parser = factory.newSAXParser();
        try {
            if (!notValidating)
                _parser.getXMLReader().setFeature("http://apache.org/xml/features/validation/schema", true);
        } catch (Exception e) {
            log.warn("Schema validation may not be supported");
            log.debug("", e);
            notValidating = true;
        }
        _parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", !notValidating);
        _parser.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", !notValidating);
        _parser.getXMLReader().setFeature("http://xml.org/sax/features/namespace-prefixes", !notValidating);
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
        throw new Error(e.toString());
    }
}

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

public void start() {
    //TODO: this method is too complex and should be refactored
    if (running)/*  w ww .jav  a  2s.  co  m*/
        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:com.connectsdk.device.netcast.NetcastHttpServer.java

public void start() {
    if (running)//from   ww w .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("Connect SDK", "got message body: " + body);

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

        PrintWriter out = null;

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

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

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

        NetcastPOSTRequestParser handler = new NetcastPOSTRequestParser();

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

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

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

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

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

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

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

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

            String newValue = "";

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

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

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

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

From source file:org.gege.caldavsyncadapter.caldav.CaldavFacade.java

private void parseXML(HttpResponse response, ContentHandler contentHandler)
        throws IOException, CaldavProtocolException {
    InputStream is = response.getEntity().getContent();
    /*BufferedReader bReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    String Content = "";//  w w  w .ja  v a  2s . c  om
    String Line = bReader.readLine();
            
    while (Line != null) {
       Content += Line;
       Line = bReader.readLine();
    }*/

    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setContentHandler(contentHandler);
        reader.parse(new InputSource(is));
    } catch (ParserConfigurationException e) {
        throw new AssertionError("ParserConfigurationException " + e.getMessage());
    } catch (IllegalStateException e) {
        throw new CaldavProtocolException(e.getMessage());
    } catch (SAXException e) {
        throw new CaldavProtocolException(e.getMessage());
    }
}

From source file:net.sf.firemox.xml.XmlParser.java

/**
 * Constructor.//from   w  ww. ja  v  a2  s.  c  om
 * 
 * @param validation
 *          validation flag.
 * @throws SAXException
 */
public XmlParser(boolean validation) throws SAXException {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(validation);
        parser = factory.newSAXParser();
        if (validation) {
            parser.setProperty(JAXP_SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI);
            parser.setProperty(JAXP_SCHEMA_SOURCE, MToolKit.getFile(MP_XML_SCHEMA));
        }
    } catch (Exception e) {
        throw new SAXException(e.toString());
    }
}

From source file:org.castor.jaxb.CastorUnmarshallerTest.java

/**
 * Tests the {@link CastorUnmarshaller#getUnmarshallerHandler()} method.
 *
 * @throws Exception if any error occurs during test
 *//*w  w  w .j av  a2 s.  c  om*/
@Test
public void testGetUnmarshallHandler() throws Exception {
    UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler();

    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);

    XMLReader xmlReader = spf.newSAXParser().getXMLReader();
    xmlReader.setContentHandler(unmarshallerHandler);
    xmlReader.parse(new InputSource(new StringReader(INPUT_XML)));

    Entity entity = (Entity) unmarshallerHandler.getResult();
    testEntity(entity);
}

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

public void parse() throws ReportedException {
    firstPassReadFile();/*  w w w.ja  v  a 2s  . c  o  m*/
    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: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  va2s. co m
        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);
    }
}