/** * Creates a node with specified configuration. * * Note: This is the only way to create a collection node. * * @param name The name of the node, which must be unique within the * pubsub service * @param config The configuration for the node * @return The node that was created * @throws XMPPErrorException * @throws NoResponseException * @throws NotConnectedException */ public Node createNode(String name, Form config) throws NoResponseException, XMPPErrorException, NotConnectedException { PubSub request = PubSub.createPubsubPacket(to, Type.set, new NodeExtension(PubSubElementType.CREATE, name), null); boolean isLeafNode = true; if (config != null) { request.addExtension(new FormNode(FormNodeType.CONFIGURE, config)); FormField nodeTypeField = config.getField(ConfigureNodeFields.node_type.getFieldName()); if (nodeTypeField != null) isLeafNode = nodeTypeField.getValues().get(0).equals(NodeType.leaf.toString()); } // Errors will cause exceptions in getReply, so it only returns // on success. sendPubsubPacket(con, request); Node newNode = isLeafNode ? new LeafNode(con, name) : new CollectionNode(con, name); newNode.setTo(to); nodeMap.put(newNode.getId(), newNode); return newNode; }
private String getItemsToSearch() { StringBuilder buf = new StringBuilder(); if (form == null) { form = Form.getFormFrom(this); } if (form == null) { return ""; } for (FormField field : form.getFields()) { String name = field.getVariable(); String value = getSingleValue(field); if (value.trim().length() > 0) { buf.append("<").append(name).append(">").append(value).append("</").append(name).append(">"); } } return buf.toString(); }
/** * Creates the initiation acceptance stanza(/packet) to forward to the stream * initiator. * * @param streamInitiationOffer The offer from the stream initiator to connect for a stream. * @param namespaces The namespace that relates to the accepted means of transfer. * @return The response to be forwarded to the initiator. */ protected static StreamInitiation createInitiationAccept( StreamInitiation streamInitiationOffer, String[] namespaces) { StreamInitiation response = new StreamInitiation(); response.setTo(streamInitiationOffer.getFrom()); response.setFrom(streamInitiationOffer.getTo()); response.setType(IQ.Type.result); response.setStanzaId(streamInitiationOffer.getStanzaId()); DataForm form = new DataForm(DataForm.Type.submit); FormField field = new FormField( FileTransferNegotiator.STREAM_DATA_FIELD_NAME); for (String namespace : namespaces) { field.addValue(namespace); } form.addField(field); response.setFeatureNegotiationForm(form); return response; }
private DataForm.Item parseItem(XmlPullParser parser) throws XmlPullParserException, IOException { final int initialDepth = parser.getDepth(); List<FormField> fields = new ArrayList<FormField>(); outerloop: while (true) { int eventType = parser.next(); switch (eventType) { case XmlPullParser.START_TAG: String name = parser.getName(); switch (name) { case "field": fields.add(parseField(parser)); break; } break; case XmlPullParser.END_TAG: if (parser.getDepth() == initialDepth) { break outerloop; } break; } } return new DataForm.Item(fields); }
private DataForm.ReportedData parseReported(XmlPullParser parser) throws XmlPullParserException, IOException { final int initialDepth = parser.getDepth(); List<FormField> fields = new ArrayList<FormField>(); outerloop: while (true) { int eventType = parser.next(); switch (eventType) { case XmlPullParser.START_TAG: String name = parser.getName(); switch (name) { case "field": fields.add(parseField(parser)); break; } break; case XmlPullParser.END_TAG: if (parser.getDepth() == initialDepth) { break outerloop; } break; } } return new DataForm.ReportedData(fields); }
private FormField.Option parseOption(XmlPullParser parser) throws XmlPullParserException, IOException { final int initialDepth = parser.getDepth(); FormField.Option option = null; String label = parser.getAttributeValue("", "label"); outerloop: while (true) { int eventType = parser.next(); switch (eventType) { case XmlPullParser.START_TAG: String name = parser.getName(); switch (name) { case "value": option = new FormField.Option(label, parser.nextText()); break; } break; case XmlPullParser.END_TAG: if (parser.getDepth() == initialDepth) { break outerloop; } break; } } return option; }
/** * * @param info * @return true if the stanza(/packet) extensions is ill-formed */ protected static boolean verifyPacketExtensions(DiscoverInfo info) { List<FormField> foundFormTypes = new LinkedList<FormField>(); for (ExtensionElement pe : info.getExtensions()) { if (pe.getNamespace().equals(DataForm.NAMESPACE)) { DataForm df = (DataForm) pe; for (FormField f : df.getFields()) { if (f.getVariable().equals("FORM_TYPE")) { for (FormField fft : foundFormTypes) { if (f.equals(fft)) return true; } foundFormTypes.add(f); } } } } return false; }
/** * @param formField * @param method */ protected void checkNonMultiConsistency(FormField formField, String method) { checkListRangeConsistency(formField); if (formField.getType() != null) { switch (formField.getType()) { case hidden: case jid_multi: case list_multi: case text_multi: throw new ValidationConsistencyException(String.format( "Field type '%1$s' is not consistent with validation method '%2$s'.", formField.getType(), method)); default: break; } } }
@Test public void validateRoomWithForm() { DataForm dataForm = new DataForm(DataForm.Type.result); FormField desc = new FormField("muc#roominfo_description"); desc.addValue("The place for all good witches!"); dataForm.addField(desc); FormField subject = new FormField("muc#roominfo_subject"); subject.addValue("Spells"); dataForm.addField(subject); FormField occupants = new FormField("muc#roominfo_occupants"); occupants.addValue("3"); dataForm.addField(occupants); DiscoverInfo discoInfo = new DiscoverInfo(); discoInfo.addExtension(dataForm); RoomInfo roomInfo = new RoomInfo(discoInfo); assertEquals("The place for all good witches!", roomInfo.getDescription()); assertEquals("Spells", roomInfo.getSubject()); assertEquals(3, roomInfo.getOccupantsCount()); }
@Test public void test() throws XmlPullParserException, IOException, SmackException { //Build a Form DataForm df = new DataForm(DataForm.Type.submit); String instruction = "InstructionTest1"; df.addInstruction(instruction); FormField field = new FormField("testField1"); df.addField(field); assertNotNull( df.toXML()); String output = df.toXML().toString(); assertEquals(TEST_OUTPUT_1, output); XmlPullParser parser = PacketParserUtils.getParserFor(output); df = pr.parse(parser); assertNotNull(df); assertNotNull(df.getFields()); assertEquals(1 , df.getFields().size() ); assertEquals(1 , df.getInstructions().size()); assertNotNull( df.toXML()); output = df.toXML().toString(); assertEquals(TEST_OUTPUT_1, output); }
@Override public void processStanza(Stanza packet) { XMPPConnection conn = getConnection(); conn.removeAsyncStanzaListener(this); IQ iq = (IQ) packet; if (iq.getType() != IQ.Type.result) { finish(XMPPError.Condition.internal_server_error); return; } DataForm response = iq.getExtension("x", "jabber:x:data"); if (response == null) { finish(XMPPError.Condition.internal_server_error); return; } String token = null; FormField field = response.getField("token"); if (field != null) token = field.getValues().get(0); EndpointServer from = Preferences.getEndpointServer(getContext()); finish(token, from != null ? from.toString() : conn.getXMPPServiceDomain().toString()); }
private Stanza prepareKeyPacket() { String privatekey = Base64.encodeToString(mPrivateKeyData, Base64.NO_WRAP); Registration iq = new Registration(); iq.setType(IQ.Type.set); iq.setTo(getConnection().getServiceName()); Form form = new Form(DataForm.Type.submit); // form type: register#privatekey FormField type = new FormField("FORM_TYPE"); type.setType(FormField.Type.hidden); type.addValue("http://kontalk.org/protocol/register#privatekey"); form.addField(type); // private key FormField fieldKey = new FormField("privatekey"); fieldKey.setLabel("Private key"); fieldKey.setType(FormField.Type.text_single); fieldKey.addValue(privatekey); form.addField(fieldKey); iq.addExtension(form.getDataFormToSend()); return iq; }
private Stanza createValidationForm() throws IOException { Registration iq = new Registration(); iq.setType(IQ.Type.set); iq.setTo(mConnector.getConnection().getServiceName()); Form form = new Form(DataForm.Type.submit); FormField type = new FormField("FORM_TYPE"); type.setType(FormField.Type.hidden); type.addValue("http://kontalk.org/protocol/register#code"); form.addField(type); if (mValidationCode != null) { FormField code = new FormField("code"); code.setLabel("Validation code"); code.setType(FormField.Type.text_single); code.addValue(mValidationCode.toString()); form.addField(code); } iq.addExtension(form.getDataFormToSend()); return iq; }
private Packet createRegistrationForm() { Registration iq = new Registration(); iq.setType(IQ.Type.SET); iq.setTo(mConnector.getConnection().getServiceName()); Form form = new Form(Form.TYPE_SUBMIT); FormField type = new FormField("FORM_TYPE"); type.setType(FormField.TYPE_HIDDEN); type.addValue("jabber:iq:register"); form.addField(type); FormField phone = new FormField("phone"); phone.setLabel("Phone number"); phone.setType(FormField.TYPE_TEXT_SINGLE); phone.addValue(mPhone); form.addField(phone); iq.addExtension(form.getDataFormToSend()); return iq; }
/** * Sends a voice request to the MUC. The room moderators usually need to approve this request. * * @throws NotConnectedException * @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 { DataForm form = new DataForm(DataForm.Type.submit); FormField formTypeField = new FormField(FormField.FORM_TYPE); formTypeField.addValue(MUCInitialPresence.NAMESPACE + "#request"); form.addField(formTypeField); FormField requestVoiceField = new FormField("muc#role"); requestVoiceField.setType(FormField.Type.text_single); requestVoiceField.setLabel("Requested role"); requestVoiceField.addValue("participant"); form.addField(requestVoiceField); Message message = new Message(room); message.addExtension(form); connection.sendStanza(message); }
/** * Sets the policy that determines who may associate children with the node. * * @param policy The policy being set */ public void setChildrenAssociationPolicy(ChildrenAssociationPolicy policy) { addField(ConfigureNodeFields.children_association_policy, FormField.Type.list_single); List<String> values = new ArrayList<String>(1); values.add(policy.toString()); setAnswer(ConfigureNodeFields.children_association_policy.getFieldName(), values); }
@Override public String toString() { StringBuilder result = new StringBuilder(getClass().getName() + " Content ["); for (FormField formField : getFields()) { result.append('('); result.append(formField.getVariable()); result.append(':'); StringBuilder valuesBuilder = new StringBuilder(); for (String value : formField.getValues()) { if (valuesBuilder.length() > 0) result.append(','); valuesBuilder.append(value); } if (valuesBuilder.length() == 0) valuesBuilder.append("NOT SET"); result.append(valuesBuilder); result.append(')'); } result.append(']'); return result.toString(); }
private void addField(ConfigureNodeFields nodeField, FormField.Type type) { String fieldName = nodeField.getFieldName(); if (getField(fieldName) == null) { FormField field = new FormField(fieldName); field.setType(type); addField(field); } }
/** * Sets the list of {@link PresenceState} for which an entity wants * to receive notifications. * * @param stateValues The list of states */ public void setShowValues(Collection<PresenceState> stateValues) { ArrayList<String> values = new ArrayList<String>(stateValues.size()); for (PresenceState state : stateValues) { values.add(state.toString()); } addField(SubscribeOptionFields.show_values, FormField.Type.list_multi); setAnswer(SubscribeOptionFields.show_values.getFieldName(), values); }
private void addField(SubscribeOptionFields nodeField, FormField.Type type) { String fieldName = nodeField.getFieldName(); if (getField(fieldName) == null) { FormField field = new FormField(fieldName); field.setType(type); addField(field); } }
private static String getSingleValue(FormField formField) { List<String> values = formField.getValues(); if (values.isEmpty()) { return ""; } else { return values.get(0); } }
private FormField getStreamMethodField(DataForm form) { for (FormField field : form.getFields()) { if (field.getVariable().equals(STREAM_DATA_FIELD_NAME)) { return field; } } return null; }
private StreamNegotiator getNegotiator(final FormField field) throws NoAcceptableTransferMechanisms { String variable; boolean isByteStream = false; boolean isIBB = false; for (FormField.Option option : field.getOptions()) { variable = option.getValue(); 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 && isIBB) { return new FaultTolerantNegotiator(connection(), byteStreamTransferManager, inbandTransferManager); } else if (isByteStream) { return byteStreamTransferManager; } else { return inbandTransferManager; } }
private StreamNegotiator getOutgoingNegotiator(final FormField field) throws NoAcceptableTransferMechanisms { boolean isByteStream = false; boolean isIBB = false; for (String variable : field.getValues()) { 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 && isIBB) { return new FaultTolerantNegotiator(connection(), byteStreamTransferManager, inbandTransferManager); } else if (isByteStream) { return byteStreamTransferManager; } else { return inbandTransferManager; } }
private DataForm createDefaultInitiationForm() { DataForm form = new DataForm(DataForm.Type.form); FormField field = new FormField(STREAM_DATA_FIELD_NAME); field.setType(FormField.Type.list_single); if (!IBB_ONLY) { field.addOption(new FormField.Option(Bytestream.NAMESPACE)); } field.addOption(new FormField.Option(DataPacketExtension.NAMESPACE)); form.addField(field); return form; }
/** * Return the form field with the given variable name or null. * * @param variableName * @return the form field or null. * @since 4.1 */ public FormField getField(String variableName) { synchronized (fields) { for (FormField field : fields) { if (variableName.equals(field.getVariable())) { return field; } } } return null; }
/** * Adds a new field as part of the form. * * @param field the field to add to the form. */ public void addField(FormField field) { String fieldVariableName = field.getVariable(); if (fieldVariableName != null && getField(fieldVariableName) != null) { throw new IllegalArgumentException("This data form already contains a form field with the variable name '" + fieldVariableName + "'"); } synchronized (fields) { fields.add(field); } }
/** * Returns the hidden FORM_TYPE field or null if this data form has none. * * @return the hidden FORM_TYPE field or null. * @since 4.1 */ public FormField getHiddenFormTypeField() { FormField field = getField(FormField.FORM_TYPE); if (field != null && field.getType() == FormField.Type.hidden) { return field; } return null; }
public CharSequence toXML() { XmlStringBuilder buf = new XmlStringBuilder(); buf.openElement(ELEMENT); // Loop through all the form items and append them to the string buffer for (FormField field : getFields()) { buf.append(field.toXML()); } buf.closeElement(ELEMENT); return buf; }
public void checkConsistency(FormField formField) { checkListRangeConsistency(formField); if (formField.getType() != null) { switch (formField.getType()) { case hidden: case jid_multi: case jid_single: throw new ValidationConsistencyException(String.format( "Field type '%1$s' is not consistent with validation method '%2$s'.", formField.getType(), BasicValidateElement.METHOD)); default: break; } } }
public void checkConsistency(FormField formField) { checkListRangeConsistency(formField); if (formField.getType() != null) { switch (formField.getType()) { case hidden: throw new ValidationConsistencyException(String.format( "Field type '%1$s' is not consistent with validation method '%2$s'.", formField.getType(), OpenValidateElement.METHOD)); default: break; } } }
public void checkConsistency(FormField formField) { checkNonMultiConsistency(formField, METHOD); if (getDatatype().equals(ValidateElement.DATATYPE_XS_STRING)) { throw new ValidationConsistencyException(String.format( "Field data type '%1$s' is not consistent with validation method '%2$s'.", getDatatype(), RangeValidateElement.METHOD)); } }
/** * The <list-range/> element SHOULD be included only when the <field/> is of type "list-multi" and SHOULD be ignored * otherwise. * * @param formField */ protected void checkListRangeConsistency(FormField formField) { ListRange listRange = getListRange(); if (listRange == null) { return; } Long max = listRange.getMax(); Long min = listRange.getMin(); if ((max != null || min != null) && formField.getType() != FormField.Type.list_multi) { throw new ValidationConsistencyException( "Field type is not of type 'list-multi' while a 'list-range' is defined."); } }
@Test public void testValidation() throws XmlPullParserException, IOException, SmackException { //Build a Form DataForm df = new DataForm(DataForm.Type.submit); String instruction = "InstructionTest1"; df.addInstruction(instruction); FormField field = new FormField("testField1"); df.addField(field); ValidateElement dv = new RangeValidateElement("xs:integer","1111", "9999"); field.setValidateElement(dv); assertNotNull( df.toXML()); String output = df.toXML().toString(); assertEquals(TEST_OUTPUT_3, output); XmlPullParser parser = PacketParserUtils.getParserFor(output); df = pr.parse(parser); assertNotNull(df); assertNotNull(df.getFields()); assertEquals(1 , df.getFields().size() ); Element element = df.getFields().get(0).getValidateElement(); assertNotNull(element); dv = (ValidateElement) element; assertEquals("xs:integer" , dv.getDatatype()); assertNotNull( df.toXML()); output = df.toXML().toString(); assertEquals(TEST_OUTPUT_3, output); }
@Test public void testCheckConsistencyFormFieldOpenValidateElement() { FormField field = new FormField("var"); field.setType(FormField.Type.hidden); OpenValidateElement element = new OpenValidateElement(null); try { element.checkConsistency(field); fail("No correct check on consistency"); } catch (ValidationConsistencyException e) { assertEquals("Field type 'hidden' is not consistent with validation method 'open'.", e.getMessage()); } }
@Test public void testCheckConsistencyFormFieldRangeValidateElement() { FormField field = new FormField("var"); field.setType(FormField.Type.text_multi); RangeValidateElement element = new RangeValidateElement("xs:integer",null, "99"); try { element.checkConsistency(field); fail("No correct check on consistency"); } catch (ValidationConsistencyException e) { assertEquals("Field type 'text-multi' is not consistent with validation method 'range'.", e.getMessage()); } }
@Test public void testCheckConsistencyFormFieldRegexValidateElement() { FormField field = new FormField("var"); field.setType(FormField.Type.list_multi); RegexValidateElement element = new RegexValidateElement(null, ".*"); try { element.checkConsistency(field); fail("No correct check on consistency"); } catch (ValidationConsistencyException e) { assertEquals("Field type 'list-multi' is not consistent with validation method 'regex'.", e.getMessage()); } }
private String findField(DataForm form, String name) { FormField field = form.getField(name); if (field != null) { List<String> values = field.getValues(); if (values != null && values.size() > 0) { String value = values.get(0); return value != null && value.trim().length() > 0 ? value : null; } } return null; }
@Override public void processStanza(Stanza packet) { LOGGER.info("response: "+packet); mConn.removeSyncStanzaListener(this); mConn.disconnect(); if (!(packet instanceof IQ)) { LOGGER.warning("response not an IQ packet"); finish(null); return; } IQ iq = (IQ) packet; if (iq.getType() != IQ.Type.result) { LOGGER.warning("ignoring response with IQ type: "+iq.getType()); this.finish(null); return; } DataForm response = iq.getExtension(DataForm.ELEMENT, DataForm.NAMESPACE); if (response == null) { this.finish(null); return; } String token = null; List<FormField> fields = response.getFields(); for (FormField field : fields) { if ("token".equals(field.getVariable())) { token = field.getValues().get(0); break; } } this.finish(token); }