org.jivesoftware.smackx.xdata.FormField Java Examples

The following examples show how to use org.jivesoftware.smackx.xdata.FormField. 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: FormFieldRegistry.java    From Smack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ReferenceEquality")
public static synchronized void register(DataForm dataForm) {
    // TODO: Also allow forms of type 'result'?
    if (dataForm.getType() != DataForm.Type.form) {
        throw new IllegalArgumentException();
    }

    String formType = null;
    TextSingleFormField hiddenFormTypeField = dataForm.getHiddenFormTypeField();
    if (hiddenFormTypeField != null) {
        formType = hiddenFormTypeField.getValue();
    }

    for (FormField formField : dataForm.getFields()) {
        // Note that we can compare here by reference equality to skip the hidden form type field.
        if (formField == hiddenFormTypeField) {
            continue;
        }

        String fieldName = formField.getFieldName();
        FormField.Type type = formField.getType();
        register(formType, fieldName, type);
    }
}
 
Example #2
Source File: MultiUserChat.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a voice request to the MUC. The room moderators usually need to approve this request.
 *
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 * @see <a href="http://xmpp.org/extensions/xep-0045.html#requestvoice">XEP-45 ยง 7.13 Requesting
 *      Voice</a>
 * @since 4.1
 */
public void requestVoice() throws NotConnectedException, InterruptedException {
    DataForm.Builder form = DataForm.builder()
                    .setFormType(MUCInitialPresence.NAMESPACE + "#request");

    TextSingleFormField.Builder requestVoiceField = FormField.textSingleBuilder("muc#role");
    requestVoiceField.setLabel("Requested role");
    requestVoiceField.setValue("participant");
    form.addField(requestVoiceField.build());

    Message message = connection.getStanzaFactory().buildMessageStanza()
            .to(room)
            .addExtension(form.build())
            .build();
    connection.sendStanza(message);
}
 
Example #3
Source File: FileTransferNegotiator.java    From Smack with Apache License 2.0 6 votes vote down vote up
private StreamNegotiator getOutgoingNegotiator(final FormField field) throws NoAcceptableTransferMechanisms {
    boolean isByteStream = false;
    boolean isIBB = false;
    for (CharSequence variable : field.getValues()) {
        String variableString = variable.toString();
        if (variableString.equals(Bytestream.NAMESPACE) && !IBB_ONLY) {
            isByteStream = true;
        }
        else if (variableString.equals(DataPacketExtension.NAMESPACE)) {
            isIBB = true;
        }
    }

    if (!isByteStream && !isIBB) {
        throw new FileTransferException.NoAcceptableTransferMechanisms();
    }

    if (isByteStream) {
        return byteStreamTransferManager;
    }
    else {
        return inbandTransferManager;
    }
}
 
Example #4
Source File: FileTransferNegotiator.java    From Smack with Apache License 2.0 6 votes vote down vote up
private StreamNegotiator getNegotiator(final ListSingleFormField field)
        throws NoAcceptableTransferMechanisms {
    String variable;
    boolean isByteStream = false;
    boolean isIBB = false;
    for (FormField.Option option : field.getOptions()) {
        variable = option.getValueString();
        if (variable.equals(Bytestream.NAMESPACE) && !IBB_ONLY) {
            isByteStream = true;
        }
        else if (variable.equals(DataPacketExtension.NAMESPACE)) {
            isIBB = true;
        }
    }

    if (!isByteStream && !isIBB) {
        throw new FileTransferException.NoAcceptableTransferMechanisms();
    }

    if (isByteStream) {
        return byteStreamTransferManager;
    }
    else {
        return inbandTransferManager;
    }
}
 
Example #5
Source File: MucConfigFormManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new MUC config form manager.
 * <p>
 * Note that the answerForm needs to be filled out with the defaults.
 * </p>
 *
 * @param multiUserChat the MUC for this configuration form.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NoResponseException if there was no response from the remote entity.
 */
MucConfigFormManager(MultiUserChat multiUserChat) throws NoResponseException,
                XMPPErrorException, NotConnectedException, InterruptedException {
    this.multiUserChat = multiUserChat;

    // Set the answer form
    Form configForm = multiUserChat.getConfigurationForm();
    this.answerForm = configForm.getFillableForm();

    // Set the local variables according to the fields found in the answer form
    FormField roomOwnersFormField = answerForm.getDataForm().getField(MUC_ROOMCONFIG_ROOMOWNERS);
    if (roomOwnersFormField != null) {
        // Set 'owners' to the currently configured owners
        List<? extends CharSequence> ownerStrings = roomOwnersFormField.getValues();
        owners = new ArrayList<>(ownerStrings.size());
        JidUtil.jidsFrom(ownerStrings, owners, null);
    }
    else {
        // roomowners not supported, this should barely be the case
        owners = null;
    }
}
 
Example #6
Source File: SimpleUserSearch.java    From Smack with Apache License 2.0 6 votes vote down vote up
private String getItemsToSearch() {
    StringBuilder buf = new StringBuilder();

    if (form == null) {
        form = DataForm.from(this);
    }

    if (form == null) {
        return "";
    }

    for (FormField field : form.getFields()) {
        String name = field.getFieldName();
        String value = getSingleValue(field);
        if (value.trim().length() > 0) {
            buf.append('<').append(name).append('>').append(value).append("</").append(name).append('>');
        }
    }

    return buf.toString();
}
 
Example #7
Source File: ConferenceUtils.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve the date (in yyyyMMdd) format of the time the room was created.
 *
 * @param roomJID the jid of the room.
 * @return the formatted date.
 * @throws Exception throws an exception if we are unable to retrieve the date.
 */
public static String getCreationDate(EntityBareJid roomJID) throws Exception {
    ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(SparkManager.getConnection());

    final DateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss");
    DiscoverInfo infoResult = discoManager.discoverInfo(roomJID);
    DataForm dataForm = infoResult.getExtension("x", "jabber:x:data");
    if (dataForm == null) {
        return "Not available";
    }
    String creationDate = "";
    for ( final FormField field : dataForm.getFields() ) {
        String label = field.getLabel();


        if (label != null && "Creation date".equalsIgnoreCase(label)) {
            for ( CharSequence value : field.getValues() ) {
                creationDate = value.toString();
                Date date = dateFormatter.parse(creationDate);
                creationDate = DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.MEDIUM).format(date);
            }
        }
    }
    return creationDate;
}
 
Example #8
Source File: DataValidationHelperTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckConsistencyFormFieldBasicValidateElement() {
    JidSingleFormField.Builder field = FormField.jidSingleBuilder("var");
    BasicValidateElement element = new BasicValidateElement(null);
    ValidationConsistencyException vce = assertThrows(ValidationConsistencyException.class,
                    () -> element.checkConsistency(field));
    assertEquals("Field type 'jid-single' is not consistent with validation method 'basic'.", vce.getMessage());

    assertThrows(IllegalArgumentException.class,
                    () -> new ListRange(-1L, 1L));

    element.setListRange(new ListRange(10L, 100L));
    vce = assertThrows(ValidationConsistencyException.class, () -> element.checkConsistency(field));
    assertEquals("Field type is not of type 'list-multi' while a 'list-range' is defined.", vce.getMessage());

    FormField.Builder<?, ?> fieldListMulti = FormField.listMultiBuilder("var");
    element.checkConsistency(fieldListMulti);
}
 
Example #9
Source File: FillableForm.java    From Smack with Apache License 2.0 6 votes vote down vote up
public FillableForm(DataForm dataForm) {
    super(dataForm);
    if (dataForm.getType() != DataForm.Type.form) {
        throw new IllegalArgumentException();
    }

    Set<String> requiredFields = new HashSet<>();
    for (FormField formField : dataForm.getFields()) {
        if (formField.isRequired()) {
            String fieldName = formField.getFieldName();
            requiredFields.add(fieldName);
            missingRequiredFields.add(fieldName);
        }
    }
    this.requiredFields = Collections.unmodifiableSet(requiredFields);
}
 
Example #10
Source File: DataFormProvider.java    From Smack with Apache License 2.0 6 votes vote down vote up
public static FormField.Option parseOption(XmlPullParser parser) throws IOException, XmlPullParserException {
    int initialDepth = parser.getDepth();
    FormField.Option option = null;
    String label = parser.getAttributeValue("", "label");
    outerloop: while (true) {
        XmlPullParser.TagEvent eventType = parser.nextTag();
        switch (eventType) {
        case START_ELEMENT:
            String name = parser.getName();
            switch (name) {
            case "value":
                option = new FormField.Option(label, parser.nextText());
                break;
            }
            break;
        case END_ELEMENT:
            if (parser.getDepth() == initialDepth) {
                break outerloop;
            }
            break;
        }
    }
    return option;
}
 
Example #11
Source File: DataFormTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    // Build a Form.
    DataForm.Builder df = DataForm.builder(DataForm.Type.form);
    String instruction = "InstructionTest1";
    df.addInstruction(instruction);
    FormField field = FormField.builder("testField1").build();
    df.addField(field);

    DataForm dataForm = df.build();
    String output = dataForm.toXML().toString();
    assertEquals(TEST_OUTPUT_1, output);

    XmlPullParser parser = PacketParserUtils.getParserFor(output);

    dataForm = pr.parse(parser);

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

    output = dataForm.toXML().toString();
    assertEquals(TEST_OUTPUT_1, output);
}
 
Example #12
Source File: EntityCapsManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that the given discovery info is not ill-formed.
 *
 * @param info the discovery info to verify.
 * @return true if the stanza extensions is not ill-formed
 */
private static boolean verifyPacketExtensions(DiscoverInfo info) {
    Set<String> foundFormTypes = new HashSet<>();
    List<DataForm> dataForms = info.getExtensions(DataForm.class);
    for (DataForm dataForm : dataForms) {
        FormField formFieldTypeField = dataForm.getHiddenFormTypeField();
        if (formFieldTypeField == null) {
            continue;
        }

        String type = formFieldTypeField.getFirstValue();
        boolean noDuplicate = foundFormTypes.add(type);
        if (!noDuplicate) {
            // Ill-formed extension: duplicate forms (by form field type string).
            return false;
        }
    }

    return true;
}
 
Example #13
Source File: MamManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
public Builder limitResultsBefore(Date end) {
    if (end == null) {
        return this;
    }

    FormField formField = FormField.builder(FORM_FIELD_END)
        .setValue(end)
        .build();
    formFields.put(formField.getFieldName(), formField);

    FormField startFormField = formFields.get(FORM_FIELD_START);
    if (startFormField != null) {
        Date start;
        try {
            start = startFormField.getFirstValueAsDate();
        } catch (ParseException e) {
            throw new IllegalStateException(e);
        }
        if (end.getTime() <= start.getTime()) {
            throw new IllegalArgumentException("Given end date (" + end
                            + ") is before the existing start date (" + start + ')');
        }
    }

    return this;
}
 
Example #14
Source File: DataFormProvider.java    From Smack with Apache License 2.0 6 votes vote down vote up
private static DataForm.ReportedData parseReported(XmlPullParser parser, XmlEnvironment xmlEnvironment, String formType, DataForm.Type dataFormType)
                throws XmlPullParserException, IOException, SmackParsingException {
    final int initialDepth = parser.getDepth();
    List<FormField> fields = new ArrayList<>();
    outerloop: while (true) {
        XmlPullParser.TagEvent eventType = parser.nextTag();
        switch (eventType) {
        case START_ELEMENT:
            String name = parser.getName();
            switch (name) {
            case "field":
                FormField field = parseField(parser, XmlEnvironment.from(parser, xmlEnvironment), formType, dataFormType);
                fields.add(field);
                break;
            }
            break;
        case END_ELEMENT:
            if (parser.getDepth() == initialDepth) {
                break outerloop;
            }
            break;
        }
    }
    return new DataForm.ReportedData(fields);
}
 
Example #15
Source File: RoomInfoTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void validateRoomWithForm() {
    DataForm.Builder dataForm = DataForm.builder(DataForm.Type.result);

    TextSingleFormField.Builder desc = FormField.builder("muc#roominfo_description");
    desc.setValue("The place for all good witches!");
    dataForm.addField(desc.build());

    TextSingleFormField.Builder subject = FormField.builder("muc#roominfo_subject");
    subject.setValue("Spells");
    dataForm.addField(subject.build());

    TextSingleFormField.Builder occupants = FormField.builder("muc#roominfo_occupants");
    occupants.setValue("3");
    dataForm.addField(occupants.build());

    DiscoverInfo discoInfo = DiscoverInfo.builder("disco1")
            .addExtension(dataForm.build())
            .build();
    RoomInfo roomInfo = new RoomInfo(discoInfo);
    assertEquals("The place for all good witches!", roomInfo.getDescription());
    assertEquals("Spells", roomInfo.getSubject());
    assertEquals(3, roomInfo.getOccupantsCount());
}
 
Example #16
Source File: FormReader.java    From Smack with Apache License 2.0 5 votes vote down vote up
default Integer readInteger(String fieldName) {
    FormField formField = getField(fieldName);
    if (formField == null) {
        return null;
    }
    AbstractSingleStringValueFormField textSingleFormField = formField.ifPossibleAs(AbstractSingleStringValueFormField.class);
    return textSingleFormField.getValueAsInt();
}
 
Example #17
Source File: DataFormProvider.java    From Smack with Apache License 2.0 5 votes vote down vote up
private static FormField.Builder<?, ?> parseBooleanFormField(String fieldName, List<FormField.Value> values) throws SmackParsingException {
    BooleanFormField.Builder builder = FormField.booleanBuilder(fieldName);
    if (values.size() == 1) {
        String value = values.get(0).getValue().toString();
        builder.setValue(value);
    }
    return builder;
}
 
Example #18
Source File: FormReader.java    From Smack with Apache License 2.0 5 votes vote down vote up
default Date readDate(String fieldName) throws ParseException {
    FormField formField = getField(fieldName);
    if (formField == null) {
        return null;
    }
    AbstractSingleStringValueFormField textSingleFormField = formField.ifPossibleAs(AbstractSingleStringValueFormField.class);
    String value = textSingleFormField.getValue();
    if (value == null) {
        return null;
    }
    return XmppDateTime.parseDate(value);
}
 
Example #19
Source File: FillableForm.java    From Smack with Apache License 2.0 5 votes vote down vote up
private static AbstractSingleStringValueFormField.Builder<?, ?> createSingleKindFieldBuilder(String fieldName, FormField.Type type) {
    switch (type) {
    case text_private:
        return FormField.textPrivateBuilder(fieldName);
    case text_single:
        return FormField.textSingleBuilder(fieldName);
    case hidden:
        return FormField.hiddenBuilder(fieldName);
    case list_multi:
        return FormField.listSingleBuilder(fieldName);
    default:
        throw new IllegalArgumentException();
    }
}
 
Example #20
Source File: FormReader.java    From Smack with Apache License 2.0 5 votes vote down vote up
default Boolean readBoolean(String fieldName) {
    FormField formField = getField(fieldName);
    if (formField == null) {
        return null;
    }
    BooleanFormField booleanFormField = formField.ifPossibleAs(BooleanFormField.class);
    return booleanFormField.getValueAsBoolean();
}
 
Example #21
Source File: FormReader.java    From Smack with Apache License 2.0 5 votes vote down vote up
default List<String> readStringValues(String fieldName) {
    FormField formField = getField(fieldName);
    if (formField == null) {
        return Collections.emptyList();
    }
    AbstractMultiFormField multiFormField = formField.ifPossibleAs(AbstractMultiFormField.class);
    return multiFormField.getValues();
}
 
Example #22
Source File: FormReader.java    From Smack with Apache License 2.0 5 votes vote down vote up
default List<? extends CharSequence> readValues(String fieldName) {
    FormField formField = getField(fieldName);
    if (formField == null) {
        return Collections.emptyList();
    }
    return formField.getValues();
}
 
Example #23
Source File: DataForm.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Return the form type from the hidden form type field.
 *
 * @return the form type or <code>null</code> if this form has none set.
 * @since 4.4.0
 */
public String getFormType() {
    FormField formTypeField = getHiddenFormTypeField();
    if (formTypeField == null) {
        return null;
    }
    return formTypeField.getFirstValue();
}
 
Example #24
Source File: FormReader.java    From Smack with Apache License 2.0 5 votes vote down vote up
default String readFirstValue(String fieldName) {
    FormField formField = getField(fieldName);
    if (formField == null) {
        return null;
    }
    return formField.getFirstValue();
}
 
Example #25
Source File: DataValidationHelperTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckConsistencyFormFieldRangeValidateElement() {
    FormField.Builder<?, ?> field = FormField.textMultiBuilder("var");
    RangeValidateElement element = new RangeValidateElement("xs:integer", null,  "99");
    ValidationConsistencyException e = assertThrows(ValidationConsistencyException.class,
                    () -> element.checkConsistency(field));
    assertEquals("Field type 'text-multi' is not consistent with validation method 'range'.", e.getMessage());
}
 
Example #26
Source File: FormFieldRegistry.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static synchronized FormFieldInformation lookup(String fieldName) {
    String formType = FIELD_NAME_TO_FORM_TYPE.get(fieldName);
    FormField.Type type = lookup(formType, fieldName);
    if (type == null) {
        return null;
    }

    return new FormFieldInformation(type, formType);
}
 
Example #27
Source File: FormFieldRegistry.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static synchronized void register(String formType, String fieldName, FormField.Type type) {
    if (formType == null) {
        FormFieldInformation formFieldInformation = lookup(fieldName);
        if (formFieldInformation != null) {
            if (Objects.equals(formType, formFieldInformation.formType)
                            && type.equals(formFieldInformation.formFieldType)) {
                // The field is already registered, nothing to do here.
                return;
            }

            String message = "There is already a field with the name'" + fieldName
                            + "' registered with the field type '" + formFieldInformation.formFieldType
                            + "', while this tries to register the field with the type '" + type + '\'';
            throw new IllegalArgumentException(message);
        }

        LOOKASIDE_REGISTRY.put(fieldName, type);
        return;
    }

    Map<String, FormField.Type> fieldNameToType = REGISTRY.get(formType);
    if (fieldNameToType == null) {
        fieldNameToType = new HashMap<>();
        REGISTRY.put(formType, fieldNameToType);
    } else {
        FormField.Type previousType = fieldNameToType.get(fieldName);
        if (previousType != null && previousType != type) {
            throw new IllegalArgumentException();
        }
    }
    fieldNameToType.put(fieldName, type);

    FIELD_NAME_TO_FORM_TYPE.put(fieldName, formType);
}
 
Example #28
Source File: SoftwareInfoForm.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Include Operating System's version as a {@link FormField}.
 * <br>
 * @param os_version Version of OS
 * @return Builder
 */
public Builder setOSVersion(String os_version) {
    TextSingleFormField.Builder builder = FormField.builder(OS_VERSION);
    builder.setValue(os_version);
    dataFormBuilder.addField(builder.build());
    return this;
}
 
Example #29
Source File: SoftwareInfoForm.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Include Operating System's name as a {@link FormField}.
 * <br>
 * @param os Name of the OS
 * @return Builder
 */
public Builder setOS(String os) {
    TextSingleFormField.Builder builder = FormField.builder(OS);
    builder.setValue(os);
    dataFormBuilder.addField(builder.build());
    return this;
}
 
Example #30
Source File: SoftwareInfoForm.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Include Software Version as a {@link FormField}.
 * <br>
 * @param softwareVersion Version of the Software in use
 * @return Builder
 */
public Builder setSoftwareVersion(String softwareVersion) {
    TextSingleFormField.Builder builder = FormField.builder(SOFTWARE_VERSION);
    builder.setValue(softwareVersion);
    dataFormBuilder.addField(builder.build());
    return this;
}