target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void testSetName() { RosterElement e = new RosterElement(JID.jidInstanceNS("[email protected]"), null, new String[] {}, null); assertNull(e.getName()); assertTrue(e.isModified()); e.getRosterElement(); assertFalse(e.isModified()); e.setName(null); assertFalse(e.isModified()); assertNull(e.getName()); e.setName("jeff"); assertTrue(e.isModified()); assertEquals("jeff", e.getName()); e.getRosterElement(); assertFalse(e.isModified()); e.setName("jeff"); assertFalse(e.isModified()); assertEquals("jeff", e.getName()); e.setName("bob"); assertTrue(e.isModified()); assertEquals("bob", e.getName()); e.getRosterElement(); assertFalse(e.isModified()); e.setName(null); assertTrue(e.isModified()); assertNull(e.getName()); e.getRosterElement(); assertFalse(e.isModified()); e.setName(null); assertFalse(e.isModified()); assertNull(e.getName()); } | public final void setName(final String name) { if(name==this.name || (name!=null && this.name!=null && name.equals(this.name))){ return ; } else { this.name = name==null?null:XMLUtils.unescape(name); this.modified = true; } } | RosterElement { public final void setName(final String name) { if(name==this.name || (name!=null && this.name!=null && name.equals(this.name))){ return ; } else { this.name = name==null?null:XMLUtils.unescape(name); this.modified = true; } } } | RosterElement { public final void setName(final String name) { if(name==this.name || (name!=null && this.name!=null && name.equals(this.name))){ return ; } else { this.name = name==null?null:XMLUtils.unescape(name); this.modified = true; } } RosterElement(Element roster_el, XMPPResourceConnection session); RosterElement(JID jid, String name, String[] groups,
XMPPResourceConnection session); } | RosterElement { public final void setName(final String name) { if(name==this.name || (name!=null && this.name!=null && name.equals(this.name))){ return ; } else { this.name = name==null?null:XMLUtils.unescape(name); this.modified = true; } } RosterElement(Element roster_el, XMPPResourceConnection session); RosterElement(JID jid, String name, String[] groups,
XMPPResourceConnection session); void addGroups(String[] groups); String[] getGroups(); JID getJid(); String getName(); String getOtherData(); Element getRosterElement(); Element getRosterItem(); @Override String toString(); SubscriptionType getSubscription(); boolean isModified(); boolean isOnline(); boolean isPresence_sent(); final void setGroups(String[] groups); final void setName(final String name); void setOnline(String resource, boolean online); void setOtherData(String other_data); void setPresence_sent(boolean presence_sent); void setSubscription(SubscriptionType subscription); boolean isPersistent(); void setPersistent(boolean persistent); double getActivity(); void setActivity(double activity); double getWeight(); void setWeight(double weight); long getLastSeen(); void setLastSeen(long lastSeen); } | RosterElement { public final void setName(final String name) { if(name==this.name || (name!=null && this.name!=null && name.equals(this.name))){ return ; } else { this.name = name==null?null:XMLUtils.unescape(name); this.modified = true; } } RosterElement(Element roster_el, XMPPResourceConnection session); RosterElement(JID jid, String name, String[] groups,
XMPPResourceConnection session); void addGroups(String[] groups); String[] getGroups(); JID getJid(); String getName(); String getOtherData(); Element getRosterElement(); Element getRosterItem(); @Override String toString(); SubscriptionType getSubscription(); boolean isModified(); boolean isOnline(); boolean isPresence_sent(); final void setGroups(String[] groups); final void setName(final String name); void setOnline(String resource, boolean online); void setOtherData(String other_data); void setPresence_sent(boolean presence_sent); void setSubscription(SubscriptionType subscription); boolean isPersistent(); void setPersistent(boolean persistent); double getActivity(); void setActivity(double activity); double getWeight(); void setWeight(double weight); long getLastSeen(); void setLastSeen(long lastSeen); } |
@Test public void testStorageOfflineMessageForBareJid() throws Exception { BareJID userJid = BareJID.bareJIDInstance("[email protected]"); JID res1 = JID.jidInstance(userJid, "res1"); JID res2 = JID.jidInstance(userJid, "res2"); XMPPResourceConnection session1 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res1); XMPPResourceConnection session2 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res2); assertEquals(Arrays.asList(session1, session2), session1.getActiveSessions()); Element packetEl = new Element("message", new String[] { "type", "from", "to" }, new String[] { "chat", "[email protected]/res1", userJid.toString() }); packetEl.addChild(new Element("body", "Test message")); Packet packet = Packet.packetInstance(packetEl); Queue<Packet> results = new ArrayDeque<Packet>(); offlineProcessor.postProcess(packet, session1, null, results, null); assertTrue("generated result even than no result should be generated", results.isEmpty()); assertTrue("no message stored, while it should be stored", !msgRepo.getStored().isEmpty()); msgRepo.getStored().clear(); session1.setPriority(1); results = new ArrayDeque<Packet>(); offlineProcessor.postProcess(packet, session1, null, results, null); assertTrue("generated result even than no result should be generated", results.isEmpty()); assertTrue("no message stored, while it should be stored", !msgRepo.getStored().isEmpty()); msgRepo.getStored().clear(); session1.setPresence(new Element("presence")); results = new ArrayDeque<Packet>(); offlineProcessor.postProcess(packet, session1, null, results, null); assertTrue("generated result even than no result should be generated", results.isEmpty()); assertTrue("message stored, while it should not be stored", msgRepo.getStored().isEmpty()); msgRepo.getStored().clear(); } | @Override public void postProcess( final Packet packet, final XMPPResourceConnection conn, final NonAuthUserRepository repo, final Queue<Packet> queue, Map<String, Object> settings ) { if ( conn == null || !message.hasConnectionForMessageDelivery(conn) ){ try { if (packet.getElemName() == tigase.server.Message.ELEM_NAME && packet.getStanzaTo() != null && packet.getStanzaTo().getResource() != null) { return; } if (conn != null && packet.getStanzaTo() != null && !conn.isUserId(packet.getStanzaTo().getBareJID())) return; MsgRepositoryIfc msg_repo = getMsgRepoImpl( repo, conn ); publishInPubSub(packet, conn, queue, settings); Authorization saveResult = savePacketForOffLineUser( packet, msg_repo, repo ); Packet result = null; switch (saveResult) { case SERVICE_UNAVAILABLE: result = saveResult.getResponseMessage(packet, "Offline messages queue is full", true); break; default: break; } if (result != null) { queue.offer(result); } } catch ( UserNotFoundException e ) { if ( log.isLoggable( Level.FINEST ) ){ log.finest( "UserNotFoundException at trying to save packet for off-line user." + packet ); } } catch (NotAuthorizedException ex) { if ( log.isLoggable( Level.FINEST ) ){ log.log(Level.FINEST, "NotAuthorizedException when checking if message is to this " + "user at trying to save packet for off-line user, {0}, {1}", new Object[]{ packet, conn }); } } catch (PacketErrorTypeException ex) { log.log(Level.FINE, "Could not sent error to packet sent to offline user which storage to offline " + "store failed. Packet is error type already: {0}", packet.toStringSecure()); } } } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { @Override public void postProcess( final Packet packet, final XMPPResourceConnection conn, final NonAuthUserRepository repo, final Queue<Packet> queue, Map<String, Object> settings ) { if ( conn == null || !message.hasConnectionForMessageDelivery(conn) ){ try { if (packet.getElemName() == tigase.server.Message.ELEM_NAME && packet.getStanzaTo() != null && packet.getStanzaTo().getResource() != null) { return; } if (conn != null && packet.getStanzaTo() != null && !conn.isUserId(packet.getStanzaTo().getBareJID())) return; MsgRepositoryIfc msg_repo = getMsgRepoImpl( repo, conn ); publishInPubSub(packet, conn, queue, settings); Authorization saveResult = savePacketForOffLineUser( packet, msg_repo, repo ); Packet result = null; switch (saveResult) { case SERVICE_UNAVAILABLE: result = saveResult.getResponseMessage(packet, "Offline messages queue is full", true); break; default: break; } if (result != null) { queue.offer(result); } } catch ( UserNotFoundException e ) { if ( log.isLoggable( Level.FINEST ) ){ log.finest( "UserNotFoundException at trying to save packet for off-line user." + packet ); } } catch (NotAuthorizedException ex) { if ( log.isLoggable( Level.FINEST ) ){ log.log(Level.FINEST, "NotAuthorizedException when checking if message is to this " + "user at trying to save packet for off-line user, {0}, {1}", new Object[]{ packet, conn }); } } catch (PacketErrorTypeException ex) { log.log(Level.FINE, "Could not sent error to packet sent to offline user which storage to offline " + "store failed. Packet is error type already: {0}", packet.toStringSecure()); } } } } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { @Override public void postProcess( final Packet packet, final XMPPResourceConnection conn, final NonAuthUserRepository repo, final Queue<Packet> queue, Map<String, Object> settings ) { if ( conn == null || !message.hasConnectionForMessageDelivery(conn) ){ try { if (packet.getElemName() == tigase.server.Message.ELEM_NAME && packet.getStanzaTo() != null && packet.getStanzaTo().getResource() != null) { return; } if (conn != null && packet.getStanzaTo() != null && !conn.isUserId(packet.getStanzaTo().getBareJID())) return; MsgRepositoryIfc msg_repo = getMsgRepoImpl( repo, conn ); publishInPubSub(packet, conn, queue, settings); Authorization saveResult = savePacketForOffLineUser( packet, msg_repo, repo ); Packet result = null; switch (saveResult) { case SERVICE_UNAVAILABLE: result = saveResult.getResponseMessage(packet, "Offline messages queue is full", true); break; default: break; } if (result != null) { queue.offer(result); } } catch ( UserNotFoundException e ) { if ( log.isLoggable( Level.FINEST ) ){ log.finest( "UserNotFoundException at trying to save packet for off-line user." + packet ); } } catch (NotAuthorizedException ex) { if ( log.isLoggable( Level.FINEST ) ){ log.log(Level.FINEST, "NotAuthorizedException when checking if message is to this " + "user at trying to save packet for off-line user, {0}, {1}", new Object[]{ packet, conn }); } } catch (PacketErrorTypeException ex) { log.log(Level.FINE, "Could not sent error to packet sent to offline user which storage to offline " + "store failed. Packet is error type already: {0}", packet.toStringSecure()); } } } } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { @Override public void postProcess( final Packet packet, final XMPPResourceConnection conn, final NonAuthUserRepository repo, final Queue<Packet> queue, Map<String, Object> settings ) { if ( conn == null || !message.hasConnectionForMessageDelivery(conn) ){ try { if (packet.getElemName() == tigase.server.Message.ELEM_NAME && packet.getStanzaTo() != null && packet.getStanzaTo().getResource() != null) { return; } if (conn != null && packet.getStanzaTo() != null && !conn.isUserId(packet.getStanzaTo().getBareJID())) return; MsgRepositoryIfc msg_repo = getMsgRepoImpl( repo, conn ); publishInPubSub(packet, conn, queue, settings); Authorization saveResult = savePacketForOffLineUser( packet, msg_repo, repo ); Packet result = null; switch (saveResult) { case SERVICE_UNAVAILABLE: result = saveResult.getResponseMessage(packet, "Offline messages queue is full", true); break; default: break; } if (result != null) { queue.offer(result); } } catch ( UserNotFoundException e ) { if ( log.isLoggable( Level.FINEST ) ){ log.finest( "UserNotFoundException at trying to save packet for off-line user." + packet ); } } catch (NotAuthorizedException ex) { if ( log.isLoggable( Level.FINEST ) ){ log.log(Level.FINEST, "NotAuthorizedException when checking if message is to this " + "user at trying to save packet for off-line user, {0}, {1}", new Object[]{ packet, conn }); } } catch (PacketErrorTypeException ex) { log.log(Level.FINE, "Could not sent error to packet sent to offline user which storage to offline " + "store failed. Packet is error type already: {0}", packet.toStringSecure()); } } } @Override String id(); @Override void init(Map<String, Object> settings); @Override void postProcess( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> queue,
Map<String, Object> settings ); @Override void process( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings ); void processIq(Packet packet, XMPPResourceConnection conn, NonAuthUserRepository repo, Queue<Packet> results); Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo ); Authorization savePacketForOffLineUser( Packet pac, MsgRepositoryIfc repo, NonAuthUserRepository userRepo); @Override Element[] supDiscoFeatures( final XMPPResourceConnection session ); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); void publishInPubSub(final Packet packet, final XMPPResourceConnection conn, final Queue<Packet> queue,
Map<String, Object> settings); } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { @Override public void postProcess( final Packet packet, final XMPPResourceConnection conn, final NonAuthUserRepository repo, final Queue<Packet> queue, Map<String, Object> settings ) { if ( conn == null || !message.hasConnectionForMessageDelivery(conn) ){ try { if (packet.getElemName() == tigase.server.Message.ELEM_NAME && packet.getStanzaTo() != null && packet.getStanzaTo().getResource() != null) { return; } if (conn != null && packet.getStanzaTo() != null && !conn.isUserId(packet.getStanzaTo().getBareJID())) return; MsgRepositoryIfc msg_repo = getMsgRepoImpl( repo, conn ); publishInPubSub(packet, conn, queue, settings); Authorization saveResult = savePacketForOffLineUser( packet, msg_repo, repo ); Packet result = null; switch (saveResult) { case SERVICE_UNAVAILABLE: result = saveResult.getResponseMessage(packet, "Offline messages queue is full", true); break; default: break; } if (result != null) { queue.offer(result); } } catch ( UserNotFoundException e ) { if ( log.isLoggable( Level.FINEST ) ){ log.finest( "UserNotFoundException at trying to save packet for off-line user." + packet ); } } catch (NotAuthorizedException ex) { if ( log.isLoggable( Level.FINEST ) ){ log.log(Level.FINEST, "NotAuthorizedException when checking if message is to this " + "user at trying to save packet for off-line user, {0}, {1}", new Object[]{ packet, conn }); } } catch (PacketErrorTypeException ex) { log.log(Level.FINE, "Could not sent error to packet sent to offline user which storage to offline " + "store failed. Packet is error type already: {0}", packet.toStringSecure()); } } } @Override String id(); @Override void init(Map<String, Object> settings); @Override void postProcess( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> queue,
Map<String, Object> settings ); @Override void process( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings ); void processIq(Packet packet, XMPPResourceConnection conn, NonAuthUserRepository repo, Queue<Packet> results); Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo ); Authorization savePacketForOffLineUser( Packet pac, MsgRepositoryIfc repo, NonAuthUserRepository userRepo); @Override Element[] supDiscoFeatures( final XMPPResourceConnection session ); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); void publishInPubSub(final Packet packet, final XMPPResourceConnection conn, final Queue<Packet> queue,
Map<String, Object> settings); static final String[] MESSAGE_EVENT_PATH; static final String[] MESSAGE_HEADER_PATH; static final String[] MESSAGE_HINTS_NO_STORE; static final String MESSAGE_HINTS_XMLNS; static final String[] MESSAGE_RECEIVED_PATH; static final String MESSAGE_RECEIVED_XMLNS; static final String[] PUBSUB_NODE_PATH; static final String PUBSUB_NODE_KEY; } |
@Test public void testStorageOfflineMessageForFullJid() throws Exception { BareJID userJid = BareJID.bareJIDInstance("[email protected]"); JID res1 = JID.jidInstance(userJid, "res1"); JID res2 = JID.jidInstance(userJid, "res2"); XMPPResourceConnection session1 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res1); XMPPResourceConnection session2 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res2); assertEquals(Arrays.asList(session1, session2), session1.getActiveSessions()); Element packetEl = new Element("message", new String[] { "type", "from", "to" }, new String[] { "chat", "[email protected]/res1", res2.toString() }); packetEl.addChild(new Element("body", "Test message")); Packet packet = Packet.packetInstance(packetEl); Queue<Packet> results = new ArrayDeque<Packet>(); offlineProcessor.postProcess(packet, session1, null, results, null); assertTrue("generated result even than no result should be generated", results.isEmpty()); assertTrue("message stored, while it should not be stored", msgRepo.getStored().isEmpty()); msgRepo.getStored().clear(); session1.setPriority(1); results = new ArrayDeque<Packet>(); offlineProcessor.postProcess(packet, session1, null, results, null); assertTrue("generated result even than no result should be generated", results.isEmpty()); assertTrue("message stored, while it should not be stored", msgRepo.getStored().isEmpty()); msgRepo.getStored().clear(); session1.setPresence(new Element("presence")); results = new ArrayDeque<Packet>(); offlineProcessor.postProcess(packet, session1, null, results, null); assertTrue("generated result even than no result should be generated", results.isEmpty()); assertTrue("message stored, while it should not be stored", msgRepo.getStored().isEmpty()); msgRepo.getStored().clear(); } | @Override public void postProcess( final Packet packet, final XMPPResourceConnection conn, final NonAuthUserRepository repo, final Queue<Packet> queue, Map<String, Object> settings ) { if ( conn == null || !message.hasConnectionForMessageDelivery(conn) ){ try { if (packet.getElemName() == tigase.server.Message.ELEM_NAME && packet.getStanzaTo() != null && packet.getStanzaTo().getResource() != null) { return; } if (conn != null && packet.getStanzaTo() != null && !conn.isUserId(packet.getStanzaTo().getBareJID())) return; MsgRepositoryIfc msg_repo = getMsgRepoImpl( repo, conn ); publishInPubSub(packet, conn, queue, settings); Authorization saveResult = savePacketForOffLineUser( packet, msg_repo, repo ); Packet result = null; switch (saveResult) { case SERVICE_UNAVAILABLE: result = saveResult.getResponseMessage(packet, "Offline messages queue is full", true); break; default: break; } if (result != null) { queue.offer(result); } } catch ( UserNotFoundException e ) { if ( log.isLoggable( Level.FINEST ) ){ log.finest( "UserNotFoundException at trying to save packet for off-line user." + packet ); } } catch (NotAuthorizedException ex) { if ( log.isLoggable( Level.FINEST ) ){ log.log(Level.FINEST, "NotAuthorizedException when checking if message is to this " + "user at trying to save packet for off-line user, {0}, {1}", new Object[]{ packet, conn }); } } catch (PacketErrorTypeException ex) { log.log(Level.FINE, "Could not sent error to packet sent to offline user which storage to offline " + "store failed. Packet is error type already: {0}", packet.toStringSecure()); } } } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { @Override public void postProcess( final Packet packet, final XMPPResourceConnection conn, final NonAuthUserRepository repo, final Queue<Packet> queue, Map<String, Object> settings ) { if ( conn == null || !message.hasConnectionForMessageDelivery(conn) ){ try { if (packet.getElemName() == tigase.server.Message.ELEM_NAME && packet.getStanzaTo() != null && packet.getStanzaTo().getResource() != null) { return; } if (conn != null && packet.getStanzaTo() != null && !conn.isUserId(packet.getStanzaTo().getBareJID())) return; MsgRepositoryIfc msg_repo = getMsgRepoImpl( repo, conn ); publishInPubSub(packet, conn, queue, settings); Authorization saveResult = savePacketForOffLineUser( packet, msg_repo, repo ); Packet result = null; switch (saveResult) { case SERVICE_UNAVAILABLE: result = saveResult.getResponseMessage(packet, "Offline messages queue is full", true); break; default: break; } if (result != null) { queue.offer(result); } } catch ( UserNotFoundException e ) { if ( log.isLoggable( Level.FINEST ) ){ log.finest( "UserNotFoundException at trying to save packet for off-line user." + packet ); } } catch (NotAuthorizedException ex) { if ( log.isLoggable( Level.FINEST ) ){ log.log(Level.FINEST, "NotAuthorizedException when checking if message is to this " + "user at trying to save packet for off-line user, {0}, {1}", new Object[]{ packet, conn }); } } catch (PacketErrorTypeException ex) { log.log(Level.FINE, "Could not sent error to packet sent to offline user which storage to offline " + "store failed. Packet is error type already: {0}", packet.toStringSecure()); } } } } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { @Override public void postProcess( final Packet packet, final XMPPResourceConnection conn, final NonAuthUserRepository repo, final Queue<Packet> queue, Map<String, Object> settings ) { if ( conn == null || !message.hasConnectionForMessageDelivery(conn) ){ try { if (packet.getElemName() == tigase.server.Message.ELEM_NAME && packet.getStanzaTo() != null && packet.getStanzaTo().getResource() != null) { return; } if (conn != null && packet.getStanzaTo() != null && !conn.isUserId(packet.getStanzaTo().getBareJID())) return; MsgRepositoryIfc msg_repo = getMsgRepoImpl( repo, conn ); publishInPubSub(packet, conn, queue, settings); Authorization saveResult = savePacketForOffLineUser( packet, msg_repo, repo ); Packet result = null; switch (saveResult) { case SERVICE_UNAVAILABLE: result = saveResult.getResponseMessage(packet, "Offline messages queue is full", true); break; default: break; } if (result != null) { queue.offer(result); } } catch ( UserNotFoundException e ) { if ( log.isLoggable( Level.FINEST ) ){ log.finest( "UserNotFoundException at trying to save packet for off-line user." + packet ); } } catch (NotAuthorizedException ex) { if ( log.isLoggable( Level.FINEST ) ){ log.log(Level.FINEST, "NotAuthorizedException when checking if message is to this " + "user at trying to save packet for off-line user, {0}, {1}", new Object[]{ packet, conn }); } } catch (PacketErrorTypeException ex) { log.log(Level.FINE, "Could not sent error to packet sent to offline user which storage to offline " + "store failed. Packet is error type already: {0}", packet.toStringSecure()); } } } } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { @Override public void postProcess( final Packet packet, final XMPPResourceConnection conn, final NonAuthUserRepository repo, final Queue<Packet> queue, Map<String, Object> settings ) { if ( conn == null || !message.hasConnectionForMessageDelivery(conn) ){ try { if (packet.getElemName() == tigase.server.Message.ELEM_NAME && packet.getStanzaTo() != null && packet.getStanzaTo().getResource() != null) { return; } if (conn != null && packet.getStanzaTo() != null && !conn.isUserId(packet.getStanzaTo().getBareJID())) return; MsgRepositoryIfc msg_repo = getMsgRepoImpl( repo, conn ); publishInPubSub(packet, conn, queue, settings); Authorization saveResult = savePacketForOffLineUser( packet, msg_repo, repo ); Packet result = null; switch (saveResult) { case SERVICE_UNAVAILABLE: result = saveResult.getResponseMessage(packet, "Offline messages queue is full", true); break; default: break; } if (result != null) { queue.offer(result); } } catch ( UserNotFoundException e ) { if ( log.isLoggable( Level.FINEST ) ){ log.finest( "UserNotFoundException at trying to save packet for off-line user." + packet ); } } catch (NotAuthorizedException ex) { if ( log.isLoggable( Level.FINEST ) ){ log.log(Level.FINEST, "NotAuthorizedException when checking if message is to this " + "user at trying to save packet for off-line user, {0}, {1}", new Object[]{ packet, conn }); } } catch (PacketErrorTypeException ex) { log.log(Level.FINE, "Could not sent error to packet sent to offline user which storage to offline " + "store failed. Packet is error type already: {0}", packet.toStringSecure()); } } } @Override String id(); @Override void init(Map<String, Object> settings); @Override void postProcess( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> queue,
Map<String, Object> settings ); @Override void process( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings ); void processIq(Packet packet, XMPPResourceConnection conn, NonAuthUserRepository repo, Queue<Packet> results); Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo ); Authorization savePacketForOffLineUser( Packet pac, MsgRepositoryIfc repo, NonAuthUserRepository userRepo); @Override Element[] supDiscoFeatures( final XMPPResourceConnection session ); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); void publishInPubSub(final Packet packet, final XMPPResourceConnection conn, final Queue<Packet> queue,
Map<String, Object> settings); } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { @Override public void postProcess( final Packet packet, final XMPPResourceConnection conn, final NonAuthUserRepository repo, final Queue<Packet> queue, Map<String, Object> settings ) { if ( conn == null || !message.hasConnectionForMessageDelivery(conn) ){ try { if (packet.getElemName() == tigase.server.Message.ELEM_NAME && packet.getStanzaTo() != null && packet.getStanzaTo().getResource() != null) { return; } if (conn != null && packet.getStanzaTo() != null && !conn.isUserId(packet.getStanzaTo().getBareJID())) return; MsgRepositoryIfc msg_repo = getMsgRepoImpl( repo, conn ); publishInPubSub(packet, conn, queue, settings); Authorization saveResult = savePacketForOffLineUser( packet, msg_repo, repo ); Packet result = null; switch (saveResult) { case SERVICE_UNAVAILABLE: result = saveResult.getResponseMessage(packet, "Offline messages queue is full", true); break; default: break; } if (result != null) { queue.offer(result); } } catch ( UserNotFoundException e ) { if ( log.isLoggable( Level.FINEST ) ){ log.finest( "UserNotFoundException at trying to save packet for off-line user." + packet ); } } catch (NotAuthorizedException ex) { if ( log.isLoggable( Level.FINEST ) ){ log.log(Level.FINEST, "NotAuthorizedException when checking if message is to this " + "user at trying to save packet for off-line user, {0}, {1}", new Object[]{ packet, conn }); } } catch (PacketErrorTypeException ex) { log.log(Level.FINE, "Could not sent error to packet sent to offline user which storage to offline " + "store failed. Packet is error type already: {0}", packet.toStringSecure()); } } } @Override String id(); @Override void init(Map<String, Object> settings); @Override void postProcess( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> queue,
Map<String, Object> settings ); @Override void process( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings ); void processIq(Packet packet, XMPPResourceConnection conn, NonAuthUserRepository repo, Queue<Packet> results); Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo ); Authorization savePacketForOffLineUser( Packet pac, MsgRepositoryIfc repo, NonAuthUserRepository userRepo); @Override Element[] supDiscoFeatures( final XMPPResourceConnection session ); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); void publishInPubSub(final Packet packet, final XMPPResourceConnection conn, final Queue<Packet> queue,
Map<String, Object> settings); static final String[] MESSAGE_EVENT_PATH; static final String[] MESSAGE_HEADER_PATH; static final String[] MESSAGE_HINTS_NO_STORE; static final String MESSAGE_HINTS_XMLNS; static final String[] MESSAGE_RECEIVED_PATH; static final String MESSAGE_RECEIVED_XMLNS; static final String[] PUBSUB_NODE_PATH; static final String PUBSUB_NODE_KEY; } |
@Test public void testRestorePacketForOffLineUser() throws Exception { BareJID userJid = BareJID.bareJIDInstance("[email protected]"); JID res1 = JID.jidInstance(userJid, "res1"); XMPPResourceConnection session1 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res1); assertEquals(Arrays.asList(session1), session1.getActiveSessions()); Element packetEl = new Element("iq", new String[] { "type", "from", "to", "time" }, new String[] { "set", "[email protected]/res1", userJid.toString(), "1440810935000" }); packetEl.addChild(new Element("jingle", new String[] { "action", "sid", "offline", "xmlns" }, new String[] { "session-terminate", UUID.randomUUID().toString(), "true", "urn:xmpp:jingle:1" })); Packet packet = Packet.packetInstance(packetEl); msgRepo.storeMessage( packet.getFrom(), packet.getTo(), null, packet.getElement(), null); packetEl = new Element("iq", new String[] { "type", "from", "to", "time" }, new String[] { "set", "[email protected]/res1", userJid.toString(), "1440810972000" }); packetEl.addChild(new Element("jingle", new String[] { "action", "sid", "offline", "xmlns" }, new String[] { "session-terminate", UUID.randomUUID().toString(), "true", "urn:xmpp:jingle:1" })); packet = Packet.packetInstance(packetEl); msgRepo.storeMessage( packet.getFrom(), packet.getTo(), null, packet.getElement(), null); assertTrue("no message stored, while it should be stored", !msgRepo.getStored().isEmpty()); Queue<Packet> restorePacketForOffLineUser = offlineProcessor.restorePacketForOffLineUser( session1, msgRepo ); assertEquals("number of restored messages differ!", restorePacketForOffLineUser.size(), 2); msgRepo.getStored().clear(); } | public Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn, MsgRepositoryIfc repo ) throws UserNotFoundException, NotAuthorizedException { Queue<Element> elems = repo.loadMessagesToJID( conn, true ); if ( elems != null ){ LinkedList<Packet> pacs = new LinkedList<Packet>(); Element elem = null; while ( ( elem = elems.poll() ) != null ) { try { Packet p = Packet.packetInstance( elem ); if (p.getElemName() == Iq.ELEM_NAME) { p.initVars(p.getStanzaFrom(), conn.getJID()); } pacs.offer( p ); } catch ( TigaseStringprepException ex ) { log.warning( "Packet addressing problem, stringprep failed: " + elem ); } } try { Collections.sort( pacs, new StampComparator() ); } catch ( NullPointerException e ) { try { log.warning( "Can not sort off line messages: " + pacs + ",\n" + e ); } catch ( Exception exc ) { log.log( Level.WARNING, "Can not print log message.", exc ); } } return pacs; } return null; } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { public Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn, MsgRepositoryIfc repo ) throws UserNotFoundException, NotAuthorizedException { Queue<Element> elems = repo.loadMessagesToJID( conn, true ); if ( elems != null ){ LinkedList<Packet> pacs = new LinkedList<Packet>(); Element elem = null; while ( ( elem = elems.poll() ) != null ) { try { Packet p = Packet.packetInstance( elem ); if (p.getElemName() == Iq.ELEM_NAME) { p.initVars(p.getStanzaFrom(), conn.getJID()); } pacs.offer( p ); } catch ( TigaseStringprepException ex ) { log.warning( "Packet addressing problem, stringprep failed: " + elem ); } } try { Collections.sort( pacs, new StampComparator() ); } catch ( NullPointerException e ) { try { log.warning( "Can not sort off line messages: " + pacs + ",\n" + e ); } catch ( Exception exc ) { log.log( Level.WARNING, "Can not print log message.", exc ); } } return pacs; } return null; } } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { public Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn, MsgRepositoryIfc repo ) throws UserNotFoundException, NotAuthorizedException { Queue<Element> elems = repo.loadMessagesToJID( conn, true ); if ( elems != null ){ LinkedList<Packet> pacs = new LinkedList<Packet>(); Element elem = null; while ( ( elem = elems.poll() ) != null ) { try { Packet p = Packet.packetInstance( elem ); if (p.getElemName() == Iq.ELEM_NAME) { p.initVars(p.getStanzaFrom(), conn.getJID()); } pacs.offer( p ); } catch ( TigaseStringprepException ex ) { log.warning( "Packet addressing problem, stringprep failed: " + elem ); } } try { Collections.sort( pacs, new StampComparator() ); } catch ( NullPointerException e ) { try { log.warning( "Can not sort off line messages: " + pacs + ",\n" + e ); } catch ( Exception exc ) { log.log( Level.WARNING, "Can not print log message.", exc ); } } return pacs; } return null; } } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { public Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn, MsgRepositoryIfc repo ) throws UserNotFoundException, NotAuthorizedException { Queue<Element> elems = repo.loadMessagesToJID( conn, true ); if ( elems != null ){ LinkedList<Packet> pacs = new LinkedList<Packet>(); Element elem = null; while ( ( elem = elems.poll() ) != null ) { try { Packet p = Packet.packetInstance( elem ); if (p.getElemName() == Iq.ELEM_NAME) { p.initVars(p.getStanzaFrom(), conn.getJID()); } pacs.offer( p ); } catch ( TigaseStringprepException ex ) { log.warning( "Packet addressing problem, stringprep failed: " + elem ); } } try { Collections.sort( pacs, new StampComparator() ); } catch ( NullPointerException e ) { try { log.warning( "Can not sort off line messages: " + pacs + ",\n" + e ); } catch ( Exception exc ) { log.log( Level.WARNING, "Can not print log message.", exc ); } } return pacs; } return null; } @Override String id(); @Override void init(Map<String, Object> settings); @Override void postProcess( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> queue,
Map<String, Object> settings ); @Override void process( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings ); void processIq(Packet packet, XMPPResourceConnection conn, NonAuthUserRepository repo, Queue<Packet> results); Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo ); Authorization savePacketForOffLineUser( Packet pac, MsgRepositoryIfc repo, NonAuthUserRepository userRepo); @Override Element[] supDiscoFeatures( final XMPPResourceConnection session ); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); void publishInPubSub(final Packet packet, final XMPPResourceConnection conn, final Queue<Packet> queue,
Map<String, Object> settings); } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { public Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn, MsgRepositoryIfc repo ) throws UserNotFoundException, NotAuthorizedException { Queue<Element> elems = repo.loadMessagesToJID( conn, true ); if ( elems != null ){ LinkedList<Packet> pacs = new LinkedList<Packet>(); Element elem = null; while ( ( elem = elems.poll() ) != null ) { try { Packet p = Packet.packetInstance( elem ); if (p.getElemName() == Iq.ELEM_NAME) { p.initVars(p.getStanzaFrom(), conn.getJID()); } pacs.offer( p ); } catch ( TigaseStringprepException ex ) { log.warning( "Packet addressing problem, stringprep failed: " + elem ); } } try { Collections.sort( pacs, new StampComparator() ); } catch ( NullPointerException e ) { try { log.warning( "Can not sort off line messages: " + pacs + ",\n" + e ); } catch ( Exception exc ) { log.log( Level.WARNING, "Can not print log message.", exc ); } } return pacs; } return null; } @Override String id(); @Override void init(Map<String, Object> settings); @Override void postProcess( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> queue,
Map<String, Object> settings ); @Override void process( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings ); void processIq(Packet packet, XMPPResourceConnection conn, NonAuthUserRepository repo, Queue<Packet> results); Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo ); Authorization savePacketForOffLineUser( Packet pac, MsgRepositoryIfc repo, NonAuthUserRepository userRepo); @Override Element[] supDiscoFeatures( final XMPPResourceConnection session ); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); void publishInPubSub(final Packet packet, final XMPPResourceConnection conn, final Queue<Packet> queue,
Map<String, Object> settings); static final String[] MESSAGE_EVENT_PATH; static final String[] MESSAGE_HEADER_PATH; static final String[] MESSAGE_HINTS_NO_STORE; static final String MESSAGE_HINTS_XMLNS; static final String[] MESSAGE_RECEIVED_PATH; static final String MESSAGE_RECEIVED_XMLNS; static final String[] PUBSUB_NODE_PATH; static final String PUBSUB_NODE_KEY; } |
@Test public void testParseSizeInt() { System.out.println( "parseSizeInt" ); assertEquals( 1, DataTypes.parseSizeInt( "1", 1 ) ); assertEquals( 1024, DataTypes.parseSizeInt( "1k", 1 ) ); assertEquals( 1024 * 1024, DataTypes.parseSizeInt( "1m", 1 ) ); assertEquals( 1024 * 1024 * 1024, DataTypes.parseSizeInt( "1g", 1 ) ); assertEquals( 1, DataTypes.parseSizeInt( "fail", 1 ) ); } | public static int parseSizeInt(String size, int def) { return parseNum(size, Integer.class, def); } | DataTypes { public static int parseSizeInt(String size, int def) { return parseNum(size, Integer.class, def); } } | DataTypes { public static int parseSizeInt(String size, int def) { return parseNum(size, Integer.class, def); } } | DataTypes { public static int parseSizeInt(String size, int def) { return parseNum(size, Integer.class, def); } static T parseNum(String num, Class<T> cls, T def); static int parseSizeInt(String size, int def); static boolean parseBool(final String val); static Object decodeValueType(char typeId, String value); static String valueToString(final Object value); static char decodeTypeIdFromName(String name); static String stripNameFromTypeId(String name); static String encodeTypeIdInName(String name, Object value); static char getTypeId(Object instance); static boolean getProperty(String key, Boolean def); static void main( String[] args ); } | DataTypes { public static int parseSizeInt(String size, int def) { return parseNum(size, Integer.class, def); } static T parseNum(String num, Class<T> cls, T def); static int parseSizeInt(String size, int def); static boolean parseBool(final String val); static Object decodeValueType(char typeId, String value); static String valueToString(final Object value); static char decodeTypeIdFromName(String name); static String stripNameFromTypeId(String name); static String encodeTypeIdInName(String name, Object value); static char getTypeId(Object instance); static boolean getProperty(String key, Boolean def); static void main( String[] args ); static final Map<String, Character> typesMap; } |
@Test public void testLoadOfflineMessages() throws Exception { BareJID userJid = BareJID.bareJIDInstance("[email protected]"); JID res1 = JID.jidInstance(userJid, "res1"); JID res2 = JID.jidInstance(userJid, "res2"); XMPPResourceConnection session1 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res1); XMPPResourceConnection session2 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res2); assertEquals(Arrays.asList(session1, session2), session1.getActiveSessions()); Element presenceEl = new Element("presence", new String[] { "from", "to" }, new String[] { res1.toString(), res2.toString() }); Packet packet = Packet.packetInstance(presenceEl); assertFalse(offlineProcessor.loadOfflineMessages(packet, session1)); presenceEl = new Element("presence", new String[] { "from" }, new String[] { res1.toString() }); packet = Packet.packetInstance(presenceEl); assertTrue(offlineProcessor.loadOfflineMessages(packet, session1)); } | protected boolean loadOfflineMessages( Packet packet, XMPPResourceConnection conn ) { if ( ( conn == null ) || conn.isAnonymous() ){ return false; } if ( conn.getSessionData( ID ) != null ){ return false; } if (packet.getStanzaTo() != null) return false; if ( conn.getCommonSessionData(FlexibleOfflineMessageRetrieval.FLEXIBLE_OFFLINE_XMLNS) != null ){ return false; } StanzaType type = packet.getType(); if ( ( type == null ) || ( type == StanzaType.available ) ){ String priority_str = packet.getElemCDataStaticStr( tigase.server.Presence.PRESENCE_PRIORITY_PATH ); int priority = 0; if ( priority_str != null ){ try { priority = Integer.decode( priority_str ); } catch ( NumberFormatException e ) { priority = 0; } } if ( priority >= 0 ){ conn.putSessionData( ID, ID ); return true; } } return false; } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { protected boolean loadOfflineMessages( Packet packet, XMPPResourceConnection conn ) { if ( ( conn == null ) || conn.isAnonymous() ){ return false; } if ( conn.getSessionData( ID ) != null ){ return false; } if (packet.getStanzaTo() != null) return false; if ( conn.getCommonSessionData(FlexibleOfflineMessageRetrieval.FLEXIBLE_OFFLINE_XMLNS) != null ){ return false; } StanzaType type = packet.getType(); if ( ( type == null ) || ( type == StanzaType.available ) ){ String priority_str = packet.getElemCDataStaticStr( tigase.server.Presence.PRESENCE_PRIORITY_PATH ); int priority = 0; if ( priority_str != null ){ try { priority = Integer.decode( priority_str ); } catch ( NumberFormatException e ) { priority = 0; } } if ( priority >= 0 ){ conn.putSessionData( ID, ID ); return true; } } return false; } } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { protected boolean loadOfflineMessages( Packet packet, XMPPResourceConnection conn ) { if ( ( conn == null ) || conn.isAnonymous() ){ return false; } if ( conn.getSessionData( ID ) != null ){ return false; } if (packet.getStanzaTo() != null) return false; if ( conn.getCommonSessionData(FlexibleOfflineMessageRetrieval.FLEXIBLE_OFFLINE_XMLNS) != null ){ return false; } StanzaType type = packet.getType(); if ( ( type == null ) || ( type == StanzaType.available ) ){ String priority_str = packet.getElemCDataStaticStr( tigase.server.Presence.PRESENCE_PRIORITY_PATH ); int priority = 0; if ( priority_str != null ){ try { priority = Integer.decode( priority_str ); } catch ( NumberFormatException e ) { priority = 0; } } if ( priority >= 0 ){ conn.putSessionData( ID, ID ); return true; } } return false; } } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { protected boolean loadOfflineMessages( Packet packet, XMPPResourceConnection conn ) { if ( ( conn == null ) || conn.isAnonymous() ){ return false; } if ( conn.getSessionData( ID ) != null ){ return false; } if (packet.getStanzaTo() != null) return false; if ( conn.getCommonSessionData(FlexibleOfflineMessageRetrieval.FLEXIBLE_OFFLINE_XMLNS) != null ){ return false; } StanzaType type = packet.getType(); if ( ( type == null ) || ( type == StanzaType.available ) ){ String priority_str = packet.getElemCDataStaticStr( tigase.server.Presence.PRESENCE_PRIORITY_PATH ); int priority = 0; if ( priority_str != null ){ try { priority = Integer.decode( priority_str ); } catch ( NumberFormatException e ) { priority = 0; } } if ( priority >= 0 ){ conn.putSessionData( ID, ID ); return true; } } return false; } @Override String id(); @Override void init(Map<String, Object> settings); @Override void postProcess( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> queue,
Map<String, Object> settings ); @Override void process( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings ); void processIq(Packet packet, XMPPResourceConnection conn, NonAuthUserRepository repo, Queue<Packet> results); Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo ); Authorization savePacketForOffLineUser( Packet pac, MsgRepositoryIfc repo, NonAuthUserRepository userRepo); @Override Element[] supDiscoFeatures( final XMPPResourceConnection session ); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); void publishInPubSub(final Packet packet, final XMPPResourceConnection conn, final Queue<Packet> queue,
Map<String, Object> settings); } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { protected boolean loadOfflineMessages( Packet packet, XMPPResourceConnection conn ) { if ( ( conn == null ) || conn.isAnonymous() ){ return false; } if ( conn.getSessionData( ID ) != null ){ return false; } if (packet.getStanzaTo() != null) return false; if ( conn.getCommonSessionData(FlexibleOfflineMessageRetrieval.FLEXIBLE_OFFLINE_XMLNS) != null ){ return false; } StanzaType type = packet.getType(); if ( ( type == null ) || ( type == StanzaType.available ) ){ String priority_str = packet.getElemCDataStaticStr( tigase.server.Presence.PRESENCE_PRIORITY_PATH ); int priority = 0; if ( priority_str != null ){ try { priority = Integer.decode( priority_str ); } catch ( NumberFormatException e ) { priority = 0; } } if ( priority >= 0 ){ conn.putSessionData( ID, ID ); return true; } } return false; } @Override String id(); @Override void init(Map<String, Object> settings); @Override void postProcess( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> queue,
Map<String, Object> settings ); @Override void process( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings ); void processIq(Packet packet, XMPPResourceConnection conn, NonAuthUserRepository repo, Queue<Packet> results); Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo ); Authorization savePacketForOffLineUser( Packet pac, MsgRepositoryIfc repo, NonAuthUserRepository userRepo); @Override Element[] supDiscoFeatures( final XMPPResourceConnection session ); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); void publishInPubSub(final Packet packet, final XMPPResourceConnection conn, final Queue<Packet> queue,
Map<String, Object> settings); static final String[] MESSAGE_EVENT_PATH; static final String[] MESSAGE_HEADER_PATH; static final String[] MESSAGE_HINTS_NO_STORE; static final String MESSAGE_HINTS_XMLNS; static final String[] MESSAGE_RECEIVED_PATH; static final String MESSAGE_RECEIVED_XMLNS; static final String[] PUBSUB_NODE_PATH; static final String PUBSUB_NODE_KEY; } |
@Test public void testIsAllowedForOfflineStorage() throws Exception { Packet packet = Packet.packetInstance(new Element("message", new Element[]{ new Element("body", "Test message") }, new String[] { "from", "to" }, new String[] { "[email protected]/res1", "[email protected]/res2" })); assertTrue(offlineProcessor.isAllowedForOfflineStorage(packet)); packet = Packet.packetInstance(new Element("message", new Element[]{ new Element("storeMe1", new String[] { "xmlns" }, new String[] { "custom_xmlns" }) }, new String[] { "from", "to" }, new String[] { "[email protected]/res1", "[email protected]/res2" })); assertFalse(offlineProcessor.isAllowedForOfflineStorage(packet)); Map<String,Object> settings = new HashMap<>(); settings.put("msg-store-offline-paths", new String[] { "/message/storeMe1[custom_xmlns]", "/message/storeMe2", "-/message/noStore1" }); offlineProcessor.init(settings); assertTrue(offlineProcessor.isAllowedForOfflineStorage(packet)); packet = Packet.packetInstance(new Element("message", new Element[]{ new Element("storeMe2", new String[] { "xmlns" }, new String[] { "custom_xmlns" }) }, new String[] { "from", "to" }, new String[] { "[email protected]/res1", "[email protected]/res2" })); assertTrue(offlineProcessor.isAllowedForOfflineStorage(packet)); packet = Packet.packetInstance(new Element("message", new Element[]{ new Element("storeMe3", new String[] { "xmlns" }, new String[] { "custom_xmlns" }) }, new String[] { "from", "to" }, new String[] { "[email protected]/res1", "[email protected]/res2" })); assertFalse(offlineProcessor.isAllowedForOfflineStorage(packet)); packet = Packet.packetInstance(new Element("message", new Element[]{ new Element("body", "Test message 123"), new Element("no-store", new String[] { "xmlns" }, new String[] { "urn:xmpp:hints" }) }, new String[] { "from", "to" }, new String[] { "[email protected]/res1", "[email protected]/res2" })); assertFalse(offlineProcessor.isAllowedForOfflineStorage(packet)); packet = Packet.packetInstance(new Element("message", new Element[]{ new Element("noStore1"), new Element("body", "body of message") }, new String[] { "from", "to" }, new String[] { "[email protected]/res1", "[email protected]/res2" })); assertFalse(offlineProcessor.isAllowedForOfflineStorage(packet)); packet = Packet.packetInstance(new Element("message", new Element[]{ new Element("body", "body of message") }, new String[] { "from", "to" }, new String[] { "[email protected]/res1", "[email protected]/res2" })); assertTrue(offlineProcessor.isAllowedForOfflineStorage(packet)); } | protected boolean isAllowedForOfflineStorage(Packet pac) { for (ElementMatcher matcher : offlineStorageMatchers) { if (matcher.matches(pac)) return matcher.getValue(); } return isAllowedForOfflineStorageDefaults(pac); } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { protected boolean isAllowedForOfflineStorage(Packet pac) { for (ElementMatcher matcher : offlineStorageMatchers) { if (matcher.matches(pac)) return matcher.getValue(); } return isAllowedForOfflineStorageDefaults(pac); } } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { protected boolean isAllowedForOfflineStorage(Packet pac) { for (ElementMatcher matcher : offlineStorageMatchers) { if (matcher.matches(pac)) return matcher.getValue(); } return isAllowedForOfflineStorageDefaults(pac); } } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { protected boolean isAllowedForOfflineStorage(Packet pac) { for (ElementMatcher matcher : offlineStorageMatchers) { if (matcher.matches(pac)) return matcher.getValue(); } return isAllowedForOfflineStorageDefaults(pac); } @Override String id(); @Override void init(Map<String, Object> settings); @Override void postProcess( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> queue,
Map<String, Object> settings ); @Override void process( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings ); void processIq(Packet packet, XMPPResourceConnection conn, NonAuthUserRepository repo, Queue<Packet> results); Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo ); Authorization savePacketForOffLineUser( Packet pac, MsgRepositoryIfc repo, NonAuthUserRepository userRepo); @Override Element[] supDiscoFeatures( final XMPPResourceConnection session ); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); void publishInPubSub(final Packet packet, final XMPPResourceConnection conn, final Queue<Packet> queue,
Map<String, Object> settings); } | OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { protected boolean isAllowedForOfflineStorage(Packet pac) { for (ElementMatcher matcher : offlineStorageMatchers) { if (matcher.matches(pac)) return matcher.getValue(); } return isAllowedForOfflineStorageDefaults(pac); } @Override String id(); @Override void init(Map<String, Object> settings); @Override void postProcess( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> queue,
Map<String, Object> settings ); @Override void process( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings ); void processIq(Packet packet, XMPPResourceConnection conn, NonAuthUserRepository repo, Queue<Packet> results); Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo ); Authorization savePacketForOffLineUser( Packet pac, MsgRepositoryIfc repo, NonAuthUserRepository userRepo); @Override Element[] supDiscoFeatures( final XMPPResourceConnection session ); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); void publishInPubSub(final Packet packet, final XMPPResourceConnection conn, final Queue<Packet> queue,
Map<String, Object> settings); static final String[] MESSAGE_EVENT_PATH; static final String[] MESSAGE_HEADER_PATH; static final String[] MESSAGE_HINTS_NO_STORE; static final String MESSAGE_HINTS_XMLNS; static final String[] MESSAGE_RECEIVED_PATH; static final String MESSAGE_RECEIVED_XMLNS; static final String[] PUBSUB_NODE_PATH; static final String PUBSUB_NODE_KEY; } |
@Test public void testValidateListGood() { List<Element> items = new ArrayList<Element>(); Authorization result = null; items.add(new Element("item", new String[] { "type", "value", "action", "order" }, new String[] { "subscription", "both", "allow", "10" })); items.add(new Element("item", new String[] { "action", "order" }, new String[] { "deny", "15" })); result = JabberIqPrivacy.validateList(null, items); assertEquals(null, result); } | public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } |
@Test public void testValidateListBadAction() { List<Element> items = new ArrayList<Element>(); Authorization result = null; items.add(new Element("item", new String[] { "type", "value", "action", "order" }, new String[] { "subscription", "both", "ignore", "10" })); items.add(new Element("item", new String[] { "action", "order" }, new String[] { "deny", "15" })); result = JabberIqPrivacy.validateList(null, items); assertEquals(Authorization.BAD_REQUEST, result); } | public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } |
@Test public void testValidateListBadSubscription() { List<Element> items = new ArrayList<Element>(); Authorization result = null; items.add(new Element("item", new String[] { "type", "value", "action", "order" }, new String[] { "subscription", "or", "allow", "10" })); items.add(new Element("item", new String[] { "action", "order" }, new String[] { "deny", "15" })); result = JabberIqPrivacy.validateList(null, items); assertEquals(Authorization.BAD_REQUEST, result); } | public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } |
@Test public void testValidateListBadType() { List<Element> items = new ArrayList<Element>(); Authorization result = null; items.add(new Element("item", new String[] { "type", "value", "action", "order" }, new String[] { "other", "both", "allow", "10" })); items.add(new Element("item", new String[] { "action", "order" }, new String[] { "deny", "15" })); result = JabberIqPrivacy.validateList(null, items); assertEquals(Authorization.BAD_REQUEST, result); } | public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } |
@Test public void testValidateListOrderUnsignedInt() { List<Element> items = new ArrayList<Element>(); Authorization result = null; items.add(new Element("item", new String[] { "type", "value", "action", "order" }, new String[] { "subscription", "both", "allow", "-10" })); items.add(new Element("item", new String[] { "action", "order" }, new String[] { "deny", "15" })); result = JabberIqPrivacy.validateList(null, items); assertEquals(Authorization.BAD_REQUEST, result); } | public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } |
@Test public void testValidateListOrderAttributeDuplicate() { List<Element> items = new ArrayList<Element>(); Authorization result = null; items.add(new Element("item", new String[] { "type", "value", "action", "order" }, new String[] { "subscription", "both", "allow", "10" })); items.add(new Element("item", new String[] { "action", "order" }, new String[] { "deny", "10" })); result = JabberIqPrivacy.validateList(null, items); assertEquals(Authorization.BAD_REQUEST, result); } | public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } |
@Test public void testFilterPresenceOut() throws Exception { JID jid = JID.jidInstance("test@example/res-1"); JID connId = JID.jidInstance("[email protected]/asdasd"); XMPPResourceConnection session = getSession(connId, jid); Element list = new Element("list", new String[] { "name" }, new String[] { "default" }); Element item = new Element("item", new String[]{"type", "value", "action", "order"}, new String[]{"jid", "test1.example.com", "deny", "100"}); item.addChild(new Element("presence-out")); list.addChild(item); list.addChild(new Element("item", new String[]{"action", "order"}, new String[]{"allow", "110"})); session.putSessionData("active-list", list); Packet presence = Packet.packetInstance(new Element("presence", new String[] { "from", "to" }, new String[] { "test@example/res-1", "test1.example.com" })); assertFalse(privacyFilter.allowed(presence, session)); presence = Packet.packetInstance(new Element("presence", new String[] { "to", "from" }, new String[] { "test@example/res-1", "test1.example.com" })); assertTrue(privacyFilter.allowed(presence, session)); } | protected boolean allowed(Packet packet, XMPPResourceConnection session) { try { if (allowedByDefault(packet, session)) return true; Element list = Privacy.getActiveList(session); if ((list == null) ) { list = Privacy.getDefaultList( session ); } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Using privcy list: {0}", list); } if (list != null) { List<Element> items = list.getChildren(); if (items != null) { BareJID sessionUserId = session.getBareJID(); JID jid = packet.getStanzaFrom(); boolean packetIn = true; if ((jid == null) || sessionUserId.equals(jid.getBareJID())) { jid = packet.getStanzaTo(); packetIn = false; } Collections.sort(items, compar); for (Element item : items) { final ITEM_ACTION action = ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); boolean type_matched = false; boolean elem_matched = false; ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); if (jid != null) { switch (type) { case jid : type_matched = jid.toString().contains(value); break; case group : String[] groups = roster_util.getBuddyGroups(session, jid); if (groups != null) { for (String group : groups) { if (type_matched = group.equals(value)) { break; } } } break; case subscription : ITEM_SUBSCRIPTIONS subscr = ITEM_SUBSCRIPTIONS.valueOf(value); switch (subscr) { case to : type_matched = roster_util.isSubscribedTo(session, jid); break; case from : type_matched = roster_util.isSubscribedFrom(session, jid); break; case none : type_matched = (!roster_util.isSubscribedFrom(session, jid) && !roster_util.isSubscribedTo(session, jid)); break; case both : type_matched = (roster_util.isSubscribedFrom(session, jid) && roster_util.isSubscribedTo(session, jid)); break; default : break; } break; case all : default : type_matched = true; break; } } else { if (type == ITEM_TYPE.all) { type_matched = true; } } if (!type_matched) { continue; } List<Element> elems = item.getChildren(); if ((elems == null) || (elems.size() == 0)) { elem_matched = true; } else { for (Element elem : elems) { if (matchToPrivacyListElement(packetIn, packet, elem, action)) { elem_matched = true; break; } } } if (!elem_matched) { break; } switch (action) { case allow : return true; case deny : return false; default : break; } } } } else { return true; } } catch (NoConnectionIdException e) { } catch (NotAuthorizedException e) { } catch (TigaseDBException e) { log.log(Level.WARNING, "Database problem, please notify the admin. {0}", e); } return true; } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { protected boolean allowed(Packet packet, XMPPResourceConnection session) { try { if (allowedByDefault(packet, session)) return true; Element list = Privacy.getActiveList(session); if ((list == null) ) { list = Privacy.getDefaultList( session ); } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Using privcy list: {0}", list); } if (list != null) { List<Element> items = list.getChildren(); if (items != null) { BareJID sessionUserId = session.getBareJID(); JID jid = packet.getStanzaFrom(); boolean packetIn = true; if ((jid == null) || sessionUserId.equals(jid.getBareJID())) { jid = packet.getStanzaTo(); packetIn = false; } Collections.sort(items, compar); for (Element item : items) { final ITEM_ACTION action = ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); boolean type_matched = false; boolean elem_matched = false; ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); if (jid != null) { switch (type) { case jid : type_matched = jid.toString().contains(value); break; case group : String[] groups = roster_util.getBuddyGroups(session, jid); if (groups != null) { for (String group : groups) { if (type_matched = group.equals(value)) { break; } } } break; case subscription : ITEM_SUBSCRIPTIONS subscr = ITEM_SUBSCRIPTIONS.valueOf(value); switch (subscr) { case to : type_matched = roster_util.isSubscribedTo(session, jid); break; case from : type_matched = roster_util.isSubscribedFrom(session, jid); break; case none : type_matched = (!roster_util.isSubscribedFrom(session, jid) && !roster_util.isSubscribedTo(session, jid)); break; case both : type_matched = (roster_util.isSubscribedFrom(session, jid) && roster_util.isSubscribedTo(session, jid)); break; default : break; } break; case all : default : type_matched = true; break; } } else { if (type == ITEM_TYPE.all) { type_matched = true; } } if (!type_matched) { continue; } List<Element> elems = item.getChildren(); if ((elems == null) || (elems.size() == 0)) { elem_matched = true; } else { for (Element elem : elems) { if (matchToPrivacyListElement(packetIn, packet, elem, action)) { elem_matched = true; break; } } } if (!elem_matched) { break; } switch (action) { case allow : return true; case deny : return false; default : break; } } } } else { return true; } } catch (NoConnectionIdException e) { } catch (NotAuthorizedException e) { } catch (TigaseDBException e) { log.log(Level.WARNING, "Database problem, please notify the admin. {0}", e); } return true; } } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { protected boolean allowed(Packet packet, XMPPResourceConnection session) { try { if (allowedByDefault(packet, session)) return true; Element list = Privacy.getActiveList(session); if ((list == null) ) { list = Privacy.getDefaultList( session ); } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Using privcy list: {0}", list); } if (list != null) { List<Element> items = list.getChildren(); if (items != null) { BareJID sessionUserId = session.getBareJID(); JID jid = packet.getStanzaFrom(); boolean packetIn = true; if ((jid == null) || sessionUserId.equals(jid.getBareJID())) { jid = packet.getStanzaTo(); packetIn = false; } Collections.sort(items, compar); for (Element item : items) { final ITEM_ACTION action = ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); boolean type_matched = false; boolean elem_matched = false; ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); if (jid != null) { switch (type) { case jid : type_matched = jid.toString().contains(value); break; case group : String[] groups = roster_util.getBuddyGroups(session, jid); if (groups != null) { for (String group : groups) { if (type_matched = group.equals(value)) { break; } } } break; case subscription : ITEM_SUBSCRIPTIONS subscr = ITEM_SUBSCRIPTIONS.valueOf(value); switch (subscr) { case to : type_matched = roster_util.isSubscribedTo(session, jid); break; case from : type_matched = roster_util.isSubscribedFrom(session, jid); break; case none : type_matched = (!roster_util.isSubscribedFrom(session, jid) && !roster_util.isSubscribedTo(session, jid)); break; case both : type_matched = (roster_util.isSubscribedFrom(session, jid) && roster_util.isSubscribedTo(session, jid)); break; default : break; } break; case all : default : type_matched = true; break; } } else { if (type == ITEM_TYPE.all) { type_matched = true; } } if (!type_matched) { continue; } List<Element> elems = item.getChildren(); if ((elems == null) || (elems.size() == 0)) { elem_matched = true; } else { for (Element elem : elems) { if (matchToPrivacyListElement(packetIn, packet, elem, action)) { elem_matched = true; break; } } } if (!elem_matched) { break; } switch (action) { case allow : return true; case deny : return false; default : break; } } } } else { return true; } } catch (NoConnectionIdException e) { } catch (NotAuthorizedException e) { } catch (TigaseDBException e) { log.log(Level.WARNING, "Database problem, please notify the admin. {0}", e); } return true; } } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { protected boolean allowed(Packet packet, XMPPResourceConnection session) { try { if (allowedByDefault(packet, session)) return true; Element list = Privacy.getActiveList(session); if ((list == null) ) { list = Privacy.getDefaultList( session ); } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Using privcy list: {0}", list); } if (list != null) { List<Element> items = list.getChildren(); if (items != null) { BareJID sessionUserId = session.getBareJID(); JID jid = packet.getStanzaFrom(); boolean packetIn = true; if ((jid == null) || sessionUserId.equals(jid.getBareJID())) { jid = packet.getStanzaTo(); packetIn = false; } Collections.sort(items, compar); for (Element item : items) { final ITEM_ACTION action = ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); boolean type_matched = false; boolean elem_matched = false; ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); if (jid != null) { switch (type) { case jid : type_matched = jid.toString().contains(value); break; case group : String[] groups = roster_util.getBuddyGroups(session, jid); if (groups != null) { for (String group : groups) { if (type_matched = group.equals(value)) { break; } } } break; case subscription : ITEM_SUBSCRIPTIONS subscr = ITEM_SUBSCRIPTIONS.valueOf(value); switch (subscr) { case to : type_matched = roster_util.isSubscribedTo(session, jid); break; case from : type_matched = roster_util.isSubscribedFrom(session, jid); break; case none : type_matched = (!roster_util.isSubscribedFrom(session, jid) && !roster_util.isSubscribedTo(session, jid)); break; case both : type_matched = (roster_util.isSubscribedFrom(session, jid) && roster_util.isSubscribedTo(session, jid)); break; default : break; } break; case all : default : type_matched = true; break; } } else { if (type == ITEM_TYPE.all) { type_matched = true; } } if (!type_matched) { continue; } List<Element> elems = item.getChildren(); if ((elems == null) || (elems.size() == 0)) { elem_matched = true; } else { for (Element elem : elems) { if (matchToPrivacyListElement(packetIn, packet, elem, action)) { elem_matched = true; break; } } } if (!elem_matched) { break; } switch (action) { case allow : return true; case deny : return false; default : break; } } } } else { return true; } } catch (NoConnectionIdException e) { } catch (NotAuthorizedException e) { } catch (TigaseDBException e) { log.log(Level.WARNING, "Database problem, please notify the admin. {0}", e); } return true; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } | JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { protected boolean allowed(Packet packet, XMPPResourceConnection session) { try { if (allowedByDefault(packet, session)) return true; Element list = Privacy.getActiveList(session); if ((list == null) ) { list = Privacy.getDefaultList( session ); } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Using privcy list: {0}", list); } if (list != null) { List<Element> items = list.getChildren(); if (items != null) { BareJID sessionUserId = session.getBareJID(); JID jid = packet.getStanzaFrom(); boolean packetIn = true; if ((jid == null) || sessionUserId.equals(jid.getBareJID())) { jid = packet.getStanzaTo(); packetIn = false; } Collections.sort(items, compar); for (Element item : items) { final ITEM_ACTION action = ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); boolean type_matched = false; boolean elem_matched = false; ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); if (jid != null) { switch (type) { case jid : type_matched = jid.toString().contains(value); break; case group : String[] groups = roster_util.getBuddyGroups(session, jid); if (groups != null) { for (String group : groups) { if (type_matched = group.equals(value)) { break; } } } break; case subscription : ITEM_SUBSCRIPTIONS subscr = ITEM_SUBSCRIPTIONS.valueOf(value); switch (subscr) { case to : type_matched = roster_util.isSubscribedTo(session, jid); break; case from : type_matched = roster_util.isSubscribedFrom(session, jid); break; case none : type_matched = (!roster_util.isSubscribedFrom(session, jid) && !roster_util.isSubscribedTo(session, jid)); break; case both : type_matched = (roster_util.isSubscribedFrom(session, jid) && roster_util.isSubscribedTo(session, jid)); break; default : break; } break; case all : default : type_matched = true; break; } } else { if (type == ITEM_TYPE.all) { type_matched = true; } } if (!type_matched) { continue; } List<Element> elems = item.getChildren(); if ((elems == null) || (elems.size() == 0)) { elem_matched = true; } else { for (Element elem : elems) { if (matchToPrivacyListElement(packetIn, packet, elem, action)) { elem_matched = true; break; } } } if (!elem_matched) { break; } switch (action) { case allow : return true; case deny : return false; default : break; } } } } else { return true; } } catch (NoConnectionIdException e) { } catch (NotAuthorizedException e) { } catch (TigaseDBException e) { log.log(Level.WARNING, "Database problem, please notify the admin. {0}", e); } return true; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } |
@Test public void testResourceSelectionForMessageDeliveryForBareJid() throws Exception { BareJID userJid = BareJID.bareJIDInstance("[email protected]"); JID res1 = JID.jidInstance(userJid, "res1"); JID res2 = JID.jidInstance(userJid, "res2"); XMPPResourceConnection session1 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res1); XMPPResourceConnection session2 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res2); session2.putSessionData(MessageCarbons.XMLNS + "-enabled", true); Map<JID,Boolean> enabled = new HashMap<>(); enabled.put(res2, true); session2.putCommonSessionData(MessageCarbons.XMLNS + "-resources", enabled); assertEquals(Arrays.asList(session1, session2), session1.getActiveSessions()); Element packetEl = new Element("message", new String[] { "type", "from", "to" }, new String[] { "chat", "[email protected]/res1", userJid.toString() }); Packet packet = Packet.packetInstance(packetEl); Queue<Packet> results = new ArrayDeque<Packet>(); carbonsProcessor.process(packet, session2, null, results, null); assertEquals("generated result even than no resource had nonnegative priority", 1, results.size()); assertEquals("packet sent to wrong jids", Arrays.asList(session2.getJID()), collectStanzaTo(results)); session1.setPresence(new Element("presence")); results = new ArrayDeque<Packet>(); carbonsProcessor.process(packet, session2, null, results, null); assertEquals("not generated result even than 1 resource had nonnegative priority", 1, results.size()); assertEquals("packet sent to wrong jids", Arrays.asList(session2.getJID()), collectStanzaTo(results)); session2.setPresence(new Element("presence")); results = new ArrayDeque<Packet>(); carbonsProcessor.process(packet, session1, null, results, null); assertEquals("not generated result even than 2 resource had nonnegative priority", 0, results.size()); assertEquals("packet sent to wrong jids", Arrays.asList(), collectStanzaTo(results)); } | @Override public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws XMPPException { if (session == null) return; if (packet.getElemName() == Iq.ELEM_NAME) { boolean enable = packet.getElement().getChild(ENABLE_ELEM_NAME, XMLNS) != null; boolean disable = packet.getElement().getChild(DISABLE_ELEM_NAME, XMLNS) != null; if ((enable && disable) || (!enable && !disable)) { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, null, false)); } else { JID sessionJid = session.getJID(); if (packet.getStanzaFrom() != null && !sessionJid.equals(packet.getStanzaFrom()) && session.isUserId(packet.getStanzaFrom().getBareJID()) && packet.getStanzaFrom().getResource() != null) { Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { synchronized (session.getParentSession()) { resources = (Map<JID, Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { resources = new ConcurrentHashMap<JID, Boolean>(); session.putCommonSessionData(ENABLED_RESOURCES_KEY, resources); } } } if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "received state notification from {0} with value = {1}", new Object[]{packet.getStanzaFrom(), enable}); } Boolean oldValue = resources.put(packet.getStanzaFrom(), enable); if (oldValue == null) { for (XMPPResourceConnection conn : session.getActiveSessions()) { notifyStateChanged(conn.getJID(), packet.getStanzaFrom(), isEnabled(conn), results); } } } else { setEnabled(session, enable, results); results.offer(packet.okResult((Element) null, 0)); } } } else if (packet.getElemName() == Message.ELEM_NAME && packet.getType() == StanzaType.chat && packet.getStanzaTo() != null) { if (C2SDeliveryErrorProcessor.isDeliveryError(packet)) return; Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null || resources.isEmpty()) { return; } if (packet.getType() == StanzaType.chat) { if (packet.getElement().getChild("received", XMLNS) != null || packet.getElement().getChild("sent", XMLNS) != null) { return; } if (packet.getAttributeStaticStr(MESSAGE_HINTS_NO_COPY, "xmlns") == MESSAGE_HINTS_XMLNS) { return; } Element privateEl = packet.getElement().getChild("private", XMLNS); if (privateEl != null) { packet.getElement().removeChild(privateEl); return; } String type = session.isUserId(packet.getStanzaTo().getBareJID()) ? "received" : "sent"; JID srcJid = JID.jidInstance(session.getBareJID()); Set<JID> skipForkingTo = null; if (session.isUserId(packet.getStanzaTo().getBareJID()) && packet.getStanzaTo().getResource() == null) { skipForkingTo = messageProcessor.getJIDsForMessageDelivery(session); for (JID jid : resources.keySet()) { if (session.getParentSession().getResourceForJID(jid) == null) skipForkingTo.add(jid); } } else { skipForkingTo = Collections.singleton(session.getJID()); } if ( log.isLoggable( Level.FINER ) ){ log.log( Level.FINER, "Sending message carbon copy, packet: {0}, resources {1}, skipForkingTo: {2}, session: {3}", new Object[] { packet, resources, skipForkingTo, session } ); } for (Map.Entry<JID, Boolean> entry : resources.entrySet()) { if (!entry.getValue()) { continue; } JID jid = entry.getKey(); if (skipForkingTo.contains(entry.getKey())) { continue; } Packet msgClone = prepareCarbonCopy(packet, srcJid, jid, type); results.offer(msgClone); } } } } | MessageCarbons extends XMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc,
XMPPPresenceUpdateProcessorIfc { @Override public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws XMPPException { if (session == null) return; if (packet.getElemName() == Iq.ELEM_NAME) { boolean enable = packet.getElement().getChild(ENABLE_ELEM_NAME, XMLNS) != null; boolean disable = packet.getElement().getChild(DISABLE_ELEM_NAME, XMLNS) != null; if ((enable && disable) || (!enable && !disable)) { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, null, false)); } else { JID sessionJid = session.getJID(); if (packet.getStanzaFrom() != null && !sessionJid.equals(packet.getStanzaFrom()) && session.isUserId(packet.getStanzaFrom().getBareJID()) && packet.getStanzaFrom().getResource() != null) { Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { synchronized (session.getParentSession()) { resources = (Map<JID, Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { resources = new ConcurrentHashMap<JID, Boolean>(); session.putCommonSessionData(ENABLED_RESOURCES_KEY, resources); } } } if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "received state notification from {0} with value = {1}", new Object[]{packet.getStanzaFrom(), enable}); } Boolean oldValue = resources.put(packet.getStanzaFrom(), enable); if (oldValue == null) { for (XMPPResourceConnection conn : session.getActiveSessions()) { notifyStateChanged(conn.getJID(), packet.getStanzaFrom(), isEnabled(conn), results); } } } else { setEnabled(session, enable, results); results.offer(packet.okResult((Element) null, 0)); } } } else if (packet.getElemName() == Message.ELEM_NAME && packet.getType() == StanzaType.chat && packet.getStanzaTo() != null) { if (C2SDeliveryErrorProcessor.isDeliveryError(packet)) return; Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null || resources.isEmpty()) { return; } if (packet.getType() == StanzaType.chat) { if (packet.getElement().getChild("received", XMLNS) != null || packet.getElement().getChild("sent", XMLNS) != null) { return; } if (packet.getAttributeStaticStr(MESSAGE_HINTS_NO_COPY, "xmlns") == MESSAGE_HINTS_XMLNS) { return; } Element privateEl = packet.getElement().getChild("private", XMLNS); if (privateEl != null) { packet.getElement().removeChild(privateEl); return; } String type = session.isUserId(packet.getStanzaTo().getBareJID()) ? "received" : "sent"; JID srcJid = JID.jidInstance(session.getBareJID()); Set<JID> skipForkingTo = null; if (session.isUserId(packet.getStanzaTo().getBareJID()) && packet.getStanzaTo().getResource() == null) { skipForkingTo = messageProcessor.getJIDsForMessageDelivery(session); for (JID jid : resources.keySet()) { if (session.getParentSession().getResourceForJID(jid) == null) skipForkingTo.add(jid); } } else { skipForkingTo = Collections.singleton(session.getJID()); } if ( log.isLoggable( Level.FINER ) ){ log.log( Level.FINER, "Sending message carbon copy, packet: {0}, resources {1}, skipForkingTo: {2}, session: {3}", new Object[] { packet, resources, skipForkingTo, session } ); } for (Map.Entry<JID, Boolean> entry : resources.entrySet()) { if (!entry.getValue()) { continue; } JID jid = entry.getKey(); if (skipForkingTo.contains(entry.getKey())) { continue; } Packet msgClone = prepareCarbonCopy(packet, srcJid, jid, type); results.offer(msgClone); } } } } } | MessageCarbons extends XMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc,
XMPPPresenceUpdateProcessorIfc { @Override public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws XMPPException { if (session == null) return; if (packet.getElemName() == Iq.ELEM_NAME) { boolean enable = packet.getElement().getChild(ENABLE_ELEM_NAME, XMLNS) != null; boolean disable = packet.getElement().getChild(DISABLE_ELEM_NAME, XMLNS) != null; if ((enable && disable) || (!enable && !disable)) { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, null, false)); } else { JID sessionJid = session.getJID(); if (packet.getStanzaFrom() != null && !sessionJid.equals(packet.getStanzaFrom()) && session.isUserId(packet.getStanzaFrom().getBareJID()) && packet.getStanzaFrom().getResource() != null) { Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { synchronized (session.getParentSession()) { resources = (Map<JID, Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { resources = new ConcurrentHashMap<JID, Boolean>(); session.putCommonSessionData(ENABLED_RESOURCES_KEY, resources); } } } if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "received state notification from {0} with value = {1}", new Object[]{packet.getStanzaFrom(), enable}); } Boolean oldValue = resources.put(packet.getStanzaFrom(), enable); if (oldValue == null) { for (XMPPResourceConnection conn : session.getActiveSessions()) { notifyStateChanged(conn.getJID(), packet.getStanzaFrom(), isEnabled(conn), results); } } } else { setEnabled(session, enable, results); results.offer(packet.okResult((Element) null, 0)); } } } else if (packet.getElemName() == Message.ELEM_NAME && packet.getType() == StanzaType.chat && packet.getStanzaTo() != null) { if (C2SDeliveryErrorProcessor.isDeliveryError(packet)) return; Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null || resources.isEmpty()) { return; } if (packet.getType() == StanzaType.chat) { if (packet.getElement().getChild("received", XMLNS) != null || packet.getElement().getChild("sent", XMLNS) != null) { return; } if (packet.getAttributeStaticStr(MESSAGE_HINTS_NO_COPY, "xmlns") == MESSAGE_HINTS_XMLNS) { return; } Element privateEl = packet.getElement().getChild("private", XMLNS); if (privateEl != null) { packet.getElement().removeChild(privateEl); return; } String type = session.isUserId(packet.getStanzaTo().getBareJID()) ? "received" : "sent"; JID srcJid = JID.jidInstance(session.getBareJID()); Set<JID> skipForkingTo = null; if (session.isUserId(packet.getStanzaTo().getBareJID()) && packet.getStanzaTo().getResource() == null) { skipForkingTo = messageProcessor.getJIDsForMessageDelivery(session); for (JID jid : resources.keySet()) { if (session.getParentSession().getResourceForJID(jid) == null) skipForkingTo.add(jid); } } else { skipForkingTo = Collections.singleton(session.getJID()); } if ( log.isLoggable( Level.FINER ) ){ log.log( Level.FINER, "Sending message carbon copy, packet: {0}, resources {1}, skipForkingTo: {2}, session: {3}", new Object[] { packet, resources, skipForkingTo, session } ); } for (Map.Entry<JID, Boolean> entry : resources.entrySet()) { if (!entry.getValue()) { continue; } JID jid = entry.getKey(); if (skipForkingTo.contains(entry.getKey())) { continue; } Packet msgClone = prepareCarbonCopy(packet, srcJid, jid, type); results.offer(msgClone); } } } } } | MessageCarbons extends XMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc,
XMPPPresenceUpdateProcessorIfc { @Override public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws XMPPException { if (session == null) return; if (packet.getElemName() == Iq.ELEM_NAME) { boolean enable = packet.getElement().getChild(ENABLE_ELEM_NAME, XMLNS) != null; boolean disable = packet.getElement().getChild(DISABLE_ELEM_NAME, XMLNS) != null; if ((enable && disable) || (!enable && !disable)) { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, null, false)); } else { JID sessionJid = session.getJID(); if (packet.getStanzaFrom() != null && !sessionJid.equals(packet.getStanzaFrom()) && session.isUserId(packet.getStanzaFrom().getBareJID()) && packet.getStanzaFrom().getResource() != null) { Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { synchronized (session.getParentSession()) { resources = (Map<JID, Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { resources = new ConcurrentHashMap<JID, Boolean>(); session.putCommonSessionData(ENABLED_RESOURCES_KEY, resources); } } } if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "received state notification from {0} with value = {1}", new Object[]{packet.getStanzaFrom(), enable}); } Boolean oldValue = resources.put(packet.getStanzaFrom(), enable); if (oldValue == null) { for (XMPPResourceConnection conn : session.getActiveSessions()) { notifyStateChanged(conn.getJID(), packet.getStanzaFrom(), isEnabled(conn), results); } } } else { setEnabled(session, enable, results); results.offer(packet.okResult((Element) null, 0)); } } } else if (packet.getElemName() == Message.ELEM_NAME && packet.getType() == StanzaType.chat && packet.getStanzaTo() != null) { if (C2SDeliveryErrorProcessor.isDeliveryError(packet)) return; Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null || resources.isEmpty()) { return; } if (packet.getType() == StanzaType.chat) { if (packet.getElement().getChild("received", XMLNS) != null || packet.getElement().getChild("sent", XMLNS) != null) { return; } if (packet.getAttributeStaticStr(MESSAGE_HINTS_NO_COPY, "xmlns") == MESSAGE_HINTS_XMLNS) { return; } Element privateEl = packet.getElement().getChild("private", XMLNS); if (privateEl != null) { packet.getElement().removeChild(privateEl); return; } String type = session.isUserId(packet.getStanzaTo().getBareJID()) ? "received" : "sent"; JID srcJid = JID.jidInstance(session.getBareJID()); Set<JID> skipForkingTo = null; if (session.isUserId(packet.getStanzaTo().getBareJID()) && packet.getStanzaTo().getResource() == null) { skipForkingTo = messageProcessor.getJIDsForMessageDelivery(session); for (JID jid : resources.keySet()) { if (session.getParentSession().getResourceForJID(jid) == null) skipForkingTo.add(jid); } } else { skipForkingTo = Collections.singleton(session.getJID()); } if ( log.isLoggable( Level.FINER ) ){ log.log( Level.FINER, "Sending message carbon copy, packet: {0}, resources {1}, skipForkingTo: {2}, session: {3}", new Object[] { packet, resources, skipForkingTo, session } ); } for (Map.Entry<JID, Boolean> entry : resources.entrySet()) { if (!entry.getValue()) { continue; } JID jid = entry.getKey(); if (skipForkingTo.contains(entry.getKey())) { continue; } Packet msgClone = prepareCarbonCopy(packet, srcJid, jid, type); results.offer(msgClone); } } } } @Override String id(); @Override void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo,
Queue<Packet> results, Map<String, Object> settings); @Override Element[] supDiscoFeatures(XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); @Override void presenceUpdate(XMPPResourceConnection session, Packet packet, Queue<Packet> results); @Override void filter(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results); } | MessageCarbons extends XMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc,
XMPPPresenceUpdateProcessorIfc { @Override public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws XMPPException { if (session == null) return; if (packet.getElemName() == Iq.ELEM_NAME) { boolean enable = packet.getElement().getChild(ENABLE_ELEM_NAME, XMLNS) != null; boolean disable = packet.getElement().getChild(DISABLE_ELEM_NAME, XMLNS) != null; if ((enable && disable) || (!enable && !disable)) { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, null, false)); } else { JID sessionJid = session.getJID(); if (packet.getStanzaFrom() != null && !sessionJid.equals(packet.getStanzaFrom()) && session.isUserId(packet.getStanzaFrom().getBareJID()) && packet.getStanzaFrom().getResource() != null) { Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { synchronized (session.getParentSession()) { resources = (Map<JID, Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { resources = new ConcurrentHashMap<JID, Boolean>(); session.putCommonSessionData(ENABLED_RESOURCES_KEY, resources); } } } if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "received state notification from {0} with value = {1}", new Object[]{packet.getStanzaFrom(), enable}); } Boolean oldValue = resources.put(packet.getStanzaFrom(), enable); if (oldValue == null) { for (XMPPResourceConnection conn : session.getActiveSessions()) { notifyStateChanged(conn.getJID(), packet.getStanzaFrom(), isEnabled(conn), results); } } } else { setEnabled(session, enable, results); results.offer(packet.okResult((Element) null, 0)); } } } else if (packet.getElemName() == Message.ELEM_NAME && packet.getType() == StanzaType.chat && packet.getStanzaTo() != null) { if (C2SDeliveryErrorProcessor.isDeliveryError(packet)) return; Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null || resources.isEmpty()) { return; } if (packet.getType() == StanzaType.chat) { if (packet.getElement().getChild("received", XMLNS) != null || packet.getElement().getChild("sent", XMLNS) != null) { return; } if (packet.getAttributeStaticStr(MESSAGE_HINTS_NO_COPY, "xmlns") == MESSAGE_HINTS_XMLNS) { return; } Element privateEl = packet.getElement().getChild("private", XMLNS); if (privateEl != null) { packet.getElement().removeChild(privateEl); return; } String type = session.isUserId(packet.getStanzaTo().getBareJID()) ? "received" : "sent"; JID srcJid = JID.jidInstance(session.getBareJID()); Set<JID> skipForkingTo = null; if (session.isUserId(packet.getStanzaTo().getBareJID()) && packet.getStanzaTo().getResource() == null) { skipForkingTo = messageProcessor.getJIDsForMessageDelivery(session); for (JID jid : resources.keySet()) { if (session.getParentSession().getResourceForJID(jid) == null) skipForkingTo.add(jid); } } else { skipForkingTo = Collections.singleton(session.getJID()); } if ( log.isLoggable( Level.FINER ) ){ log.log( Level.FINER, "Sending message carbon copy, packet: {0}, resources {1}, skipForkingTo: {2}, session: {3}", new Object[] { packet, resources, skipForkingTo, session } ); } for (Map.Entry<JID, Boolean> entry : resources.entrySet()) { if (!entry.getValue()) { continue; } JID jid = entry.getKey(); if (skipForkingTo.contains(entry.getKey())) { continue; } Packet msgClone = prepareCarbonCopy(packet, srcJid, jid, type); results.offer(msgClone); } } } } @Override String id(); @Override void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo,
Queue<Packet> results, Map<String, Object> settings); @Override Element[] supDiscoFeatures(XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); @Override void presenceUpdate(XMPPResourceConnection session, Packet packet, Queue<Packet> results); @Override void filter(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results); static final String XMLNS; } |
@Test public void testFind() { final HashMap<String, String> domains = new HashMap<String, String>(); domains.put("one.com", "one.com"); domains.put("a.two.com", "a.two.com"); domains.put("*.two.com", "*.two.com"); assertEquals("one.com", SSLContextContainer.find(domains, "one.com")); assertNull(SSLContextContainer.find(domains, "tone.com")); assertNull(SSLContextContainer.find(domains, "zero.com")); assertEquals("a.two.com", SSLContextContainer.find(domains, "a.two.com")); assertEquals("*.two.com", SSLContextContainer.find(domains, "b.two.com")); assertEquals("*.two.com", SSLContextContainer.find(domains, "b.two.com")); assertNull(SSLContextContainer.find(domains, "btwo.com")); assertEquals("*.two.com", SSLContextContainer.find(domains, ".two.com")); } | public static <T> T find(Map<String, T> data, String key) { if (data.containsKey(key)) { return data.get(key); } int idx = key.indexOf("."); if (idx >= 0) { String asteriskKey = "*" + key.substring(idx); T value = data.get(asteriskKey); if (value != null) { data.put(key, value); return value; } } return null; } | SSLContextContainer implements SSLContextContainerIfc { public static <T> T find(Map<String, T> data, String key) { if (data.containsKey(key)) { return data.get(key); } int idx = key.indexOf("."); if (idx >= 0) { String asteriskKey = "*" + key.substring(idx); T value = data.get(asteriskKey); if (value != null) { data.put(key, value); return value; } } return null; } } | SSLContextContainer implements SSLContextContainerIfc { public static <T> T find(Map<String, T> data, String key) { if (data.containsKey(key)) { return data.get(key); } int idx = key.indexOf("."); if (idx >= 0) { String asteriskKey = "*" + key.substring(idx); T value = data.get(asteriskKey); if (value != null) { data.put(key, value); return value; } } return null; } } | SSLContextContainer implements SSLContextContainerIfc { public static <T> T find(Map<String, T> data, String key) { if (data.containsKey(key)) { return data.get(key); } int idx = key.indexOf("."); if (idx >= 0) { String asteriskKey = "*" + key.substring(idx); T value = data.get(asteriskKey); if (value != null) { data.put(key, value); return value; } } return null; } @Override void addCertificates(Map<String, String> params); SSLContext getSSLContext(String protocol, String hostname, boolean clientMode); static T find(Map<String, T> data, String key); @Override SSLContext getSSLContext(String protocol, String hostname, boolean clientMode, TrustManager... tms); @Override KeyStore getTrustStore(); @Override void init(Map<String, Object> params); } | SSLContextContainer implements SSLContextContainerIfc { public static <T> T find(Map<String, T> data, String key) { if (data.containsKey(key)) { return data.get(key); } int idx = key.indexOf("."); if (idx >= 0) { String asteriskKey = "*" + key.substring(idx); T value = data.get(asteriskKey); if (value != null) { data.put(key, value); return value; } } return null; } @Override void addCertificates(Map<String, String> params); SSLContext getSSLContext(String protocol, String hostname, boolean clientMode); static T find(Map<String, T> data, String key); @Override SSLContext getSSLContext(String protocol, String hostname, boolean clientMode, TrustManager... tms); @Override KeyStore getTrustStore(); @Override void init(Map<String, Object> params); final static String PER_DOMAIN_CERTIFICATE_KEY; } |
@Test public void testResourceSelectionForMessageDeliveryForFullJid() throws Exception { BareJID userJid = BareJID.bareJIDInstance("[email protected]"); JID res1 = JID.jidInstance(userJid, "res1"); JID res2 = JID.jidInstance(userJid, "res2"); XMPPResourceConnection session1 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res1); XMPPResourceConnection session2 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res2); session2.putSessionData(MessageCarbons.XMLNS + "-enabled", true); Map<JID,Boolean> enabled = new HashMap<>(); enabled.put(res2, true); session2.putCommonSessionData(MessageCarbons.XMLNS + "-resources", enabled); assertEquals(Arrays.asList(session1, session2), session1.getActiveSessions()); Element packetEl = new Element("message", new String[] { "type", "from", "to" }, new String[] { "chat", "[email protected]/res1", res1.toString() }); Packet packet = Packet.packetInstance(packetEl); Queue<Packet> results = new ArrayDeque<Packet>(); carbonsProcessor.process(packet, session1, null, results, null); assertEquals("generated result even than no resource had nonnegative priority", 1, results.size()); assertEquals("packet sent to wrong jids", Arrays.asList(session2.getJID()), collectStanzaTo(results)); session1.setPresence(new Element("presence")); results = new ArrayDeque<Packet>(); carbonsProcessor.process(packet, session1, null, results, null); assertEquals("not generated result even than 1 resource had nonnegative priority", 1, results.size()); assertEquals("packet sent to wrong jids", Arrays.asList(session2.getJID()), collectStanzaTo(results)); session2.setPresence(new Element("presence")); results = new ArrayDeque<Packet>(); carbonsProcessor.process(packet, session1, null, results, null); assertEquals("not generated result even than 2 resource had nonnegative priority", 1, results.size()); assertEquals("packet sent to wrong jids", Arrays.asList(session2.getJID()), collectStanzaTo(results)); results = new ArrayDeque<Packet>(); Packet packet1 = packet.copyElementOnly(); packet1.getElement().addChild(new Element("no-copy", new String[] { "xmlns" }, new String[] { "urn:xmpp:hints" })); carbonsProcessor.process(packet1, session1, null, results, null); assertEquals("generated result even that no-copy was sent", 0, results.size()); assertEquals("packet sent to wrong jids", Collections.EMPTY_LIST, collectStanzaTo(results)); } | @Override public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws XMPPException { if (session == null) return; if (packet.getElemName() == Iq.ELEM_NAME) { boolean enable = packet.getElement().getChild(ENABLE_ELEM_NAME, XMLNS) != null; boolean disable = packet.getElement().getChild(DISABLE_ELEM_NAME, XMLNS) != null; if ((enable && disable) || (!enable && !disable)) { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, null, false)); } else { JID sessionJid = session.getJID(); if (packet.getStanzaFrom() != null && !sessionJid.equals(packet.getStanzaFrom()) && session.isUserId(packet.getStanzaFrom().getBareJID()) && packet.getStanzaFrom().getResource() != null) { Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { synchronized (session.getParentSession()) { resources = (Map<JID, Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { resources = new ConcurrentHashMap<JID, Boolean>(); session.putCommonSessionData(ENABLED_RESOURCES_KEY, resources); } } } if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "received state notification from {0} with value = {1}", new Object[]{packet.getStanzaFrom(), enable}); } Boolean oldValue = resources.put(packet.getStanzaFrom(), enable); if (oldValue == null) { for (XMPPResourceConnection conn : session.getActiveSessions()) { notifyStateChanged(conn.getJID(), packet.getStanzaFrom(), isEnabled(conn), results); } } } else { setEnabled(session, enable, results); results.offer(packet.okResult((Element) null, 0)); } } } else if (packet.getElemName() == Message.ELEM_NAME && packet.getType() == StanzaType.chat && packet.getStanzaTo() != null) { if (C2SDeliveryErrorProcessor.isDeliveryError(packet)) return; Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null || resources.isEmpty()) { return; } if (packet.getType() == StanzaType.chat) { if (packet.getElement().getChild("received", XMLNS) != null || packet.getElement().getChild("sent", XMLNS) != null) { return; } if (packet.getAttributeStaticStr(MESSAGE_HINTS_NO_COPY, "xmlns") == MESSAGE_HINTS_XMLNS) { return; } Element privateEl = packet.getElement().getChild("private", XMLNS); if (privateEl != null) { packet.getElement().removeChild(privateEl); return; } String type = session.isUserId(packet.getStanzaTo().getBareJID()) ? "received" : "sent"; JID srcJid = JID.jidInstance(session.getBareJID()); Set<JID> skipForkingTo = null; if (session.isUserId(packet.getStanzaTo().getBareJID()) && packet.getStanzaTo().getResource() == null) { skipForkingTo = messageProcessor.getJIDsForMessageDelivery(session); for (JID jid : resources.keySet()) { if (session.getParentSession().getResourceForJID(jid) == null) skipForkingTo.add(jid); } } else { skipForkingTo = Collections.singleton(session.getJID()); } if ( log.isLoggable( Level.FINER ) ){ log.log( Level.FINER, "Sending message carbon copy, packet: {0}, resources {1}, skipForkingTo: {2}, session: {3}", new Object[] { packet, resources, skipForkingTo, session } ); } for (Map.Entry<JID, Boolean> entry : resources.entrySet()) { if (!entry.getValue()) { continue; } JID jid = entry.getKey(); if (skipForkingTo.contains(entry.getKey())) { continue; } Packet msgClone = prepareCarbonCopy(packet, srcJid, jid, type); results.offer(msgClone); } } } } | MessageCarbons extends XMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc,
XMPPPresenceUpdateProcessorIfc { @Override public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws XMPPException { if (session == null) return; if (packet.getElemName() == Iq.ELEM_NAME) { boolean enable = packet.getElement().getChild(ENABLE_ELEM_NAME, XMLNS) != null; boolean disable = packet.getElement().getChild(DISABLE_ELEM_NAME, XMLNS) != null; if ((enable && disable) || (!enable && !disable)) { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, null, false)); } else { JID sessionJid = session.getJID(); if (packet.getStanzaFrom() != null && !sessionJid.equals(packet.getStanzaFrom()) && session.isUserId(packet.getStanzaFrom().getBareJID()) && packet.getStanzaFrom().getResource() != null) { Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { synchronized (session.getParentSession()) { resources = (Map<JID, Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { resources = new ConcurrentHashMap<JID, Boolean>(); session.putCommonSessionData(ENABLED_RESOURCES_KEY, resources); } } } if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "received state notification from {0} with value = {1}", new Object[]{packet.getStanzaFrom(), enable}); } Boolean oldValue = resources.put(packet.getStanzaFrom(), enable); if (oldValue == null) { for (XMPPResourceConnection conn : session.getActiveSessions()) { notifyStateChanged(conn.getJID(), packet.getStanzaFrom(), isEnabled(conn), results); } } } else { setEnabled(session, enable, results); results.offer(packet.okResult((Element) null, 0)); } } } else if (packet.getElemName() == Message.ELEM_NAME && packet.getType() == StanzaType.chat && packet.getStanzaTo() != null) { if (C2SDeliveryErrorProcessor.isDeliveryError(packet)) return; Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null || resources.isEmpty()) { return; } if (packet.getType() == StanzaType.chat) { if (packet.getElement().getChild("received", XMLNS) != null || packet.getElement().getChild("sent", XMLNS) != null) { return; } if (packet.getAttributeStaticStr(MESSAGE_HINTS_NO_COPY, "xmlns") == MESSAGE_HINTS_XMLNS) { return; } Element privateEl = packet.getElement().getChild("private", XMLNS); if (privateEl != null) { packet.getElement().removeChild(privateEl); return; } String type = session.isUserId(packet.getStanzaTo().getBareJID()) ? "received" : "sent"; JID srcJid = JID.jidInstance(session.getBareJID()); Set<JID> skipForkingTo = null; if (session.isUserId(packet.getStanzaTo().getBareJID()) && packet.getStanzaTo().getResource() == null) { skipForkingTo = messageProcessor.getJIDsForMessageDelivery(session); for (JID jid : resources.keySet()) { if (session.getParentSession().getResourceForJID(jid) == null) skipForkingTo.add(jid); } } else { skipForkingTo = Collections.singleton(session.getJID()); } if ( log.isLoggable( Level.FINER ) ){ log.log( Level.FINER, "Sending message carbon copy, packet: {0}, resources {1}, skipForkingTo: {2}, session: {3}", new Object[] { packet, resources, skipForkingTo, session } ); } for (Map.Entry<JID, Boolean> entry : resources.entrySet()) { if (!entry.getValue()) { continue; } JID jid = entry.getKey(); if (skipForkingTo.contains(entry.getKey())) { continue; } Packet msgClone = prepareCarbonCopy(packet, srcJid, jid, type); results.offer(msgClone); } } } } } | MessageCarbons extends XMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc,
XMPPPresenceUpdateProcessorIfc { @Override public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws XMPPException { if (session == null) return; if (packet.getElemName() == Iq.ELEM_NAME) { boolean enable = packet.getElement().getChild(ENABLE_ELEM_NAME, XMLNS) != null; boolean disable = packet.getElement().getChild(DISABLE_ELEM_NAME, XMLNS) != null; if ((enable && disable) || (!enable && !disable)) { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, null, false)); } else { JID sessionJid = session.getJID(); if (packet.getStanzaFrom() != null && !sessionJid.equals(packet.getStanzaFrom()) && session.isUserId(packet.getStanzaFrom().getBareJID()) && packet.getStanzaFrom().getResource() != null) { Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { synchronized (session.getParentSession()) { resources = (Map<JID, Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { resources = new ConcurrentHashMap<JID, Boolean>(); session.putCommonSessionData(ENABLED_RESOURCES_KEY, resources); } } } if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "received state notification from {0} with value = {1}", new Object[]{packet.getStanzaFrom(), enable}); } Boolean oldValue = resources.put(packet.getStanzaFrom(), enable); if (oldValue == null) { for (XMPPResourceConnection conn : session.getActiveSessions()) { notifyStateChanged(conn.getJID(), packet.getStanzaFrom(), isEnabled(conn), results); } } } else { setEnabled(session, enable, results); results.offer(packet.okResult((Element) null, 0)); } } } else if (packet.getElemName() == Message.ELEM_NAME && packet.getType() == StanzaType.chat && packet.getStanzaTo() != null) { if (C2SDeliveryErrorProcessor.isDeliveryError(packet)) return; Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null || resources.isEmpty()) { return; } if (packet.getType() == StanzaType.chat) { if (packet.getElement().getChild("received", XMLNS) != null || packet.getElement().getChild("sent", XMLNS) != null) { return; } if (packet.getAttributeStaticStr(MESSAGE_HINTS_NO_COPY, "xmlns") == MESSAGE_HINTS_XMLNS) { return; } Element privateEl = packet.getElement().getChild("private", XMLNS); if (privateEl != null) { packet.getElement().removeChild(privateEl); return; } String type = session.isUserId(packet.getStanzaTo().getBareJID()) ? "received" : "sent"; JID srcJid = JID.jidInstance(session.getBareJID()); Set<JID> skipForkingTo = null; if (session.isUserId(packet.getStanzaTo().getBareJID()) && packet.getStanzaTo().getResource() == null) { skipForkingTo = messageProcessor.getJIDsForMessageDelivery(session); for (JID jid : resources.keySet()) { if (session.getParentSession().getResourceForJID(jid) == null) skipForkingTo.add(jid); } } else { skipForkingTo = Collections.singleton(session.getJID()); } if ( log.isLoggable( Level.FINER ) ){ log.log( Level.FINER, "Sending message carbon copy, packet: {0}, resources {1}, skipForkingTo: {2}, session: {3}", new Object[] { packet, resources, skipForkingTo, session } ); } for (Map.Entry<JID, Boolean> entry : resources.entrySet()) { if (!entry.getValue()) { continue; } JID jid = entry.getKey(); if (skipForkingTo.contains(entry.getKey())) { continue; } Packet msgClone = prepareCarbonCopy(packet, srcJid, jid, type); results.offer(msgClone); } } } } } | MessageCarbons extends XMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc,
XMPPPresenceUpdateProcessorIfc { @Override public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws XMPPException { if (session == null) return; if (packet.getElemName() == Iq.ELEM_NAME) { boolean enable = packet.getElement().getChild(ENABLE_ELEM_NAME, XMLNS) != null; boolean disable = packet.getElement().getChild(DISABLE_ELEM_NAME, XMLNS) != null; if ((enable && disable) || (!enable && !disable)) { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, null, false)); } else { JID sessionJid = session.getJID(); if (packet.getStanzaFrom() != null && !sessionJid.equals(packet.getStanzaFrom()) && session.isUserId(packet.getStanzaFrom().getBareJID()) && packet.getStanzaFrom().getResource() != null) { Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { synchronized (session.getParentSession()) { resources = (Map<JID, Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { resources = new ConcurrentHashMap<JID, Boolean>(); session.putCommonSessionData(ENABLED_RESOURCES_KEY, resources); } } } if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "received state notification from {0} with value = {1}", new Object[]{packet.getStanzaFrom(), enable}); } Boolean oldValue = resources.put(packet.getStanzaFrom(), enable); if (oldValue == null) { for (XMPPResourceConnection conn : session.getActiveSessions()) { notifyStateChanged(conn.getJID(), packet.getStanzaFrom(), isEnabled(conn), results); } } } else { setEnabled(session, enable, results); results.offer(packet.okResult((Element) null, 0)); } } } else if (packet.getElemName() == Message.ELEM_NAME && packet.getType() == StanzaType.chat && packet.getStanzaTo() != null) { if (C2SDeliveryErrorProcessor.isDeliveryError(packet)) return; Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null || resources.isEmpty()) { return; } if (packet.getType() == StanzaType.chat) { if (packet.getElement().getChild("received", XMLNS) != null || packet.getElement().getChild("sent", XMLNS) != null) { return; } if (packet.getAttributeStaticStr(MESSAGE_HINTS_NO_COPY, "xmlns") == MESSAGE_HINTS_XMLNS) { return; } Element privateEl = packet.getElement().getChild("private", XMLNS); if (privateEl != null) { packet.getElement().removeChild(privateEl); return; } String type = session.isUserId(packet.getStanzaTo().getBareJID()) ? "received" : "sent"; JID srcJid = JID.jidInstance(session.getBareJID()); Set<JID> skipForkingTo = null; if (session.isUserId(packet.getStanzaTo().getBareJID()) && packet.getStanzaTo().getResource() == null) { skipForkingTo = messageProcessor.getJIDsForMessageDelivery(session); for (JID jid : resources.keySet()) { if (session.getParentSession().getResourceForJID(jid) == null) skipForkingTo.add(jid); } } else { skipForkingTo = Collections.singleton(session.getJID()); } if ( log.isLoggable( Level.FINER ) ){ log.log( Level.FINER, "Sending message carbon copy, packet: {0}, resources {1}, skipForkingTo: {2}, session: {3}", new Object[] { packet, resources, skipForkingTo, session } ); } for (Map.Entry<JID, Boolean> entry : resources.entrySet()) { if (!entry.getValue()) { continue; } JID jid = entry.getKey(); if (skipForkingTo.contains(entry.getKey())) { continue; } Packet msgClone = prepareCarbonCopy(packet, srcJid, jid, type); results.offer(msgClone); } } } } @Override String id(); @Override void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo,
Queue<Packet> results, Map<String, Object> settings); @Override Element[] supDiscoFeatures(XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); @Override void presenceUpdate(XMPPResourceConnection session, Packet packet, Queue<Packet> results); @Override void filter(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results); } | MessageCarbons extends XMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc,
XMPPPresenceUpdateProcessorIfc { @Override public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws XMPPException { if (session == null) return; if (packet.getElemName() == Iq.ELEM_NAME) { boolean enable = packet.getElement().getChild(ENABLE_ELEM_NAME, XMLNS) != null; boolean disable = packet.getElement().getChild(DISABLE_ELEM_NAME, XMLNS) != null; if ((enable && disable) || (!enable && !disable)) { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, null, false)); } else { JID sessionJid = session.getJID(); if (packet.getStanzaFrom() != null && !sessionJid.equals(packet.getStanzaFrom()) && session.isUserId(packet.getStanzaFrom().getBareJID()) && packet.getStanzaFrom().getResource() != null) { Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { synchronized (session.getParentSession()) { resources = (Map<JID, Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { resources = new ConcurrentHashMap<JID, Boolean>(); session.putCommonSessionData(ENABLED_RESOURCES_KEY, resources); } } } if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "received state notification from {0} with value = {1}", new Object[]{packet.getStanzaFrom(), enable}); } Boolean oldValue = resources.put(packet.getStanzaFrom(), enable); if (oldValue == null) { for (XMPPResourceConnection conn : session.getActiveSessions()) { notifyStateChanged(conn.getJID(), packet.getStanzaFrom(), isEnabled(conn), results); } } } else { setEnabled(session, enable, results); results.offer(packet.okResult((Element) null, 0)); } } } else if (packet.getElemName() == Message.ELEM_NAME && packet.getType() == StanzaType.chat && packet.getStanzaTo() != null) { if (C2SDeliveryErrorProcessor.isDeliveryError(packet)) return; Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null || resources.isEmpty()) { return; } if (packet.getType() == StanzaType.chat) { if (packet.getElement().getChild("received", XMLNS) != null || packet.getElement().getChild("sent", XMLNS) != null) { return; } if (packet.getAttributeStaticStr(MESSAGE_HINTS_NO_COPY, "xmlns") == MESSAGE_HINTS_XMLNS) { return; } Element privateEl = packet.getElement().getChild("private", XMLNS); if (privateEl != null) { packet.getElement().removeChild(privateEl); return; } String type = session.isUserId(packet.getStanzaTo().getBareJID()) ? "received" : "sent"; JID srcJid = JID.jidInstance(session.getBareJID()); Set<JID> skipForkingTo = null; if (session.isUserId(packet.getStanzaTo().getBareJID()) && packet.getStanzaTo().getResource() == null) { skipForkingTo = messageProcessor.getJIDsForMessageDelivery(session); for (JID jid : resources.keySet()) { if (session.getParentSession().getResourceForJID(jid) == null) skipForkingTo.add(jid); } } else { skipForkingTo = Collections.singleton(session.getJID()); } if ( log.isLoggable( Level.FINER ) ){ log.log( Level.FINER, "Sending message carbon copy, packet: {0}, resources {1}, skipForkingTo: {2}, session: {3}", new Object[] { packet, resources, skipForkingTo, session } ); } for (Map.Entry<JID, Boolean> entry : resources.entrySet()) { if (!entry.getValue()) { continue; } JID jid = entry.getKey(); if (skipForkingTo.contains(entry.getKey())) { continue; } Packet msgClone = prepareCarbonCopy(packet, srcJid, jid, type); results.offer(msgClone); } } } } @Override String id(); @Override void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo,
Queue<Packet> results, Map<String, Object> settings); @Override Element[] supDiscoFeatures(XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); @Override void presenceUpdate(XMPPResourceConnection session, Packet packet, Queue<Packet> results); @Override void filter(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results); static final String XMLNS; } |
@Test public void testAuthorizationForSingleDomain() throws TigaseStringprepException { Queue<Packet> results = new ArrayDeque<>(); handler = new S2SConnectionHandlerImpl(results); dialback.init(handler, new HashMap()); String key = UUID.randomUUID().toString(); S2SIOService serv = new S2SIOService(); serv.setSessionId("sess-id-1"); Map<String,Object> props = new HashMap<>(); props.put(PORT_TYPE_PROP_KEY, "accept"); serv.setSessionData(props); Packet p = null; Element resultEl = new Element("db:result"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("from", remote1); resultEl.setAttribute("to", local); resultEl.setCData(key); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); Packet r = results.poll(); resultEl = new Element("db:verify"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("id", r.getAttributeStaticStr("id")); resultEl.setAttribute("from", r.getAttributeStaticStr("to")); resultEl.setAttribute("to", r.getAttributeStaticStr("from")); resultEl.setAttribute("type", "valid"); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); p = results.poll(); assertTrue(p.getType() == StanzaType.valid && remote1.equals(p.getStanzaTo().getDomain())); serv.getCIDs().forEach((CID cid) -> assertEquals(remote1, cid.getRemoteHost())); } | @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } Dialback(); } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } Dialback(); @Override int order(); @Override boolean process(Packet p, S2SIOService serv, Queue<Packet> results); @Override void serviceStarted(S2SIOService serv); @Override void streamFeatures(S2SIOService serv, List<Element> results); @Override String streamOpened(S2SIOService serv, Map<String, String> attribs); } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } Dialback(); @Override int order(); @Override boolean process(Packet p, S2SIOService serv, Queue<Packet> results); @Override void serviceStarted(S2SIOService serv); @Override void streamFeatures(S2SIOService serv, List<Element> results); @Override String streamOpened(S2SIOService serv, Map<String, String> attribs); } |
@Test public void testAuthorizationForSingleDomainFailure() throws TigaseStringprepException { Queue<Packet> results = new ArrayDeque<>(); handler = new S2SConnectionHandlerImpl(results); dialback.init(handler, new HashMap()); String key = UUID.randomUUID().toString(); S2SIOService serv = new S2SIOService(); serv.setSessionId("sess-id-1"); Map<String,Object> props = new HashMap<>(); props.put(PORT_TYPE_PROP_KEY, "accept"); serv.setSessionData(props); Packet p = null; Element resultEl = new Element("db:result"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("from", remote1); resultEl.setAttribute("to", local); resultEl.setCData(key); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); Packet r = results.poll(); resultEl = new Element("db:verify"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("id", r.getAttributeStaticStr("id")); resultEl.setAttribute("from", r.getAttributeStaticStr("to")); resultEl.setAttribute("to", r.getAttributeStaticStr("from")); resultEl.setAttribute("type", "invalid"); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); p = results.poll(); assertTrue(p.getType() == StanzaType.invalid && remote1.equals(p.getStanzaTo().getDomain())); serv.getCIDs().forEach((CID cid) -> assertNotSame(remote1, cid.getRemoteHost())); } | @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } Dialback(); } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } Dialback(); @Override int order(); @Override boolean process(Packet p, S2SIOService serv, Queue<Packet> results); @Override void serviceStarted(S2SIOService serv); @Override void streamFeatures(S2SIOService serv, List<Element> results); @Override String streamOpened(S2SIOService serv, Map<String, String> attribs); } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } Dialback(); @Override int order(); @Override boolean process(Packet p, S2SIOService serv, Queue<Packet> results); @Override void serviceStarted(S2SIOService serv); @Override void streamFeatures(S2SIOService serv, List<Element> results); @Override String streamOpened(S2SIOService serv, Map<String, String> attribs); } |
@Test public void testAuthorizationWithMultiplexing() throws TigaseStringprepException { Queue<Packet> results = new ArrayDeque<>(); handler = new S2SConnectionHandlerImpl(results); dialback.init(handler, new HashMap()); String key = UUID.randomUUID().toString(); S2SIOService serv = new S2SIOService(); serv.setSessionId("sess-id-1"); Map<String,Object> props = new HashMap<>(); props.put(PORT_TYPE_PROP_KEY, "accept"); serv.setSessionData(props); Packet p = null; Element resultEl = new Element("db:result"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("from", remote1); resultEl.setAttribute("to", local); resultEl.setCData(key); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); Packet r = results.poll(); resultEl = new Element("db:verify"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("id", r.getAttributeStaticStr("id")); resultEl.setAttribute("from", r.getAttributeStaticStr("to")); resultEl.setAttribute("to", r.getAttributeStaticStr("from")); resultEl.setAttribute("type", "valid"); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); p = results.poll(); assertTrue(p.getType() == StanzaType.valid && remote1.equals(p.getStanzaTo().getDomain())); serv.getCIDs().forEach((CID cid) -> assertEquals(remote1, cid.getRemoteHost())); key = UUID.randomUUID().toString(); resultEl = new Element("db:result"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("from", remote2); resultEl.setAttribute("to", local); resultEl.setCData(key); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); r = results.poll(); resultEl = new Element("db:verify"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("id", r.getAttributeStaticStr("id")); resultEl.setAttribute("from", r.getAttributeStaticStr("to")); resultEl.setAttribute("to", r.getAttributeStaticStr("from")); resultEl.setAttribute("type", "valid"); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); p = results.poll(); assertTrue(p.getType() == StanzaType.valid && remote2.equals(p.getStanzaTo().getDomain())); assertTrue(serv.getCIDs().stream().anyMatch((CID cid) -> remote1.equals(cid.getRemoteHost()))); assertTrue(serv.getCIDs().stream().anyMatch((CID cid) -> remote2.equals(cid.getRemoteHost()))); } | @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } Dialback(); } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } Dialback(); @Override int order(); @Override boolean process(Packet p, S2SIOService serv, Queue<Packet> results); @Override void serviceStarted(S2SIOService serv); @Override void streamFeatures(S2SIOService serv, List<Element> results); @Override String streamOpened(S2SIOService serv, Map<String, String> attribs); } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } Dialback(); @Override int order(); @Override boolean process(Packet p, S2SIOService serv, Queue<Packet> results); @Override void serviceStarted(S2SIOService serv); @Override void streamFeatures(S2SIOService serv, List<Element> results); @Override String streamOpened(S2SIOService serv, Map<String, String> attribs); } |
@Test public void testAuthorizationWithMultiplexingWithFailure() throws TigaseStringprepException { Queue<Packet> results = new ArrayDeque<>(); handler = new S2SConnectionHandlerImpl(results); dialback.init(handler, new HashMap()); String key = UUID.randomUUID().toString(); S2SIOService serv = new S2SIOService(); serv.setSessionId("sess-id-1"); Map<String,Object> props = new HashMap<>(); props.put(PORT_TYPE_PROP_KEY, "accept"); serv.setSessionData(props); Packet p = null; Element resultEl = new Element("db:result"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("from", remote1); resultEl.setAttribute("to", local); resultEl.setCData(key); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); Packet r = results.poll(); resultEl = new Element("db:verify"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("id", r.getAttributeStaticStr("id")); resultEl.setAttribute("from", r.getAttributeStaticStr("to")); resultEl.setAttribute("to", r.getAttributeStaticStr("from")); resultEl.setAttribute("type", "valid"); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); p = results.poll(); assertTrue(p.getType() == StanzaType.valid && remote1.equals(p.getStanzaTo().getDomain())); serv.getCIDs().forEach((CID cid) -> assertEquals(remote1, cid.getRemoteHost())); key = UUID.randomUUID().toString(); resultEl = new Element("db:result"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("from", remote2); resultEl.setAttribute("to", local); resultEl.setCData(key); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); r = results.poll(); resultEl = new Element("db:verify"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("id", r.getAttributeStaticStr("id")); resultEl.setAttribute("from", r.getAttributeStaticStr("to")); resultEl.setAttribute("to", r.getAttributeStaticStr("from")); resultEl.setAttribute("type", "invalid"); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); p = results.poll(); assertTrue(p.getType() == StanzaType.invalid && remote2.equals(p.getStanzaTo().getDomain())); assertTrue(serv.getCIDs().stream().anyMatch((CID cid) -> remote1.equals(cid.getRemoteHost()))); assertTrue(serv.getCIDs().stream().allMatch((CID cid) -> !remote2.equals(cid.getRemoteHost()))); } | @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } Dialback(); } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } Dialback(); @Override int order(); @Override boolean process(Packet p, S2SIOService serv, Queue<Packet> results); @Override void serviceStarted(S2SIOService serv); @Override void streamFeatures(S2SIOService serv, List<Element> results); @Override String streamOpened(S2SIOService serv, Map<String, String> attribs); } | Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } Dialback(); @Override int order(); @Override boolean process(Packet p, S2SIOService serv, Queue<Packet> results); @Override void serviceStarted(S2SIOService serv); @Override void streamFeatures(S2SIOService serv, List<Element> results); @Override String streamOpened(S2SIOService serv, Map<String, String> attribs); } |
@Test public void testHandshakeFail() throws NoSuchAlgorithmException, IOException { final ByteBuffer tmp = ByteBuffer.allocate(2048); WebSocketXMPPIOService<Object> io = new WebSocketXMPPIOService<Object>(new WebSocketProtocolIfc[]{ new WebSocketHixie76() }) { @Override protected void writeBytes(ByteBuffer data) { tmp.put(data); } @Override public int getLocalPort() { return 80; } }; Map<String,String> params = new HashMap<String,String>(); params.put("Sec-WebSocket-Key1", "1C2J899_05 6 ! M 9 ^4"); params.put("Sec-WebSocket-Key2", "23 2ff0M_E0#.454X23"); params.put("Sec-WebSocket-Protocol", "xmpp"); byte[] bytes = new byte[10]; bytes[0] = '\r'; bytes[1] = '\n'; Assert.assertFalse("Handshake succeeded", impl.handshake(io, params, bytes)); } | @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (!headers.containsKey(WS_VERSION_KEY)) { return false; } StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); int version = Integer.parseInt(headers.get(WS_VERSION_KEY)); String key = headers.get(WS_KEY_KEY) + GUID; MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] resp = md.digest(key.getBytes()); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); response.append(WS_ACCEPT_KEY + ": "); response.append(Base64.encode(resp)); response.append("\r\n"); response.append("\r\n"); service.maskingKey = new byte[4]; service.writeRawData(response.toString()); return true; } | WebSocketHybi implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (!headers.containsKey(WS_VERSION_KEY)) { return false; } StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); int version = Integer.parseInt(headers.get(WS_VERSION_KEY)); String key = headers.get(WS_KEY_KEY) + GUID; MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] resp = md.digest(key.getBytes()); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); response.append(WS_ACCEPT_KEY + ": "); response.append(Base64.encode(resp)); response.append("\r\n"); response.append("\r\n"); service.maskingKey = new byte[4]; service.writeRawData(response.toString()); return true; } } | WebSocketHybi implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (!headers.containsKey(WS_VERSION_KEY)) { return false; } StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); int version = Integer.parseInt(headers.get(WS_VERSION_KEY)); String key = headers.get(WS_KEY_KEY) + GUID; MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] resp = md.digest(key.getBytes()); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); response.append(WS_ACCEPT_KEY + ": "); response.append(Base64.encode(resp)); response.append("\r\n"); response.append("\r\n"); service.maskingKey = new byte[4]; service.writeRawData(response.toString()); return true; } } | WebSocketHybi implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (!headers.containsKey(WS_VERSION_KEY)) { return false; } StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); int version = Integer.parseInt(headers.get(WS_VERSION_KEY)); String key = headers.get(WS_KEY_KEY) + GUID; MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] resp = md.digest(key.getBytes()); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); response.append(WS_ACCEPT_KEY + ": "); response.append(Base64.encode(resp)); response.append("\r\n"); response.append("\r\n"); service.maskingKey = new byte[4]; service.writeRawData(response.toString()); return true; } @Override String getId(); @Override boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf); @Override ByteBuffer decodeFrame(WebSocketXMPPIOService service, ByteBuffer buf); @Override void encodeFrameAndWrite(WebSocketXMPPIOService service, ByteBuffer buf); @Override void closeConnection(WebSocketXMPPIOService service); } | WebSocketHybi implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (!headers.containsKey(WS_VERSION_KEY)) { return false; } StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); int version = Integer.parseInt(headers.get(WS_VERSION_KEY)); String key = headers.get(WS_KEY_KEY) + GUID; MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] resp = md.digest(key.getBytes()); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); response.append(WS_ACCEPT_KEY + ": "); response.append(Base64.encode(resp)); response.append("\r\n"); response.append("\r\n"); service.maskingKey = new byte[4]; service.writeRawData(response.toString()); return true; } @Override String getId(); @Override boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf); @Override ByteBuffer decodeFrame(WebSocketXMPPIOService service, ByteBuffer buf); @Override void encodeFrameAndWrite(WebSocketXMPPIOService service, ByteBuffer buf); @Override void closeConnection(WebSocketXMPPIOService service); static final String ID; } |
@Test public void testHandshakeOK() throws NoSuchAlgorithmException, IOException { final ByteBuffer tmp = ByteBuffer.allocate(2048); WebSocketXMPPIOService<Object> io = new WebSocketXMPPIOService<Object>(new WebSocketProtocolIfc[]{ new WebSocketHixie76() }) { @Override protected void writeBytes(ByteBuffer data) { tmp.put(data); } @Override public int getLocalPort() { return 80; } }; Map<String,String> params = new HashMap<String,String>(); params.put("Sec-WebSocket-Version", "13"); params.put("Sec-WebSocket-Key", "some random data as a key"); params.put("Sec-WebSocket-Protocol", "xmpp"); byte[] bytes = new byte[10]; bytes[0] = '\r'; bytes[1] = '\n'; Assert.assertTrue("Handshake failed", impl.handshake(io, params, bytes)); } | @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (!headers.containsKey(WS_VERSION_KEY)) { return false; } StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); int version = Integer.parseInt(headers.get(WS_VERSION_KEY)); String key = headers.get(WS_KEY_KEY) + GUID; MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] resp = md.digest(key.getBytes()); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); response.append(WS_ACCEPT_KEY + ": "); response.append(Base64.encode(resp)); response.append("\r\n"); response.append("\r\n"); service.maskingKey = new byte[4]; service.writeRawData(response.toString()); return true; } | WebSocketHybi implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (!headers.containsKey(WS_VERSION_KEY)) { return false; } StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); int version = Integer.parseInt(headers.get(WS_VERSION_KEY)); String key = headers.get(WS_KEY_KEY) + GUID; MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] resp = md.digest(key.getBytes()); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); response.append(WS_ACCEPT_KEY + ": "); response.append(Base64.encode(resp)); response.append("\r\n"); response.append("\r\n"); service.maskingKey = new byte[4]; service.writeRawData(response.toString()); return true; } } | WebSocketHybi implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (!headers.containsKey(WS_VERSION_KEY)) { return false; } StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); int version = Integer.parseInt(headers.get(WS_VERSION_KEY)); String key = headers.get(WS_KEY_KEY) + GUID; MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] resp = md.digest(key.getBytes()); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); response.append(WS_ACCEPT_KEY + ": "); response.append(Base64.encode(resp)); response.append("\r\n"); response.append("\r\n"); service.maskingKey = new byte[4]; service.writeRawData(response.toString()); return true; } } | WebSocketHybi implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (!headers.containsKey(WS_VERSION_KEY)) { return false; } StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); int version = Integer.parseInt(headers.get(WS_VERSION_KEY)); String key = headers.get(WS_KEY_KEY) + GUID; MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] resp = md.digest(key.getBytes()); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); response.append(WS_ACCEPT_KEY + ": "); response.append(Base64.encode(resp)); response.append("\r\n"); response.append("\r\n"); service.maskingKey = new byte[4]; service.writeRawData(response.toString()); return true; } @Override String getId(); @Override boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf); @Override ByteBuffer decodeFrame(WebSocketXMPPIOService service, ByteBuffer buf); @Override void encodeFrameAndWrite(WebSocketXMPPIOService service, ByteBuffer buf); @Override void closeConnection(WebSocketXMPPIOService service); } | WebSocketHybi implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (!headers.containsKey(WS_VERSION_KEY)) { return false; } StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); int version = Integer.parseInt(headers.get(WS_VERSION_KEY)); String key = headers.get(WS_KEY_KEY) + GUID; MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] resp = md.digest(key.getBytes()); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); response.append(WS_ACCEPT_KEY + ": "); response.append(Base64.encode(resp)); response.append("\r\n"); response.append("\r\n"); service.maskingKey = new byte[4]; service.writeRawData(response.toString()); return true; } @Override String getId(); @Override boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf); @Override ByteBuffer decodeFrame(WebSocketXMPPIOService service, ByteBuffer buf); @Override void encodeFrameAndWrite(WebSocketXMPPIOService service, ByteBuffer buf); @Override void closeConnection(WebSocketXMPPIOService service); static final String ID; } |
@Test public void testHttpHeadersParsingWithSpaces() throws UnsupportedEncodingException { byte[] data = prepareHTTPRequest(headers, true); Map<String, String> parsedHeaders = new HashMap<>(); service.parseHttpHeaders(data, parsedHeaders); assertMaps(headers, parsedHeaders); } | protected int parseHttpHeaders(byte[] buf, Map<String, String> headers) { int i = 0; while (buf[i] != '\n') { i++; } i++; if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "parsing request = \n{0}", new String(buf)); } StringBuilder builder = new StringBuilder(64); String key = null; boolean skipWhitespace = false; for (; i < buf.length; i++) { switch (buf[i]) { case ':': if (key == null) { key = builder.toString().trim(); builder = new StringBuilder(64); skipWhitespace = true; } else { builder.append((char) buf[i]); } break; case '\r': headers.put(key, builder.toString().trim()); key = null; builder = new StringBuilder(64); if (buf[i + 2] == '\r') { i += 3; } else { i++; } break; case ' ': case '\t': if (!skipWhitespace) { builder.append((char) buf[i]); } break; default: skipWhitespace = false; builder.append((char) buf[i]); } } return i; } | WebSocketXMPPIOService extends XMPPIOService<RefObject> { protected int parseHttpHeaders(byte[] buf, Map<String, String> headers) { int i = 0; while (buf[i] != '\n') { i++; } i++; if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "parsing request = \n{0}", new String(buf)); } StringBuilder builder = new StringBuilder(64); String key = null; boolean skipWhitespace = false; for (; i < buf.length; i++) { switch (buf[i]) { case ':': if (key == null) { key = builder.toString().trim(); builder = new StringBuilder(64); skipWhitespace = true; } else { builder.append((char) buf[i]); } break; case '\r': headers.put(key, builder.toString().trim()); key = null; builder = new StringBuilder(64); if (buf[i + 2] == '\r') { i += 3; } else { i++; } break; case ' ': case '\t': if (!skipWhitespace) { builder.append((char) buf[i]); } break; default: skipWhitespace = false; builder.append((char) buf[i]); } } return i; } } | WebSocketXMPPIOService extends XMPPIOService<RefObject> { protected int parseHttpHeaders(byte[] buf, Map<String, String> headers) { int i = 0; while (buf[i] != '\n') { i++; } i++; if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "parsing request = \n{0}", new String(buf)); } StringBuilder builder = new StringBuilder(64); String key = null; boolean skipWhitespace = false; for (; i < buf.length; i++) { switch (buf[i]) { case ':': if (key == null) { key = builder.toString().trim(); builder = new StringBuilder(64); skipWhitespace = true; } else { builder.append((char) buf[i]); } break; case '\r': headers.put(key, builder.toString().trim()); key = null; builder = new StringBuilder(64); if (buf[i + 2] == '\r') { i += 3; } else { i++; } break; case ' ': case '\t': if (!skipWhitespace) { builder.append((char) buf[i]); } break; default: skipWhitespace = false; builder.append((char) buf[i]); } } return i; } WebSocketXMPPIOService(WebSocketProtocolIfc[] enabledProtocols); } | WebSocketXMPPIOService extends XMPPIOService<RefObject> { protected int parseHttpHeaders(byte[] buf, Map<String, String> headers) { int i = 0; while (buf[i] != '\n') { i++; } i++; if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "parsing request = \n{0}", new String(buf)); } StringBuilder builder = new StringBuilder(64); String key = null; boolean skipWhitespace = false; for (; i < buf.length; i++) { switch (buf[i]) { case ':': if (key == null) { key = builder.toString().trim(); builder = new StringBuilder(64); skipWhitespace = true; } else { builder.append((char) buf[i]); } break; case '\r': headers.put(key, builder.toString().trim()); key = null; builder = new StringBuilder(64); if (buf[i + 2] == '\r') { i += 3; } else { i++; } break; case ' ': case '\t': if (!skipWhitespace) { builder.append((char) buf[i]); } break; default: skipWhitespace = false; builder.append((char) buf[i]); } } return i; } WebSocketXMPPIOService(WebSocketProtocolIfc[] enabledProtocols); @Override void stop(); void dumpHeaders(Map<String,String> headers); } | WebSocketXMPPIOService extends XMPPIOService<RefObject> { protected int parseHttpHeaders(byte[] buf, Map<String, String> headers) { int i = 0; while (buf[i] != '\n') { i++; } i++; if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "parsing request = \n{0}", new String(buf)); } StringBuilder builder = new StringBuilder(64); String key = null; boolean skipWhitespace = false; for (; i < buf.length; i++) { switch (buf[i]) { case ':': if (key == null) { key = builder.toString().trim(); builder = new StringBuilder(64); skipWhitespace = true; } else { builder.append((char) buf[i]); } break; case '\r': headers.put(key, builder.toString().trim()); key = null; builder = new StringBuilder(64); if (buf[i + 2] == '\r') { i += 3; } else { i++; } break; case ' ': case '\t': if (!skipWhitespace) { builder.append((char) buf[i]); } break; default: skipWhitespace = false; builder.append((char) buf[i]); } } return i; } WebSocketXMPPIOService(WebSocketProtocolIfc[] enabledProtocols); @Override void stop(); void dumpHeaders(Map<String,String> headers); } |
@Test public void testHttpHeadersParsingWithoutSpaces() throws UnsupportedEncodingException { byte[] data = prepareHTTPRequest(headers, false); Map<String, String> parsedHeaders = new HashMap<>(); service.parseHttpHeaders(data, parsedHeaders); assertMaps(headers, parsedHeaders); } | protected int parseHttpHeaders(byte[] buf, Map<String, String> headers) { int i = 0; while (buf[i] != '\n') { i++; } i++; if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "parsing request = \n{0}", new String(buf)); } StringBuilder builder = new StringBuilder(64); String key = null; boolean skipWhitespace = false; for (; i < buf.length; i++) { switch (buf[i]) { case ':': if (key == null) { key = builder.toString().trim(); builder = new StringBuilder(64); skipWhitespace = true; } else { builder.append((char) buf[i]); } break; case '\r': headers.put(key, builder.toString().trim()); key = null; builder = new StringBuilder(64); if (buf[i + 2] == '\r') { i += 3; } else { i++; } break; case ' ': case '\t': if (!skipWhitespace) { builder.append((char) buf[i]); } break; default: skipWhitespace = false; builder.append((char) buf[i]); } } return i; } | WebSocketXMPPIOService extends XMPPIOService<RefObject> { protected int parseHttpHeaders(byte[] buf, Map<String, String> headers) { int i = 0; while (buf[i] != '\n') { i++; } i++; if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "parsing request = \n{0}", new String(buf)); } StringBuilder builder = new StringBuilder(64); String key = null; boolean skipWhitespace = false; for (; i < buf.length; i++) { switch (buf[i]) { case ':': if (key == null) { key = builder.toString().trim(); builder = new StringBuilder(64); skipWhitespace = true; } else { builder.append((char) buf[i]); } break; case '\r': headers.put(key, builder.toString().trim()); key = null; builder = new StringBuilder(64); if (buf[i + 2] == '\r') { i += 3; } else { i++; } break; case ' ': case '\t': if (!skipWhitespace) { builder.append((char) buf[i]); } break; default: skipWhitespace = false; builder.append((char) buf[i]); } } return i; } } | WebSocketXMPPIOService extends XMPPIOService<RefObject> { protected int parseHttpHeaders(byte[] buf, Map<String, String> headers) { int i = 0; while (buf[i] != '\n') { i++; } i++; if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "parsing request = \n{0}", new String(buf)); } StringBuilder builder = new StringBuilder(64); String key = null; boolean skipWhitespace = false; for (; i < buf.length; i++) { switch (buf[i]) { case ':': if (key == null) { key = builder.toString().trim(); builder = new StringBuilder(64); skipWhitespace = true; } else { builder.append((char) buf[i]); } break; case '\r': headers.put(key, builder.toString().trim()); key = null; builder = new StringBuilder(64); if (buf[i + 2] == '\r') { i += 3; } else { i++; } break; case ' ': case '\t': if (!skipWhitespace) { builder.append((char) buf[i]); } break; default: skipWhitespace = false; builder.append((char) buf[i]); } } return i; } WebSocketXMPPIOService(WebSocketProtocolIfc[] enabledProtocols); } | WebSocketXMPPIOService extends XMPPIOService<RefObject> { protected int parseHttpHeaders(byte[] buf, Map<String, String> headers) { int i = 0; while (buf[i] != '\n') { i++; } i++; if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "parsing request = \n{0}", new String(buf)); } StringBuilder builder = new StringBuilder(64); String key = null; boolean skipWhitespace = false; for (; i < buf.length; i++) { switch (buf[i]) { case ':': if (key == null) { key = builder.toString().trim(); builder = new StringBuilder(64); skipWhitespace = true; } else { builder.append((char) buf[i]); } break; case '\r': headers.put(key, builder.toString().trim()); key = null; builder = new StringBuilder(64); if (buf[i + 2] == '\r') { i += 3; } else { i++; } break; case ' ': case '\t': if (!skipWhitespace) { builder.append((char) buf[i]); } break; default: skipWhitespace = false; builder.append((char) buf[i]); } } return i; } WebSocketXMPPIOService(WebSocketProtocolIfc[] enabledProtocols); @Override void stop(); void dumpHeaders(Map<String,String> headers); } | WebSocketXMPPIOService extends XMPPIOService<RefObject> { protected int parseHttpHeaders(byte[] buf, Map<String, String> headers) { int i = 0; while (buf[i] != '\n') { i++; } i++; if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "parsing request = \n{0}", new String(buf)); } StringBuilder builder = new StringBuilder(64); String key = null; boolean skipWhitespace = false; for (; i < buf.length; i++) { switch (buf[i]) { case ':': if (key == null) { key = builder.toString().trim(); builder = new StringBuilder(64); skipWhitespace = true; } else { builder.append((char) buf[i]); } break; case '\r': headers.put(key, builder.toString().trim()); key = null; builder = new StringBuilder(64); if (buf[i + 2] == '\r') { i += 3; } else { i++; } break; case ' ': case '\t': if (!skipWhitespace) { builder.append((char) buf[i]); } break; default: skipWhitespace = false; builder.append((char) buf[i]); } } return i; } WebSocketXMPPIOService(WebSocketProtocolIfc[] enabledProtocols); @Override void stop(); void dumpHeaders(Map<String,String> headers); } |
@Test public void testHandshakeOK() throws NoSuchAlgorithmException, IOException { final ByteBuffer tmp = ByteBuffer.allocate(2048); WebSocketXMPPIOService<Object> io = new WebSocketXMPPIOService<Object>(new WebSocketProtocolIfc[]{ new WebSocketHixie76() }) { @Override protected void writeBytes(ByteBuffer data) { tmp.put(data); } @Override public int getLocalPort() { return 80; } }; Map<String,String> params = new HashMap<String,String>(); params.put("Sec-WebSocket-Key1", "1C2J899_05 6 ! M 9 ^4"); params.put("Sec-WebSocket-Key2", "23 2ff0M_E0#.454X23"); params.put("Sec-WebSocket-Protocol", "xmpp"); byte[] bytes = new byte[10]; bytes[0] = '\r'; bytes[1] = '\n'; Assert.assertTrue("Handshake failed", impl.handshake(io, params, bytes)); } | @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (headers.containsKey(WS_VERSION_KEY)) { return false; } byte[] secBufArr = new byte[16]; Long secKey1 = decodeHyxie76SecKey(headers.get(WS_KEY1_KEY)); Long secKey2 = decodeHyxie76SecKey(headers.get(WS_KEY2_KEY)); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "WS-KEY1 = {0}", secKey1); log.log(Level.FINEST, "WS-KEY2 = {0}", secKey2); } uintToBytes(secBufArr, 0, secKey1); uintToBytes(secBufArr, 4, secKey2); if (buf[buf.length - 9] != '\n') { throw new IOException("buf[len-9] != \\n!!"); } for (int j = 8; j > 0; j--) { secBufArr[8 + 8 - j] = buf[buf.length - j]; } MessageDigest md = MessageDigest.getInstance("MD5"); byte[] resp = md.digest(secBufArr); StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); response.append("Content-Length: ").append(resp.length).append("\r\n"); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); if (headers.containsKey(ORIGIN_KEY)) { response.append(WS_ORIGIN_KEY).append(": ").append(headers.get(ORIGIN_KEY)).append("\r\n"); } boolean ssl = SocketType.ssl == ((SocketType) service.getSessionData().get("socket")); int localPort = service.getLocalPort(); String location = (ssl ? "wss: + headers.get(HOST_KEY) + (((ssl && localPort == 443) || (!ssl && localPort == 80) || headers.get(HOST_KEY).contains(":")) ? "" : (":" + localPort)) + "/"; response.append(WS_LOCATION_KEY).append(": ").append(location).append("\r\n"); response.append("\r\n"); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "sending response = \n{0}", response.toString()); } byte[] respBytes = response.toString().getBytes(); ByteBuffer out = ByteBuffer.allocate(respBytes.length + 16); out.put(respBytes); out.put(resp); out.flip(); service.writeBytes(out); return true; } | WebSocketHixie76 implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (headers.containsKey(WS_VERSION_KEY)) { return false; } byte[] secBufArr = new byte[16]; Long secKey1 = decodeHyxie76SecKey(headers.get(WS_KEY1_KEY)); Long secKey2 = decodeHyxie76SecKey(headers.get(WS_KEY2_KEY)); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "WS-KEY1 = {0}", secKey1); log.log(Level.FINEST, "WS-KEY2 = {0}", secKey2); } uintToBytes(secBufArr, 0, secKey1); uintToBytes(secBufArr, 4, secKey2); if (buf[buf.length - 9] != '\n') { throw new IOException("buf[len-9] != \\n!!"); } for (int j = 8; j > 0; j--) { secBufArr[8 + 8 - j] = buf[buf.length - j]; } MessageDigest md = MessageDigest.getInstance("MD5"); byte[] resp = md.digest(secBufArr); StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); response.append("Content-Length: ").append(resp.length).append("\r\n"); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); if (headers.containsKey(ORIGIN_KEY)) { response.append(WS_ORIGIN_KEY).append(": ").append(headers.get(ORIGIN_KEY)).append("\r\n"); } boolean ssl = SocketType.ssl == ((SocketType) service.getSessionData().get("socket")); int localPort = service.getLocalPort(); String location = (ssl ? "wss: + headers.get(HOST_KEY) + (((ssl && localPort == 443) || (!ssl && localPort == 80) || headers.get(HOST_KEY).contains(":")) ? "" : (":" + localPort)) + "/"; response.append(WS_LOCATION_KEY).append(": ").append(location).append("\r\n"); response.append("\r\n"); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "sending response = \n{0}", response.toString()); } byte[] respBytes = response.toString().getBytes(); ByteBuffer out = ByteBuffer.allocate(respBytes.length + 16); out.put(respBytes); out.put(resp); out.flip(); service.writeBytes(out); return true; } } | WebSocketHixie76 implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (headers.containsKey(WS_VERSION_KEY)) { return false; } byte[] secBufArr = new byte[16]; Long secKey1 = decodeHyxie76SecKey(headers.get(WS_KEY1_KEY)); Long secKey2 = decodeHyxie76SecKey(headers.get(WS_KEY2_KEY)); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "WS-KEY1 = {0}", secKey1); log.log(Level.FINEST, "WS-KEY2 = {0}", secKey2); } uintToBytes(secBufArr, 0, secKey1); uintToBytes(secBufArr, 4, secKey2); if (buf[buf.length - 9] != '\n') { throw new IOException("buf[len-9] != \\n!!"); } for (int j = 8; j > 0; j--) { secBufArr[8 + 8 - j] = buf[buf.length - j]; } MessageDigest md = MessageDigest.getInstance("MD5"); byte[] resp = md.digest(secBufArr); StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); response.append("Content-Length: ").append(resp.length).append("\r\n"); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); if (headers.containsKey(ORIGIN_KEY)) { response.append(WS_ORIGIN_KEY).append(": ").append(headers.get(ORIGIN_KEY)).append("\r\n"); } boolean ssl = SocketType.ssl == ((SocketType) service.getSessionData().get("socket")); int localPort = service.getLocalPort(); String location = (ssl ? "wss: + headers.get(HOST_KEY) + (((ssl && localPort == 443) || (!ssl && localPort == 80) || headers.get(HOST_KEY).contains(":")) ? "" : (":" + localPort)) + "/"; response.append(WS_LOCATION_KEY).append(": ").append(location).append("\r\n"); response.append("\r\n"); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "sending response = \n{0}", response.toString()); } byte[] respBytes = response.toString().getBytes(); ByteBuffer out = ByteBuffer.allocate(respBytes.length + 16); out.put(respBytes); out.put(resp); out.flip(); service.writeBytes(out); return true; } } | WebSocketHixie76 implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (headers.containsKey(WS_VERSION_KEY)) { return false; } byte[] secBufArr = new byte[16]; Long secKey1 = decodeHyxie76SecKey(headers.get(WS_KEY1_KEY)); Long secKey2 = decodeHyxie76SecKey(headers.get(WS_KEY2_KEY)); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "WS-KEY1 = {0}", secKey1); log.log(Level.FINEST, "WS-KEY2 = {0}", secKey2); } uintToBytes(secBufArr, 0, secKey1); uintToBytes(secBufArr, 4, secKey2); if (buf[buf.length - 9] != '\n') { throw new IOException("buf[len-9] != \\n!!"); } for (int j = 8; j > 0; j--) { secBufArr[8 + 8 - j] = buf[buf.length - j]; } MessageDigest md = MessageDigest.getInstance("MD5"); byte[] resp = md.digest(secBufArr); StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); response.append("Content-Length: ").append(resp.length).append("\r\n"); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); if (headers.containsKey(ORIGIN_KEY)) { response.append(WS_ORIGIN_KEY).append(": ").append(headers.get(ORIGIN_KEY)).append("\r\n"); } boolean ssl = SocketType.ssl == ((SocketType) service.getSessionData().get("socket")); int localPort = service.getLocalPort(); String location = (ssl ? "wss: + headers.get(HOST_KEY) + (((ssl && localPort == 443) || (!ssl && localPort == 80) || headers.get(HOST_KEY).contains(":")) ? "" : (":" + localPort)) + "/"; response.append(WS_LOCATION_KEY).append(": ").append(location).append("\r\n"); response.append("\r\n"); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "sending response = \n{0}", response.toString()); } byte[] respBytes = response.toString().getBytes(); ByteBuffer out = ByteBuffer.allocate(respBytes.length + 16); out.put(respBytes); out.put(resp); out.flip(); service.writeBytes(out); return true; } @Override String getId(); @Override boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf); @Override ByteBuffer decodeFrame(WebSocketXMPPIOService service, ByteBuffer buf); @Override void encodeFrameAndWrite(WebSocketXMPPIOService service, ByteBuffer buf); @Override void closeConnection(WebSocketXMPPIOService service); } | WebSocketHixie76 implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (headers.containsKey(WS_VERSION_KEY)) { return false; } byte[] secBufArr = new byte[16]; Long secKey1 = decodeHyxie76SecKey(headers.get(WS_KEY1_KEY)); Long secKey2 = decodeHyxie76SecKey(headers.get(WS_KEY2_KEY)); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "WS-KEY1 = {0}", secKey1); log.log(Level.FINEST, "WS-KEY2 = {0}", secKey2); } uintToBytes(secBufArr, 0, secKey1); uintToBytes(secBufArr, 4, secKey2); if (buf[buf.length - 9] != '\n') { throw new IOException("buf[len-9] != \\n!!"); } for (int j = 8; j > 0; j--) { secBufArr[8 + 8 - j] = buf[buf.length - j]; } MessageDigest md = MessageDigest.getInstance("MD5"); byte[] resp = md.digest(secBufArr); StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); response.append("Content-Length: ").append(resp.length).append("\r\n"); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); if (headers.containsKey(ORIGIN_KEY)) { response.append(WS_ORIGIN_KEY).append(": ").append(headers.get(ORIGIN_KEY)).append("\r\n"); } boolean ssl = SocketType.ssl == ((SocketType) service.getSessionData().get("socket")); int localPort = service.getLocalPort(); String location = (ssl ? "wss: + headers.get(HOST_KEY) + (((ssl && localPort == 443) || (!ssl && localPort == 80) || headers.get(HOST_KEY).contains(":")) ? "" : (":" + localPort)) + "/"; response.append(WS_LOCATION_KEY).append(": ").append(location).append("\r\n"); response.append("\r\n"); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "sending response = \n{0}", response.toString()); } byte[] respBytes = response.toString().getBytes(); ByteBuffer out = ByteBuffer.allocate(respBytes.length + 16); out.put(respBytes); out.put(resp); out.flip(); service.writeBytes(out); return true; } @Override String getId(); @Override boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf); @Override ByteBuffer decodeFrame(WebSocketXMPPIOService service, ByteBuffer buf); @Override void encodeFrameAndWrite(WebSocketXMPPIOService service, ByteBuffer buf); @Override void closeConnection(WebSocketXMPPIOService service); static final String ID; } |
@Test public void testGetData() throws InterruptedException { System.out.println( "repo: " + repo ); if ( repo != null ){ LocalDateTime localNow = LocalDateTime.now(); long initalDelay = 5; ScheduledExecutorService scheduler = Executors.newScheduledThreadPool( 10 ); final int iter = 50; final int threads = 10; for ( int i = 0 ; i < threads ; i++ ) { scheduler.scheduleAtFixedRate( new RunnableImpl( iter ), initalDelay, 100, TimeUnit.MILLISECONDS ); } Thread.sleep( threads * 1000 ); } } | @Override public String getData(BareJID user_id, final String subnode, final String key, final String def) throws UserNotFoundException, TigaseDBException { try { long nid = getNodeNID(null, user_id, subnode); if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "Loading data for key: {0}, user: {1}, node: {2}, def: {3}, found nid: {4}", new Object[] { key, user_id, subnode, def, nid }); } if (nid > 0) { ResultSet rs = null; PreparedStatement data_for_node_st = data_repo.getPreparedStatement(user_id, DATA_FOR_NODE_QUERY); synchronized (data_for_node_st) { try { String result = def; data_for_node_st.setLong(1, nid); data_for_node_st.setString(2, key); rs = data_for_node_st.executeQuery(); if (rs.next()) { result = rs.getString(1); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Found data: {0}", result); } } return result; } finally { data_repo.release(null, rs); } } } else { return def; } } catch (SQLException e) { throw new TigaseDBException("Error getting user data for: " + user_id + "/" + subnode + "/" + key, e); } } | JDBCRepository implements AuthRepository, UserRepository { @Override public String getData(BareJID user_id, final String subnode, final String key, final String def) throws UserNotFoundException, TigaseDBException { try { long nid = getNodeNID(null, user_id, subnode); if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "Loading data for key: {0}, user: {1}, node: {2}, def: {3}, found nid: {4}", new Object[] { key, user_id, subnode, def, nid }); } if (nid > 0) { ResultSet rs = null; PreparedStatement data_for_node_st = data_repo.getPreparedStatement(user_id, DATA_FOR_NODE_QUERY); synchronized (data_for_node_st) { try { String result = def; data_for_node_st.setLong(1, nid); data_for_node_st.setString(2, key); rs = data_for_node_st.executeQuery(); if (rs.next()) { result = rs.getString(1); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Found data: {0}", result); } } return result; } finally { data_repo.release(null, rs); } } } else { return def; } } catch (SQLException e) { throw new TigaseDBException("Error getting user data for: " + user_id + "/" + subnode + "/" + key, e); } } } | JDBCRepository implements AuthRepository, UserRepository { @Override public String getData(BareJID user_id, final String subnode, final String key, final String def) throws UserNotFoundException, TigaseDBException { try { long nid = getNodeNID(null, user_id, subnode); if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "Loading data for key: {0}, user: {1}, node: {2}, def: {3}, found nid: {4}", new Object[] { key, user_id, subnode, def, nid }); } if (nid > 0) { ResultSet rs = null; PreparedStatement data_for_node_st = data_repo.getPreparedStatement(user_id, DATA_FOR_NODE_QUERY); synchronized (data_for_node_st) { try { String result = def; data_for_node_st.setLong(1, nid); data_for_node_st.setString(2, key); rs = data_for_node_st.executeQuery(); if (rs.next()) { result = rs.getString(1); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Found data: {0}", result); } } return result; } finally { data_repo.release(null, rs); } } } else { return def; } } catch (SQLException e) { throw new TigaseDBException("Error getting user data for: " + user_id + "/" + subnode + "/" + key, e); } } } | JDBCRepository implements AuthRepository, UserRepository { @Override public String getData(BareJID user_id, final String subnode, final String key, final String def) throws UserNotFoundException, TigaseDBException { try { long nid = getNodeNID(null, user_id, subnode); if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "Loading data for key: {0}, user: {1}, node: {2}, def: {3}, found nid: {4}", new Object[] { key, user_id, subnode, def, nid }); } if (nid > 0) { ResultSet rs = null; PreparedStatement data_for_node_st = data_repo.getPreparedStatement(user_id, DATA_FOR_NODE_QUERY); synchronized (data_for_node_st) { try { String result = def; data_for_node_st.setLong(1, nid); data_for_node_st.setString(2, key); rs = data_for_node_st.executeQuery(); if (rs.next()) { result = rs.getString(1); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Found data: {0}", result); } } return result; } finally { data_repo.release(null, rs); } } } else { return def; } } catch (SQLException e) { throw new TigaseDBException("Error getting user data for: " + user_id + "/" + subnode + "/" + key, e); } } @Override void addDataList(BareJID user_id, final String subnode, final String key,
final String[] list); @Override void addUser(BareJID user_id); @Override void addUser(BareJID user, final String password); @Override @Deprecated boolean digestAuth(BareJID user, final String digest, final String id,
final String alg); @Override String getData(BareJID user_id, final String subnode, final String key,
final String def); @Override String getData(BareJID user_id, final String subnode, final String key); @Override String getData(BareJID user_id, final String key); @Override String[] getDataList(BareJID user_id, final String subnode, final String key); @Override String[] getKeys(BareJID user_id, final String subnode); @Override String[] getKeys(BareJID user_id); @Override String getResourceUri(); @Override String[] getSubnodes(BareJID user_id, final String subnode); @Override String[] getSubnodes(BareJID user_id); @Override long getUserUID(BareJID user_id); long getUserUID(DataRepository repo, BareJID user_id); @Override List<BareJID> getUsers(); @Override long getUsersCount(); @Override long getUsersCount(String domain); @Override void initRepository(final String connection_str, Map<String, String> params); @Override void logout(BareJID user); @Override boolean otherAuth(final Map<String, Object> props); @Override @Deprecated boolean plainAuth(BareJID user, final String password); @Override void queryAuth(Map<String, Object> authProps); @Override void removeData(BareJID user_id, final String subnode, final String key); @Override void removeData(BareJID user_id, final String key); @Override void removeSubnode(BareJID user_id, final String subnode); @Override void removeUser(BareJID user_id); @Override void setData(BareJID user_id, final String subnode, final String key,
final String value); @Override void setData(BareJID user_id, final String key, final String value); @Override void setDataList(BareJID user_id, final String subnode, final String key,
final String[] list); @Override void updatePassword(BareJID user, final String password); @Override boolean userExists(BareJID user); @Override String getPassword(BareJID user); @Override boolean isUserDisabled(BareJID user); @Override void setUserDisabled(BareJID user, Boolean value); } | JDBCRepository implements AuthRepository, UserRepository { @Override public String getData(BareJID user_id, final String subnode, final String key, final String def) throws UserNotFoundException, TigaseDBException { try { long nid = getNodeNID(null, user_id, subnode); if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "Loading data for key: {0}, user: {1}, node: {2}, def: {3}, found nid: {4}", new Object[] { key, user_id, subnode, def, nid }); } if (nid > 0) { ResultSet rs = null; PreparedStatement data_for_node_st = data_repo.getPreparedStatement(user_id, DATA_FOR_NODE_QUERY); synchronized (data_for_node_st) { try { String result = def; data_for_node_st.setLong(1, nid); data_for_node_st.setString(2, key); rs = data_for_node_st.executeQuery(); if (rs.next()) { result = rs.getString(1); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Found data: {0}", result); } } return result; } finally { data_repo.release(null, rs); } } } else { return def; } } catch (SQLException e) { throw new TigaseDBException("Error getting user data for: " + user_id + "/" + subnode + "/" + key, e); } } @Override void addDataList(BareJID user_id, final String subnode, final String key,
final String[] list); @Override void addUser(BareJID user_id); @Override void addUser(BareJID user, final String password); @Override @Deprecated boolean digestAuth(BareJID user, final String digest, final String id,
final String alg); @Override String getData(BareJID user_id, final String subnode, final String key,
final String def); @Override String getData(BareJID user_id, final String subnode, final String key); @Override String getData(BareJID user_id, final String key); @Override String[] getDataList(BareJID user_id, final String subnode, final String key); @Override String[] getKeys(BareJID user_id, final String subnode); @Override String[] getKeys(BareJID user_id); @Override String getResourceUri(); @Override String[] getSubnodes(BareJID user_id, final String subnode); @Override String[] getSubnodes(BareJID user_id); @Override long getUserUID(BareJID user_id); long getUserUID(DataRepository repo, BareJID user_id); @Override List<BareJID> getUsers(); @Override long getUsersCount(); @Override long getUsersCount(String domain); @Override void initRepository(final String connection_str, Map<String, String> params); @Override void logout(BareJID user); @Override boolean otherAuth(final Map<String, Object> props); @Override @Deprecated boolean plainAuth(BareJID user, final String password); @Override void queryAuth(Map<String, Object> authProps); @Override void removeData(BareJID user_id, final String subnode, final String key); @Override void removeData(BareJID user_id, final String key); @Override void removeSubnode(BareJID user_id, final String subnode); @Override void removeUser(BareJID user_id); @Override void setData(BareJID user_id, final String subnode, final String key,
final String value); @Override void setData(BareJID user_id, final String key, final String value); @Override void setDataList(BareJID user_id, final String subnode, final String key,
final String[] list); @Override void updatePassword(BareJID user, final String password); @Override boolean userExists(BareJID user); @Override String getPassword(BareJID user); @Override boolean isUserDisabled(BareJID user); @Override void setUserDisabled(BareJID user, Boolean value); static final String CURRENT_DB_SCHEMA_VER; static final String DEF_MAXIDS_TBL; static final String DEF_NODES_TBL; static final String DEF_PAIRS_TBL; static final String DEF_ROOT_NODE; static final String DEF_USERS_TBL; static final String DERBY_GETSCHEMAVER_QUERY; static final String SQLSERVER_GETSCHEMAVER_QUERY; static final String JDBC_GETSCHEMAVER_QUERY; static final String SCHEMA_UPGRADE_LINK; } |
@Test public void testHandshakeFail() throws NoSuchAlgorithmException, IOException { final ByteBuffer tmp = ByteBuffer.allocate(2048); WebSocketXMPPIOService<Object> io = new WebSocketXMPPIOService<Object>(new WebSocketProtocolIfc[]{ new WebSocketHixie76() }) { @Override protected void writeBytes(ByteBuffer data) { tmp.put(data); } @Override public int getLocalPort() { return 80; } }; Map<String,String> params = new HashMap<String,String>(); params.put("Sec-WebSocket-Version", "13"); params.put("Sec-WebSocket-Protocol", "xmpp"); byte[] bytes = new byte[10]; bytes[0] = '\r'; bytes[1] = '\n'; Assert.assertFalse("Handshake succeeded", impl.handshake(io, params, bytes)); } | @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (headers.containsKey(WS_VERSION_KEY)) { return false; } byte[] secBufArr = new byte[16]; Long secKey1 = decodeHyxie76SecKey(headers.get(WS_KEY1_KEY)); Long secKey2 = decodeHyxie76SecKey(headers.get(WS_KEY2_KEY)); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "WS-KEY1 = {0}", secKey1); log.log(Level.FINEST, "WS-KEY2 = {0}", secKey2); } uintToBytes(secBufArr, 0, secKey1); uintToBytes(secBufArr, 4, secKey2); if (buf[buf.length - 9] != '\n') { throw new IOException("buf[len-9] != \\n!!"); } for (int j = 8; j > 0; j--) { secBufArr[8 + 8 - j] = buf[buf.length - j]; } MessageDigest md = MessageDigest.getInstance("MD5"); byte[] resp = md.digest(secBufArr); StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); response.append("Content-Length: ").append(resp.length).append("\r\n"); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); if (headers.containsKey(ORIGIN_KEY)) { response.append(WS_ORIGIN_KEY).append(": ").append(headers.get(ORIGIN_KEY)).append("\r\n"); } boolean ssl = SocketType.ssl == ((SocketType) service.getSessionData().get("socket")); int localPort = service.getLocalPort(); String location = (ssl ? "wss: + headers.get(HOST_KEY) + (((ssl && localPort == 443) || (!ssl && localPort == 80) || headers.get(HOST_KEY).contains(":")) ? "" : (":" + localPort)) + "/"; response.append(WS_LOCATION_KEY).append(": ").append(location).append("\r\n"); response.append("\r\n"); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "sending response = \n{0}", response.toString()); } byte[] respBytes = response.toString().getBytes(); ByteBuffer out = ByteBuffer.allocate(respBytes.length + 16); out.put(respBytes); out.put(resp); out.flip(); service.writeBytes(out); return true; } | WebSocketHixie76 implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (headers.containsKey(WS_VERSION_KEY)) { return false; } byte[] secBufArr = new byte[16]; Long secKey1 = decodeHyxie76SecKey(headers.get(WS_KEY1_KEY)); Long secKey2 = decodeHyxie76SecKey(headers.get(WS_KEY2_KEY)); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "WS-KEY1 = {0}", secKey1); log.log(Level.FINEST, "WS-KEY2 = {0}", secKey2); } uintToBytes(secBufArr, 0, secKey1); uintToBytes(secBufArr, 4, secKey2); if (buf[buf.length - 9] != '\n') { throw new IOException("buf[len-9] != \\n!!"); } for (int j = 8; j > 0; j--) { secBufArr[8 + 8 - j] = buf[buf.length - j]; } MessageDigest md = MessageDigest.getInstance("MD5"); byte[] resp = md.digest(secBufArr); StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); response.append("Content-Length: ").append(resp.length).append("\r\n"); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); if (headers.containsKey(ORIGIN_KEY)) { response.append(WS_ORIGIN_KEY).append(": ").append(headers.get(ORIGIN_KEY)).append("\r\n"); } boolean ssl = SocketType.ssl == ((SocketType) service.getSessionData().get("socket")); int localPort = service.getLocalPort(); String location = (ssl ? "wss: + headers.get(HOST_KEY) + (((ssl && localPort == 443) || (!ssl && localPort == 80) || headers.get(HOST_KEY).contains(":")) ? "" : (":" + localPort)) + "/"; response.append(WS_LOCATION_KEY).append(": ").append(location).append("\r\n"); response.append("\r\n"); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "sending response = \n{0}", response.toString()); } byte[] respBytes = response.toString().getBytes(); ByteBuffer out = ByteBuffer.allocate(respBytes.length + 16); out.put(respBytes); out.put(resp); out.flip(); service.writeBytes(out); return true; } } | WebSocketHixie76 implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (headers.containsKey(WS_VERSION_KEY)) { return false; } byte[] secBufArr = new byte[16]; Long secKey1 = decodeHyxie76SecKey(headers.get(WS_KEY1_KEY)); Long secKey2 = decodeHyxie76SecKey(headers.get(WS_KEY2_KEY)); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "WS-KEY1 = {0}", secKey1); log.log(Level.FINEST, "WS-KEY2 = {0}", secKey2); } uintToBytes(secBufArr, 0, secKey1); uintToBytes(secBufArr, 4, secKey2); if (buf[buf.length - 9] != '\n') { throw new IOException("buf[len-9] != \\n!!"); } for (int j = 8; j > 0; j--) { secBufArr[8 + 8 - j] = buf[buf.length - j]; } MessageDigest md = MessageDigest.getInstance("MD5"); byte[] resp = md.digest(secBufArr); StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); response.append("Content-Length: ").append(resp.length).append("\r\n"); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); if (headers.containsKey(ORIGIN_KEY)) { response.append(WS_ORIGIN_KEY).append(": ").append(headers.get(ORIGIN_KEY)).append("\r\n"); } boolean ssl = SocketType.ssl == ((SocketType) service.getSessionData().get("socket")); int localPort = service.getLocalPort(); String location = (ssl ? "wss: + headers.get(HOST_KEY) + (((ssl && localPort == 443) || (!ssl && localPort == 80) || headers.get(HOST_KEY).contains(":")) ? "" : (":" + localPort)) + "/"; response.append(WS_LOCATION_KEY).append(": ").append(location).append("\r\n"); response.append("\r\n"); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "sending response = \n{0}", response.toString()); } byte[] respBytes = response.toString().getBytes(); ByteBuffer out = ByteBuffer.allocate(respBytes.length + 16); out.put(respBytes); out.put(resp); out.flip(); service.writeBytes(out); return true; } } | WebSocketHixie76 implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (headers.containsKey(WS_VERSION_KEY)) { return false; } byte[] secBufArr = new byte[16]; Long secKey1 = decodeHyxie76SecKey(headers.get(WS_KEY1_KEY)); Long secKey2 = decodeHyxie76SecKey(headers.get(WS_KEY2_KEY)); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "WS-KEY1 = {0}", secKey1); log.log(Level.FINEST, "WS-KEY2 = {0}", secKey2); } uintToBytes(secBufArr, 0, secKey1); uintToBytes(secBufArr, 4, secKey2); if (buf[buf.length - 9] != '\n') { throw new IOException("buf[len-9] != \\n!!"); } for (int j = 8; j > 0; j--) { secBufArr[8 + 8 - j] = buf[buf.length - j]; } MessageDigest md = MessageDigest.getInstance("MD5"); byte[] resp = md.digest(secBufArr); StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); response.append("Content-Length: ").append(resp.length).append("\r\n"); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); if (headers.containsKey(ORIGIN_KEY)) { response.append(WS_ORIGIN_KEY).append(": ").append(headers.get(ORIGIN_KEY)).append("\r\n"); } boolean ssl = SocketType.ssl == ((SocketType) service.getSessionData().get("socket")); int localPort = service.getLocalPort(); String location = (ssl ? "wss: + headers.get(HOST_KEY) + (((ssl && localPort == 443) || (!ssl && localPort == 80) || headers.get(HOST_KEY).contains(":")) ? "" : (":" + localPort)) + "/"; response.append(WS_LOCATION_KEY).append(": ").append(location).append("\r\n"); response.append("\r\n"); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "sending response = \n{0}", response.toString()); } byte[] respBytes = response.toString().getBytes(); ByteBuffer out = ByteBuffer.allocate(respBytes.length + 16); out.put(respBytes); out.put(resp); out.flip(); service.writeBytes(out); return true; } @Override String getId(); @Override boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf); @Override ByteBuffer decodeFrame(WebSocketXMPPIOService service, ByteBuffer buf); @Override void encodeFrameAndWrite(WebSocketXMPPIOService service, ByteBuffer buf); @Override void closeConnection(WebSocketXMPPIOService service); } | WebSocketHixie76 implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (headers.containsKey(WS_VERSION_KEY)) { return false; } byte[] secBufArr = new byte[16]; Long secKey1 = decodeHyxie76SecKey(headers.get(WS_KEY1_KEY)); Long secKey2 = decodeHyxie76SecKey(headers.get(WS_KEY2_KEY)); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "WS-KEY1 = {0}", secKey1); log.log(Level.FINEST, "WS-KEY2 = {0}", secKey2); } uintToBytes(secBufArr, 0, secKey1); uintToBytes(secBufArr, 4, secKey2); if (buf[buf.length - 9] != '\n') { throw new IOException("buf[len-9] != \\n!!"); } for (int j = 8; j > 0; j--) { secBufArr[8 + 8 - j] = buf[buf.length - j]; } MessageDigest md = MessageDigest.getInstance("MD5"); byte[] resp = md.digest(secBufArr); StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); response.append("Content-Length: ").append(resp.length).append("\r\n"); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); if (headers.containsKey(ORIGIN_KEY)) { response.append(WS_ORIGIN_KEY).append(": ").append(headers.get(ORIGIN_KEY)).append("\r\n"); } boolean ssl = SocketType.ssl == ((SocketType) service.getSessionData().get("socket")); int localPort = service.getLocalPort(); String location = (ssl ? "wss: + headers.get(HOST_KEY) + (((ssl && localPort == 443) || (!ssl && localPort == 80) || headers.get(HOST_KEY).contains(":")) ? "" : (":" + localPort)) + "/"; response.append(WS_LOCATION_KEY).append(": ").append(location).append("\r\n"); response.append("\r\n"); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "sending response = \n{0}", response.toString()); } byte[] respBytes = response.toString().getBytes(); ByteBuffer out = ByteBuffer.allocate(respBytes.length + 16); out.put(respBytes); out.put(resp); out.flip(); service.writeBytes(out); return true; } @Override String getId(); @Override boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf); @Override ByteBuffer decodeFrame(WebSocketXMPPIOService service, ByteBuffer buf); @Override void encodeFrameAndWrite(WebSocketXMPPIOService service, ByteBuffer buf); @Override void closeConnection(WebSocketXMPPIOService service); static final String ID; } |
@Test @SuppressWarnings("deprecation") public void testGetMethodName() { SimpleParser parser = new SimpleParser(); DomBuilderHandler handler = new DomBuilderHandler(); char[] data = "<cluster to=\"sess-man@blue\" type=\"set\" id=\"cl-6627\" xmlns=\"tigase:cluster\" from=\"sess-man@green\"><control><visited-nodes><node-id>sess-man@green</node-id></visited-nodes><method-call name=\"packet-forward-sm-cmd\"/><first-node>sess-man@green</first-node></control><data><presence to=\"test2@test\" xmlns=\"jabber:client\" from=\"test1@test/test\"><status/><priority>5</priority></presence></data></cluster>".toCharArray(); parser.parse(handler, data, 0, data.length); Element elem = handler.getParsedElements().poll(); assertEquals( "packet-forward-sm-cmd", elem.findChild("/cluster/control/method-call").getAttributeStaticStr("name")); ClusterElement clElem = new ClusterElement(elem); assertEquals("packet-forward-sm-cmd", clElem.getMethodName()); } | public String getMethodName() { return method_name; } | ClusterElement { public String getMethodName() { return method_name; } } | ClusterElement { public String getMethodName() { return method_name; } ClusterElement(Element elem); ClusterElement(JID from, JID to, StanzaType type, Packet packet); } | ClusterElement { public String getMethodName() { return method_name; } ClusterElement(Element elem); ClusterElement(JID from, JID to, StanzaType type, Packet packet); static Element clusterElement(JID from, JID to, StanzaType type); static Element createClusterElement(JID from, JID to, StanzaType type,
String packet_from); static ClusterElement createClusterMethodCall(JID from, JID to, StanzaType type,
String method_name, Map<String, String> params); static ClusterElement createForNextNode(ClusterElement clel,
List<JID> cluster_nodes, JID comp_id); void addDataPacket(Packet packet); void addDataPacket(Element packet); void addDataPackets(Queue<Element> packets); void addMethodResult(String key, String val); void addVisitedNode(JID node_id); void addVisitedNodes(Set<JID> nodes); ClusterElement createMethodResponse(JID from, StanzaType type,
Map<String, String> results); ClusterElement createMethodResponse(JID from, JID to, StanzaType type,
Map<String, String> results); Map<String, String> getAllMethodParams(); Map<String, String> getAllMethodResults(); Element getClusterElement(String id); Queue<Element> getDataPackets(); JID getFirstNode(); String getMethodName(); String getMethodParam(String par_name); long getMethodParam(String par_name, long def); String getMethodResultVal(String val_name); long getMethodResultVal(String val_name, long def); Priority getPriority(); Set<JID> getVisitedNodes(); boolean isVisitedNode(JID node_id); void setPriority(Priority priority); ClusterElement nextClusterNode(JID node_id); } | ClusterElement { public String getMethodName() { return method_name; } ClusterElement(Element elem); ClusterElement(JID from, JID to, StanzaType type, Packet packet); static Element clusterElement(JID from, JID to, StanzaType type); static Element createClusterElement(JID from, JID to, StanzaType type,
String packet_from); static ClusterElement createClusterMethodCall(JID from, JID to, StanzaType type,
String method_name, Map<String, String> params); static ClusterElement createForNextNode(ClusterElement clel,
List<JID> cluster_nodes, JID comp_id); void addDataPacket(Packet packet); void addDataPacket(Element packet); void addDataPackets(Queue<Element> packets); void addMethodResult(String key, String val); void addVisitedNode(JID node_id); void addVisitedNodes(Set<JID> nodes); ClusterElement createMethodResponse(JID from, StanzaType type,
Map<String, String> results); ClusterElement createMethodResponse(JID from, JID to, StanzaType type,
Map<String, String> results); Map<String, String> getAllMethodParams(); Map<String, String> getAllMethodResults(); Element getClusterElement(String id); Queue<Element> getDataPackets(); JID getFirstNode(); String getMethodName(); String getMethodParam(String par_name); long getMethodParam(String par_name, long def); String getMethodResultVal(String val_name); long getMethodResultVal(String val_name, long def); Priority getPriority(); Set<JID> getVisitedNodes(); boolean isVisitedNode(JID node_id); void setPriority(Priority priority); ClusterElement nextClusterNode(JID node_id); static final String CLUSTER_CONTROL_EL_NAME; static final String CLUSTER_DATA_EL_NAME; static final String CLUSTER_EL_NAME; static final String CLUSTER_METHOD_EL_NAME; static final String CLUSTER_METHOD_PAR_EL_NAME; static final String CLUSTER_METHOD_RESULTS_EL_NAME; static final String CLUSTER_METHOD_RESULTS_VAL_EL_NAME; static final String CLUSTER_NAME_ATTR; static final String FIRST_NODE_EL_NAME; static final String NODE_ID_EL_NAME; static final String VISITED_NODES_EL_NAME; static final String XMLNS; static final String[] VISITED_NODES_PATH; static final String[] FIRST_NODE_PATH; static final String[] CLUSTER_METHOD_RESULTS_PATH; static final String[] CLUSTER_METHOD_PATH; static final String[] CLUSTER_DATA_PATH; static final String[] CLUSTER_CONTROL_PATH; } |
@Test public void testSelectConnection() throws Exception { ClusterConnection conn = new ClusterConnection("test"); ClusterConnectionSelector selector = new ClusterConnectionSelector(); selector.setClusterConnectionHandler(new ClusterConnectionHandler() { @Override public int hashCodeForPacket(Packet packet) { return packet.getStanzaFrom().hashCode(); } }); Map<String,Object> props = new HashMap<>(); props.put(CLUSTER_SYS_CONNECTIONS_PER_NODE_PROP_KEY, 1); selector.setProperties(props); Element el = new Element("iq", new String[] { "from" }, new String[] { "test1" }); Packet p = Packet.packetInstance(el); assertNull(selector.selectConnection(p, conn)); XMPPIOService<Object> serv1 = new XMPPIOService<Object>(); conn.addConn(serv1); assertEquals(serv1, selector.selectConnection(p, conn)); p.setPriority(Priority.SYSTEM); assertEquals(serv1, selector.selectConnection(p, conn)); p.setPriority(null); XMPPIOService<Object> serv2 = new XMPPIOService<Object>(); conn.addConn(serv2); assertEquals(2, conn.size()); assertEquals(serv2, selector.selectConnection(p, conn)); p.setPriority(Priority.SYSTEM); assertEquals(serv1, selector.selectConnection(p, conn)); p.setPriority(null); XMPPIOService<Object> serv3 = new XMPPIOService<Object>(); conn.addConn(serv3); assertEquals(3, conn.size()); assertNotSame(serv1, selector.selectConnection(p, conn)); p.setPriority(Priority.SYSTEM); assertEquals(serv1, selector.selectConnection(p, conn)); el = new Element("iq", new String[] { "from" }, new String[] { "test2" }); p = Packet.packetInstance(el); assertEquals(3, conn.size()); assertNotSame(serv1, selector.selectConnection(p, conn)); el = new Element("iq", new String[] { "from" }, new String[] { "test3" }); p = Packet.packetInstance(el); assertEquals(3, conn.size()); assertNotSame(serv1, selector.selectConnection(p, conn)); el = new Element("iq", new String[] { "from" }, new String[] { "test4" }); p = Packet.packetInstance(el); assertEquals(3, conn.size()); assertNotSame(serv1, selector.selectConnection(p, conn)); } | @Override public XMPPIOService<Object> selectConnection(Packet p, ClusterConnection conn) { if (conn == null) return null; int code = Math.abs(handler.hashCodeForPacket(p)); List<XMPPIOService<Object>> conns = conn.getConnections(); if (conns.size() > 0) { if (conns.size() > sysConns) { if (p.getPriority() != null && p.getPriority().ordinal() <= Priority.CLUSTER.ordinal()) { return conns.get(code % sysConns); } else { return conns.get(sysConns + (code % (conns.size() - sysConns))); } } else { return conns.get(code % conns.size()); } } return null; } | ClusterConnectionSelector implements ClusterConnectionSelectorIfc { @Override public XMPPIOService<Object> selectConnection(Packet p, ClusterConnection conn) { if (conn == null) return null; int code = Math.abs(handler.hashCodeForPacket(p)); List<XMPPIOService<Object>> conns = conn.getConnections(); if (conns.size() > 0) { if (conns.size() > sysConns) { if (p.getPriority() != null && p.getPriority().ordinal() <= Priority.CLUSTER.ordinal()) { return conns.get(code % sysConns); } else { return conns.get(sysConns + (code % (conns.size() - sysConns))); } } else { return conns.get(code % conns.size()); } } return null; } } | ClusterConnectionSelector implements ClusterConnectionSelectorIfc { @Override public XMPPIOService<Object> selectConnection(Packet p, ClusterConnection conn) { if (conn == null) return null; int code = Math.abs(handler.hashCodeForPacket(p)); List<XMPPIOService<Object>> conns = conn.getConnections(); if (conns.size() > 0) { if (conns.size() > sysConns) { if (p.getPriority() != null && p.getPriority().ordinal() <= Priority.CLUSTER.ordinal()) { return conns.get(code % sysConns); } else { return conns.get(sysConns + (code % (conns.size() - sysConns))); } } else { return conns.get(code % conns.size()); } } return null; } } | ClusterConnectionSelector implements ClusterConnectionSelectorIfc { @Override public XMPPIOService<Object> selectConnection(Packet p, ClusterConnection conn) { if (conn == null) return null; int code = Math.abs(handler.hashCodeForPacket(p)); List<XMPPIOService<Object>> conns = conn.getConnections(); if (conns.size() > 0) { if (conns.size() > sysConns) { if (p.getPriority() != null && p.getPriority().ordinal() <= Priority.CLUSTER.ordinal()) { return conns.get(code % sysConns); } else { return conns.get(sysConns + (code % (conns.size() - sysConns))); } } else { return conns.get(code % conns.size()); } } return null; } @Override XMPPIOService<Object> selectConnection(Packet p, ClusterConnection conn); @Override void setClusterConnectionHandler(ClusterConnectionHandler handler); @Override void setProperties(Map<String,Object> props); } | ClusterConnectionSelector implements ClusterConnectionSelectorIfc { @Override public XMPPIOService<Object> selectConnection(Packet p, ClusterConnection conn) { if (conn == null) return null; int code = Math.abs(handler.hashCodeForPacket(p)); List<XMPPIOService<Object>> conns = conn.getConnections(); if (conns.size() > 0) { if (conns.size() > sysConns) { if (p.getPriority() != null && p.getPriority().ordinal() <= Priority.CLUSTER.ordinal()) { return conns.get(code % sysConns); } else { return conns.get(sysConns + (code % (conns.size() - sysConns))); } } else { return conns.get(code % conns.size()); } } return null; } @Override XMPPIOService<Object> selectConnection(Packet p, ClusterConnection conn); @Override void setClusterConnectionHandler(ClusterConnectionHandler handler); @Override void setProperties(Map<String,Object> props); } |
@Test public void testParseRules() throws TigaseStringprepException, ParseException { System.out.println( "parseRules" ); Set<Rule> expResult = new TreeSet<>(); Rule rule = new Rule( 1, true, RuleType.self, null ); if ( rule != null ){ expResult.add( rule ); } rule = new Rule( 2, true, RuleType.jid, JID.jidInstance( "[email protected]" ) ); if ( rule != null ){ expResult.add( rule ); } rule = new Rule( 3, true, RuleType.jid, JID.jidInstance( "[email protected]" ) ); if ( rule != null ){ expResult.add( rule ); } rule = new Rule( 4, false, RuleType.all, null ); if ( rule != null ){ expResult.add( rule ); } Set<Rule> result = CustomDomainFilter.parseRules( rules ); assertEquals( expResult, result ); } | public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } | CustomDomainFilter { public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } } | CustomDomainFilter { public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } private CustomDomainFilter(); } | CustomDomainFilter { public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } private CustomDomainFilter(); static Set<Rule> parseRules( String rules ); static Set<Rule> parseRules( String[] rules ); static boolean isAllowed( JID source, JID destination, String rules ); static boolean isAllowed( JID source, JID destination, String[] rules ); static boolean isAllowed( JID source, JID destination, Set<Rule> rules ); } | CustomDomainFilter { public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } private CustomDomainFilter(); static Set<Rule> parseRules( String rules ); static Set<Rule> parseRules( String[] rules ); static boolean isAllowed( JID source, JID destination, String rules ); static boolean isAllowed( JID source, JID destination, String[] rules ); static boolean isAllowed( JID source, JID destination, Set<Rule> rules ); } |
@Test public void testParseRulesString() throws TigaseStringprepException, ParseException { System.out.println( "parseRules" ); String rulseString = "4|deny|all;1|allow|self;3|allow|jid|[email protected];2|allow|jid|[email protected]"; Set<Rule> expResult = new TreeSet<>(); Rule rule = new Rule( 1, true, RuleType.self, null ); if ( rule != null ){ expResult.add( rule ); } rule = new Rule( 2, true, RuleType.jid, JID.jidInstance( "[email protected]" ) ); if ( rule != null ){ expResult.add( rule ); } rule = new Rule( 3, true, RuleType.jid, JID.jidInstance( "[email protected]" ) ); if ( rule != null ){ expResult.add( rule ); } rule = new Rule( 4, false, RuleType.all, null ); if ( rule != null ){ expResult.add( rule ); } Set<Rule> result = CustomDomainFilter.parseRules( rulseString ); assertEquals( expResult, result ); rulseString = "1|allow|self;2|allow|jid|[email protected];3|allow|jid|[email protected];4|deny|all;"; String resultString = new String(); for ( Rule res : result) { resultString += res.toConfigurationString(); } assertEquals( rulseString, resultString ); } | public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } | CustomDomainFilter { public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } } | CustomDomainFilter { public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } private CustomDomainFilter(); } | CustomDomainFilter { public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } private CustomDomainFilter(); static Set<Rule> parseRules( String rules ); static Set<Rule> parseRules( String[] rules ); static boolean isAllowed( JID source, JID destination, String rules ); static boolean isAllowed( JID source, JID destination, String[] rules ); static boolean isAllowed( JID source, JID destination, Set<Rule> rules ); } | CustomDomainFilter { public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } private CustomDomainFilter(); static Set<Rule> parseRules( String rules ); static Set<Rule> parseRules( String[] rules ); static boolean isAllowed( JID source, JID destination, String rules ); static boolean isAllowed( JID source, JID destination, String[] rules ); static boolean isAllowed( JID source, JID destination, Set<Rule> rules ); } |
@Test(expected = ParseException.class) public void testParseRulesException() throws TigaseStringprepException, ParseException { String[] rules_fail = { "8|deny|||self,", "|||18|||deny,self::::" }; Set<Rule> result = CustomDomainFilter.parseRules( rules_fail ); } | public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } | CustomDomainFilter { public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } } | CustomDomainFilter { public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } private CustomDomainFilter(); } | CustomDomainFilter { public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } private CustomDomainFilter(); static Set<Rule> parseRules( String rules ); static Set<Rule> parseRules( String[] rules ); static boolean isAllowed( JID source, JID destination, String rules ); static boolean isAllowed( JID source, JID destination, String[] rules ); static boolean isAllowed( JID source, JID destination, Set<Rule> rules ); } | CustomDomainFilter { public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } private CustomDomainFilter(); static Set<Rule> parseRules( String rules ); static Set<Rule> parseRules( String[] rules ); static boolean isAllowed( JID source, JID destination, String rules ); static boolean isAllowed( JID source, JID destination, String[] rules ); static boolean isAllowed( JID source, JID destination, Set<Rule> rules ); } |
@Test public void testIsAllowed() throws TigaseStringprepException, ParseException { JID jid1_r1 = JID.jidInstance( "user1", "domain1", "resource1" ); JID jid1_r2 = JID.jidInstance( "user1", "domain1", "resource2" ); JID jid2_r1 = JID.jidInstance( "user2", "domain1", "resource1" ); JID jid3_r1 = JID.jidInstance( "user3", "domain1", "resource1" ); JID admin = JID.jidInstance( "admin", "test2.com" ); JID pubsub = JID.jidInstance( "pubsub", "test.com" ); boolean allowed = CustomDomainFilter.isAllowed( jid1_r1, jid1_r2, rules ); assertTrue( "should be allowed / self / permitted jid", allowed ); allowed = CustomDomainFilter.isAllowed( jid1_r1, admin, rules ); assertTrue( "should be allowed / permitted jid", allowed ); allowed = CustomDomainFilter.isAllowed( jid1_r1, pubsub, rules ); assertTrue( "should be allowed / permitted jid", allowed ); allowed = CustomDomainFilter.isAllowed( jid1_r1, jid2_r1, rules ); assertFalse( "should be denyed / permitted jid", allowed ); allowed = CustomDomainFilter.isAllowed( jid2_r1, jid2_r1, rules ); assertTrue( "should be allowed / self", allowed ); allowed = CustomDomainFilter.isAllowed( jid3_r1, jid2_r1, rules ); assertFalse( "should be denied / not permitted jids", allowed ); } | public static boolean isAllowed( JID source, JID destination, String rules ) { try { Set<Rule> parseRules = parseRules( rules ); if ( parseRules != null ){ return isAllowed( source, destination, parseRules ); } else { return true; } } catch ( ParseException e ) { return true; } } | CustomDomainFilter { public static boolean isAllowed( JID source, JID destination, String rules ) { try { Set<Rule> parseRules = parseRules( rules ); if ( parseRules != null ){ return isAllowed( source, destination, parseRules ); } else { return true; } } catch ( ParseException e ) { return true; } } } | CustomDomainFilter { public static boolean isAllowed( JID source, JID destination, String rules ) { try { Set<Rule> parseRules = parseRules( rules ); if ( parseRules != null ){ return isAllowed( source, destination, parseRules ); } else { return true; } } catch ( ParseException e ) { return true; } } private CustomDomainFilter(); } | CustomDomainFilter { public static boolean isAllowed( JID source, JID destination, String rules ) { try { Set<Rule> parseRules = parseRules( rules ); if ( parseRules != null ){ return isAllowed( source, destination, parseRules ); } else { return true; } } catch ( ParseException e ) { return true; } } private CustomDomainFilter(); static Set<Rule> parseRules( String rules ); static Set<Rule> parseRules( String[] rules ); static boolean isAllowed( JID source, JID destination, String rules ); static boolean isAllowed( JID source, JID destination, String[] rules ); static boolean isAllowed( JID source, JID destination, Set<Rule> rules ); } | CustomDomainFilter { public static boolean isAllowed( JID source, JID destination, String rules ) { try { Set<Rule> parseRules = parseRules( rules ); if ( parseRules != null ){ return isAllowed( source, destination, parseRules ); } else { return true; } } catch ( ParseException e ) { return true; } } private CustomDomainFilter(); static Set<Rule> parseRules( String rules ); static Set<Rule> parseRules( String[] rules ); static boolean isAllowed( JID source, JID destination, String rules ); static boolean isAllowed( JID source, JID destination, String[] rules ); static boolean isAllowed( JID source, JID destination, Set<Rule> rules ); } |
@Test public void testCreateNodeName() throws Exception { assertEquals("1|2", NodeNameUtil.createNodeName("1", "2")); assertEquals("*|2", NodeNameUtil.createNodeName(null, "2")); assertEquals("*|*", NodeNameUtil.createNodeName(null, null)); assertEquals("1|*", NodeNameUtil.createNodeName("1", null)); } | public static String createNodeName(String eventName, String xmlns) { return (eventName == null ? "*" : eventName) + "|" + (xmlns == null ? "*" : xmlns); } | NodeNameUtil { public static String createNodeName(String eventName, String xmlns) { return (eventName == null ? "*" : eventName) + "|" + (xmlns == null ? "*" : xmlns); } } | NodeNameUtil { public static String createNodeName(String eventName, String xmlns) { return (eventName == null ? "*" : eventName) + "|" + (xmlns == null ? "*" : xmlns); } private NodeNameUtil(); } | NodeNameUtil { public static String createNodeName(String eventName, String xmlns) { return (eventName == null ? "*" : eventName) + "|" + (xmlns == null ? "*" : xmlns); } private NodeNameUtil(); static String createNodeName(String eventName, String xmlns); static EventName parseNodeName(String nodeName); } | NodeNameUtil { public static String createNodeName(String eventName, String xmlns) { return (eventName == null ? "*" : eventName) + "|" + (xmlns == null ? "*" : xmlns); } private NodeNameUtil(); static String createNodeName(String eventName, String xmlns); static EventName parseNodeName(String nodeName); } |
@Test public void testParseNodeName() throws Exception { assertEquals(new EventName("1", "2"), NodeNameUtil.parseNodeName("1|2")); assertEquals(new EventName(null, "2"), NodeNameUtil.parseNodeName("*|2")); assertEquals(new EventName(null, null), NodeNameUtil.parseNodeName("*|*")); assertEquals(new EventName("1", null), NodeNameUtil.parseNodeName("1|*")); assertEquals(new EventName("1", ""), NodeNameUtil.parseNodeName("1|")); assertEquals(new EventName("", ""), NodeNameUtil.parseNodeName("|")); } | public static EventName parseNodeName(String nodeName) { int i = nodeName.indexOf('|'); String n = nodeName.substring(0, i); String x = nodeName.substring(i + 1); return new EventName(n.equals("*") ? null : n, x.equals("*") ? null : x); } | NodeNameUtil { public static EventName parseNodeName(String nodeName) { int i = nodeName.indexOf('|'); String n = nodeName.substring(0, i); String x = nodeName.substring(i + 1); return new EventName(n.equals("*") ? null : n, x.equals("*") ? null : x); } } | NodeNameUtil { public static EventName parseNodeName(String nodeName) { int i = nodeName.indexOf('|'); String n = nodeName.substring(0, i); String x = nodeName.substring(i + 1); return new EventName(n.equals("*") ? null : n, x.equals("*") ? null : x); } private NodeNameUtil(); } | NodeNameUtil { public static EventName parseNodeName(String nodeName) { int i = nodeName.indexOf('|'); String n = nodeName.substring(0, i); String x = nodeName.substring(i + 1); return new EventName(n.equals("*") ? null : n, x.equals("*") ? null : x); } private NodeNameUtil(); static String createNodeName(String eventName, String xmlns); static EventName parseNodeName(String nodeName); } | NodeNameUtil { public static EventName parseNodeName(String nodeName) { int i = nodeName.indexOf('|'); String n = nodeName.substring(0, i); String x = nodeName.substring(i + 1); return new EventName(n.equals("*") ? null : n, x.equals("*") ? null : x); } private NodeNameUtil(); static String createNodeName(String eventName, String xmlns); static EventName parseNodeName(String nodeName); } |
@Test public void testEquals() throws Exception { assertEquals(new EventName(null, null), new EventName(null, null)); assertEquals(new EventName(null, "2"), new EventName(null, "2")); assertEquals(new EventName("1", "2"), new EventName("1", "2")); assertNotEquals(new EventName(null, null), new EventName("2", "2")); assertNotEquals(new EventName(null, null), new EventName(null, "2")); assertNotEquals(new EventName(null, null), new EventName("2", null)); assertNotEquals(new EventName("1", null), new EventName("2", "2")); assertNotEquals(new EventName(null, "2"), new EventName("2", "2")); assertNotEquals(new EventName("2", "1"), new EventName("2", "2")); } | @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EventName other = (EventName) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (xmlns == null) { if (other.xmlns != null) return false; } else if (!xmlns.equals(other.xmlns)) return false; return true; } | EventName { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EventName other = (EventName) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (xmlns == null) { if (other.xmlns != null) return false; } else if (!xmlns.equals(other.xmlns)) return false; return true; } } | EventName { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EventName other = (EventName) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (xmlns == null) { if (other.xmlns != null) return false; } else if (!xmlns.equals(other.xmlns)) return false; return true; } EventName(String name, String xmlns); } | EventName { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EventName other = (EventName) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (xmlns == null) { if (other.xmlns != null) return false; } else if (!xmlns.equals(other.xmlns)) return false; return true; } EventName(String name, String xmlns); @Override boolean equals(Object obj); String getName(); String getXmlns(); @Override int hashCode(); String toEventBusNode(); @Override String toString(); } | EventName { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EventName other = (EventName) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (xmlns == null) { if (other.xmlns != null) return false; } else if (!xmlns.equals(other.xmlns)) return false; return true; } EventName(String name, String xmlns); @Override boolean equals(Object obj); String getName(); String getXmlns(); @Override int hashCode(); String toEventBusNode(); @Override String toString(); } |
@Test public void testRecipientDisabledFor2ResourcesMessage() throws TigaseStringprepException, NotAuthorizedException { String recipient = "recipient-1@localhost"; JID recp1 = JID.jidInstanceNS(recipient + "/res1"); JID recp2 = JID.jidInstanceNS(recipient + "/res2"); JID connId1 = JID.jidInstanceNS("c2s@localhost/recipient1-res1"); JID connId2 = JID.jidInstanceNS("c2s@localhost/recipient1-res2"); XMPPResourceConnection session1 = getSession(connId1, recp1); getSession(connId2, recp2); Packet p = Packet.packetInstance("message", "sender-1@localhost/res1", recp1.toString(), StanzaType.chat); p.setPacketTo(connId1); ArrayDeque<Packet> results = new ArrayDeque<Packet>(); results.offer(p); Packet[] expected = results.toArray(new Packet[0]); mobileV3.filter(p, session1, null, results); Packet[] processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); } | @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } | MobileV3 extends AnnotatedXMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc { @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } } | MobileV3 extends AnnotatedXMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc { @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } } | MobileV3 extends AnnotatedXMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc { @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } @Override void init(Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supStreamFeatures(XMPPResourceConnection session); @Override @SuppressWarnings("unchecked") void filter(Packet _packet, XMPPResourceConnection sessionFromSM,
NonAuthUserRepository repo, Queue<Packet> results); } | MobileV3 extends AnnotatedXMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc { @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } @Override void init(Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supStreamFeatures(XMPPResourceConnection session); @Override @SuppressWarnings("unchecked") void filter(Packet _packet, XMPPResourceConnection sessionFromSM,
NonAuthUserRepository repo, Queue<Packet> results); } |
@Test public void testRecipientEnabledFor2ResourcesMessage() throws TigaseStringprepException, NotAuthorizedException { String recipient = "recipient-1@localhost"; JID recp1 = JID.jidInstanceNS(recipient + "/res1"); JID recp2 = JID.jidInstanceNS(recipient + "/res2"); JID connId1 = JID.jidInstanceNS("c2s@localhost/recipient1-res1"); JID connId2 = JID.jidInstanceNS("c2s@localhost/recipient1-res2"); XMPPResourceConnection session1 = getSession(connId1, recp1); getSession(connId2, recp2); enableMobileV3(session1, recp1); Packet p = Packet.packetInstance("message", "sender-1@localhost/res1", recp1.toString(), StanzaType.chat); p.setPacketTo(connId1); ArrayDeque<Packet> results = new ArrayDeque<Packet>(); results.offer(p); Packet[] expected = results.toArray(new Packet[0]); mobileV3.filter(p, session1, null, results); Packet[] processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); } | @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } | MobileV3 extends AnnotatedXMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc { @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } } | MobileV3 extends AnnotatedXMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc { @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } } | MobileV3 extends AnnotatedXMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc { @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } @Override void init(Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supStreamFeatures(XMPPResourceConnection session); @Override @SuppressWarnings("unchecked") void filter(Packet _packet, XMPPResourceConnection sessionFromSM,
NonAuthUserRepository repo, Queue<Packet> results); } | MobileV3 extends AnnotatedXMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc { @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } @Override void init(Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supStreamFeatures(XMPPResourceConnection session); @Override @SuppressWarnings("unchecked") void filter(Packet _packet, XMPPResourceConnection sessionFromSM,
NonAuthUserRepository repo, Queue<Packet> results); } |
@Test public void testRecipientDisabledFor2ResourcesPresence() throws TigaseStringprepException, NotAuthorizedException { String recipient = "recipient-1@localhost"; JID recp1 = JID.jidInstanceNS(recipient + "/res1"); JID recp2 = JID.jidInstanceNS(recipient + "/res2"); JID connId1 = JID.jidInstanceNS("c2s@localhost/recipient1-res1"); JID connId2 = JID.jidInstanceNS("c2s@localhost/recipient1-res2"); XMPPResourceConnection session1 = getSession(connId1, recp1); getSession(connId2, recp2); Packet p = Packet.packetInstance("presence", "sender-1@localhost/res1", recp1.toString(), StanzaType.chat); p.setPacketTo(connId1); ArrayDeque<Packet> results = new ArrayDeque<Packet>(); results.offer(p); Packet[] expected = results.toArray(new Packet[0]); mobileV3.filter(p, session1, null, results); Packet[] processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); } | @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } | MobileV3 extends AnnotatedXMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc { @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } } | MobileV3 extends AnnotatedXMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc { @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } } | MobileV3 extends AnnotatedXMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc { @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } @Override void init(Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supStreamFeatures(XMPPResourceConnection session); @Override @SuppressWarnings("unchecked") void filter(Packet _packet, XMPPResourceConnection sessionFromSM,
NonAuthUserRepository repo, Queue<Packet> results); } | MobileV3 extends AnnotatedXMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc { @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } @Override void init(Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supStreamFeatures(XMPPResourceConnection session); @Override @SuppressWarnings("unchecked") void filter(Packet _packet, XMPPResourceConnection sessionFromSM,
NonAuthUserRepository repo, Queue<Packet> results); } |
@Test(expected = IIOException.class) public void testResizeNullImage() throws Exception { cut.resize((BufferedImage) null); } | public byte[] resize(BufferedImage originalImage) throws IOException { if (originalImage == null) { throw new IIOException("Image is null. Did ImageIO fail to decode the image?"); } BufferedImage resized = ImageUtil.resizeImage(originalImage, size, size); originalImage.flush(); byte[] resizedBytes = com.github.dozedoff.similarImage.util.ImageUtil.imageToBytes(resized); resized.flush(); return resizedBytes; } | ImageResizer { public byte[] resize(BufferedImage originalImage) throws IOException { if (originalImage == null) { throw new IIOException("Image is null. Did ImageIO fail to decode the image?"); } BufferedImage resized = ImageUtil.resizeImage(originalImage, size, size); originalImage.flush(); byte[] resizedBytes = com.github.dozedoff.similarImage.util.ImageUtil.imageToBytes(resized); resized.flush(); return resizedBytes; } } | ImageResizer { public byte[] resize(BufferedImage originalImage) throws IOException { if (originalImage == null) { throw new IIOException("Image is null. Did ImageIO fail to decode the image?"); } BufferedImage resized = ImageUtil.resizeImage(originalImage, size, size); originalImage.flush(); byte[] resizedBytes = com.github.dozedoff.similarImage.util.ImageUtil.imageToBytes(resized); resized.flush(); return resizedBytes; } ImageResizer(int size); } | ImageResizer { public byte[] resize(BufferedImage originalImage) throws IOException { if (originalImage == null) { throw new IIOException("Image is null. Did ImageIO fail to decode the image?"); } BufferedImage resized = ImageUtil.resizeImage(originalImage, size, size); originalImage.flush(); byte[] resizedBytes = com.github.dozedoff.similarImage.util.ImageUtil.imageToBytes(resized); resized.flush(); return resizedBytes; } ImageResizer(int size); byte[] resize(BufferedImage originalImage); } | ImageResizer { public byte[] resize(BufferedImage originalImage) throws IOException { if (originalImage == null) { throw new IIOException("Image is null. Did ImageIO fail to decode the image?"); } BufferedImage resized = ImageUtil.resizeImage(originalImage, size, size); originalImage.flush(); byte[] resizedBytes = com.github.dozedoff.similarImage.util.ImageUtil.imageToBytes(resized); resized.flush(); return resizedBytes; } ImageResizer(int size); byte[] resize(BufferedImage originalImage); } |
@Test public void testGetByHashNotFound() throws Exception { assertThat(cut.getByHash(HASH_NEW_RECORD), hasSize(0)); } | @Override public List<ImageRecord> getByHash(long hash) throws RepositoryException { try { return imageDao.queryForMatching(new ImageRecord(null, hash)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getByHash(long hash) throws RepositoryException { try { return imageDao.queryForMatching(new ImageRecord(null, hash)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getByHash(long hash) throws RepositoryException { try { return imageDao.queryForMatching(new ImageRecord(null, hash)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getByHash(long hash) throws RepositoryException { try { return imageDao.queryForMatching(new ImageRecord(null, hash)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getByHash(long hash) throws RepositoryException { try { return imageDao.queryForMatching(new ImageRecord(null, hash)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } |
@Test public void testGetByPathExists() throws Exception { assertThat(cut.getByPath(Paths.get(pathExisting)), is(imageExisting)); } | @Override public ImageRecord getByPath(Path path) throws RepositoryException { try { return imageDao.queryForId(path.toString()); } catch (SQLException e) { throw new RepositoryException("Failed to query for path", e); } } | OrmliteImageRepository implements ImageRepository { @Override public ImageRecord getByPath(Path path) throws RepositoryException { try { return imageDao.queryForId(path.toString()); } catch (SQLException e) { throw new RepositoryException("Failed to query for path", e); } } } | OrmliteImageRepository implements ImageRepository { @Override public ImageRecord getByPath(Path path) throws RepositoryException { try { return imageDao.queryForId(path.toString()); } catch (SQLException e) { throw new RepositoryException("Failed to query for path", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); } | OrmliteImageRepository implements ImageRepository { @Override public ImageRecord getByPath(Path path) throws RepositoryException { try { return imageDao.queryForId(path.toString()); } catch (SQLException e) { throw new RepositoryException("Failed to query for path", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | OrmliteImageRepository implements ImageRepository { @Override public ImageRecord getByPath(Path path) throws RepositoryException { try { return imageDao.queryForId(path.toString()); } catch (SQLException e) { throw new RepositoryException("Failed to query for path", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } |
@Test public void testGetByPathNotFound() throws Exception { assertThat(cut.getByPath(Paths.get(pathNew)), is(nullValue())); } | @Override public ImageRecord getByPath(Path path) throws RepositoryException { try { return imageDao.queryForId(path.toString()); } catch (SQLException e) { throw new RepositoryException("Failed to query for path", e); } } | OrmliteImageRepository implements ImageRepository { @Override public ImageRecord getByPath(Path path) throws RepositoryException { try { return imageDao.queryForId(path.toString()); } catch (SQLException e) { throw new RepositoryException("Failed to query for path", e); } } } | OrmliteImageRepository implements ImageRepository { @Override public ImageRecord getByPath(Path path) throws RepositoryException { try { return imageDao.queryForId(path.toString()); } catch (SQLException e) { throw new RepositoryException("Failed to query for path", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); } | OrmliteImageRepository implements ImageRepository { @Override public ImageRecord getByPath(Path path) throws RepositoryException { try { return imageDao.queryForId(path.toString()); } catch (SQLException e) { throw new RepositoryException("Failed to query for path", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | OrmliteImageRepository implements ImageRepository { @Override public ImageRecord getByPath(Path path) throws RepositoryException { try { return imageDao.queryForId(path.toString()); } catch (SQLException e) { throw new RepositoryException("Failed to query for path", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } |
@Test public void testStartsWithPath() throws Exception { assertThat(cut.startsWithPath(Paths.get("exi")), containsInAnyOrder(imageExisting)); } | @Override public synchronized List<ImageRecord> startsWithPath(Path directory) throws RepositoryException { argStartsWithPath.setValue(directory.toString() + STRING_QUERY_WILDCARD); try { return imageDao.query(queryStartsWithPath); } catch (SQLException e) { throw new RepositoryException("Failed to query for starts with path", e); } } | OrmliteImageRepository implements ImageRepository { @Override public synchronized List<ImageRecord> startsWithPath(Path directory) throws RepositoryException { argStartsWithPath.setValue(directory.toString() + STRING_QUERY_WILDCARD); try { return imageDao.query(queryStartsWithPath); } catch (SQLException e) { throw new RepositoryException("Failed to query for starts with path", e); } } } | OrmliteImageRepository implements ImageRepository { @Override public synchronized List<ImageRecord> startsWithPath(Path directory) throws RepositoryException { argStartsWithPath.setValue(directory.toString() + STRING_QUERY_WILDCARD); try { return imageDao.query(queryStartsWithPath); } catch (SQLException e) { throw new RepositoryException("Failed to query for starts with path", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); } | OrmliteImageRepository implements ImageRepository { @Override public synchronized List<ImageRecord> startsWithPath(Path directory) throws RepositoryException { argStartsWithPath.setValue(directory.toString() + STRING_QUERY_WILDCARD); try { return imageDao.query(queryStartsWithPath); } catch (SQLException e) { throw new RepositoryException("Failed to query for starts with path", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | OrmliteImageRepository implements ImageRepository { @Override public synchronized List<ImageRecord> startsWithPath(Path directory) throws RepositoryException { argStartsWithPath.setValue(directory.toString() + STRING_QUERY_WILDCARD); try { return imageDao.query(queryStartsWithPath); } catch (SQLException e) { throw new RepositoryException("Failed to query for starts with path", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } |
@Test public void testRemoveImageRecord() throws Exception { cut.remove(imageExisting); assertThat(imageDao.queryForMatching(imageExisting), hasSize(0)); } | @Override public void remove(ImageRecord image) throws RepositoryException { try { imageDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove image", e); } } | OrmliteImageRepository implements ImageRepository { @Override public void remove(ImageRecord image) throws RepositoryException { try { imageDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove image", e); } } } | OrmliteImageRepository implements ImageRepository { @Override public void remove(ImageRecord image) throws RepositoryException { try { imageDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove image", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); } | OrmliteImageRepository implements ImageRepository { @Override public void remove(ImageRecord image) throws RepositoryException { try { imageDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove image", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | OrmliteImageRepository implements ImageRepository { @Override public void remove(ImageRecord image) throws RepositoryException { try { imageDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove image", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } |
@Test public void testRemoveImageRecordCollection() throws Exception { imageDao.create(imageNew); List<ImageRecord> toRemove = new LinkedList<ImageRecord>(); toRemove.add(imageExisting); toRemove.add(imageNew); assertThat(imageDao.queryForAll(), hasSize(2)); cut.remove(toRemove); assertThat(imageDao.queryForMatching(imageExisting), hasSize(0)); } | @Override public void remove(ImageRecord image) throws RepositoryException { try { imageDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove image", e); } } | OrmliteImageRepository implements ImageRepository { @Override public void remove(ImageRecord image) throws RepositoryException { try { imageDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove image", e); } } } | OrmliteImageRepository implements ImageRepository { @Override public void remove(ImageRecord image) throws RepositoryException { try { imageDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove image", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); } | OrmliteImageRepository implements ImageRepository { @Override public void remove(ImageRecord image) throws RepositoryException { try { imageDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove image", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | OrmliteImageRepository implements ImageRepository { @Override public void remove(ImageRecord image) throws RepositoryException { try { imageDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove image", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } |
@Test public void testGetAll() throws Exception { imageDao.create(imageNew); assertThat(cut.getAll(), containsInAnyOrder(imageExisting, imageNew)); } | @Override public List<ImageRecord> getAll() throws RepositoryException { try { return imageDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query all", e); } } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAll() throws RepositoryException { try { return imageDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query all", e); } } } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAll() throws RepositoryException { try { return imageDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query all", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAll() throws RepositoryException { try { return imageDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query all", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAll() throws RepositoryException { try { return imageDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query all", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } |
@Test public void testGetAllWithoutIgnored() throws Exception { imageDao.create(imageNew); List<ImageRecord> result = cut.getAllWithoutIgnored(); assertThat(result, hasItem(imageNew)); assertThat(result, hasSize(1)); } | @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } |
@Test public void testGetAllWithoutIgnoredPath() throws Exception { imageDao.create(imageNew); List<ImageRecord> result = cut.getAllWithoutIgnored(Paths.get(pathNew)); assertThat(result, hasItem(imageNew)); assertThat(result, hasSize(1)); } | @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } |
@Test public void testGetAllWithoutIgnoredPathNoMatch() throws Exception { imageDao.create(imageNew); List<ImageRecord> result = cut.getAllWithoutIgnored(Paths.get(pathExisting)); assertThat(result, is(empty())); } | @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } |
@Test public void testSetExtendedAttributePathStringString() throws Exception { ExtendedAttribute.setExtendedAttribute(tempFile, TEST_NAME, TEST_VALUE); } | public static void setExtendedAttribute(Path path, String name, String value) throws IOException { setExtendedAttribute(path, name, StandardCharsets.US_ASCII.encode(value)); } | ExtendedAttribute implements ExtendedAttributeQuery { public static void setExtendedAttribute(Path path, String name, String value) throws IOException { setExtendedAttribute(path, name, StandardCharsets.US_ASCII.encode(value)); } } | ExtendedAttribute implements ExtendedAttributeQuery { public static void setExtendedAttribute(Path path, String name, String value) throws IOException { setExtendedAttribute(path, name, StandardCharsets.US_ASCII.encode(value)); } } | ExtendedAttribute implements ExtendedAttributeQuery { public static void setExtendedAttribute(Path path, String name, String value) throws IOException { setExtendedAttribute(path, name, StandardCharsets.US_ASCII.encode(value)); } static String createName(String... names); static boolean supportsExtendedAttributes(Path path); static void deleteExtendedAttribute(Path path, String name); static void setExtendedAttribute(Path path, String name, String value); static void setExtendedAttribute(Path path, String name, ByteBuffer value); static ByteBuffer readExtendedAttribute(Path path, String name); static String readExtendedAttributeAsString(Path path, String name); static boolean isExtendedAttributeSet(Path path, String name); @Override boolean isEaSupported(Path path); } | ExtendedAttribute implements ExtendedAttributeQuery { public static void setExtendedAttribute(Path path, String name, String value) throws IOException { setExtendedAttribute(path, name, StandardCharsets.US_ASCII.encode(value)); } static String createName(String... names); static boolean supportsExtendedAttributes(Path path); static void deleteExtendedAttribute(Path path, String name); static void setExtendedAttribute(Path path, String name, String value); static void setExtendedAttribute(Path path, String name, ByteBuffer value); static ByteBuffer readExtendedAttribute(Path path, String name); static String readExtendedAttributeAsString(Path path, String name); static boolean isExtendedAttributeSet(Path path, String name); @Override boolean isEaSupported(Path path); static final String SIMILARIMAGE_NAMESPACE; } |
@Test public void testGetByName() throws Exception { Tag result = cut.getByName(TAG_EXSTING); assertThat(result, is(tagExsting)); } | @Override public synchronized Tag getByName(String name) throws RepositoryException { try { nameArg.setValue(name); return tagDao.queryForFirst(nameQuery); } catch (SQLException e) { throw new RepositoryException("Failed to query by name", e); } } | OrmliteTagRepository implements TagRepository { @Override public synchronized Tag getByName(String name) throws RepositoryException { try { nameArg.setValue(name); return tagDao.queryForFirst(nameQuery); } catch (SQLException e) { throw new RepositoryException("Failed to query by name", e); } } } | OrmliteTagRepository implements TagRepository { @Override public synchronized Tag getByName(String name) throws RepositoryException { try { nameArg.setValue(name); return tagDao.queryForFirst(nameQuery); } catch (SQLException e) { throw new RepositoryException("Failed to query by name", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); } | OrmliteTagRepository implements TagRepository { @Override public synchronized Tag getByName(String name) throws RepositoryException { try { nameArg.setValue(name); return tagDao.queryForFirst(nameQuery); } catch (SQLException e) { throw new RepositoryException("Failed to query by name", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } | OrmliteTagRepository implements TagRepository { @Override public synchronized Tag getByName(String name) throws RepositoryException { try { nameArg.setValue(name); return tagDao.queryForFirst(nameQuery); } catch (SQLException e) { throw new RepositoryException("Failed to query by name", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } |
@Test public void testStore() throws Exception { cut.store(tagNew); Tag result = cut.getByName(TAG_NEW); assertThat(result, is(tagNew)); } | @Override public void store(Tag tag) throws RepositoryException { try { tagDao.createOrUpdate(tag); } catch (SQLException e) { throw new RepositoryException("Failed to store", e); } } | OrmliteTagRepository implements TagRepository { @Override public void store(Tag tag) throws RepositoryException { try { tagDao.createOrUpdate(tag); } catch (SQLException e) { throw new RepositoryException("Failed to store", e); } } } | OrmliteTagRepository implements TagRepository { @Override public void store(Tag tag) throws RepositoryException { try { tagDao.createOrUpdate(tag); } catch (SQLException e) { throw new RepositoryException("Failed to store", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); } | OrmliteTagRepository implements TagRepository { @Override public void store(Tag tag) throws RepositoryException { try { tagDao.createOrUpdate(tag); } catch (SQLException e) { throw new RepositoryException("Failed to store", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } | OrmliteTagRepository implements TagRepository { @Override public void store(Tag tag) throws RepositoryException { try { tagDao.createOrUpdate(tag); } catch (SQLException e) { throw new RepositoryException("Failed to store", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } |
@Test(expected = RepositoryException.class) public void testStoreDuplicate() throws Exception { cut.store(tagNew); cut.store(new Tag(TAG_NEW)); } | @Override public void store(Tag tag) throws RepositoryException { try { tagDao.createOrUpdate(tag); } catch (SQLException e) { throw new RepositoryException("Failed to store", e); } } | OrmliteTagRepository implements TagRepository { @Override public void store(Tag tag) throws RepositoryException { try { tagDao.createOrUpdate(tag); } catch (SQLException e) { throw new RepositoryException("Failed to store", e); } } } | OrmliteTagRepository implements TagRepository { @Override public void store(Tag tag) throws RepositoryException { try { tagDao.createOrUpdate(tag); } catch (SQLException e) { throw new RepositoryException("Failed to store", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); } | OrmliteTagRepository implements TagRepository { @Override public void store(Tag tag) throws RepositoryException { try { tagDao.createOrUpdate(tag); } catch (SQLException e) { throw new RepositoryException("Failed to store", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } | OrmliteTagRepository implements TagRepository { @Override public void store(Tag tag) throws RepositoryException { try { tagDao.createOrUpdate(tag); } catch (SQLException e) { throw new RepositoryException("Failed to store", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } |
@Test public void testRemove() throws Exception { cut.remove(tagExsting); Tag result = cut.getByName(TAG_EXSTING); assertThat(result, is(nullValue())); } | @Override public void remove(Tag tag) throws RepositoryException { try { tagDao.delete(tag); } catch (SQLException e) { throw new RepositoryException("Failed to delete", e); } } | OrmliteTagRepository implements TagRepository { @Override public void remove(Tag tag) throws RepositoryException { try { tagDao.delete(tag); } catch (SQLException e) { throw new RepositoryException("Failed to delete", e); } } } | OrmliteTagRepository implements TagRepository { @Override public void remove(Tag tag) throws RepositoryException { try { tagDao.delete(tag); } catch (SQLException e) { throw new RepositoryException("Failed to delete", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); } | OrmliteTagRepository implements TagRepository { @Override public void remove(Tag tag) throws RepositoryException { try { tagDao.delete(tag); } catch (SQLException e) { throw new RepositoryException("Failed to delete", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } | OrmliteTagRepository implements TagRepository { @Override public void remove(Tag tag) throws RepositoryException { try { tagDao.delete(tag); } catch (SQLException e) { throw new RepositoryException("Failed to delete", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } |
@Test public void testGetAll() throws Exception { List<Tag> results = cut.getAll(); assertThat(results, containsInAnyOrder(tagContext, tagExsting)); } | @Override public List<Tag> getAll() throws RepositoryException { try { return tagDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query all", e); } } | OrmliteTagRepository implements TagRepository { @Override public List<Tag> getAll() throws RepositoryException { try { return tagDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query all", e); } } } | OrmliteTagRepository implements TagRepository { @Override public List<Tag> getAll() throws RepositoryException { try { return tagDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query all", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); } | OrmliteTagRepository implements TagRepository { @Override public List<Tag> getAll() throws RepositoryException { try { return tagDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query all", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } | OrmliteTagRepository implements TagRepository { @Override public List<Tag> getAll() throws RepositoryException { try { return tagDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query all", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } |
@Test public void testGetWithContext() throws Exception { List<Tag> results = cut.getWithContext(); assertThat(results, containsInAnyOrder(tagContext)); } | @Override public List<Tag> getWithContext() throws RepositoryException { try { return tagDao.queryForMatching(new Tag(null, true)); } catch (SQLException e) { throw new RepositoryException("Failed to query by context flag", e); } } | OrmliteTagRepository implements TagRepository { @Override public List<Tag> getWithContext() throws RepositoryException { try { return tagDao.queryForMatching(new Tag(null, true)); } catch (SQLException e) { throw new RepositoryException("Failed to query by context flag", e); } } } | OrmliteTagRepository implements TagRepository { @Override public List<Tag> getWithContext() throws RepositoryException { try { return tagDao.queryForMatching(new Tag(null, true)); } catch (SQLException e) { throw new RepositoryException("Failed to query by context flag", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); } | OrmliteTagRepository implements TagRepository { @Override public List<Tag> getWithContext() throws RepositoryException { try { return tagDao.queryForMatching(new Tag(null, true)); } catch (SQLException e) { throw new RepositoryException("Failed to query by context flag", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } | OrmliteTagRepository implements TagRepository { @Override public List<Tag> getWithContext() throws RepositoryException { try { return tagDao.queryForMatching(new Tag(null, true)); } catch (SQLException e) { throw new RepositoryException("Failed to query by context flag", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } |
@Test public void testGetByHash() throws Exception { List<FilterRecord> filters = cut.getByHash(HASH_TWO); assertThat(filters, containsInAnyOrder(new FilterRecord(HASH_TWO, TAG_TWO, null))); } | @Override public List<FilterRecord> getByHash(long hash) throws RepositoryException { try { return filterDao.queryForMatching(new FilterRecord(hash, null, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByHash(long hash) throws RepositoryException { try { return filterDao.queryForMatching(new FilterRecord(hash, null, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByHash(long hash) throws RepositoryException { try { return filterDao.queryForMatching(new FilterRecord(hash, null, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByHash(long hash) throws RepositoryException { try { return filterDao.queryForMatching(new FilterRecord(hash, null, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByHash(long hash) throws RepositoryException { try { return filterDao.queryForMatching(new FilterRecord(hash, null, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } |
@Test(expected = RepositoryException.class) public void testGetByHashException() throws Exception { deleteFilterTable(); cut.getByHash(HASH_TWO); } | @Override public List<FilterRecord> getByHash(long hash) throws RepositoryException { try { return filterDao.queryForMatching(new FilterRecord(hash, null, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByHash(long hash) throws RepositoryException { try { return filterDao.queryForMatching(new FilterRecord(hash, null, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByHash(long hash) throws RepositoryException { try { return filterDao.queryForMatching(new FilterRecord(hash, null, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByHash(long hash) throws RepositoryException { try { return filterDao.queryForMatching(new FilterRecord(hash, null, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByHash(long hash) throws RepositoryException { try { return filterDao.queryForMatching(new FilterRecord(hash, null, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } |
@Test public void testGetByTag() throws Exception { List<FilterRecord> filters = cut.getByTag(TAG_ONE); assertThat(filters, containsInAnyOrder(new FilterRecord(HASH_ONE, TAG_ONE, null))); } | @Override public List<FilterRecord> getByTag(Tag tag) throws RepositoryException { try { return filterDao.queryForMatchingArgs(new FilterRecord(0, tag, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by tag", e); } } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByTag(Tag tag) throws RepositoryException { try { return filterDao.queryForMatchingArgs(new FilterRecord(0, tag, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by tag", e); } } } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByTag(Tag tag) throws RepositoryException { try { return filterDao.queryForMatchingArgs(new FilterRecord(0, tag, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by tag", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByTag(Tag tag) throws RepositoryException { try { return filterDao.queryForMatchingArgs(new FilterRecord(0, tag, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by tag", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByTag(Tag tag) throws RepositoryException { try { return filterDao.queryForMatchingArgs(new FilterRecord(0, tag, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by tag", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } |
@Test(expected = RepositoryException.class) public void testGetByTagException() throws Exception { deleteFilterTable(); cut.getByTag(TAG_ONE); } | @Override public List<FilterRecord> getByTag(Tag tag) throws RepositoryException { try { return filterDao.queryForMatchingArgs(new FilterRecord(0, tag, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by tag", e); } } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByTag(Tag tag) throws RepositoryException { try { return filterDao.queryForMatchingArgs(new FilterRecord(0, tag, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by tag", e); } } } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByTag(Tag tag) throws RepositoryException { try { return filterDao.queryForMatchingArgs(new FilterRecord(0, tag, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by tag", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByTag(Tag tag) throws RepositoryException { try { return filterDao.queryForMatchingArgs(new FilterRecord(0, tag, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by tag", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByTag(Tag tag) throws RepositoryException { try { return filterDao.queryForMatchingArgs(new FilterRecord(0, tag, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by tag", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } |
@Test public void testReadExtendedAttributeAsString() throws Exception { ExtendedAttribute.setExtendedAttribute(tempFile, TEST_NAME, TEST_VALUE); assertThat(ExtendedAttribute.readExtendedAttributeAsString(tempFile, TEST_NAME), is(TEST_VALUE)); } | public static String readExtendedAttributeAsString(Path path, String name) throws IOException { ByteBuffer buffer = readExtendedAttribute(path, name); return StandardCharsets.US_ASCII.decode(buffer).toString(); } | ExtendedAttribute implements ExtendedAttributeQuery { public static String readExtendedAttributeAsString(Path path, String name) throws IOException { ByteBuffer buffer = readExtendedAttribute(path, name); return StandardCharsets.US_ASCII.decode(buffer).toString(); } } | ExtendedAttribute implements ExtendedAttributeQuery { public static String readExtendedAttributeAsString(Path path, String name) throws IOException { ByteBuffer buffer = readExtendedAttribute(path, name); return StandardCharsets.US_ASCII.decode(buffer).toString(); } } | ExtendedAttribute implements ExtendedAttributeQuery { public static String readExtendedAttributeAsString(Path path, String name) throws IOException { ByteBuffer buffer = readExtendedAttribute(path, name); return StandardCharsets.US_ASCII.decode(buffer).toString(); } static String createName(String... names); static boolean supportsExtendedAttributes(Path path); static void deleteExtendedAttribute(Path path, String name); static void setExtendedAttribute(Path path, String name, String value); static void setExtendedAttribute(Path path, String name, ByteBuffer value); static ByteBuffer readExtendedAttribute(Path path, String name); static String readExtendedAttributeAsString(Path path, String name); static boolean isExtendedAttributeSet(Path path, String name); @Override boolean isEaSupported(Path path); } | ExtendedAttribute implements ExtendedAttributeQuery { public static String readExtendedAttributeAsString(Path path, String name) throws IOException { ByteBuffer buffer = readExtendedAttribute(path, name); return StandardCharsets.US_ASCII.decode(buffer).toString(); } static String createName(String... names); static boolean supportsExtendedAttributes(Path path); static void deleteExtendedAttribute(Path path, String name); static void setExtendedAttribute(Path path, String name, String value); static void setExtendedAttribute(Path path, String name, ByteBuffer value); static ByteBuffer readExtendedAttribute(Path path, String name); static String readExtendedAttributeAsString(Path path, String name); static boolean isExtendedAttributeSet(Path path, String name); @Override boolean isEaSupported(Path path); static final String SIMILARIMAGE_NAMESPACE; } |
@Test public void testGetAll() throws Exception { List<FilterRecord> filters = cut.getAll(); assertThat(filters, containsInAnyOrder(allFilters.toArray(new FilterRecord[0]))); } | @Override public List<FilterRecord> getAll() throws RepositoryException { try { return filterDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to get all filters", e); } } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getAll() throws RepositoryException { try { return filterDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to get all filters", e); } } } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getAll() throws RepositoryException { try { return filterDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to get all filters", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getAll() throws RepositoryException { try { return filterDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to get all filters", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getAll() throws RepositoryException { try { return filterDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to get all filters", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } |
@Test(expected = RepositoryException.class) public void testGetAllException() throws Exception { deleteFilterTable(); cut.getAll(); } | @Override public List<FilterRecord> getAll() throws RepositoryException { try { return filterDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to get all filters", e); } } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getAll() throws RepositoryException { try { return filterDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to get all filters", e); } } } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getAll() throws RepositoryException { try { return filterDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to get all filters", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getAll() throws RepositoryException { try { return filterDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to get all filters", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } | OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getAll() throws RepositoryException { try { return filterDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to get all filters", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } |
@Test(expected = RepositoryException.class) public void testStoreThumbnailException() throws Exception { TableUtils.dropTable(cs, Thumbnail.class, false); cut.store(new FilterRecord(HASH_NEW_THUMBNAIL, TAG_ONE, newThumbnail)); } | @Override public void store(FilterRecord toStore) throws RepositoryException { if (toStore.hasThumbnail()) { checkAndCreateThumbnail(toStore); } try { if (filterDao.queryForMatchingArgs(toStore).isEmpty()) { filterDao.create(toStore); } } catch (SQLException e) { throw new RepositoryException(STORE_FILTER_ERROR_MSG, e); } } | OrmliteFilterRepository implements FilterRepository { @Override public void store(FilterRecord toStore) throws RepositoryException { if (toStore.hasThumbnail()) { checkAndCreateThumbnail(toStore); } try { if (filterDao.queryForMatchingArgs(toStore).isEmpty()) { filterDao.create(toStore); } } catch (SQLException e) { throw new RepositoryException(STORE_FILTER_ERROR_MSG, e); } } } | OrmliteFilterRepository implements FilterRepository { @Override public void store(FilterRecord toStore) throws RepositoryException { if (toStore.hasThumbnail()) { checkAndCreateThumbnail(toStore); } try { if (filterDao.queryForMatchingArgs(toStore).isEmpty()) { filterDao.create(toStore); } } catch (SQLException e) { throw new RepositoryException(STORE_FILTER_ERROR_MSG, e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); } | OrmliteFilterRepository implements FilterRepository { @Override public void store(FilterRecord toStore) throws RepositoryException { if (toStore.hasThumbnail()) { checkAndCreateThumbnail(toStore); } try { if (filterDao.queryForMatchingArgs(toStore).isEmpty()) { filterDao.create(toStore); } } catch (SQLException e) { throw new RepositoryException(STORE_FILTER_ERROR_MSG, e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } | OrmliteFilterRepository implements FilterRepository { @Override public void store(FilterRecord toStore) throws RepositoryException { if (toStore.hasThumbnail()) { checkAndCreateThumbnail(toStore); } try { if (filterDao.queryForMatchingArgs(toStore).isEmpty()) { filterDao.create(toStore); } } catch (SQLException e) { throw new RepositoryException(STORE_FILTER_ERROR_MSG, e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } |
@Test(expected = RepositoryException.class) public void testStoreFilterException() throws Exception { TableUtils.dropTable(cs, FilterRecord.class, false); cut.store(new FilterRecord(HASH_NEW_THUMBNAIL, TAG_ONE, null)); } | @Override public void store(FilterRecord toStore) throws RepositoryException { if (toStore.hasThumbnail()) { checkAndCreateThumbnail(toStore); } try { if (filterDao.queryForMatchingArgs(toStore).isEmpty()) { filterDao.create(toStore); } } catch (SQLException e) { throw new RepositoryException(STORE_FILTER_ERROR_MSG, e); } } | OrmliteFilterRepository implements FilterRepository { @Override public void store(FilterRecord toStore) throws RepositoryException { if (toStore.hasThumbnail()) { checkAndCreateThumbnail(toStore); } try { if (filterDao.queryForMatchingArgs(toStore).isEmpty()) { filterDao.create(toStore); } } catch (SQLException e) { throw new RepositoryException(STORE_FILTER_ERROR_MSG, e); } } } | OrmliteFilterRepository implements FilterRepository { @Override public void store(FilterRecord toStore) throws RepositoryException { if (toStore.hasThumbnail()) { checkAndCreateThumbnail(toStore); } try { if (filterDao.queryForMatchingArgs(toStore).isEmpty()) { filterDao.create(toStore); } } catch (SQLException e) { throw new RepositoryException(STORE_FILTER_ERROR_MSG, e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); } | OrmliteFilterRepository implements FilterRepository { @Override public void store(FilterRecord toStore) throws RepositoryException { if (toStore.hasThumbnail()) { checkAndCreateThumbnail(toStore); } try { if (filterDao.queryForMatchingArgs(toStore).isEmpty()) { filterDao.create(toStore); } } catch (SQLException e) { throw new RepositoryException(STORE_FILTER_ERROR_MSG, e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } | OrmliteFilterRepository implements FilterRepository { @Override public void store(FilterRecord toStore) throws RepositoryException { if (toStore.hasThumbnail()) { checkAndCreateThumbnail(toStore); } try { if (filterDao.queryForMatchingArgs(toStore).isEmpty()) { filterDao.create(toStore); } } catch (SQLException e) { throw new RepositoryException(STORE_FILTER_ERROR_MSG, e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } |
@Test public void testRemove() throws Exception { FilterRecord toRemove = allFilters.get(0); cut.remove(toRemove); assertThat(cut.getAll(), not(hasItem(toRemove))); } | @Override public void remove(FilterRecord filter) throws RepositoryException { try { filterDao.delete(filter); } catch (SQLException e) { throw new RepositoryException("Failed to remove Filter", e); } } | OrmliteFilterRepository implements FilterRepository { @Override public void remove(FilterRecord filter) throws RepositoryException { try { filterDao.delete(filter); } catch (SQLException e) { throw new RepositoryException("Failed to remove Filter", e); } } } | OrmliteFilterRepository implements FilterRepository { @Override public void remove(FilterRecord filter) throws RepositoryException { try { filterDao.delete(filter); } catch (SQLException e) { throw new RepositoryException("Failed to remove Filter", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); } | OrmliteFilterRepository implements FilterRepository { @Override public void remove(FilterRecord filter) throws RepositoryException { try { filterDao.delete(filter); } catch (SQLException e) { throw new RepositoryException("Failed to remove Filter", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } | OrmliteFilterRepository implements FilterRepository { @Override public void remove(FilterRecord filter) throws RepositoryException { try { filterDao.delete(filter); } catch (SQLException e) { throw new RepositoryException("Failed to remove Filter", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } |
@Test public void testStoreNew() throws Exception { cut.store(newIgnore); assertThat(dao.queryForAll(), hasItem(newIgnore)); } | @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } |
@Test public void testStoreDuplicate() throws Exception { cut.store(existingIgnore); assertThat(dao.queryForAll(), hasSize(1)); } | @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } |
@Test public void testStoreNewSize() throws Exception { cut.store(newIgnore); assertThat(dao.queryForAll(), hasSize(2)); } | @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } |
@Test public void testRemove() throws Exception { cut.remove(existingIgnore); assertThat(dao.queryForAll(), not(hasItem(existingIgnore))); } | @Override public void remove(IgnoreRecord toRemove) throws RepositoryException { try { ignoreDao.delete(toRemove); } catch (SQLException e) { throw new RepositoryException("Failed to delete ignore", e); } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void remove(IgnoreRecord toRemove) throws RepositoryException { try { ignoreDao.delete(toRemove); } catch (SQLException e) { throw new RepositoryException("Failed to delete ignore", e); } } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void remove(IgnoreRecord toRemove) throws RepositoryException { try { ignoreDao.delete(toRemove); } catch (SQLException e) { throw new RepositoryException("Failed to delete ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void remove(IgnoreRecord toRemove) throws RepositoryException { try { ignoreDao.delete(toRemove); } catch (SQLException e) { throw new RepositoryException("Failed to delete ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void remove(IgnoreRecord toRemove) throws RepositoryException { try { ignoreDao.delete(toRemove); } catch (SQLException e) { throw new RepositoryException("Failed to delete ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } |
@Test public void testRemoveSize() throws Exception { cut.remove(existingIgnore); assertThat(dao.queryForAll(), is(empty())); } | @Override public void remove(IgnoreRecord toRemove) throws RepositoryException { try { ignoreDao.delete(toRemove); } catch (SQLException e) { throw new RepositoryException("Failed to delete ignore", e); } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void remove(IgnoreRecord toRemove) throws RepositoryException { try { ignoreDao.delete(toRemove); } catch (SQLException e) { throw new RepositoryException("Failed to delete ignore", e); } } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void remove(IgnoreRecord toRemove) throws RepositoryException { try { ignoreDao.delete(toRemove); } catch (SQLException e) { throw new RepositoryException("Failed to delete ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void remove(IgnoreRecord toRemove) throws RepositoryException { try { ignoreDao.delete(toRemove); } catch (SQLException e) { throw new RepositoryException("Failed to delete ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public void remove(IgnoreRecord toRemove) throws RepositoryException { try { ignoreDao.delete(toRemove); } catch (SQLException e) { throw new RepositoryException("Failed to delete ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } |
@Test public void testExtendedAttributeIsNotSet() throws Exception { assertThat(ExtendedAttribute.isExtendedAttributeSet(tempFile, TEST_NAME), is(false)); } | public static boolean isExtendedAttributeSet(Path path, String name) throws IOException { return createUserDefinedFileAttributeView(path).list().contains(name); } | ExtendedAttribute implements ExtendedAttributeQuery { public static boolean isExtendedAttributeSet(Path path, String name) throws IOException { return createUserDefinedFileAttributeView(path).list().contains(name); } } | ExtendedAttribute implements ExtendedAttributeQuery { public static boolean isExtendedAttributeSet(Path path, String name) throws IOException { return createUserDefinedFileAttributeView(path).list().contains(name); } } | ExtendedAttribute implements ExtendedAttributeQuery { public static boolean isExtendedAttributeSet(Path path, String name) throws IOException { return createUserDefinedFileAttributeView(path).list().contains(name); } static String createName(String... names); static boolean supportsExtendedAttributes(Path path); static void deleteExtendedAttribute(Path path, String name); static void setExtendedAttribute(Path path, String name, String value); static void setExtendedAttribute(Path path, String name, ByteBuffer value); static ByteBuffer readExtendedAttribute(Path path, String name); static String readExtendedAttributeAsString(Path path, String name); static boolean isExtendedAttributeSet(Path path, String name); @Override boolean isEaSupported(Path path); } | ExtendedAttribute implements ExtendedAttributeQuery { public static boolean isExtendedAttributeSet(Path path, String name) throws IOException { return createUserDefinedFileAttributeView(path).list().contains(name); } static String createName(String... names); static boolean supportsExtendedAttributes(Path path); static void deleteExtendedAttribute(Path path, String name); static void setExtendedAttribute(Path path, String name, String value); static void setExtendedAttribute(Path path, String name, ByteBuffer value); static ByteBuffer readExtendedAttribute(Path path, String name); static String readExtendedAttributeAsString(Path path, String name); static boolean isExtendedAttributeSet(Path path, String name); @Override boolean isEaSupported(Path path); static final String SIMILARIMAGE_NAMESPACE; } |
@Test public void testFindByPathPath() throws Exception { assertThat(cut.findByPath(toPath(PATH_A)), is(existingIgnore)); } | @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } |
@Test public void testFindByPathPathNotFound() throws Exception { assertThat(cut.findByPath(toPath(PATH_B)), is(nullValue())); } | @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } |
@Test public void testFindByPathString() throws Exception { assertThat(cut.findByPath(PATH_A), is(existingIgnore)); } | @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } |
@Test public void testFindByPathStringNotFound() throws Exception { assertThat(cut.isPathIgnored(PATH_B), is(false)); } | @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } |
@Test public void testIsPathIgnoredString() throws Exception { assertThat(cut.isPathIgnored(PATH_A), is(true)); } | @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } |
@Test public void testIsPathIgnoredStringNope() throws Exception { assertThat(cut.isPathIgnored(PATH_B), is(false)); } | @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } |
@Test public void testIsPathIgnoredPath() throws Exception { assertThat(cut.isPathIgnored(toPath(PATH_A)), is(true)); } | @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } |
@Test public void testGetAll() throws Exception { dao.create(newIgnore); assertThat(cut.getAll(), containsInAnyOrder(newIgnore, existingIgnore)); } | @Override public List<IgnoreRecord> getAll() throws RepositoryException { try { return ignoreDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query for all ingored images: " + e.toString(), e); } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public List<IgnoreRecord> getAll() throws RepositoryException { try { return ignoreDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query for all ingored images: " + e.toString(), e); } } } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public List<IgnoreRecord> getAll() throws RepositoryException { try { return ignoreDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query for all ingored images: " + e.toString(), e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public List<IgnoreRecord> getAll() throws RepositoryException { try { return ignoreDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query for all ingored images: " + e.toString(), e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | OrmliteIgnoreRepository implements IgnoreRepository { @Override public List<IgnoreRecord> getAll() throws RepositoryException { try { return ignoreDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query for all ingored images: " + e.toString(), e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } |
@Test public void testEquals() throws Exception { EqualsVerifier.forClass(Tag.class).withIgnoredFields("userTagId") .suppress(Warning.NONFINAL_FIELDS).verify();; } | @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Tag)) { return false; } Tag other = (Tag) obj; if (contextMenu != other.contextMenu) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } return true; } | Tag { @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Tag)) { return false; } Tag other = (Tag) obj; if (contextMenu != other.contextMenu) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } return true; } } | Tag { @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Tag)) { return false; } Tag other = (Tag) obj; if (contextMenu != other.contextMenu) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } return true; } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); } | Tag { @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Tag)) { return false; } Tag other = (Tag) obj; if (contextMenu != other.contextMenu) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } return true; } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); } | Tag { @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Tag)) { return false; } Tag other = (Tag) obj; if (contextMenu != other.contextMenu) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } return true; } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); static final String NAME_FIELD_NAME; } |
@Test public void testTagStringName() throws Exception { assertThat(cut.getTag(), is(TEST_TAG)); } | public final String getTag() { return tag; } | Tag { public final String getTag() { return tag; } } | Tag { public final String getTag() { return tag; } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); } | Tag { public final String getTag() { return tag; } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); } | Tag { public final String getTag() { return tag; } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); static final String NAME_FIELD_NAME; } |
@Test public void testCreateName() throws Exception { assertThat(ExtendedAttribute.createName("foo", "bar"), is(ExtendedAttribute.SIMILARIMAGE_NAMESPACE + ".foo.bar")); } | public static String createName(String... names) { StringBuilder sb = new StringBuilder(SIMILARIMAGE_NAMESPACE); for (String name : names) { sb.append("."); sb.append(name); } return sb.toString(); } | ExtendedAttribute implements ExtendedAttributeQuery { public static String createName(String... names) { StringBuilder sb = new StringBuilder(SIMILARIMAGE_NAMESPACE); for (String name : names) { sb.append("."); sb.append(name); } return sb.toString(); } } | ExtendedAttribute implements ExtendedAttributeQuery { public static String createName(String... names) { StringBuilder sb = new StringBuilder(SIMILARIMAGE_NAMESPACE); for (String name : names) { sb.append("."); sb.append(name); } return sb.toString(); } } | ExtendedAttribute implements ExtendedAttributeQuery { public static String createName(String... names) { StringBuilder sb = new StringBuilder(SIMILARIMAGE_NAMESPACE); for (String name : names) { sb.append("."); sb.append(name); } return sb.toString(); } static String createName(String... names); static boolean supportsExtendedAttributes(Path path); static void deleteExtendedAttribute(Path path, String name); static void setExtendedAttribute(Path path, String name, String value); static void setExtendedAttribute(Path path, String name, ByteBuffer value); static ByteBuffer readExtendedAttribute(Path path, String name); static String readExtendedAttributeAsString(Path path, String name); static boolean isExtendedAttributeSet(Path path, String name); @Override boolean isEaSupported(Path path); } | ExtendedAttribute implements ExtendedAttributeQuery { public static String createName(String... names) { StringBuilder sb = new StringBuilder(SIMILARIMAGE_NAMESPACE); for (String name : names) { sb.append("."); sb.append(name); } return sb.toString(); } static String createName(String... names); static boolean supportsExtendedAttributes(Path path); static void deleteExtendedAttribute(Path path, String name); static void setExtendedAttribute(Path path, String name, String value); static void setExtendedAttribute(Path path, String name, ByteBuffer value); static ByteBuffer readExtendedAttribute(Path path, String name); static String readExtendedAttributeAsString(Path path, String name); static boolean isExtendedAttributeSet(Path path, String name); @Override boolean isEaSupported(Path path); static final String SIMILARIMAGE_NAMESPACE; } |
@Test public void testTagStringContextMenu() throws Exception { assertThat(cut.isContextMenu(), is(false)); } | public final boolean isContextMenu() { return contextMenu; } | Tag { public final boolean isContextMenu() { return contextMenu; } } | Tag { public final boolean isContextMenu() { return contextMenu; } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); } | Tag { public final boolean isContextMenu() { return contextMenu; } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); } | Tag { public final boolean isContextMenu() { return contextMenu; } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); static final String NAME_FIELD_NAME; } |
@Test public void testIsMatchAll() throws Exception { assertThat(cut.isMatchAll(), is(false)); } | public boolean isMatchAll() { return StringUtil.MATCH_ALL_TAGS.equals(tag); } | Tag { public boolean isMatchAll() { return StringUtil.MATCH_ALL_TAGS.equals(tag); } } | Tag { public boolean isMatchAll() { return StringUtil.MATCH_ALL_TAGS.equals(tag); } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); } | Tag { public boolean isMatchAll() { return StringUtil.MATCH_ALL_TAGS.equals(tag); } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); } | Tag { public boolean isMatchAll() { return StringUtil.MATCH_ALL_TAGS.equals(tag); } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); static final String NAME_FIELD_NAME; } |
@Test public void testIsMatchAllAsterisk() throws Exception { cut = new Tag(StringUtil.MATCH_ALL_TAGS); assertThat(cut.isMatchAll(), is(true)); } | public boolean isMatchAll() { return StringUtil.MATCH_ALL_TAGS.equals(tag); } | Tag { public boolean isMatchAll() { return StringUtil.MATCH_ALL_TAGS.equals(tag); } } | Tag { public boolean isMatchAll() { return StringUtil.MATCH_ALL_TAGS.equals(tag); } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); } | Tag { public boolean isMatchAll() { return StringUtil.MATCH_ALL_TAGS.equals(tag); } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); } | Tag { public boolean isMatchAll() { return StringUtil.MATCH_ALL_TAGS.equals(tag); } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); static final String NAME_FIELD_NAME; } |
@Test public void testGetCs() throws Exception { assertThat(cut.getCs().isOpen(EMPTY_STRING), is(true)); } | @Override public ConnectionSource getCs() { return connectionSource; } | SQLiteDatabase implements Database { @Override public ConnectionSource getCs() { return connectionSource; } } | SQLiteDatabase implements Database { @Override public ConnectionSource getCs() { return connectionSource; } SQLiteDatabase(); SQLiteDatabase(Path dbPath); SQLiteDatabase(String dbPath); } | SQLiteDatabase implements Database { @Override public ConnectionSource getCs() { return connectionSource; } SQLiteDatabase(); SQLiteDatabase(Path dbPath); SQLiteDatabase(String dbPath); @Override ConnectionSource getCs(); @Override void close(); } | SQLiteDatabase implements Database { @Override public ConnectionSource getCs() { return connectionSource; } SQLiteDatabase(); SQLiteDatabase(Path dbPath); SQLiteDatabase(String dbPath); @Override ConnectionSource getCs(); @Override void close(); } |
@Ignore("Closing a closed connection when using pooled connections results in NPE") @Test public void testClose() throws Exception { ConnectionSource cs = cut.getCs(); assertThat(cs.isOpen(EMPTY_STRING), is(true)); cut.close(); assertThat(cs.isOpen(EMPTY_STRING), is(false)); } | @Override public void close() { connectionSource.closeQuietly(); } | SQLiteDatabase implements Database { @Override public void close() { connectionSource.closeQuietly(); } } | SQLiteDatabase implements Database { @Override public void close() { connectionSource.closeQuietly(); } SQLiteDatabase(); SQLiteDatabase(Path dbPath); SQLiteDatabase(String dbPath); } | SQLiteDatabase implements Database { @Override public void close() { connectionSource.closeQuietly(); } SQLiteDatabase(); SQLiteDatabase(Path dbPath); SQLiteDatabase(String dbPath); @Override ConnectionSource getCs(); @Override void close(); } | SQLiteDatabase implements Database { @Override public void close() { connectionSource.closeQuietly(); } SQLiteDatabase(); SQLiteDatabase(Path dbPath); SQLiteDatabase(String dbPath); @Override ConnectionSource getCs(); @Override void close(); } |
@Test public void testGetpHash() throws Exception { assertThat(filterRecord.getpHash(), is(HASH_ONE)); } | public long getpHash() { return pHash; } | FilterRecord { public long getpHash() { return pHash; } } | FilterRecord { public long getpHash() { return pHash; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); } | FilterRecord { public long getpHash() { return pHash; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } | FilterRecord { public long getpHash() { return pHash; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } |
@Test public void testSetpHash() throws Exception { assertThat(GUARD_MSG, filterRecord.getpHash(), is(HASH_ONE)); filterRecord.setpHash(HASH_TWO); assertThat(filterRecord.getpHash(), is(HASH_TWO)); } | public void setpHash(long pHash) { this.pHash = pHash; } | FilterRecord { public void setpHash(long pHash) { this.pHash = pHash; } } | FilterRecord { public void setpHash(long pHash) { this.pHash = pHash; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); } | FilterRecord { public void setpHash(long pHash) { this.pHash = pHash; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } | FilterRecord { public void setpHash(long pHash) { this.pHash = pHash; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } |
@Test public void testGetReason() throws Exception { assertThat(filterRecord.getTag(), is(TEST_TAG_ONE)); } | public Tag getTag() { return tag; } | FilterRecord { public Tag getTag() { return tag; } } | FilterRecord { public Tag getTag() { return tag; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); } | FilterRecord { public Tag getTag() { return tag; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } | FilterRecord { public Tag getTag() { return tag; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } |
@Test public void testEqualsIsEqual() throws Exception { FilterRecord other = new FilterRecord(HASH_ONE, TEST_TAG_ONE, null); assertThat(filterRecord.equals(other), is(true)); } | @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } FilterRecord other = (FilterRecord) obj; if (pHash != other.pHash) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } if (thumbnail == null) { if (other.thumbnail != null) { return false; } } else if (!thumbnail.equals(other.thumbnail)) { return false; } return true; } | FilterRecord { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } FilterRecord other = (FilterRecord) obj; if (pHash != other.pHash) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } if (thumbnail == null) { if (other.thumbnail != null) { return false; } } else if (!thumbnail.equals(other.thumbnail)) { return false; } return true; } } | FilterRecord { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } FilterRecord other = (FilterRecord) obj; if (pHash != other.pHash) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } if (thumbnail == null) { if (other.thumbnail != null) { return false; } } else if (!thumbnail.equals(other.thumbnail)) { return false; } return true; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); } | FilterRecord { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } FilterRecord other = (FilterRecord) obj; if (pHash != other.pHash) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } if (thumbnail == null) { if (other.thumbnail != null) { return false; } } else if (!thumbnail.equals(other.thumbnail)) { return false; } return true; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } | FilterRecord { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } FilterRecord other = (FilterRecord) obj; if (pHash != other.pHash) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } if (thumbnail == null) { if (other.thumbnail != null) { return false; } } else if (!thumbnail.equals(other.thumbnail)) { return false; } return true; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } |
@Test public void testEquals() throws Exception { EqualsVerifier.forClass(FilterRecord.class).withIgnoredFields("id").suppress(Warning.NONFINAL_FIELDS).verify(); } | @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } FilterRecord other = (FilterRecord) obj; if (pHash != other.pHash) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } if (thumbnail == null) { if (other.thumbnail != null) { return false; } } else if (!thumbnail.equals(other.thumbnail)) { return false; } return true; } | FilterRecord { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } FilterRecord other = (FilterRecord) obj; if (pHash != other.pHash) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } if (thumbnail == null) { if (other.thumbnail != null) { return false; } } else if (!thumbnail.equals(other.thumbnail)) { return false; } return true; } } | FilterRecord { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } FilterRecord other = (FilterRecord) obj; if (pHash != other.pHash) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } if (thumbnail == null) { if (other.thumbnail != null) { return false; } } else if (!thumbnail.equals(other.thumbnail)) { return false; } return true; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); } | FilterRecord { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } FilterRecord other = (FilterRecord) obj; if (pHash != other.pHash) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } if (thumbnail == null) { if (other.thumbnail != null) { return false; } } else if (!thumbnail.equals(other.thumbnail)) { return false; } return true; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } | FilterRecord { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } FilterRecord other = (FilterRecord) obj; if (pHash != other.pHash) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } if (thumbnail == null) { if (other.thumbnail != null) { return false; } } else if (!thumbnail.equals(other.thumbnail)) { return false; } return true; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } |
@Test public void testIsEaSupportedUseCache() throws Exception { assertThat(cut.isEaSupported(subDirectory), is(true)); when(eaQuery.isEaSupported(any(Path.class))).thenReturn(false); assertThat(cut.isEaSupported(subDirectory), is(true)); } | @Override public boolean isEaSupported(Path path) { Path parent = path.getParent(); if (path.getRoot() != null && path.equals(path.getRoot())) { parent = path; } if (parent == null) { return false; } return eaSupport.getUnchecked(parent); } | ExtendedAttributeDirectoryCache implements ExtendedAttributeQuery { @Override public boolean isEaSupported(Path path) { Path parent = path.getParent(); if (path.getRoot() != null && path.equals(path.getRoot())) { parent = path; } if (parent == null) { return false; } return eaSupport.getUnchecked(parent); } } | ExtendedAttributeDirectoryCache implements ExtendedAttributeQuery { @Override public boolean isEaSupported(Path path) { Path parent = path.getParent(); if (path.getRoot() != null && path.equals(path.getRoot())) { parent = path; } if (parent == null) { return false; } return eaSupport.getUnchecked(parent); } @Inject ExtendedAttributeDirectoryCache(ExtendedAttributeQuery eaQuery); ExtendedAttributeDirectoryCache(ExtendedAttributeQuery eaQuery, int expireTime, TimeUnit expireUnit); } | ExtendedAttributeDirectoryCache implements ExtendedAttributeQuery { @Override public boolean isEaSupported(Path path) { Path parent = path.getParent(); if (path.getRoot() != null && path.equals(path.getRoot())) { parent = path; } if (parent == null) { return false; } return eaSupport.getUnchecked(parent); } @Inject ExtendedAttributeDirectoryCache(ExtendedAttributeQuery eaQuery); ExtendedAttributeDirectoryCache(ExtendedAttributeQuery eaQuery, int expireTime, TimeUnit expireUnit); @Override boolean isEaSupported(Path path); } | ExtendedAttributeDirectoryCache implements ExtendedAttributeQuery { @Override public boolean isEaSupported(Path path) { Path parent = path.getParent(); if (path.getRoot() != null && path.equals(path.getRoot())) { parent = path; } if (parent == null) { return false; } return eaSupport.getUnchecked(parent); } @Inject ExtendedAttributeDirectoryCache(ExtendedAttributeQuery eaQuery); ExtendedAttributeDirectoryCache(ExtendedAttributeQuery eaQuery, int expireTime, TimeUnit expireUnit); @Override boolean isEaSupported(Path path); } |
@Test public void testGetTags() throws Exception { FilterRecord.getTags(filterRepository, TEST_TAG_ONE); verify(filterRepository).getByTag(TEST_TAG_ONE); } | public static List<FilterRecord> getTags(FilterRepository repository, Tag tag) throws RepositoryException { if (tag.isMatchAll()) { return repository.getAll(); } else { return repository.getByTag(tag); } } | FilterRecord { public static List<FilterRecord> getTags(FilterRepository repository, Tag tag) throws RepositoryException { if (tag.isMatchAll()) { return repository.getAll(); } else { return repository.getByTag(tag); } } } | FilterRecord { public static List<FilterRecord> getTags(FilterRepository repository, Tag tag) throws RepositoryException { if (tag.isMatchAll()) { return repository.getAll(); } else { return repository.getByTag(tag); } } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); } | FilterRecord { public static List<FilterRecord> getTags(FilterRepository repository, Tag tag) throws RepositoryException { if (tag.isMatchAll()) { return repository.getAll(); } else { return repository.getByTag(tag); } } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } | FilterRecord { public static List<FilterRecord> getTags(FilterRepository repository, Tag tag) throws RepositoryException { if (tag.isMatchAll()) { return repository.getAll(); } else { return repository.getByTag(tag); } } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } |
@Test public void testGetTagsAllTags() throws Exception { FilterRecord.getTags(filterRepository, new Tag(StringUtil.MATCH_ALL_TAGS)); verify(filterRepository).getAll(); } | public static List<FilterRecord> getTags(FilterRepository repository, Tag tag) throws RepositoryException { if (tag.isMatchAll()) { return repository.getAll(); } else { return repository.getByTag(tag); } } | FilterRecord { public static List<FilterRecord> getTags(FilterRepository repository, Tag tag) throws RepositoryException { if (tag.isMatchAll()) { return repository.getAll(); } else { return repository.getByTag(tag); } } } | FilterRecord { public static List<FilterRecord> getTags(FilterRepository repository, Tag tag) throws RepositoryException { if (tag.isMatchAll()) { return repository.getAll(); } else { return repository.getByTag(tag); } } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); } | FilterRecord { public static List<FilterRecord> getTags(FilterRepository repository, Tag tag) throws RepositoryException { if (tag.isMatchAll()) { return repository.getAll(); } else { return repository.getByTag(tag); } } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } | FilterRecord { public static List<FilterRecord> getTags(FilterRepository repository, Tag tag) throws RepositoryException { if (tag.isMatchAll()) { return repository.getAll(); } else { return repository.getByTag(tag); } } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } |
@Test public void testGetPathAsString() throws Exception { assertThat(cut.getImage(), is(IMAGE)); } | public ImageRecord getImage() { return image; } | IgnoreRecord { public ImageRecord getImage() { return image; } } | IgnoreRecord { public ImageRecord getImage() { return image; } @Deprecated IgnoreRecord(); IgnoreRecord(ImageRecord image); } | IgnoreRecord { public ImageRecord getImage() { return image; } @Deprecated IgnoreRecord(); IgnoreRecord(ImageRecord image); ImageRecord getImage(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); } | IgnoreRecord { public ImageRecord getImage() { return image; } @Deprecated IgnoreRecord(); IgnoreRecord(ImageRecord image); ImageRecord getImage(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static final String IMAGEPATH_FIELD_NAME; } |
@Test public void testEquals() throws Exception { assertThat(cut.equals(new IgnoreRecord(IMAGE)), is(true)); } | @Override public boolean equals(Object obj) { if (obj instanceof IgnoreRecord) { IgnoreRecord other = (IgnoreRecord) obj; return Objects.equals(this.image, other.image); } return false; } | IgnoreRecord { @Override public boolean equals(Object obj) { if (obj instanceof IgnoreRecord) { IgnoreRecord other = (IgnoreRecord) obj; return Objects.equals(this.image, other.image); } return false; } } | IgnoreRecord { @Override public boolean equals(Object obj) { if (obj instanceof IgnoreRecord) { IgnoreRecord other = (IgnoreRecord) obj; return Objects.equals(this.image, other.image); } return false; } @Deprecated IgnoreRecord(); IgnoreRecord(ImageRecord image); } | IgnoreRecord { @Override public boolean equals(Object obj) { if (obj instanceof IgnoreRecord) { IgnoreRecord other = (IgnoreRecord) obj; return Objects.equals(this.image, other.image); } return false; } @Deprecated IgnoreRecord(); IgnoreRecord(ImageRecord image); ImageRecord getImage(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); } | IgnoreRecord { @Override public boolean equals(Object obj) { if (obj instanceof IgnoreRecord) { IgnoreRecord other = (IgnoreRecord) obj; return Objects.equals(this.image, other.image); } return false; } @Deprecated IgnoreRecord(); IgnoreRecord(ImageRecord image); ImageRecord getImage(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static final String IMAGEPATH_FIELD_NAME; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.