Example usage for org.xml.sax InputSource InputSource

List of usage examples for org.xml.sax InputSource InputSource

Introduction

In this page you can find the example usage for org.xml.sax InputSource InputSource.

Prototype

public InputSource(Reader characterStream) 

Source Link

Document

Create a new input source with a character stream.

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser parser = null;// w  w  w  .ja  va2s .c o m
    spf.setNamespaceAware(true);
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        spf.setSchema(sf.newSchema(new SAXSource(new InputSource(new StringReader(schemaString)))));

        parser = spf.newSAXParser();
    } catch (SAXException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    } catch (ParserConfigurationException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
    MySAXHandler handler = new MySAXHandler();
    System.out.println(schemaString);
    parser.parse(new InputSource(new StringReader(xmlString)), handler);
}

From source file:SAXDemo.java

/** The main method sets things up for parsing */
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {
    // Create a JAXP "parser factory" for creating SAX parsers
    javax.xml.parsers.SAXParserFactory spf = SAXParserFactory.newInstance();

    // Configure the parser factory for the type of parsers we require
    spf.setValidating(false); // No validation required

    // Now use the parser factory to create a SAXParser object
    // Note that SAXParser is a JAXP class, not a SAX class
    javax.xml.parsers.SAXParser sp = spf.newSAXParser();

    // Create a SAX input source for the file argument
    org.xml.sax.InputSource input = new InputSource(new FileReader(args[0]));

    // Give the InputSource an absolute URL for the file, so that
    // it can resolve relative URLs in a <!DOCTYPE> declaration, e.g.
    input.setSystemId("file://" + new File(args[0]).getAbsolutePath());

    // Create an instance of this class; it defines all the handler methods
    SAXDemo handler = new SAXDemo();

    // Finally, tell the parser to parse the input and notify the handler
    sp.parse(input, handler);/*from   w w  w .  j a v a 2  s.  c  om*/

    // Instead of using the SAXParser.parse() method, which is part of the
    // JAXP API, we could also use the SAX1 API directly. Note the
    // difference between the JAXP class javax.xml.parsers.SAXParser and
    // the SAX1 class org.xml.sax.Parser
    //
    // org.xml.sax.Parser parser = sp.getParser(); // Get the SAX parser
    // parser.setDocumentHandler(handler); // Set main handler
    // parser.setErrorHandler(handler); // Set error handler
    // parser.parse(input); // Parse!
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String xml = "<?xml version='1.0'?><test><test2></test2></test>";
    String schemaString = //
            "<?xml version='1.0'?>"//
                    + "<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' elementFormDefault='unqualified' attributeFormDefault='unqualified'>"//
                    + "<xsd:element name='test' type='Test'/>"//
                    + "<xsd:element name='test2' type='Test2'/>"//
                    + "<xsd:complexType name='Test'>"//
                    + "<xsd:sequence>"//
                    + "<xsd:element ref='test2' minOccurs='1' maxOccurs='unbounded'/>"//
                    + "</xsd:sequence>"//
                    + "</xsd:complexType>"//
                    + "<xsd:simpleType name='Test2'>"//
                    + "<xsd:restriction base='xsd:string'><xsd:minLength value='1'/></xsd:restriction>"//
                    + "</xsd:simpleType>"//
                    + "</xsd:schema>";

    Source schemaSource = new StreamSource(new StringReader(schemaString));
    Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaSource);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);// ww  w  . j av a 2  s. c o m
    factory.setSchema(schema);
    SAXParser parser = factory.newSAXParser();
    MyContentHandler handler = new MyContentHandler();
    parser.parse(new InputSource(new StringReader(xml)), handler);

}

From source file:MainClass.java

public static void main(String args[]) {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setValidating(true); // and validating parser feaures
    builderFactory.setIgnoringElementContentWhitespace(true);

    DocumentBuilder builder = null;
    try {//from w w w  . j a v a2  s.c  om
        builder = builderFactory.newDocumentBuilder(); // Create the parser
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    Document xmlDoc = null;

    try {
        xmlDoc = builder.parse(new InputSource(new StringReader(xmlString)));

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

    } catch (IOException e) {
        e.printStackTrace();
    }
    DocumentType doctype = xmlDoc.getDoctype();
    if (doctype == null) {
        System.out.println("DOCTYPE is null");
    } else {
        System.out.println("DOCTYPE node:\n" + doctype.getInternalSubset());
    }

    System.out.println("\nDocument body contents are:");
    listNodes(xmlDoc.getDocumentElement(), ""); // Root element & children
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser parser = null;/*from   w  w w . j  a  v a2  s  .  co m*/
    spf.setNamespaceAware(true);
    spf.setValidating(true);
    try {
        spf.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
        parser = spf.newSAXParser();
        System.out.println("Parser object is: " + parser);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    MySAXHandler handler = new MySAXHandler();
    parser.parse(new InputSource(new StringReader(xmlString)), handler);
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser parser = null;//from   w w w .  j a  v a 2 s.co  m
    spf.setNamespaceAware(true);
    spf.setValidating(true);
    try {
        spf.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
        parser = spf.newSAXParser();
        System.out.println("Parser object is: " + parser);
    } catch (SAXException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    } catch (ParserConfigurationException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }

    MySAXHandler handler = new MySAXHandler();
    parser.parse(new InputSource(new StringReader(xmlString)), handler);
}

From source file:de.zib.gndms.gritserv.tests.EncTest.java

public static void main(String[] args) throws Exception {

    //        String delfac = "https://130.73.72.106:8443/wsrf/services/DelegationFactoryService";

    //       GlobusCredential cred = DelegationAux.findCredential( null );
    //       EndpointReferenceType epr = DelegationAux.createProxy( delfac, cred );

    String eprs = "<DelegatedEPR xsi:type=\"ns1:EndpointReferenceType\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns1=\"http://schemas.xmlsoap.org/ws/2004/03/addressing\">"
            + "<ns1:Address xsi:type=\"ns1:AttributedURI\">https://130.73.72.106:8443/wsrf/services/DelegationService</ns1:Address>"
            + "<ns1:ReferenceProperties xsi:type=\"ns1:ReferencePropertiesType\">"
            + "<ns1:DelegationKey xmlns:ns1=\"http://www.globus.org/08/2004/delegationService\">e54cb3e0-f834-11dd-93ce-a15e7f2269a5</ns1:DelegationKey>"
            + "</ns1:ReferenceProperties>"
            + "<ns1:ReferenceParameters xsi:type=\"ns1:ReferenceParametersType\"/>" + "</DelegatedEPR>";

    InputSource is = new InputSource(new StringReader(eprs));
    EndpointReferenceType epr = (EndpointReferenceType) ObjectDeserializer.deserialize(is,
            EndpointReferenceType.class);
    fieldTest(epr);/*from  w w w .  j a v  a2 s.co m*/

}

From source file:FragmentContentHandler.java

public static void main(String[] args) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();

    xr.setContentHandler(new FragmentContentHandler(xr));
    xr.parse(new InputSource(new FileInputStream("input.xml")));
}

From source file:org.alfresco.util.xml.SchemaHelper.java

public static void main(String... args) {
    if (args.length < 2 || !args[0].startsWith("--compile-xsd=") && !args[1].startsWith("--output-dir=")) {
        System.out.println("Usage: SchemaHelper --compile-xsd=<URL> --output-dir=<directory>");
        System.exit(1);/*w w w . j  a v  a2s .  c o  m*/
    }
    final String urlStr = args[0].substring(14);
    if (urlStr.length() == 0) {
        System.out.println("Usage: SchemaHelper --compile-xsd=<URL> --output-dir=<directory>");
        System.exit(1);
    }
    final String dirStr = args[1].substring(13);
    if (dirStr.length() == 0) {
        System.out.println("Usage: SchemaHelper --compile-xsd=<URL> --output-dir=<directory>");
        System.exit(1);
    }
    try {
        URL url = ResourceUtils.getURL(urlStr);
        File dir = new File(dirStr);
        if (!dir.exists() || !dir.isDirectory()) {
            System.out.println("Output directory not found: " + dirStr);
            System.exit(1);
        }

        ErrorListener errorListener = new ErrorListener() {
            public void warning(SAXParseException e) {
                System.out.println("WARNING: " + e.getMessage());
            }

            public void info(SAXParseException e) {
                System.out.println("INFO: " + e.getMessage());
            }

            public void fatalError(SAXParseException e) {
                handleException(urlStr, e);
            }

            public void error(SAXParseException e) {
                handleException(urlStr, e);
            }
        };

        SchemaCompiler compiler = XJC.createSchemaCompiler();
        compiler.setErrorListener(errorListener);
        compiler.parseSchema(new InputSource(url.toExternalForm()));
        S2JJAXBModel model = compiler.bind();
        if (model == null) {
            System.out.println("Failed to produce binding model for URL " + urlStr);
            System.exit(1);
        }
        JCodeModel codeModel = model.generateCode(null, errorListener);
        codeModel.build(dir);
    } catch (Throwable e) {
        handleException(urlStr, e);
        System.exit(1);
    }
}

From source file:ebay.Ebay.java

/**
 * @param args the command line arguments
 *//*from  w w  w .j a  va 2  s . c o m*/
public static void main(String[] args) {
    HttpClient client = null;
    HttpResponse response = null;
    BufferedReader rd = null;
    Document doc = null;
    String xml = "";
    EbayDAO<Producto> db = new EbayDAO<>(Producto.class);
    String busqueda;

    while (true) {
        busqueda = JOptionPane.showInputDialog(null, "ingresa una busqueda");
        if (busqueda != null) {
            busqueda = busqueda.replaceAll(" ", "%20");
            try {
                client = new DefaultHttpClient();
                /*
                 peticion GET
                 */
                HttpGet request = new HttpGet("http://open.api.ebay.com/shopping?" + "callname=FindPopularItems"
                        + "&appid=student11-6428-4bd4-ac0d-6ed9d84e345" + "&version=517&QueryKeywords="
                        + busqueda + "&siteid=0" + "&responseencoding=XML");
                /*
                 se ejecuta la peticion GET
                 */
                response = client.execute(request);
                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                /*
                 comienza la lectura de la respuesta a la peticion GET
                 */
                String line;
                while ((line = rd.readLine()) != null) {
                    xml += line + "\n";
                }
            } catch (IOException ex) {
                Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex);
            }

            /*
             creamos nuestro documentBulder(documento constructor) y obtenemos 
             nuestro objeto documento apartir de documentBuilder
             */
            try {
                DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                doc = documentBuilder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));
            } catch (ParserConfigurationException | SAXException | IOException ex) {
                Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex);
            }

            Element raiz = doc.getDocumentElement();
            if (raiz == null) {
                System.exit(0);
            }
            if (raiz.getElementsByTagName("Ack").item(0).getTextContent().equals("Success")) {
                NodeList array = raiz.getElementsByTagName("ItemArray").item(0).getChildNodes();
                for (int i = 0; i < array.getLength(); ++i) {
                    Node n = array.item(i);

                    if (n.getNodeType() != Node.TEXT_NODE) {
                        Producto p = new Producto();
                        if (((Element) n).getElementsByTagName("ItemID").item(0) != null)
                            p.setId(new Long(
                                    ((Element) n).getElementsByTagName("ItemID").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("EndTime").item(0) != null)
                            p.setEndtime(
                                    ((Element) n).getElementsByTagName("EndTime").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch").item(0) != null)
                            p.setViewurl(((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch")
                                    .item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("ListingType").item(0) != null)
                            p.setListingtype(
                                    ((Element) n).getElementsByTagName("ListingType").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("GalleryURL").item(0) != null)
                            p.setGalleryurl(
                                    ((Element) n).getElementsByTagName("GalleryURL").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("PrimaryCategoryID").item(0) != null)
                            p.setPrimarycategoryid(new Integer(((Element) n)
                                    .getElementsByTagName("PrimaryCategoryID").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("PrimaryCategoryName").item(0) != null)
                            p.setPrimarycategoryname(((Element) n).getElementsByTagName("PrimaryCategoryName")
                                    .item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("BidCount").item(0) != null)
                            p.setBidcount(new Integer(
                                    ((Element) n).getElementsByTagName("BidCount").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ConvertedCurrentPrice").item(0) != null)
                            p.setConvertedcurrentprice(new Double(((Element) n)
                                    .getElementsByTagName("ConvertedCurrentPrice").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ListingStatus").item(0) != null)
                            p.setListingstatus(((Element) n).getElementsByTagName("ListingStatus").item(0)
                                    .getTextContent());
                        if (((Element) n).getElementsByTagName("TimeLeft").item(0) != null)
                            p.setTimeleft(
                                    ((Element) n).getElementsByTagName("TimeLeft").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("Title").item(0) != null)
                            p.setTitle(((Element) n).getElementsByTagName("Title").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("ShippingServiceCost").item(0) != null)
                            p.setShippingservicecost(new Double(((Element) n)
                                    .getElementsByTagName("ShippingServiceCost").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ShippingType").item(0) != null)
                            p.setShippingtype(((Element) n).getElementsByTagName("ShippingType").item(0)
                                    .getTextContent());
                        if (((Element) n).getElementsByTagName("WatchCount").item(0) != null)
                            p.setWatchcount(new Integer(
                                    ((Element) n).getElementsByTagName("WatchCount").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ListedShippingServiceCost").item(0) != null)
                            p.setListedshippingservicecost(
                                    new Double(((Element) n).getElementsByTagName("ListedShippingServiceCost")
                                            .item(0).getTextContent()));
                        try {
                            db.insert(p);
                        } catch (Exception e) {
                            db.update(p);
                        }
                    }
                }
            }
            Ventana.crear(xml);
        } else
            System.exit(0);

    }
}