Package org.w3c.dom.ls

Examples of org.w3c.dom.ls.LSParser


     * @throws IOException For errors parsing the document.
     */
    public static Document streamToDom(final InputStream inputStream, final LSResourceResolver resourceResolver)
            throws IOException {
        final DOMImplementationLS impl = DomUtil.getDOMImplementation();
        final LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
        final DOMConfiguration domConfiguration = builder.getDomConfig();
        if (resourceResolver != null
                && domConfiguration.canSetParameter("resource-resolver", resourceResolver)) {
            domConfiguration.setParameter("resource-resolver", resourceResolver);
        }

        final LSInput lsInput = impl.createLSInput();
        lsInput.setByteStream(inputStream);

        final Document document = builder.parse(lsInput);
        return document;
    }
View Full Code Here


  }

  private Document getDocument(InputStream is) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    final DOMImplementationLS impl = (DOMImplementationLS)registry.getDOMImplementation("LS");
    final LSParser parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
    // we need to ignore whitespace here so the nodeToString() method will be able to indent it properly:
    parser.setFilter(new IgnoreWhitespaceFilter());
    LSInput domInput = impl.createLSInput();
    domInput.setByteStream(is);
    return parser.parse(domInput);
  }
View Full Code Here

        xml = xml.replaceAll("\\s*<", "<");
        xml = xml.replaceAll(">\\s*", ">");

        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS domLS = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSParser lsParser = domLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

        LSInput input = domLS.createLSInput();
        input.setStringData(xml);
        Document document = lsParser.parse(input);

        LSSerializer lsSerializer = domLS.createLSSerializer();
        lsSerializer.getDomConfig().setParameter("comments", Boolean.FALSE);
        lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
        return lsSerializer.writeToString(document);
View Full Code Here

           
            DOMImplementationLS impl = (DOMImplementationLS)DOMImplementationRegistry.newInstance().getDOMImplementation("LS");

            Assertion.verify(impl!=null, "domImplementation != null");

            LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS,
                                                       null);

            LSSerializer writer = impl.createLSSerializer();
            DOMConfiguration config = writer.getDomConfig();
            config.setParameter("namespaces",(namespaces)?Boolean.TRUE:Boolean.FALSE);
            config.setParameter("validate",Boolean.FALSE);
           
            //----------------------------
            // TEST: lookupPrefix
            //       isDefaultNamespace
            //       lookupNamespaceURI
            //----------------------------
            //System.out.println("TEST #1: lookupPrefix, isDefaultNamespace, lookupNamespaceURI, input: tests/dom/dom3/input.xml");
            {

                Document doc = builder.parseURI("tests/dom/dom3/input.xml");
                NodeList ls = doc.getElementsByTagName("a:elem_a");

                NodeImpl elem = (NodeImpl)ls.item(0);
                if (namespaces) {
                    //System.out.println("[a:elem_a].lookupPrefix('http://www.example.com', true) == null");
                    Assertion.verify(elem.lookupPrefix("http://www.example.com").equals("ns1"),
                                     "[a:elem_a].lookupPrefix(http://www.example.com)==null");


                    //System.out.println("[a:elem_a].isDefaultNamespace('http://www.example.com') == true");
                    Assertion.verify(elem.isDefaultNamespace("http://www.example.com") == true,
                                     "[a:elem_a].isDefaultNamespace(http://www.example.com)==true");


                    //System.out.println("[a:elem_a].lookupPrefix('http://www.example.com', false) == ns1");
                    Assertion.verify(elem.lookupPrefix("http://www.example.com").equals("ns1"),
                                     "[a:elem_a].lookupPrefix(http://www.example.com)==ns1");


                    Assertion.verify(elem.lookupNamespaceURI("xsi").equals("http://www.w3.org/2001/XMLSchema-instance"),
                                     "[a:elem_a].lookupNamespaceURI('xsi') == 'http://www.w3.org/2001/XMLSchema-instance'" );

                } else {
                    Assertion.verify( elem.lookupPrefix("http://www.example.com") == null,"lookupPrefix(http://www.example.com)==null");
                }

                ls = doc.getElementsByTagName("bar:leaf");
                elem = (NodeImpl)ls.item(0);
                Assertion.verify(elem.lookupPrefix("url1:").equals("foo"),
                                 "[bar:leaf].lookupPrefix('url1:', false) == foo");
                //System.out.println("[bar:leaf].lookupPrefix('url1:', false) == "+ );

                //System.out.println("==>Create b:baz with namespace 'b:' and xmlns:x='b:'");
                ls = doc.getElementsByTagName("baz");
                elem = (NodeImpl)ls.item(0);
                ls = doc.getElementsByTagName("elem8");
                elem = (NodeImpl)ls.item(0);
                Element e1 = doc.createElementNS("b:","p:baz");
                e1.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:x", "b:");
                elem.appendChild(e1);


                Assertion.verify(((NodeImpl)e1).lookupPrefix("b:").equals("p"),
                                 "[p:baz].lookupPrefix('b:', false) == p");



                //System.out.println("[p:baz].lookupPrefix('b:', false) == "+ ((NodeImpl)e1).lookupPrefix("b:",false));

                Assertion.verify(elem.lookupNamespaceURI("xsi").equals("http://www.w3.org/2001/XMLSchema-instance"),
                                 "[bar:leaf].lookupNamespaceURI('xsi') == 'http://www.w3.org/2001/XMLSchema-instance'" );

           
            }

            //************************
            //* Test normalizeDocument()
            //************************
            //System.out.println("TEST #2: normalizeDocumention() - 3 errors, input: tests/dom/dom3/schema.xml");
            {
                errorCounter = 0;
                config = builder.getDomConfig();
                config.setParameter("error-handler",errorHandler);
                config.setParameter("validate", Boolean.TRUE);
                Document core = builder.parseURI("tests/dom/dom3/schema.xml");
                Assertion.verify(errorCounter == 0, "No errors should be reported");
               
                errorCounter = 0;   
                NodeList ls2 = core.getElementsByTagName("decVal");
                Element testElem = (Element)ls2.item(0);
                testElem.removeAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns");

                ls2 = core.getElementsByTagName("v02:decVal");
                testElem = (Element)ls2.item(0);
                testElem.setPrefix("myPrefix");
                Element root = core.getDocumentElement();

                Element newElem = core.createElementNS(null, "decVal");
                String data="4.5";
                if (true) {
                        data = "string";
                }
                newElem.appendChild(core.createTextNode(data));
                root.insertBefore(newElem, testElem);

                newElem = core.createElementNS(null,  "notInSchema");
                newElem.appendChild(core.createTextNode("added new element"));
                root.insertBefore(newElem, testElem);

                root.appendChild(core.createElementNS("UndefinedNamespace", "NS1:foo"));
                config = core.getDomConfig();
                config.setParameter("error-handler",errorHandler);
                config.setParameter("validate", Boolean.TRUE);
                config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema");
                core.normalizeDocument();
                Assertion.verify(errorCounter == 3, "3 errors should be reported");
       
                errorCounter = 0;
                config.setParameter("validate", Boolean.FALSE);
                config.setParameter("comments", Boolean.FALSE);
                core.normalizeDocument();
                Assertion.verify(errorCounter == 0, "No errors should be reported");


                config = builder.getDomConfig();
                config.setParameter("validate", Boolean.FALSE);
               
            }


            //************************
            //* Test normalizeDocument()
            //************************
            // System.out.println("TEST #3: normalizeDocumention() + psvi, input: data/personal-schema.xml");
            {
                errorCounter = 0;
                config = builder.getDomConfig();
                config.setParameter("error-handler",errorHandler);
                config.setParameter("validate", Boolean.TRUE);
                config.setParameter("psvi", Boolean.TRUE);
                Document core = builder.parseURI("data/personal-schema.xml");
                Assertion.verify(errorCounter == 0, "No errors should be reported");

                NodeList ls2 = core.getElementsByTagName("person");

                Element testElem = (Element)ls2.item(0);
                Assertion.verify(((ElementPSVI)testElem).getElementDeclaration().getName().equals("person"), "testElem decl");
                Element e1 = core.createElementNS(null, "person");
               
                core.getDocumentElement().appendChild(e1);
                e1.setAttributeNS(null, "id", "newEmp");
                Element e2 = core.createElementNS(null, "name");
                e2.appendChild(core.createElementNS(null, "family"));
                e2.appendChild(core.createElementNS(null, "given"));
                e1.appendChild(e2);
                e1.appendChild(core.createElementNS(null, "email"));
                Element e3 = core.createElementNS(null, "link");
                e3.setAttributeNS(null, "manager", "Big.Boss");
                e1.appendChild(e3);

                testElem.removeAttributeNode(testElem.getAttributeNodeNS(null, "contr"));
                NamedNodeMap map = testElem.getAttributes();
                config = core.getDomConfig();
                errorCounter = 0;
                config.setParameter("psvi", Boolean.TRUE);
                config.setParameter("error-handler",errorHandler);
                config.setParameter("validate", Boolean.TRUE);
                config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema");
                core.normalizeDocument();
                Assertion.verify(errorCounter == 0, "No errors should be reported");
                Assertion.verify(((ElementPSVI)e1).getElementDeclaration().getName().equals("person"), "e1 decl");             
               
                config = builder.getDomConfig();
                config.setParameter("validate", Boolean.FALSE);
               

            }

            //************************
            //* Test normalizeDocument(): core tests
            //************************
            // System.out.println("TEST #4: normalizeDocument() core");
            {

                // check that namespace normalization algorithm works correctly
                Document doc= new DocumentImpl();
                Element root = doc.createElementNS("http://www.w3.org/1999/XSL/Transform", "xsl:stylesheet");
                doc.appendChild(root);
                root.setAttributeNS("http://attr1", "xsl:attr1","");

                Element child1 = doc.createElementNS("http://child1", "NS2:child1");
                child1.setAttributeNS("http://attr2", "NS2:attr2","");
                root.appendChild(child1);

                Element child2 = doc.createElementNS("http://child2","NS4:child2");
                child2.setAttributeNS("http://attr3","attr3", "");
                root.appendChild(child2);

                Element child3 = doc.createElementNS("http://www.w3.org/1999/XSL/Transform","xsl:child3");
                child3.setAttributeNS("http://a1","attr1", "");
                child3.setAttributeNS("http://a2","xsl:attr2", "");
                child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:a1", "http://a1");
                child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", "http://a2");
               
                Element child4 = doc.createElementNS(null, "child4");
                child4.setAttributeNS("http://a1", "xsl:attr1", "");
                child4.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "default");
                child3.appendChild(child4);
                root.appendChild(child3);

                doc.normalizeDocument();
               
                //
                // assertions
                //

                // xsl:stylesheet should include 2 namespace declarations
                String name = root.getNodeName();
                Assertion.verify(name.equals("xsl:stylesheet"), "xsl:stylesheet");

                String value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl");
                Assertion.verify(value!=null, "xmlns:xsl != null");
                Assertion.verify(value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value);
               
                value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1");

                Assertion.verify(value!=null &&
                                 value.equals("http://attr1"), "xmlns:NS1="+value);

                // child includes 2 namespace decls

                Assertion.verify(child1.getNodeName().equals("NS2:child1"), "NS2:child1");
                value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS2");
                Assertion.verify(value!=null &&
                                 value.equals("http://child1"), "xmlns:NS2="+value);

                value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1");
                Assertion.verify(value!=null &&
                                 value.equals("http://attr2"), "xmlns:NS1="+value);


                // child3
               

                Assertion.verify(child3.getNodeName().equals("xsl:child3"), "xsl:child3");
                value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1");
                Assertion.verify(value!=null &&
                                 value.equals("http://a2"), "xmlns:NS1="+value);


                value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "a1");
                Assertion.verify(value!=null &&
                                 value.equals("http://a1"), "xmlns:a1="+value);


                value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl");
                Assertion.verify(value!=null &&
                                 value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value);

               
                Attr attr = child3.getAttributeNodeNS("http://a2", "attr2");
                Assertion.verify(attr != null, "NS1:attr2 !=null");

                Assertion.verify(child3.getAttributes().getLength() == 5, "xsl:child3 has 5 attrs");
               
                // child 4
                Attr temp = child4.getAttributeNodeNS("http://www.w3.org/2000/xmlns/", "xmlns");
                Assertion.verify(temp.getNodeName().equals("xmlns"), "attribute name is xmlns");
                Assertion.verify(temp.getNodeValue().length() == 0, "xmlns=''");               
                /*
                OutputFormat format = new OutputFormat((Document)doc);
                format.setLineSeparator(LineSeparator.Windows);
                format.setIndenting(true);
                format.setLineWidth(0);            
                format.setPreserveSpace(true);
                XMLSerializer serializer = new XMLSerializer(System.out, format);
                serializer.serialize(doc);
                */              

            }


            //************************
            //* Test normalizeDocument(): core tests
            //************************
            //System.out.println("TEST #4: namespace fixup during serialization");
            {

                Document doc= new DocumentImpl();
                Element root = doc.createElementNS("http://www.w3.org/1999/XSL/Transform", "xsl:stylesheet");
                doc.appendChild(root);
                root.setAttributeNS("http://attr1", "xsl:attr1","");

                Element child1 = doc.createElementNS("http://child1", "NS2:child1");
                child1.setAttributeNS("http://attr2", "NS2:attr2","");
                root.appendChild(child1);

                Element child2 = doc.createElementNS("http://child2","NS4:child2");
                child2.setAttributeNS("http://attr3","attr3", "");
                root.appendChild(child2);

                Element child3 = doc.createElementNS("http://www.w3.org/1999/XSL/Transform","xsl:child3");
                child3.setAttributeNS("http://a1","attr1", "");
                child3.setAttributeNS("http://a2","xsl:attr2", "");
                child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:a1", "http://a1");
                child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", "http://a2");
               
                Element child4 = doc.createElementNS(null, "child4");
                child4.setAttributeNS("http://a1", "xsl:attr1", "");
                child4.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "default");

                child3.appendChild(child4);
                root.appendChild(child3);


                // serialize data
                writer.getDomConfig().setParameter("namespaces", Boolean.TRUE);
                String xmlData = writer.writeToString(doc);
                Reader r = new StringReader(xmlData);
                LSInput in = impl.createLSInput();
                in.setCharacterStream(r);
                doc = builder.parse(in);

                //
                // make sure algorithm works correctly
                //

                root = doc.getDocumentElement();
                child1 = (Element)root.getFirstChild();
                child2 = (Element)child1.getNextSibling();
                child3 = (Element)child2.getNextSibling();


                // xsl:stylesheet should include 2 namespace declarations
                String name = root.getNodeName();
                Assertion.verify(name.equals("xsl:stylesheet"), "xsl:stylesheet");

                String value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl");
                Assertion.verify(value!=null, "xmlns:xsl != null");
                Assertion.verify(value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value);
               
                value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1");

                Assertion.verify(value!=null &&
                                 value.equals("http://attr1"), "xmlns:NS1="+value);

                // child includes 2 namespace decls

                Assertion.verify(child1.getNodeName().equals("NS2:child1"), "NS2:child1");
                value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS2");
                Assertion.verify(value!=null &&
                                 value.equals("http://child1"), "xmlns:NS2="+value);

                value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1");
                Assertion.verify(value!=null &&
                                 value.equals("http://attr2"), "xmlns:NS1="+value);


                // child3
               

                Assertion.verify(child3.getNodeName().equals("xsl:child3"), "xsl:child3");
                value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1");
                Assertion.verify(value!=null &&
                                 value.equals("http://a2"), "xmlns:NS1="+value);


                value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "a1");
                Assertion.verify(value!=null &&
                                 value.equals("http://a1"), "xmlns:a1="+value);


                value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl");
                Assertion.verify(value!=null &&
                                 value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value);

               
                Attr attr = child3.getAttributeNodeNS("http://a2", "attr2");
                Assertion.verify(attr != null, "NS6:attr2 !=null");

                Assertion.verify(child3.getAttributes().getLength() == 5, "xsl:child3 has 5 attrs");


               
                //OutputFormat format = new OutputFormat((Document)doc);
                //format.setLineSeparator(LineSeparator.Windows);
                //format.setIndenting(true);
                //format.setLineWidth(0);            
                //format.setPreserveSpace(true);

                //XMLSerializer serializer = new XMLSerializer(System.out, format);
                //serializer.serialize(doc);               

            }


            //************************
            // TEST: replaceWholeText()
            //       getWholeText()
            //      
            //************************
          
            //System.out.println("TEST #5: wholeText, input: tests/dom/dom3/wholeText.xml");
           {
            config = builder.getDomConfig();
            config.setParameter("error-handler",errorHandler);
            config.setParameter("validate", Boolean.FALSE);
            config.setParameter("entities", Boolean.TRUE);
            Document doc = builder.parseURI("tests/dom/dom3/wholeText.xml");

            Element root = doc.getDocumentElement();
            Element test = (Element)doc.getElementsByTagName("elem").item(0);
           
            test.appendChild(doc.createTextNode("Address: "));
            test.appendChild(doc.createEntityReference("ent2"));
            test.appendChild(doc.createTextNode("City: "));
           
            test.appendChild(doc.createEntityReference("ent1"));
            DocumentType doctype = doc.getDoctype();
            Node entity = doctype.getEntities().getNamedItem("ent3");

            NodeList ls = test.getChildNodes();
            Assertion.verify(ls.getLength()==5, "List length");
           
            String compare1 = "Home Address: 1900 Dallas Road (East) City: Dallas. California. USA  PO #5668";
            Assertion.verify(((Text)ls.item(0)).getWholeText().equals(compare1), "Compare1");
            String compare2 = "Home Address: 1900 Dallas Road (East) City: Dallas. California. USA  PO #5668";
            Assertion.verify(((Text)ls.item(1)).getWholeText().equals(compare2), "Compare2");
           

            //TEST replaceWholeText()
            ((NodeImpl)ls.item(0)).setReadOnly(true, true);
           
            Text original = (Text)ls.item(0);
            Node newNode = original.replaceWholeText("Replace with this text");
            ls = test.getChildNodes();
            Assertion.verify(ls.getLength() == 1, "Length == 1");
            Assertion.verify(ls.item(0).getNodeValue().equals("Replace with this text"), "Replacement works");
            Assertion.verify(newNode != original, "New node created");

            // replace text for node which is not yet attached to the tree
            Text text = doc.createTextNode("readonly");
            ((NodeImpl)text).setReadOnly(true, true);
            text = text.replaceWholeText("Data");
            Assertion.verify(text.getNodeValue().equals("Data"), "New value 'Data'");

            // test with second child that does not have any content
            test = (Element)doc.getElementsByTagName("elem").item(1);
            try {           
                ((Text)test.getFirstChild()).replaceWholeText("can't replace");
            } catch (DOMException e){
               Assertion.verify(e !=null);
            }
            String compare3 = "Test: The Content ends here. ";
            //Assertion.assert(((Text)test.getFirstChild()).getWholeText().equals(compare3), "Compare3");
           
           }

            //************************
            // TEST: schema-type
            //       schema-location
            //      
            //************************
            {
                errorCounter = 0;
                config = builder.getDomConfig();
                config.setParameter("error-handler",errorHandler);
                config.setParameter("resource-resolver",resolver);
                config.setParameter("validate", Boolean.TRUE);
                config.setParameter("psvi", Boolean.TRUE);
               
                // schema-type is not set validate against both grammars
                errorCounter = 0;
                Document core2 = builder.parseURI("tests/dom/dom3/both-error.xml");
                Assertion.verify(errorCounter == 4, "4 errors should be reported");
               
                errorCounter = 0;
                // set schema-type to be XML Schema
                config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema");
                // test parsing a file that has both XML schema and DTD
                core2 = builder.parseURI("tests/dom/dom3/both.xml");
                Assertion.verify(errorCounter == 0, "No errors should be reported");
               
           
                // parse a file with XML schema and DTD but validate against DTD only
                errorCounter = 0;
                config.setParameter("schema-type","http://www.w3.org/TR/REC-xml");
                core2 = builder.parseURI("tests/dom/dom3/both-error.xml");
                Assertion.verify(errorCounter == 3, "3 errors should be reported");
               
                // parse a file with DTD only but set schema-location and
                // validate against XML Schema
                // set schema location
               
               
                core2 = builder.parseURI("tests/dom/dom3/both-error.xml");
               
                // normalize document
                errorCounter = 0;
                Element root = core2.getDocumentElement();
                root.removeAttributeNS("http://www.w3.org/2001/XMLSchema", "xsi");              
                root.removeAttributeNS("http://www.w3.org/2001/XMLSchema", "noNamespaceSchemaLocation");
                config = core2.getDomConfig();
                config.setParameter("error-handler",errorHandler);
                config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema");
                config.setParameter("schema-location","personal.xsd");
                config.setParameter("resource-resolver",resolver);
                config.setParameter("validate", Boolean.TRUE);
                core2.normalizeDocument();
                Assertion.verify(errorCounter == 1, "1 error should be reported: "+errorCounter);
   
            }
           
           
            // baseURI tests
            {
        LSParser parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS,
                               null);
        Document doc = parser.parseURI("tests/dom/dom3/baseURI.xml");
        Element root = doc.getDocumentElement();
        NodeList ls = doc.getElementsByTagNameNS(null, "streetNum");
        Node e = ls.item(0);
        Assertion.verify(((NodeImpl)e).getBaseURI().endsWith("tests/dom/dom3/baseURI.xml"),
                 "baseURI=tests/dom/dom3/baseURI.xml");
View Full Code Here

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");

    LSInput input = impl.createLSInput();
    input.setByteStream(new ByteArrayInputStream(ba));
    LSParser parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS,null);


    SimulatorParser pas = new SimulatorParser(new Seed(seedInt-info.idIndex), parser.parse(input));

    pas.parseMapCells(info.idIndex);

//    p.println("cell maped");
//    System.out.println(pas.ls.base+ " "+pas.ls.neuron_end);
 
    pas.parseNeuronDef();

    pas.parsePopNeurons(info.idIndex);
//    p.println("cell poped");
    pas.parseScaffold(info.idIndex);
    pas.layerStructure.buildStructure(info.idIndex);
    pas.parseConnection(info.idIndex);

    pas.parseTarget(info);


//    pas.ls.sortSynapses(info.idIndex); //sort the  synapses, not necessary unless tune the parameters
//    p.println("connected");
    pas.parseExp(info.idIndex);
//    p.println("exp");
                pas.findMinDelay();
//    p.close();

    CyclicBarrier barrier = new CyclicBarrier(2);

    /*
    //receiving neurons
    m = info.jpvm.pvm_recv(NetMessageTag.sendNeurons);
    int numNeurons;
    numNeurons = m.buffer.upkint();
    int base = m.buffer.upkint();
    Neuron neurons[] = new Neuron[numNeurons+1]; // the last neuron is a sync neuron;
    m.buffer.unpack(neurons,numNeurons,1);
    */



    /*
    out=out+"\n";
    for(int i=0; i< numNeurons; i++)
    {
      out=out+"Neurons are:"+neurons[i].toString();
    }
    */

    Seed idum= new Seed(seedInt-info.idIndex);


    if(pas.layerStructure.axons == null) throw new RuntimeException("no axon info");

    // neurons,pvminfo,base index, mini delay, background freq, seed number
   
    final Network testNet = new ANetwork (
      pas.getModelFactory ( ),
      pas.getDiscreteEventQueue ( ),
      pas.getModulatedSynapseSeq ( ),
      pas.layerStructure.neurons,
      pas.layerStructure.axons,
      info,
      pas.layerStructure.base,
      pas.minDelay,
      pas,
      idum,
      pas.experiment );
   
    testNet.initNet();

//    pas.p = testNet.p;


//    if(info.idIndex==0) pas.ls.connectFrom("O,0,0,E", testNet.p);
//    if(info.idIndex==4) pas.ls.connectFrom("O,0,16,0,E", testNet.p);
  //  pas.ls.connectFrom("T,27,9,L", testNet.p);

    testNet.p.println("Host id "+info.idIndex+"\n");
    testNet.p.println("base "+testNet.base+"\n");
    testNet.p.println("idum "+idum.seed+"\n");
    testNet.p.println("NumOfSyn "+pas.layerStructure.numSYN+"\n");


//    testNet.p.flush();

    Object lock = new Object();
    Object synLock = new Object();
//    ListenInput listen = new ListenInput(testNet,lock);
//                PCommunicationThread p1 = new PCommunicationThread(testNet, lock);
//               PComputationThread p2 = new PComputationThread(testNet, lock);
   
               PRun p1 = new PRun (
                 testNet.getDiscreteEventQueue ( ),
                 testNet,
                 lock,
                 barrier );

   //    pas.ls.cellmap=null;
         System.gc();

              Thread run = new Thread(p1);
        run.setDaemon(true);
        run.start();

//Barrier Sync
    jpvmBuffer buf = new jpvmBuffer();
    buf.pack("NetHost "+info.jpvm.pvm_mytid().toString()+" is ready to go"); //send out ready info;
    info.jpvm.pvm_send(buf, info.tids[info.idIndex] ,NetMessageTag.readySig);
//    m = info.jpvm.pvm_recv(NetMessageTag.readySig);
//Barrier Sync

        while (!testNet.stop)
        {
          m = testNet.info.jpvm.pvm_recv(); //receive info from others
          if(m.messageTag==NetMessageTag.trialDone)testNet.trialDone=false;
//          synchronized(lock)
          {
//            testNet.p.println("message "+m.messageTag);
            // lock.notify();
            switch(m.messageTag)
            {
              case NetMessageTag.sendSpike:
                synchronized (lock)
                {

                  int sourceID = m.buffer.upkint();
                  int trialID = m.buffer.upkint();
                  if(trialID==testNet.countTrial)
                  {
                    //                    testNet.p.println("received and processed");
                    testNet.spikeState=true;
                    (testNet.received[sourceID])++;
                    for(int iter=0;iter<info.numTasks;iter++)
                    {
                      if(iter!=info.idIndex && testNet.received[iter]==0) testNet.spikeState=false;
                    }
                    SpikeBuffer sbuff = (SpikeBuffer)m.buffer.upkcnsobj();
                    Iterator<NetMessage> iter = sbuff.buff.iterator();
                    while(iter.hasNext())
                    {
                      NetMessage message = iter.next();
//                      try {
                        for(int ii =0; ii <testNet.axons.get(message.from).branches.length; ii++)
                        {
                          // new input events
                         
                          testNet.getInputEventSlot ( ).offer (
                            new AInputEvent (
                              message.time
                                + testNet.axons.get ( message.from )
                                .branches [ ii ].delay,
                              testNet.axons.get ( message.from )
                                .branches [ ii ],
                              message.from,
                              ( ( ANetMessage ) message ).sourceId,
                              ( ( ANetMessage ) message ).avalancheId ) );
                        }
//                      }
//                      catch(Exception ex) {
//                        throw new RuntimeException(ex.getMessage()+"\n from:"+message.from+" host id:"+info.idIndex+" axons"+testNet.axons.size());
//                      }
                    }
                    lock.notify();
                  }
                  /*
               else
               {
                  //                    testNet.p.println("received and ignored");
               }
               */
                }
                break;
              case NetMessageTag.syncRoot: //if its a message about time
                synchronized (lock)
                {

                  if(!testNet.trialDone)
                  {

                    testNet.rootTime=m.buffer.upkdouble();
                    lock.notify();
                  }
                }
                break;
              case NetMessageTag.stopSig: //if its a message about time
                testNet.p.println("get stop message root "+testNet.rootTime);
                testNet.p.flush();
                buf = new jpvmBuffer();
                buf.pack(testNet.recorderData);
                //buf.pack(info.idIndex);
                buf.pack(((ANetwork) testNet).aData);
                testNet.p.println("Size of couting "+ ((ANetwork) testNet).aData.avalancheCounter.size());
                testNet.p.flush();

                info.jpvm.pvm_send(buf, info.tids[info.idIndex], NetMessageTag.getBackData);
               
                testNet.clearQueues ( );

                testNet.stop=true;
                testNet.p.close();
                synchronized (lock)
                {
                  lock.notify();
                }
                break;
              case NetMessageTag.tempStopSig: //if its a message about time
                buf = new jpvmBuffer();
                buf.pack(testNet.recorderData);
                buf.pack(info.idIndex);
                info.jpvm.pvm_send(buf, info.tids[info.idIndex], NetMessageTag.getBackData);
                testNet.recorderData.clear();
                break;
              case NetMessageTag.trialDone: // new trial begins
                //                        testNet.p.println("begin nofiying");
                //
                synchronized (lock)
                {
                  testNet.trialId = m.buffer.upkint();
                  testNet.subExpId = m.buffer.upkint();
                  testNet.endOfTrial = testNet.experiment.subExp[testNet.subExpId].trialLength;
                  Thread.yield();
                  Thread.yield();
                  barrier.await();
//                  synchronized (synLock)
//                  {
//                    synLock.notify();
          //          testNet.startSig=true;
//                  }
                  lock.notify();
                }
                break;
              case NetMessageTag.changeConnection:
                seedInt = m.buffer.upkint();
                baLength = m.buffer.upkint();
                ba = new byte[baLength];
                m.buffer.unpack(ba,baLength,1);

                // DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
                // DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
                input = impl.createLSInput();
                input.setByteStream(new ByteArrayInputStream(ba));
                parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS,null);

                NodeList conns = pas.rootElement.getElementsByTagName("Connections");
                testNet.p.println("connection num"+conns.getLength());
                pas.rootElement.removeChild(conns.item(0));
                Node dup = pas.document.importNode(parser.parse(input).getDocumentElement().getElementsByTagName("Connections").item(0) , true);
                pas.rootElement.appendChild(dup);
                double weight;
                weight = pas.parseChangeConnection(info.idIndex); //change the connections;
                //synchroniz
                //                testNet.p.println("connection change done with weight "+weight);
View Full Code Here

        xml = xml.replaceAll("\\s*<", "<");
        xml = xml.replaceAll(">\\s*", ">");

        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS domLS = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSParser lsParser = domLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

        LSInput input = domLS.createLSInput();
        input.setStringData(xml);
        Document document = lsParser.parse(input);

        LSSerializer lsSerializer = domLS.createLSSerializer();
        lsSerializer.getDomConfig().setParameter("comments", Boolean.FALSE);
        lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
        return lsSerializer.writeToString(document);
View Full Code Here

        xml = xml.replaceAll("\\s*<", "<");
        xml = xml.replaceAll(">\\s*", ">");

        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS domLS = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSParser lsParser = domLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

        LSInput input = domLS.createLSInput();
        input.setStringData(xml);
        Document document = lsParser.parse(input);

        LSSerializer lsSerializer = domLS.createLSSerializer();
        lsSerializer.getDomConfig().setParameter("comments", Boolean.FALSE);
        lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
        return lsSerializer.writeToString(document);
View Full Code Here

        return parse(input, validateIfSchema);
    }

    private static Document parse(LSInput input, boolean validateIfSchema) {
        DOMImplementationLS impl = getDOMImpl();
        LSParser parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
        DOMConfiguration config = parser.getDomConfig();
        config.setParameter("element-content-whitespace", false);
        config.setParameter("namespaces", true);
        config.setParameter("validate-if-schema", validateIfSchema);
        return parser.parse(input);
    }
View Full Code Here

     * Reads file import locations from Spring bean application context.
     * @param configFile
     * @return
     */
    public List<File> getConfigImports(File configFile) {
        LSParser parser = XMLUtils.createLSParser();

        GetSpringImportsFilter filter = new GetSpringImportsFilter(configFile);
        parser.setFilter(filter);
        parser.parseURI(configFile.toURI().toString());

        return filter.getImportedFiles();
    }
View Full Code Here

     * @param id
     * @param type
     * @return
     */
    public <T> T getBeanDefinition(File configFile, String id, Class<T> type) {
        LSParser parser = XMLUtils.createLSParser();

        GetSpringBeanFilter filter = new GetSpringBeanFilter(id, type);
        parser.setFilter(filter);

        List<File> configFiles = new ArrayList<File>();
        configFiles.add(configFile);
        configFiles.addAll(getConfigImports(configFile));

        for (File file : configFiles) {
            parser.parseURI(file.toURI().toString());

            if (filter.getBeanDefinition() != null) {
                return createJaxbObjectFromElement(filter.getBeanDefinition(), type);
            }
        }
View Full Code Here

TOP

Related Classes of org.w3c.dom.ls.LSParser

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.