Example usage for org.xml.sax InputSource setCharacterStream

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

Introduction

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

Prototype

public void setCharacterStream(Reader characterStream) 

Source Link

Document

Set the character stream for this input source.

Usage

From source file:com.esri.gpt.server.openls.provider.services.geocode.GeocodeProvider.java

/**
 * Parses Geocode response/*  www  .  j  ava 2 s  .co m*/
 * @param sResponse
 * @return
 * @throws Throwable
 */
private ArrayList<GeocodedAddress> parseGeocodeResponse(String sResponse) throws Throwable {

    try {

        JSONObject jResponse = new JSONObject(sResponse);
        ArrayList<GeocodedAddress> gAddrList = new ArrayList<GeocodedAddress>();
        String xResponse = "<?xml version='1.0'?><response>" + org.json.XML.toString(jResponse) + "</response>";
        LOGGER.info("XML from JSON = " + xResponse);
        String addressName = "";

        Address respAddr = null;
        String street = "";
        String intStreet = "";
        String city = "";
        String state = "";
        String zip = "";
        String scoreStr = "";
        String x = "";
        String y = "";

        DocumentBuilderFactory xfactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = xfactory.newDocumentBuilder();
        InputSource inStream = new InputSource();
        inStream.setCharacterStream(new StringReader(xResponse));
        Document doc = db.parse(inStream);

        doc.getDocumentElement().normalize();
        LOGGER.info("Root element " + doc.getDocumentElement().getNodeName());
        NodeList nodeLst = doc.getElementsByTagName("candidates");
        LOGGER.info("Information of all candidates:");
        String country = "US";
        GeocodedAddress gAddr = null;
        for (int s = 0; s < nodeLst.getLength(); s++) {
            Node fstNode = nodeLst.item(s);
            gAddr = new GeocodedAddress();
            Element fstElmnt = (Element) fstNode;

            street = "";
            intStreet = "";
            city = "";
            state = "";
            zip = "";
            scoreStr = "";

            // LOCATION
            NodeList locationList = fstElmnt.getElementsByTagName("location");
            Element fstNmElmnt = (Element) locationList.item(0);
            NodeList nodeY = fstNmElmnt.getElementsByTagName("y");
            y = nodeY.item(0).getTextContent();
            LOGGER.info("y = " + y);
            NodeList nodeX = fstNmElmnt.getElementsByTagName("x");
            x = nodeX.item(0).getTextContent();
            LOGGER.info("x = " + x);

            gAddr.setCountry(country);
            gAddr.setX(x);
            gAddr.setY(y);

            // ADDRESS
            NodeList addressList = fstElmnt.getElementsByTagName("address");

            addressName = addressList.item(0).getTextContent();
            LOGGER.info("addressName = " + addressName);
            String[] addressParts = addressName.split(",");
            int count = 0;
            for (String addr : addressParts) {
                count++;
                if (count == 1) {
                    street = addr.trim();
                } else if (count == 2) {
                    city = addr.trim();
                } else if (count == 3) {
                    state = addr.trim();
                } else if (count == 4) {
                    zip = addr.trim();
                }
            }

            // SCORE
            NodeList scoreList = fstElmnt.getElementsByTagName("score");
            scoreStr = scoreList.item(0).getTextContent();
            LOGGER.info("score = " + scoreStr);

            // NOW ADD THIS RESULT TO THE OUTPUT pos
            respAddr = new Address();
            respAddr.setStreet(street);
            respAddr.setMunicipality(city);
            respAddr.setPostalCode(zip);
            respAddr.setCountrySubdivision(state);
            respAddr.setIntersection(intStreet);

            gAddr.setAddress(respAddr);
            gAddr.setScore(new Double(scoreStr));
            gAddrList.add(gAddr);
        }
        return gAddrList;
    } catch (Exception p_e) {
        Logger.getLogger("Caught Exception" + p_e.getLocalizedMessage());
    }
    return null;
}

From source file:com.marklogic.client.functionaltest.TestEvalXquery.java

@Test
public void testXqueryInvokeModuleRetDiffTypes() throws Exception {

    InputStream inputStream = null;
    DatabaseClient moduleClient = DatabaseClientFactory.newClient("localhost", restPort,
            (restServerName + "-modules"), "admin", "admin", Authentication.DIGEST);
    try {/*  w w  w .  j a  v  a  2s.c o  m*/
        inputStream = new FileInputStream(
                "src/test/java/com/marklogic/client/functionaltest/data/xquery-modules-with-diff-variable-types.xqy");
        InputStreamHandle ish = new InputStreamHandle();
        ish.set(inputStream);
        DocumentMetadataHandle metadataHandle = new DocumentMetadataHandle();
        metadataHandle.getPermissions().add("test-eval", Capability.UPDATE, Capability.READ,
                Capability.EXECUTE);
        DocumentManager dm = moduleClient.newDocumentManager();
        dm.write("/data/xquery-modules-with-diff-variable-types.xqy", metadataHandle, ish);
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(
                "<foo attr=\"attribute\"><?processing instruction?><!--comment-->test1</foo>"));
        Document doc = db.parse(is);
        ServerEvaluationCall evl = client.newServerEval()
                .modulePath("/data/xquery-modules-with-diff-variable-types.xqy");
        evl.addNamespace("test", "http://marklogic.com/test").addVariable("test:myString", "xml")
                .addVariable("myBool", true).addVariable("myInteger", (int) 31).addVariable("myDecimal", 10.5)
                .addVariable("myDouble", 1.0471975511966).addVariable("myFloat", 20)
                .addVariableAs("myXmlNode", new DOMHandle(doc)).addVariableAs("myNull", (String) null);
        EvalResultIterator evr = evl.eval();
        this.validateReturnTypes(evr);

    } catch (Exception e) {
        throw e;
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        moduleClient.release();
    }

}

From source file:com.marklogic.client.functionaltest.TestEvalJavaScript.java

@Test
public void testJSDifferentVariableTypesNoNullNodes() throws Exception {

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(
            new StringReader("<foo attr=\"attribute\"><?processing instruction?><!--comment-->test1</foo>"));
    Document doc = db.parse(is);//from   www  .ja v  a  2 s .c  o  m
    System.out.println(this.convertXMLDocumentToString(doc));
    try {
        String query1 = " var results = [];" + "var myString;" + "var myBool ;" + "var myInteger;"
                + "var myDecimal;" + "var myJsonObject;" + "var myNull;" + "var myJsonArray;"
                + "results.push(myString,myBool,myInteger,myDecimal,myJsonObject,myJsonArray,myNull);"
                + "xdmp.arrayValues(results)";

        ServerEvaluationCall evl = client.newServerEval().javascript(query1);
        evl.addVariable("myString", "xml").addVariable("myBool", true).addVariable("myInteger", (int) 31)
                .addVariable("myDecimal", (double) 1.0471975511966)
                .addVariableAs("myJsonObject",
                        new ObjectMapper().createObjectNode().put("foo", "v1").putNull("testNull"))
                .addVariableAs("myNull", (String) null)
                .addVariableAs("myJsonArray", new ObjectMapper().createArrayNode().add(1).add(2).add(3));
        System.out.println(new ObjectMapper().createObjectNode().nullNode().toString());
        EvalResultIterator evr = evl.eval();
        this.validateReturnTypes(evr);

    } catch (Exception e) {
        throw e;
    }
}

From source file:com.cloud.hypervisor.kvm.resource.LibvirtDomainXMLParser.java

public boolean parseDomainXML(String domXML) {
    DocumentBuilder builder;/*  w  w w .  j  a v  a 2s .  com*/
    try {
        builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(domXML));
        Document doc = builder.parse(is);

        Element rootElement = doc.getDocumentElement();

        desc = getTagValue("description", rootElement);

        Element devices = (Element) rootElement.getElementsByTagName("devices").item(0);
        NodeList disks = devices.getElementsByTagName("disk");
        for (int i = 0; i < disks.getLength(); i++) {
            Element disk = (Element) disks.item(i);
            String type = disk.getAttribute("type");
            DiskDef def = new DiskDef();
            if (type.equalsIgnoreCase("network")) {
                String diskFmtType = getAttrValue("driver", "type", disk);
                String diskCacheMode = getAttrValue("driver", "cache", disk);
                String diskPath = getAttrValue("source", "name", disk);
                String protocol = getAttrValue("source", "protocol", disk);
                String authUserName = getAttrValue("auth", "username", disk);
                String poolUuid = getAttrValue("secret", "uuid", disk);
                String host = getAttrValue("host", "name", disk);
                int port = Integer.parseInt(getAttrValue("host", "port", disk));
                String diskLabel = getAttrValue("target", "dev", disk);
                String bus = getAttrValue("target", "bus", disk);

                DiskDef.DiskFmtType fmt = null;
                if (diskFmtType != null) {
                    fmt = DiskDef.DiskFmtType.valueOf(diskFmtType.toUpperCase());
                }

                def.defNetworkBasedDisk(diskPath, host, port, authUserName, poolUuid, diskLabel,
                        DiskDef.DiskBus.valueOf(bus.toUpperCase()),
                        DiskDef.DiskProtocol.valueOf(protocol.toUpperCase()), fmt);
                def.setCacheMode(DiskDef.DiskCacheMode.valueOf(diskCacheMode.toUpperCase()));
            } else {
                String diskFmtType = getAttrValue("driver", "type", disk);
                String diskCacheMode = getAttrValue("driver", "cache", disk);
                String diskFile = getAttrValue("source", "file", disk);
                String diskDev = getAttrValue("source", "dev", disk);

                String diskLabel = getAttrValue("target", "dev", disk);
                String bus = getAttrValue("target", "bus", disk);
                String device = disk.getAttribute("device");

                if (type.equalsIgnoreCase("file")) {
                    if (device.equalsIgnoreCase("disk")) {
                        DiskDef.DiskFmtType fmt = null;
                        if (diskFmtType != null) {
                            fmt = DiskDef.DiskFmtType.valueOf(diskFmtType.toUpperCase());
                        }
                        def.defFileBasedDisk(diskFile, diskLabel, DiskDef.DiskBus.valueOf(bus.toUpperCase()),
                                fmt);
                    } else if (device.equalsIgnoreCase("cdrom")) {
                        def.defISODisk(diskFile);
                    }
                } else if (type.equalsIgnoreCase("block")) {
                    def.defBlockBasedDisk(diskDev, diskLabel, DiskDef.DiskBus.valueOf(bus.toUpperCase()));
                }
                if (diskCacheMode != null) {
                    def.setCacheMode(DiskDef.DiskCacheMode.valueOf(diskCacheMode.toUpperCase()));
                }
            }

            NodeList iotune = disk.getElementsByTagName("iotune");
            if ((iotune != null) && (iotune.getLength() != 0)) {
                String bytesReadRateStr = getTagValue("read_bytes_sec", (Element) iotune.item(0));
                if (bytesReadRateStr != null) {
                    Long bytesReadRate = Long.parseLong(bytesReadRateStr);
                    def.setBytesReadRate(bytesReadRate);
                }
                String bytesWriteRateStr = getTagValue("write_bytes_sec", (Element) iotune.item(0));
                if (bytesWriteRateStr != null) {
                    Long bytesWriteRate = Long.parseLong(bytesWriteRateStr);
                    def.setBytesWriteRate(bytesWriteRate);
                }
                String iopsReadRateStr = getTagValue("read_iops_sec", (Element) iotune.item(0));
                if (iopsReadRateStr != null) {
                    Long iopsReadRate = Long.parseLong(iopsReadRateStr);
                    def.setIopsReadRate(iopsReadRate);
                }
                String iopsWriteRateStr = getTagValue("write_iops_sec", (Element) iotune.item(0));
                if (iopsWriteRateStr != null) {
                    Long iopsWriteRate = Long.parseLong(iopsWriteRateStr);
                    def.setIopsWriteRate(iopsWriteRate);
                }
            }

            diskDefs.add(def);
        }

        NodeList nics = devices.getElementsByTagName("interface");
        for (int i = 0; i < nics.getLength(); i++) {
            Element nic = (Element) nics.item(i);

            String type = nic.getAttribute("type");
            String mac = getAttrValue("mac", "address", nic);
            String dev = getAttrValue("target", "dev", nic);
            String model = getAttrValue("model", "type", nic);
            String slot = StringUtils.removeStart(getAttrValue("address", "slot", nic), "0x");

            InterfaceDef def = new InterfaceDef();
            NodeList bandwidth = nic.getElementsByTagName("bandwidth");
            Integer networkRateKBps = 0;
            if ((bandwidth != null) && (bandwidth.getLength() != 0)) {
                Integer inbound = Integer
                        .valueOf(getAttrValue("inbound", "average", (Element) bandwidth.item(0)));
                Integer outbound = Integer
                        .valueOf(getAttrValue("outbound", "average", (Element) bandwidth.item(0)));
                if (inbound.equals(outbound)) {
                    networkRateKBps = inbound;
                }
            }
            if (type.equalsIgnoreCase("network")) {
                String network = getAttrValue("source", "network", nic);
                def.defPrivateNet(network, dev, mac, NicModel.valueOf(model.toUpperCase()), networkRateKBps);
            } else if (type.equalsIgnoreCase("bridge")) {
                String bridge = getAttrValue("source", "bridge", nic);
                def.defBridgeNet(bridge, dev, mac, NicModel.valueOf(model.toUpperCase()), networkRateKBps);
            } else if (type.equalsIgnoreCase("ethernet")) {
                String scriptPath = getAttrValue("script", "path", nic);
                def.defEthernet(dev, mac, NicModel.valueOf(model.toUpperCase()), scriptPath, networkRateKBps);
            }

            if (StringUtils.isNotBlank(slot)) {
                def.setSlot(Integer.parseInt(slot, 16));
            }

            interfaces.add(def);
        }

        NodeList ports = devices.getElementsByTagName("channel");
        for (int i = 0; i < ports.getLength(); i++) {
            Element channel = (Element) ports.item(i);

            String type = channel.getAttribute("type");
            String path = getAttrValue("source", "path", channel);
            String name = getAttrValue("target", "name", channel);
            String state = getAttrValue("target", "state", channel);

            ChannelDef def = null;
            if (!StringUtils.isNotBlank(state)) {
                def = new ChannelDef(name, ChannelDef.ChannelType.valueOf(type.toUpperCase()), new File(path));
            } else {
                def = new ChannelDef(name, ChannelDef.ChannelType.valueOf(type.toUpperCase()),
                        ChannelDef.ChannelState.valueOf(state.toUpperCase()), new File(path));
            }

            channels.add(def);
        }

        Element graphic = (Element) devices.getElementsByTagName("graphics").item(0);

        if (graphic != null) {
            String port = graphic.getAttribute("port");
            if (port != null) {
                try {
                    vncPort = Integer.parseInt(port);
                    if (vncPort != -1) {
                        vncPort = vncPort - 5900;
                    } else {
                        vncPort = null;
                    }
                } catch (NumberFormatException nfe) {
                    vncPort = null;
                }
            }
        }

        NodeList rngs = devices.getElementsByTagName("rng");
        for (int i = 0; i < rngs.getLength(); i++) {
            RngDef def = null;
            Element rng = (Element) rngs.item(i);
            String backendModel = getAttrValue("backend", "model", rng);
            String path = getTagValue("backend", rng);
            String bytes = getAttrValue("rate", "bytes", rng);
            String period = getAttrValue("rate", "period", rng);

            if (Strings.isNullOrEmpty(backendModel)) {
                def = new RngDef(path, Integer.parseInt(bytes), Integer.parseInt(period));
            } else {
                def = new RngDef(path, RngBackendModel.valueOf(backendModel.toUpperCase()),
                        Integer.parseInt(bytes), Integer.parseInt(period));
            }

            rngDefs.add(def);
        }

        NodeList watchDogs = devices.getElementsByTagName("watchdog");
        for (int i = 0; i < watchDogs.getLength(); i++) {
            WatchDogDef def = null;
            Element watchDog = (Element) watchDogs.item(i);
            String action = watchDog.getAttribute("action");
            String model = watchDog.getAttribute("model");

            if (Strings.isNullOrEmpty(model)) {
                continue;
            }

            if (Strings.isNullOrEmpty(action)) {
                def = new WatchDogDef(WatchDogModel.valueOf(model.toUpperCase()));
            } else {
                def = new WatchDogDef(WatchDogAction.valueOf(action.toUpperCase()),
                        WatchDogModel.valueOf(model.toUpperCase()));
            }

            watchDogDefs.add(def);
        }

        return true;
    } catch (ParserConfigurationException e) {
        s_logger.debug(e.toString());
    } catch (SAXException e) {
        s_logger.debug(e.toString());
    } catch (IOException e) {
        s_logger.debug(e.toString());
    }
    return false;
}

From source file:com.marklogic.client.functionaltest.TestEvalJavaScript.java

@Test(expected = IllegalArgumentException.class)
public void testJSDifferentVariableTypes() throws Exception {

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(
            new StringReader("<foo attr=\"attribute\"><?processing instruction?><!--comment-->test1</foo>"));
    Document doc = db.parse(is);/*from w ww  .j a v a 2s  . c  om*/
    System.out.println(this.convertXMLDocumentToString(doc));
    try {
        String query1 = " var results = [];" + "var myString;" + "var myBool ;" + "var myInteger;"
                + "var myDecimal;" + "var myJsonObject;" + "var myNull;" + "var myJsonArray;"
                + "var myJsonNull;"
                + "results.push(myString,myBool,myInteger,myDecimal,myJsonObject,myJsonArray,myNull,myJsonNull);"
                + "xdmp.arrayValues(results)";

        ServerEvaluationCall evl = client.newServerEval().javascript(query1);
        evl.addVariable("myString", "xml").addVariable("myBool", true).addVariable("myInteger", (int) 31)
                .addVariable("myDecimal", (double) 1.0471975511966)
                .addVariableAs("myJsonObject",
                        new ObjectMapper().createObjectNode().put("foo", "v1").putNull("testNull"))
                .addVariableAs("myNull", (String) null)
                .addVariableAs("myJsonArray", new ObjectMapper().createArrayNode().add(1).add(2).add(3))
                .addVariableAs("myJsonNull", new ObjectMapper().createObjectNode().nullNode());
        System.out.println(new ObjectMapper().createObjectNode().nullNode().toString());
        EvalResultIterator evr = evl.eval();
        this.validateReturnTypes(evr);

    } catch (Exception e) {
        throw e;
    }
}

From source file:com.marklogic.client.functionaltest.TestEvalJavaScript.java

@Test
public void testJSDifferentVariableTypesWithNulls() throws Exception {

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(
            new StringReader("<foo attr=\"attribute\"><?processing instruction?><!--comment-->test1</foo>"));
    Document doc = db.parse(is);/* w w w . ja v  a  2 s.co  m*/
    System.out.println(this.convertXMLDocumentToString(doc));
    try {
        String query1 = " var results = [];" + "var myString;" + "var myBool ;" + "var myInteger;"
                + "var myDecimal;" + "var myJsonObject;" + "var myNull;" + "var myJsonArray;"
                + "var myJsonNull;"
                + "results.push(myString,myBool,myInteger,myDecimal,myJsonObject,myJsonArray,myNull,myJsonNull);"
                + "xdmp.arrayValues(results)";

        ServerEvaluationCall evl = client.newServerEval().javascript(query1);
        evl.addVariable("myString", "xml").addVariable("myBool", true).addVariable("myInteger", (int) 31)
                .addVariable("myDecimal", (double) 1.0471975511966)
                .addVariableAs("myJsonObject",
                        new ObjectMapper().createObjectNode().put("foo", "v1").putNull("testNull"))
                .addVariableAs("myNull", (String) null)
                .addVariableAs("myJsonArray", new ObjectMapper().createArrayNode().add(1).add(2).add(3))
                .addVariableAs("myJsonNull", null);
        System.out.println(new ObjectMapper().createObjectNode().nullNode().toString());
        EvalResultIterator evr = evl.eval();
        this.validateReturnTypes(evr);

    } catch (Exception e) {
        throw e;
    }
}

From source file:net.sf.ginp.setup.SetupManagerImpl.java

/**
 * @throws SetupException if there's a problem reading the doc
 * note: don't be fooled, we can't report the path of the
 *       offending document because it is supplied as a Stream.
 * @throws IOException/*from w  w w. j a va 2 s  . c o m*/
 * @see net.sf.ginp.setup.SetupManager#testValidConfig(java.io.InputStream)
 */
public final Document testValidConfig(final InputStream stream) throws SetupException, IOException {
    String reader = GinpUtil.readBufferIntoMemory(stream);

    try {
        return validateConfig(new ByteArrayInputStream(reader.getBytes()));
    } catch (DocumentException d) {
        SAXReader read = new SAXReader(false);

        try {
            InputSource source = new InputSource();
            source.setCharacterStream(new StringReader(reader));

            String ginpFile = this.getClass().getResource("/net/sf/ginp/config/ginp.dtd").toExternalForm();
            ginpFile = ginpFile.substring(0, ginpFile.lastIndexOf("/") + 1);
            source.setSystemId(ginpFile);
            source.setPublicId("ginp.dtd");

            Document document = read.read(source);
            List list = document.selectNodes("/ginp/collection/users");
            list.addAll(document.selectNodes("/ginp/collection/admins"));

            Iterator iter = list.iterator();

            while (iter.hasNext()) {
                Element e = (Element) iter.next();
                String value = e.getText();
                String[] users = value.split(",");

                for (int x = 0; x < users.length; x++) {
                    if (users[x].length() == 0) {
                        continue;
                    }

                    Element element = e.addElement("username");
                    element.setText(users[x].trim());
                }

                e.setText("");
            }

            try {
                return validateConfig(new ByteArrayInputStream(document.asXML().getBytes()));
            } catch (DocumentException e) {
                //Some XML parsers don't support validation
                if (e.getMessage().indexOf("not supported") >= 0) {
                    log.warn("Validation Not Supported by your XML parser", e);

                    return document;
                } else {
                    log.error("Validation Error:", e);
                }

                throw e;
            }
        } catch (DocumentException e) {
            log.error("throwing new SetupException", e);
            throw new SetupException(GinpUtil.message(TROUBLE_PARSING), d);
        }
    }
}

From source file:com.marklogic.client.functionaltest.TestEvalXquery.java

@Test
public void testXqueryDifferentVariableTypes() throws Exception {

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(
            new StringReader("<foo attr=\"attribute\"><?processing instruction?><!--comment-->test1</foo>"));
    Document doc = db.parse(is);//  www  .  ja v  a  2  s.c o m
    String jsonNode = "{ \"a\" : {\"obj\": \"value\"}, \"b\" : \"s0\",\"c1\" : 1,\"c2\" : 2,\"d\" : null,\"f\" : true,\"g\" : [\"s1\", \"s2\", \"s3\" ]}";
    System.out.println(this.convertXMLDocumentToString(doc));
    try {
        String query1 = "declare namespace test=\"http://marklogic.com/test\";"
                + "declare variable $test:myString as xs:string external;"
                + "declare variable $myBool as xs:boolean external;"
                + "declare variable $myInteger as xs:integer external;"
                + "declare variable $myDecimal as xs:decimal external;"
                + "declare variable $myDouble as xs:double external;"
                + "declare variable $myFloat as xs:float external;"
                + "declare variable $myXmlNode as document-node() external;"
                + "declare variable $myNull  external;"
                + "( $test:myString, $myBool,$myInteger,$myDecimal,$myDouble,$myFloat, document{ ($myXmlNode) },"
                + "($myXmlNode)//comment(),($myXmlNode)//text(),($myXmlNode)//*,"
                + "($myXmlNode)/@attr, ($myXmlNode)//processing-instruction())";

        ServerEvaluationCall evl = client.newServerEval().xquery(query1);
        evl.addNamespace("test", "http://marklogic.com/test").addVariable("test:myString", "xml")
                .addVariable("myBool", true).addVariable("myInteger", (int) 31).addVariable("myDecimal", 10.5)
                .addVariable("myDouble", 1.0471975511966).addVariable("myFloat", 20)
                .addVariableAs("myXmlNode", new DOMHandle(doc)).addVariableAs("myNull", (String) null);
        EvalResultIterator evr = evl.eval();
        this.validateReturnTypes(evr);
        String query2 = "declare namespace test=\"http://marklogic.com/test\";"
                + "declare variable $myArray as json:array external;"
                + "declare variable $myObject as json:object external;"
                // +"declare variable $myJsonNode as xs:string external;"
                //+"($myArray,$myObject,xdmp:unquote($myJsonNode)/a,xdmp:unquote($myJsonNode)/b,xdmp:unquote($myJsonNode)/c1,"
                + "($myArray,$myObject)";
        //+"xdmp:unquote($myJsonNode)/d,xdmp:unquote($myJsonNode)/f,xdmp:unquote($myJsonNode)/g )";
        System.out.println(query2);
        evl = client.newServerEval().xquery(query2);
        evl.addVariableAs("myArray", new ObjectMapper().createArrayNode().add(1).add(2).add(3))
                .addVariableAs("myObject",
                        new ObjectMapper().createObjectNode().put("foo", "v1").putNull("testNull"))
                .addVariableAs("myXmlNode", new DOMHandle(doc)).addVariableAs("myNull", null);
        //.addVariableAs("myJsonNode", new StringHandle(jsonNode).withFormat(Format.JSON));
        evr = evl.eval();
        while (evr.hasNext()) {
            EvalResult er = evr.next();
            if (er.getType().equals(Type.JSON)) {
                JacksonHandle jh = new JacksonHandle();
                jh = er.get(jh);

                if (jh.get().isArray()) {
                    //                System.out.println("Type Array :"+jh.get().toString());
                    assertEquals("array value at index 0 ", 1, jh.get().get(0).asInt());
                    assertEquals("array value at index 1 ", 2, jh.get().get(1).asInt());
                    assertEquals("array value at index 2 ", 3, jh.get().get(2).asInt());
                } else if (jh.get().isObject()) {
                    System.out.println("Type Object :" + jh.get().toString());
                    if (jh.get().has("foo")) {
                        assertNull("this object also has null node", jh.get().get("testNull").textValue());
                    } else if (jh.get().has("obj")) {
                        assertEquals("Value of the object is ", "value", jh.get().get("obj").asText());
                    } else {
                        assertFalse("getting a wrong object ", true);
                    }

                } else if (jh.get().isNumber()) {
                    //                System.out.println("Type Number :"+jh.get().toString());
                    assertEquals("Number value", 1, jh.get().asInt());
                } else if (jh.get().isNull()) {
                    //                System.out.println("Type Null :"+jh.get().toString());
                    assertNull("Returned Null", jh.get().textValue());
                } else if (jh.get().isBoolean()) {
                    //                System.out.println("Type boolean :"+jh.get().toString());
                    assertTrue("Boolean value returned false", jh.get().asBoolean());
                } else {
                    //                System.out.println("Running into different types than expected");
                    assertFalse("Running into different types than expected", true);
                }

            } else if (er.getType().equals(Type.TEXTNODE)) {
                assertTrue("document contains", er.getAs(String.class).contains("s"));
                //             System.out.println("type txt node :"+er.getAs(String.class));
            } else {
                System.out.println("No corresponding type found for :" + er.getType());
            }
        }

    } catch (Exception e) {
        throw e;
    }
}

From source file:com.marklogic.client.functionaltest.TestEvalJavaScript.java

@Test
public void testJSReturningDifferentTypesOrder3fromModules() throws Exception {

    InputStream inputStream = null;
    DatabaseClient moduleClient = DatabaseClientFactory.newClient("localhost", restPort,
            (restServerName + "-modules"), "admin", "admin", Authentication.DIGEST);
    try {/*from www . jav  a  2s  .  c  o m*/
        inputStream = new FileInputStream(
                "src/test/java/com/marklogic/client/functionaltest/data/javascriptQueries.sjs");
        InputStreamHandle ish = new InputStreamHandle();
        ish.set(inputStream);
        DocumentMetadataHandle metadataHandle = new DocumentMetadataHandle();
        metadataHandle.getPermissions().add("test-js-eval", Capability.UPDATE, Capability.READ,
                Capability.EXECUTE);
        DocumentManager dm = moduleClient.newDocumentManager();
        dm.write("/data/javascriptQueries.sjs", metadataHandle, ish);
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(
                "<foo attr=\"attribute\"><?processing instruction?><!--comment-->test1</foo>"));
        Document doc = db.parse(is);
        ServerEvaluationCall evl = client.newServerEval().modulePath("/data/javascriptQueries.sjs");

        EvalResultIterator evr = evl.eval();
        while (evr.hasNext()) {
            EvalResult er = evr.next();
            if (er.getType().equals(Type.XML)) {
                DOMHandle dh = new DOMHandle();
                dh = er.get(dh);
                assertEquals("document has content", "<foo>test1</foo>", convertXMLDocumentToString(dh.get()));
            } else if (er.getType().equals(Type.JSON)) {
                JacksonHandle jh = new JacksonHandle();
                jh = er.get(jh);
                assertTrue("document has object?", jh.get().has("test"));
            } else if (er.getType().equals(Type.TEXTNODE)) {
                assertTrue("document contains", er.getAs(String.class).equals("This is a text document."));

            } else if (er.getType().equals(Type.BINARY)) {
                FileHandle fh = new FileHandle();
                fh = er.get(fh);
                assertEquals("files size", 2, fh.get().length());

            } else {
                System.out.println("Something went wrong");
            }
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        moduleClient.release();
    }
}

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

private void parseXmlString(String file) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {/* w  ww  .jav a2s .  co  m*/
        keepScreenOn.acquire();

        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        NewServerRssHandler handler = new NewServerRssHandler(this);
        xr.setContentHandler(handler);

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(file));
        xr.parse(is);
        server_lst = handler.getNewSrvs();
        get_apks = handler.getNewApks();

        keepScreenOn.release();

    } catch (IOException e) {
    } catch (SAXException e) {
    } catch (ParserConfigurationException e) {
    }
}