Java 类org.jivesoftware.smack.util.PacketParserUtils 实例源码

项目:Smack    文件:XMPPTCPConnection.java   
/**
 * Resets the parser using the latest connection's reader. Reseting the parser is necessary
 * when the plain connection has been secured or when a new opening stream element is going
 * to be sent by the server.
 *
 * @throws SmackException if the parser could not be reset.
 */
void openStream() throws SmackException {
    // If possible, provide the receiving entity of the stream open tag, i.e. the server, as much information as
    // possible. The 'to' attribute is *always* available. The 'from' attribute if set by the user and no external
    // mechanism is used to determine the local entity (user). And the 'id' attribute is available after the first
    // response from the server (see e.g. RFC 6120 § 9.1.1 Step 2.)
    CharSequence to = getServiceName();
    CharSequence from = null;
    CharSequence localpart = config.getUsername();
    if (localpart != null) {
        from = XmppStringUtils.completeJidFrom(localpart, to);
    }
    String id = getStreamId();
    // 发送一个SteamOpen
    send(new StreamOpen(to, from, id));
    try {
        packetReader.parser = PacketParserUtils.newXmppParser(reader);
    }
    catch (XmlPullParserException e) {
        throw new SmackException(e);
    }
}
项目:Smack    文件:ParseStreamManagementTest.java   
@Test
public void testParseEnabled() throws Exception {
    String stanzaID = "zid615d9";
    boolean resume = true;
    String location = "test";
    int max = 42;

    String enabledStanza = XMLBuilder.create("enabled")
            .a("xmlns", "urn:xmpp:sm:3")
            .a("id", "zid615d9")
            .a("resume", String.valueOf(resume))
            .a("location", location)
            .a("max", String.valueOf(max))
            .asString(outputProperties);

    StreamManagement.Enabled enabledPacket = ParseStreamManagement.enabled(
            PacketParserUtils.getParserFor(enabledStanza));

    assertThat(enabledPacket, is(notNullValue()));
    assertThat(enabledPacket.getId(), equalTo(stanzaID));
    assertThat(enabledPacket.getLocation(), equalTo(location));
    assertThat(enabledPacket.isResumeSet(), equalTo(resume));
    assertThat(enabledPacket.getMaxResumptionTime(), equalTo(max));
}
项目:Smack    文件:ParseStreamManagementTest.java   
@Test
public void testParseFailedError() throws Exception {
    XMPPError.Condition errorCondition = XMPPError.Condition.unexpected_request;

    String failedStanza = XMLBuilder.create("failed")
            .a("xmlns", "urn:xmpp:sm:3")
            .element(errorCondition.toString(), XMPPError.NAMESPACE)
            .asString(outputProperties);

    System.err.println(failedStanza);

    StreamManagement.Failed failedPacket = ParseStreamManagement.failed(
            PacketParserUtils.getParserFor(failedStanza));

    assertThat(failedPacket, is(notNullValue()));
    assertTrue(failedPacket.getXMPPErrorCondition() == errorCondition);
}
项目:Smack    文件:ParseStreamManagementTest.java   
@Test
public void testParseResumed() throws Exception {
    long handledPackets = 42;
    String previousID = "zid615d9";

    String resumedStanza = XMLBuilder.create("resumed")
            .a("xmlns", "urn:xmpp:sm:3")
            .a("h", String.valueOf(handledPackets))
            .a("previd", previousID)
            .asString(outputProperties);

    StreamManagement.Resumed resumedPacket = ParseStreamManagement.resumed(
            PacketParserUtils.getParserFor(resumedStanza));

    assertThat(resumedPacket, is(notNullValue()));
    assertThat(resumedPacket.getHandledCount(), equalTo(handledPackets));
    assertThat(resumedPacket.getPrevId(), equalTo(previousID));
}
项目:Smack    文件:Base64BinaryChunkProviderTest.java   
@Test
public void isNonLatsChunkParsedCorrectly() throws Exception {
    String base64Text = "iVBORw0KGgoAAAANSUhEUgAAASwAAAGQCAYAA";
    String string = "<chunk xmlns='urn:xmpp:http' streamId='Stream0001' nr='0'>" + base64Text + "</chunk>";

    Base64BinaryChunkProvider provider = new Base64BinaryChunkProvider();
    XmlPullParser parser = PacketParserUtils.getParserFor(string);

    ExtensionElement extension = provider.parse(parser);
    assertTrue(extension instanceof Base64BinaryChunk);

    Base64BinaryChunk chunk = (Base64BinaryChunk) extension;
    assertEquals("Stream0001", chunk.getStreamId());
    assertFalse(chunk.isLast());
    assertEquals(base64Text, chunk.getText());
    assertEquals(0, chunk.getNr());
}
项目:Smack    文件:Base64BinaryChunkProviderTest.java   
@Test
public void isLatsChunkParsedCorrectly() throws Exception {
    String base64Text = "2uPzi9u+tVWJd+e+y1AAAAABJRU5ErkJggg==";
    String string = "<chunk xmlns='urn:xmpp:http' streamId='Stream0001' nr='1' last='true'>" + base64Text + "</chunk>";

    Base64BinaryChunkProvider provider = new Base64BinaryChunkProvider();
    XmlPullParser parser = PacketParserUtils.getParserFor(string);

    ExtensionElement extension = provider.parse(parser);
    assertTrue(extension instanceof Base64BinaryChunk);

    Base64BinaryChunk chunk = (Base64BinaryChunk) extension;
    assertEquals("Stream0001", chunk.getStreamId());
    assertTrue(chunk.isLast());
    assertEquals(base64Text, chunk.getText());
    assertEquals(1, chunk.getNr());
}
项目:Smack    文件:AbstractHttpOverXmppProviderTest.java   
@Test
public void areRespHeadersParsedCorrectly() throws Exception {
    String string = "<resp xmlns='urn:xmpp:http' version='1.1' statusCode='200' statusMessage='OK'>"
            + "<headers xmlns='http://jabber.org/protocol/shim'>"
            + "<header name='Date'>Fri, 03 May 2013 13:52:10 GMT-4</header>"
            + "<header name='Allow'>OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE</header>"
            + "<header name='Content-Length'>0</header>"
            + "</headers>"
            + "</resp>";
    Map<String, String> expectedHeaders = new HashMap<String, String>();
    expectedHeaders.put("Date", "Fri, 03 May 2013 13:52:10 GMT-4");
    expectedHeaders.put("Allow", "OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE");
    expectedHeaders.put("Content-Length", "0");

    HttpOverXmppRespProvider provider = new HttpOverXmppRespProvider();
    XmlPullParser parser = PacketParserUtils.getParserFor(string);

    IQ iq = provider.parse(parser);
    assertTrue(iq instanceof HttpOverXmppResp);
    HttpOverXmppResp body = ((HttpOverXmppResp) iq);

    checkHeaders(body.getHeaders(), expectedHeaders);
}
项目:Smack    文件:AbstractHttpOverXmppProviderTest.java   
@Test
public void areReqHeadersParsedCorrectly() throws Exception {
    String string = "<req xmlns='urn:xmpp:http' method='GET' resource='/rdf/xep' version='1.1'>"
            + "<headers xmlns='http://jabber.org/protocol/shim'>"
            + "<header name='Host'>clayster.com</header>"
            + "</headers>"
            + "</req>";
    Map<String, String> expectedHeaders = new HashMap<String, String>();
    expectedHeaders.put("Host", "clayster.com");

    HttpOverXmppReqProvider provider = new HttpOverXmppReqProvider();
    XmlPullParser parser = PacketParserUtils.getParserFor(string);

    IQ iq = provider.parse(parser);
    assertTrue(iq instanceof HttpOverXmppReq);
    HttpOverXmppReq body = ((HttpOverXmppReq) iq);

    checkHeaders(body.getHeaders(), expectedHeaders);
}
项目:Smack    文件:AbstractXMPPConnection.java   
protected void parseAndProcessStanza(XmlPullParser parser) throws Exception {
    ParserUtils.assertAtStartTag(parser);
    int parserDepth = parser.getDepth();
    Stanza stanza = null;
    try {
        stanza = PacketParserUtils.parseStanza(parser);
    }
    catch (Exception e) {
        CharSequence content = PacketParserUtils.parseContentDepth(parser,
                        parserDepth);
        UnparsablePacket message = new UnparsablePacket(content, e);
        ParsingExceptionCallback callback = getParsingExceptionCallback();
        if (callback != null) {
            callback.handleUnparsablePacket(message);
        }
    }
    ParserUtils.assertAtEndTag(parser);
    if (stanza != null) {
        processPacket(stanza);
    }
}
项目:Smack    文件:EmbeddedExtensionProvider.java   
@Override
public final PE parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException,
                SmackException {
    final String namespace = parser.getNamespace();
    final String name = parser.getName();
    final int attributeCount = parser.getAttributeCount();
    Map<String, String> attMap = new HashMap<>(attributeCount);

    for (int i = 0; i < attributeCount; i++) {
        attMap.put(parser.getAttributeName(i), parser.getAttributeValue(i));
    }

    List<ExtensionElement> extensions = new ArrayList<>();
    int event;
    do {
        event = parser.next();

        if (event == XmlPullParser.START_TAG)
            PacketParserUtils.addExtensionElement(extensions, parser);
    }
    while (!(event == XmlPullParser.END_TAG && parser.getDepth() == initialDepth));

    return createReturnExtension(name, namespace, attMap, extensions);
}
项目:Smack    文件:StreamErrorTest.java   
@Test
public void testParsingOfSimpleStreamError() {
    StreamError error = null;
    final String xml =
            // Usually the stream:stream element has more attributes (to, version, ...)
            // We omit those, since they are not relevant for testing
            "<stream:stream from='im.example.com' id='++TR84Sm6A3hnt3Q065SnAbbk3Y=' xmlns:stream='http://etherx.jabber.org/streams'>" +
            "<stream:error>" +
            "<conflict xmlns='urn:ietf:params:xml:ns:xmpp-streams' /> +" +
            "</stream:error>" +
            "</stream:stream>";
    try {
        XmlPullParser parser = PacketParserUtils.getParserFor(xml, "error");
        error = PacketParserUtils.parseStreamError(parser);
    } catch (Exception e) {
        fail(e.getMessage());
    }
    assertNotNull(error);
    assertEquals(Condition.conflict, error.getCondition());
}
项目:Smack    文件:StreamErrorTest.java   
@Test
public void testParsingOfStreamErrorWithText() {
    StreamError error = null;
    final String xml =
            // Usually the stream:stream element has more attributes (to, version, ...)
            // We omit those, since they are not relevant for testing
            "<stream:stream from='im.example.com' id='++TR84Sm6A3hnt3Q065SnAbbk3Y=' xmlns:stream='http://etherx.jabber.org/streams'>" +
            "<stream:error>" +
            "<conflict xmlns='urn:ietf:params:xml:ns:xmpp-streams' />" +
            "<text xml:lang='' xmlns='urn:ietf:params:xml:ns:xmpp-streams'>" +
                "Replaced by new connection" +
            "</text>" +
            "</stream:error>" +
            "</stream:stream>";
    try {
        XmlPullParser parser = PacketParserUtils.getParserFor(xml, "error");
        error = PacketParserUtils.parseStreamError(parser);
    } catch (Exception e) {
        fail(e.getMessage());
    }
    assertNotNull(error);
    assertEquals(Condition.conflict, error.getCondition());
    assertEquals("Replaced by new connection", error.getDescriptiveText());
}
项目:Smack    文件:TranscriptSearch.java   
@Override
public TranscriptSearch parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException, SmackException {
    TranscriptSearch answer = new TranscriptSearch();

    boolean done = false;
    while (!done) {
        int eventType = parser.next();
        if (eventType == XmlPullParser.START_TAG) {
            // Parse the packet extension
            PacketParserUtils.addExtensionElement(answer, parser);
        }
        else if (eventType == XmlPullParser.END_TAG) {
            if (parser.getName().equals(ELEMENT_NAME)) {
                done = true;
            }
        }
    }

    return answer;
}
项目:Smack    文件:TranscriptProvider.java   
@Override
public Transcript parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException, SmackException {
    String sessionID = parser.getAttributeValue("", "sessionID");
    List<Stanza> packets = new ArrayList<Stanza>();

    boolean done = false;
    while (!done) {
        int eventType = parser.next();
        if (eventType == XmlPullParser.START_TAG) {
            if (parser.getName().equals("message")) {
                packets.add(PacketParserUtils.parseMessage(parser));
            }
            else if (parser.getName().equals("presence")) {
                packets.add(PacketParserUtils.parsePresence(parser));
            }
        }
        else if (eventType == XmlPullParser.END_TAG) {
            if (parser.getName().equals("transcript")) {
                done = true;
            }
        }
    }

    return new Transcript(sessionID, packets);
}
项目:Smack    文件:WorkgroupForm.java   
@Override
public WorkgroupForm parse(XmlPullParser parser, int initialDepth)
                throws XmlPullParserException, IOException,
                SmackException {
    WorkgroupForm answer = new WorkgroupForm();

    boolean done = false;
    while (!done) {
        int eventType = parser.next();
        if (eventType == XmlPullParser.START_TAG) {
            // Parse the packet extension
            PacketParserUtils.addExtensionElement(answer, parser);
        }
        else if (eventType == XmlPullParser.END_TAG) {
            if (parser.getName().equals(ELEMENT_NAME)) {
                done = true;
            }
        }
    }

    return answer;
}
项目:Smack    文件:XHTMLExtensionProvider.java   
@Override
public XHTMLExtension parse(XmlPullParser parser, int initialDepth) throws IOException, XmlPullParserException {
    XHTMLExtension xhtmlExtension = new XHTMLExtension();

    while (true) {
        int eventType = parser.getEventType();
        String name = parser.getName();
        if (eventType == XmlPullParser.START_TAG) {
            if (name.equals(Message.BODY)) {
                xhtmlExtension.addBody(PacketParserUtils.parseElement(parser));
            }
        } else if (eventType == XmlPullParser.END_TAG) {
            if (parser.getDepth() == initialDepth) {
                return xhtmlExtension;
            }
        }
        parser.next();
    }
}
项目:Smack    文件:PubSubProvider.java   
@Override
   public PubSub parse(XmlPullParser parser, int initialDepth)
                   throws XmlPullParserException, IOException, SmackException {
       String namespace = parser.getNamespace();
       PubSubNamespace pubSubNamespace = PubSubNamespace.valueOfFromXmlns(namespace);
       PubSub pubsub = new PubSub(pubSubNamespace);

       outerloop: while (true) 
       {
           int eventType = parser.next();
           switch (eventType) {
           case XmlPullParser.START_TAG:
               PacketParserUtils.addExtensionElement(pubsub, parser);
               break;
           case XmlPullParser.END_TAG:
               if (parser.getDepth() == initialDepth) {
                   break outerloop;
               }
               break;
           }
       }
       return pubsub;
}
项目:Smack    文件:SimpleDirectoryPersistentCache.java   
/**
 * Tries to restore an DiscoverInfo stanza(/packet) from a file.
 * 
 * @param file
 * @return the restored DiscoverInfo
 * @throws Exception
 */
private static DiscoverInfo restoreInfoFromFile(File file) throws Exception {
    DataInputStream dis = new DataInputStream(new FileInputStream(file));
    String fileContent = null;
    try {
        fileContent = dis.readUTF();
    } finally {
        dis.close();
    }
    if (fileContent == null) {
        return null;
    }
    DiscoverInfo info = (DiscoverInfo) PacketParserUtils.parseStanza(fileContent);

    return info;
}
项目:Smack    文件:DataFormTest.java   
@Test
public void test() throws XmlPullParserException, IOException, SmackException {
    //Build a Form
    DataForm df = new DataForm(DataForm.Type.submit);
    String instruction = "InstructionTest1";
    df.addInstruction(instruction);
    FormField field = new FormField("testField1");
    df.addField(field);

    assertNotNull( df.toXML());
    String output = df.toXML().toString();
    assertEquals(TEST_OUTPUT_1, output);

    XmlPullParser parser = PacketParserUtils.getParserFor(output);

    df = pr.parse(parser);

    assertNotNull(df);
    assertNotNull(df.getFields());
    assertEquals(1 , df.getFields().size() );
    assertEquals(1 , df.getInstructions().size());

    assertNotNull( df.toXML());
    output = df.toXML().toString();
    assertEquals(TEST_OUTPUT_1, output);
}
项目:Smack    文件:DataLayoutTest.java   
@Test
public void testLayout() throws XmlPullParserException, IOException, SmackException {
    DataLayout layout = new DataLayout("Label");
    Fieldref reffield = new Fieldref("testField1");
    layout.getPageLayout().add(reffield);
    Section section = new Section("section Label");
    section.getSectionLayout().add(new Text("SectionText"));
    layout.getPageLayout().add(section);
    layout.getPageLayout().add(new Text( "PageText"));

    assertNotNull( layout.toXML());
    String output = layout.toXML().toString();
    assertEquals(TEST_OUTPUT_2, output);

    XmlPullParser parser = PacketParserUtils.getParserFor(output);

    layout = DataLayoutProvider.parse(parser);

    assertEquals(3 , layout.getPageLayout().size());
    assertEquals("Label", layout.getLabel());

    assertNotNull( layout.toXML());
    output = layout.toXML().toString();
    assertEquals(TEST_OUTPUT_2, output);
}
项目:EIM    文件:TranscriptSearch.java   
public IQ parseIQ(XmlPullParser parser) throws Exception {
    TranscriptSearch answer = new TranscriptSearch();

    boolean done = false;
    while (!done) {
        int eventType = parser.next();
        if (eventType == XmlPullParser.START_TAG) {
            // Parse the packet extension
            answer.addExtension(PacketParserUtils.parsePacketExtension(parser.getName(), parser.getNamespace(), parser));
        }
        else if (eventType == XmlPullParser.END_TAG) {
            if (parser.getName().equals(ELEMENT_NAME)) {
                done = true;
            }
        }
    }

    return answer;
}
项目:EIM    文件:TranscriptProvider.java   
public IQ parseIQ(XmlPullParser parser) throws Exception {
    String sessionID = parser.getAttributeValue("", "sessionID");
    List<Packet> packets = new ArrayList<Packet>();

    boolean done = false;
    while (!done) {
        int eventType = parser.next();
        if (eventType == XmlPullParser.START_TAG) {
            if (parser.getName().equals("message")) {
                packets.add(PacketParserUtils.parseMessage(parser));
            }
            else if (parser.getName().equals("presence")) {
                packets.add(PacketParserUtils.parsePresence(parser));
            }
        }
        else if (eventType == XmlPullParser.END_TAG) {
            if (parser.getName().equals("transcript")) {
                done = true;
            }
        }
    }

    return new Transcript(sessionID, packets);
}
项目:EIM    文件:WorkgroupForm.java   
public IQ parseIQ(XmlPullParser parser) throws Exception {
    WorkgroupForm answer = new WorkgroupForm();

    boolean done = false;
    while (!done) {
        int eventType = parser.next();
        if (eventType == XmlPullParser.START_TAG) {
            // Parse the packet extension
            answer.addExtension(PacketParserUtils.parsePacketExtension(parser.getName(),
                    parser.getNamespace(), parser));
        }
        else if (eventType == XmlPullParser.END_TAG) {
            if (parser.getName().equals(ELEMENT_NAME)) {
                done = true;
            }
        }
    }

    return answer;
}
项目:EIM    文件:EmbeddedExtensionProvider.java   
final public PacketExtension parseExtension(XmlPullParser parser) throws Exception
{
       String namespace = parser.getNamespace();
       String name = parser.getName();
       Map<String, String> attMap = new HashMap<String, String>();

       for(int i=0; i<parser.getAttributeCount(); i++)
       {
        attMap.put(parser.getAttributeName(i), parser.getAttributeValue(i));
       }
       List<PacketExtension> extensions = new ArrayList<PacketExtension>();

       do
       {
           int tag = parser.next();

           if (tag == XmlPullParser.START_TAG) 
            extensions.add(PacketParserUtils.parsePacketExtension(parser.getName(), parser.getNamespace(), parser));
       } while (!name.equals(parser.getName()));

    return createReturnExtension(name, namespace, attMap, extensions);
}
项目:androidPN-client.    文件:EmbeddedExtensionProvider.java   
final public PacketExtension parseExtension(XmlPullParser parser) throws Exception
{
       String namespace = parser.getNamespace();
       String name = parser.getName();
       Map<String, String> attMap = new HashMap<String, String>();

       for(int i=0; i<parser.getAttributeCount(); i++)
       {
        attMap.put(parser.getAttributeName(i), parser.getAttributeValue(i));
       }
       List<PacketExtension> extensions = new ArrayList<PacketExtension>();

       do
       {
           int tag = parser.next();

           if (tag == XmlPullParser.START_TAG) 
            extensions.add(PacketParserUtils.parsePacketExtension(parser.getName(), parser.getNamespace(), parser));
       } while (!name.equals(parser.getName()));

    return createReturnExtension(name, namespace, attMap, extensions);
}
项目:androidPN-client.    文件:TranscriptSearch.java   
public IQ parseIQ(XmlPullParser parser) throws Exception {
    TranscriptSearch answer = new TranscriptSearch();

    boolean done = false;
    while (!done) {
        int eventType = parser.next();
        if (eventType == XmlPullParser.START_TAG) {
            // Parse the packet extension
            answer.addExtension(PacketParserUtils.parsePacketExtension(parser.getName(), parser.getNamespace(), parser));
        }
        else if (eventType == XmlPullParser.END_TAG) {
            if (parser.getName().equals(ELEMENT_NAME)) {
                done = true;
            }
        }
    }

    return answer;
}
项目:androidPN-client.    文件:TranscriptProvider.java   
public IQ parseIQ(XmlPullParser parser) throws Exception {
    String sessionID = parser.getAttributeValue("", "sessionID");
    List<Packet> packets = new ArrayList<Packet>();

    boolean done = false;
    while (!done) {
        int eventType = parser.next();
        if (eventType == XmlPullParser.START_TAG) {
            if (parser.getName().equals("message")) {
                packets.add(PacketParserUtils.parseMessage(parser));
            }
            else if (parser.getName().equals("presence")) {
                packets.add(PacketParserUtils.parsePresence(parser));
            }
        }
        else if (eventType == XmlPullParser.END_TAG) {
            if (parser.getName().equals("transcript")) {
                done = true;
            }
        }
    }

    return new Transcript(sessionID, packets);
}