Java Code Examples for org.jivesoftware.smack.util.StringUtils#randomString()

The following examples show how to use org.jivesoftware.smack.util.StringUtils#randomString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IoTDiscoveryIntegrationTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@SmackIntegrationTest
public void registerClaimAndUnregisterThing()
                throws XMPPErrorException, InterruptedException, SmackException {
    final String key = StringUtils.randomString(12);
    final String sn = StringUtils.randomString(12);
    final Thing thing = Thing.builder().setKey(key).setSerialNumber(sn).setManufacturer("Ignite Realtime").setModel(
                    "Smack").setVersion("0.1").build();

    registerThing(discoveryManagerOne, thing);

    IoTClaimed iotClaimed = discoveryManagerTwo.claimThing(thing.getMetaTags());
    assertEquals(conOne.getUser().asBareJid(), iotClaimed.getJid());

    discoveryManagerTwo.disownThing(iotClaimed.getJid());

    discoveryManagerOne.unregister();
}
 
Example 2
Source File: IoT.java    From Smack with Apache License 2.0 6 votes vote down vote up
private static ThingState actAsDataThing(XMPPTCPConnection connection) throws XMPPException, SmackException, InterruptedException {
    final String key = StringUtils.randomString(12);
    final String sn = StringUtils.randomString(12);
    Thing dataThing = Thing.builder()
                    .setKey(key)
                    .setSerialNumber(sn)
                    .setManufacturer("IgniteRealtime")
                    .setModel("Smack")
                    .setVersion("0.1")
                    .setMomentaryReadOutRequestHandler(new ThingMomentaryReadOutRequest() {
        @Override
        public void momentaryReadOutRequest(ThingMomentaryReadOutResult callback) {
            IoTDataField.IntField field = new IntField("timestamp", (int) (System.currentTimeMillis() / 1000));
            callback.momentaryReadOut(Collections.singletonList(field));
        }
    })
                    .build();
    IoTDiscoveryManager iotDiscoveryManager = IoTDiscoveryManager.getInstanceFor(connection);
    ThingState state = IoTDiscoveryIntegrationTest.registerThing(iotDiscoveryManager, dataThing);
    printStatus("SUCCESS: Thing registered:" + dataThing);
    return state;
}
 
Example 3
Source File: ChatRoomImpl.java    From Spark with Apache License 2.0 6 votes vote down vote up
@Override
protected void sendChatState(ChatState state) throws SmackException.NotConnectedException, InterruptedException
{
    if ( !active )
    {
        return;
    }

    final Message message = new Message();
    message.setType( Message.Type.chat );
    message.setTo( participantJID );
    message.setFrom( SparkManager.getSessionManager().getJID());

    if (threadID == null) {
        threadID = StringUtils.randomString(6);
    }
    message.setThread(threadID);
    message.addExtension( new ChatStateExtension( state ) );

    SparkManager.getConnection().sendStanza( message );
}
 
Example 4
Source File: OTREngineHost.java    From Spark with Apache License 2.0 6 votes vote down vote up
@Override
public void injectMessage(SessionID arg0, String arg1) {
    Message injection = new Message();
    injection.setType(Message.Type.chat);
    injection.setTo(_chatRoom.getParticipantJID());
    injection.setFrom(SparkManager.getSessionManager().getJID());
    String threadID = StringUtils.randomString(6);
    injection.setThread(threadID);
    injection.setBody(arg1);
    try
    {
        SparkManager.getConnection().sendStanza(injection);
    }
    catch ( SmackException.NotConnectedException e )
    {
        Log.warning( "Unable to send injection to " + injection.getTo(), e );
    }
}
 
Example 5
Source File: RandomStringStanzaIdSource.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public StanzaIdSource constructStanzaIdSource() {
    StanzaIdSource stanzaIdSource;
    if (verySecure) {
        stanzaIdSource = () -> StringUtils.randomString(length);
    } else {
        stanzaIdSource = () -> StringUtils.insecureRandomString(length);
    }
    return stanzaIdSource;
}
 
Example 6
Source File: JingleIBBTransportTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Test
public void parserTest() throws Exception {
    String sid = StringUtils.randomString(24);
    short size = 8192;

    String xml = "<transport xmlns='urn:xmpp:jingle:transports:ibb:1' block-size='8192' sid='" + sid + "'/>";

    JingleIBBTransport transport = new JingleIBBTransport(size, sid);
    assertEquals(xml, transport.toXML().toString());
    assertEquals(size, transport.getBlockSize());
    assertEquals(sid, transport.getSessionId());

    JingleIBBTransport parsed = new JingleIBBTransportProvider()
            .parse(TestUtils.getParser(xml));
    assertEquals(transport, parsed);
    assertTrue(transport.equals(parsed));
    assertEquals(xml, parsed.toXML().toString());

    JingleIBBTransport transport1 = new JingleIBBTransport((short) 1024);
    assertEquals((short) 1024, transport1.getBlockSize());
    assertNotSame(transport, transport1);
    assertNotSame(transport.getSessionId(), transport1.getSessionId());

    assertFalse(transport.equals(null));

    JingleIBBTransport transport2 = new JingleIBBTransport();
    assertEquals(JingleIBBTransport.DEFAULT_BLOCK_SIZE, transport2.getBlockSize());
    assertFalse(transport1.equals(transport2));

    JingleIBBTransport transport3 = new JingleIBBTransport((short) -1024);
    assertEquals(JingleIBBTransport.DEFAULT_BLOCK_SIZE, transport3.getBlockSize());

    assertEquals(transport3.getNamespace(), JingleIBBTransport.NAMESPACE_V1);
    assertEquals(transport3.getElementName(), "transport");

    JingleIBBTransport transport4 = new JingleIBBTransport("session-id");
    assertEquals(JingleIBBTransport.DEFAULT_BLOCK_SIZE, transport4.getBlockSize());
}
 
Example 7
Source File: MultiUserChatLowLevelIntegrationTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@SmackIntegrationTest
public void testMucBookmarksAutojoin(AbstractXMPPConnection connection) throws InterruptedException,
                TestNotPossibleException, XMPPException, SmackException, IOException {
    final BookmarkManager bookmarkManager = BookmarkManager.getBookmarkManager(connection);
    if (!bookmarkManager.isSupported()) {
        throw new TestNotPossibleException("Private data storage not supported");
    }
    final MultiUserChatManager multiUserChatManager = MultiUserChatManager.getInstanceFor(connection);
    final Resourcepart mucNickname = Resourcepart.from("Nick-" + StringUtils.randomString(6));
    final String randomMucName = StringUtils.randomString(6);
    final DomainBareJid mucComponent = multiUserChatManager.getMucServiceDomains().get(0);
    final MultiUserChat muc = multiUserChatManager.getMultiUserChat(JidCreate.entityBareFrom(
                    Localpart.from(randomMucName), mucComponent));

    MucCreateConfigFormHandle handle = muc.createOrJoin(mucNickname);
    if (handle != null) {
        handle.makeInstant();
    }
    muc.leave();

    bookmarkManager.addBookmarkedConference("Smack Inttest: " + testRunId, muc.getRoom(), true,
                    mucNickname, null);

    connection.disconnect();
    connection.connect().login();

    // MucBookmarkAutojoinManager is also able to do its task automatically
    // after every login, it's not deterministic when this will be finished.
    // So we trigger it manually here.
    MucBookmarkAutojoinManager.getInstanceFor(connection).autojoinBookmarkedConferences();

   assertTrue(muc.isJoined());

   // If the test went well, leave the MUC
   muc.leave();
}
 
Example 8
Source File: XmppConnectionManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
private <C extends AbstractXMPPConnection> C constructConnection(
        XmppConnectionDescriptor<C, ? extends ConnectionConfiguration, ? extends ConnectionConfiguration.Builder<?, ?>> connectionDescriptor,
        Collection<ConnectionConfigurationBuilderApplier> customConnectionConfigurationAppliers)
        throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    String username = "sinttest-" + testRunId + '-' + (connections.size() + 1);
    String password = StringUtils.randomString(24);

    return constructConnection(username, password, connectionDescriptor, customConnectionConfigurationAppliers);
}
 
Example 9
Source File: SparkTransferManager.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
  * Send an image to a user.
  *
  * @param image the image to send.
  * @param room  the ChatRoom of the user you wish to send the image to.
  */
 public void sendImage(final BufferedImage image, final ChatRoom room) {
     File tmpDirectory = new File(Spark.getSparkUserHome(), "/tempImages");
     tmpDirectory.mkdirs();

     String imageName = "image_" + StringUtils.randomString(2) + ".png";
     final File imageFile = new File(tmpDirectory, imageName);

     // Write image to system.
     room.setCursor(new Cursor(Cursor.WAIT_CURSOR));

     SwingWorker writeImageThread = new SwingWorker() {
         @Override
public Object construct() {
             try {
                 // Write out file in separate thread.
                 ImageIO.write(image, "png", imageFile);
             }
             catch (IOException e) {
                 Log.error(e);
             }
             return true;
         }

         @Override
public void finished() {
             ChatRoomImpl roomImpl = (ChatRoomImpl)room;
             sendFile(imageFile, roomImpl.getParticipantJID());
             SparkManager.getChatManager().getChatContainer().activateChatRoom(room);
             room.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
         }
     };
     writeImageThread.start();
 }
 
Example 10
Source File: ChatRoomImpl.java    From Spark with Apache License 2.0 5 votes vote down vote up
@Override
public void sendMessage(String text) {
       final Message message = new Message();

       if (threadID == null) {
           threadID = StringUtils.randomString(6);
       }
       message.setThread(threadID);

       if ( privateChat )
       {
           // XEP-0045: 7.5 Sending a Private Message
           message.addExtension( new MUCUser() );
       }

       // Set the body of the message using typedMessage and remove control
       // characters
       text = text.replaceAll("[\\u0001-\\u0008\\u000B-\\u001F]", "");
       message.setBody(text);
       
       // IF there is no body, just return and do nothing
       if (!ModelUtil.hasLength(text)) {
           return;
       }

       // Fire Message Filters
       SparkManager.getChatManager().filterOutgoingMessage(this, message);

       // Fire Global Filters
       SparkManager.getChatManager().fireGlobalMessageSentListeners(this, message);

       sendMessage(message);          	    	
   }
 
Example 11
Source File: EncryptedOpenPgpContentElement.java    From Smack with Apache License 2.0 4 votes vote down vote up
private static String createRandomPadding() {
    int len = RandomUtil.nextSecureRandomInt(256);
    return StringUtils.randomString(len);
}
 
Example 12
Source File: JingleManager.java    From Smack with Apache License 2.0 4 votes vote down vote up
public static String randomId() {
    return StringUtils.randomString(24);
}
 
Example 13
Source File: JingleS5BTransportCandidate.java    From Smack with Apache License 2.0 4 votes vote down vote up
public JingleS5BTransportCandidate(Bytestream.StreamHost streamHost, int priority, Type type) {
    this(StringUtils.randomString(24), streamHost.getAddress(), streamHost.getJID(), streamHost.getPort(), priority, type);
}
 
Example 14
Source File: JingleIBBTransport.java    From Smack with Apache License 2.0 4 votes vote down vote up
public JingleIBBTransport(short blockSize) {
    this(blockSize, StringUtils.randomString(24));
}
 
Example 15
Source File: IoTDataIntegrationTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Connection one provides a thing, which momentary value is read out by connection two.
 *
 * @throws Exception if an exception occurs.
 * @throws TimeoutException if there was a timeout.
 */
@SmackIntegrationTest
public void dataTest() throws Exception {
    final String key = StringUtils.randomString(12);
    final String sn = StringUtils.randomString(12);
    final int value = INSECURE_RANDOM.nextInt();

    Thing dataThing = Thing.builder().setKey(key).setSerialNumber(sn).setMomentaryReadOutRequestHandler(new ThingMomentaryReadOutRequest() {
        @Override
        public void momentaryReadOutRequest(ThingMomentaryReadOutResult callback) {
            IoTDataField.IntField field = new IntField(testRunId, value);
            callback.momentaryReadOut(Collections.singletonList(field));
        }
    }).build();

    iotDataManagerOne.installThing(dataThing);

    List<IoTFieldsExtension> values;
    try {
        IntegrationTestRosterUtil.ensureBothAccountsAreSubscribedToEachOther(conOne, conTwo, timeout);

        values = iotDataManagerTwo.requestMomentaryValuesReadOut(conOne.getUser());
    }
    finally {
        iotDataManagerOne.uninstallThing(dataThing);
        IntegrationTestRosterUtil.ensureBothAccountsAreNotInEachOthersRoster(conOne, conTwo);
    }

    assertEquals(1, values.size());
    IoTFieldsExtension iotFieldsExtension = values.get(0);
    List<NodeElement> nodes = iotFieldsExtension.getNodes();

    assertEquals(1, nodes.size());
    NodeElement node = nodes.get(0);
    List<TimestampElement> timestamps = node.getTimestampElements();

    assertEquals(1, timestamps.size());
    TimestampElement timestamp = timestamps.get(0);
    List<? extends IoTDataField> fields = timestamp.getDataFields();

    assertEquals(1, fields.size());
    IoTDataField dataField = fields.get(0);
    assertTrue(dataField instanceof IoTDataField.IntField);
    IoTDataField.IntField intDataField = (IoTDataField.IntField) dataField;
    assertEquals(testRunId, intDataField.getName());
    assertEquals(value, intDataField.getValue());
}
 
Example 16
Source File: ConferenceServices.java    From Spark with Apache License 2.0 4 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
          Localpart userName = SparkManager.getSessionManager().getJID().getLocalpart();
          final String roomName = userName + "_" + StringUtils.randomString(3);


          final List<EntityBareJid> jids = new ArrayList<>();
          jids.add(((ChatRoomImpl)chatRoom).getParticipantJID());

          final DomainBareJid serviceName = getDefaultServiceName();
          if (serviceName != null) {
              SwingWorker worker = new SwingWorker() {
                  @Override
			public Object construct() {
                      try {
                          Thread.sleep(25);
                      }
                      catch (InterruptedException e1) {
                          Log.error(e1);
                      }
                      return "ok";
                  }

                  @Override
			public void finished() {
                      try {
                          BookmarkedConference selectedBookmarkedConf = _localPreferences.isUseAdHocRoom() ? null : getDefaultBookmark();
                          if (selectedBookmarkedConf == null) {
                              ConferenceUtils.createPrivateConference(serviceName,
                                      Res.getString("message.please.join.in.conference"), roomName, jids);
                          } else {
                              ConferenceUtils.joinConferenceOnSeperateThread(selectedBookmarkedConf.getName(),
                                      selectedBookmarkedConf.getJid(), selectedBookmarkedConf.getPassword(),
                                      Res.getString("message.please.join.in.conference"), jids);
                          }
                      }
                      catch (SmackException | InterruptedException ex) {
                      	UIManager.put("OptionPane.okButtonText", Res.getString("ok"));
                          JOptionPane.showMessageDialog(chatRoom, "An error occurred.", Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
                      }
                  }
              };
              worker.start();
          }
      }