Smack Api Group not working - java

I am trying to create Group using Smack Api
I use the following code
It crashes on muc#roomconfig_roomowners tag
If i remove that line, it works fine, Group creates
But no group is assigned to the current user, no one is owner
public void createGroup() {
MultiUserChat chatRoom = MultiUserChatManager.getInstanceFor(mConnection).getMultiUserChat("room719#conference." + MYSITE);
try {
chatRoom.create("room719");
Form form = chatRoom.getConfigurationForm().createAnswerForm();
form.setAnswer("muc#roomconfig_publicroom", true);
form.setAnswer("muc#roomconfig_roomname", "room719");
// List owners = new ArrayList();
// owners.add("currUser#"+MYSITE);
form.setAnswer("muc#roomconfig_roomowners", Arrays.asList("currUser#"+MYSITE));
form.setAnswer("muc#roomconfig_persistentroom", true);
chatRoom.sendConfigurationForm(form);
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}

This code is working for me, can you try this?
if( !chatRoom.isJoined() ){
chatRoom.createOrJoin("your nickname");
List<String> owners = new ArrayList<String>();
owners.add("currUser#"+MYSITE);
Form form = chatRoom.getConfigurationForm().createAnswerForm();
form.setAnswer("muc#roomconfig_roomname", "your roomname");
form.setAnswer("muc#roomconfig_roomowners", owners);
form.setAnswer("muc#roomconfig_persistentroom", true);
form.setAnswer("muc#roomconfig_publicroom", true);
chatRoom.sendConfigurationForm(form);
}

Related

How do I save the id from chatid with the telegram api

Hello. I'm trying to solve this problem for a while now. For some
reason I keep getting null pointer exception when I try to save a
object in my repository. Below you can see what happens and my
functions.
java.lang.NullPointerException at com.br.einstein.api.service.ApiTelegram.sendMsg(ApiTelegram.java:104)
at
com.br.einstein.api.service.ApiTelegram.onUpdateReceived(ApiTelegram.java:81)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) at
org.telegram.telegrambots.meta.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
at
org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:317)
public void onUpdateReceived(Update update) {
ApiEinstein api = new ApiEinstein();
try {
JsonObject objSession = api.getSessionDetails();
String message = update.getMessage().getText();
api.sendChatRequest(objSession);
List < String > list = new ApiEinstein().ReadChatDetails(objSession);
sendMsg(update.getMessage().getChatId().toString(), list.toString());
new ApiEinstein().SendChatMessage(objSession, message);
api.syncChatSession(objSession);
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void sendMsg(String chatId, String s) {
SendMessage sendMessage = new SendMessage();
// sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId);
sendMessage.setText(s);
long id = Long.valueOf(chatId);
Telegram telegram = new Telegram();
telegram.setChatId(id);
repository.save(telegram);
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} ```

Error while joining MUC room in XMPP(smack)

I am trying to create a multi user chat. I am getting error while joining the room.
Method for creating chat room :
public void createMultiUserChatRoom(String roomName, String nickName) {
// Get the MultiUserChatManager
MultiUserChatManager multiUserChatManager = MultiUserChatManager.getInstanceFor(connection);
// Get a MultiUserChat using MultiUserChatManager
MultiUserChat multiUserChat = multiUserChatManager.getMultiUserChat(roomName+"#conference.localhost");
try {
multiUserChat.create(nickName);
Form form = multiUserChat.getConfigurationForm();
Form submitForm = form.createAnswerForm();
List<FormField> formFieldList = submitForm.getFields();
for (FormField formField : formFieldList) {
if(!FormField.Type.hidden.equals(formField.getType()) && formField.getVariable() != null) {
submitForm.setDefaultAnswer(formField.getVariable());
}
}
submitForm.setAnswer("muc#roomconfig_persistentroom", true);
submitForm.setAnswer("muc#roomconfig_publicroom", true);
multiUserChat.sendConfigurationForm(submitForm);
} catch (Exception e) {
e.printStackTrace();
}
}
Method for joining MUC room :
public void joinMultiUserChatRoom(String userName, String roomName) {
// Get the MultiUserChatManager
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
// Create a MultiUserChat using an XMPPConnection for a room
MultiUserChat multiUserChat = manager.getMultiUserChat(roomName + "#conference.localhost");
DiscussionHistory history = new DiscussionHistory();
history.setMaxStanzas(-1);
try {
multiUserChat.join(userName, "", history, connection.getPacketReplyTimeout());
} catch (Exception e) {
e.printStackTrace();
}
}
Getting list of joined room by user :
public List<String> getJoinedGroupByUserName(String userName) {
// Get the MultiUserChatManager
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
List<String> joinedRooms = null;
try {
// Get the rooms where user3#host.org has joined
joinedRooms = manager.getJoinedRooms(userName+"#conference.localhost");
} catch (Exception e) {
e.printStackTrace();
}
return joinedRooms;
}
While user join the room i get this message : "This room is locked from entry until configuration is confirmed."
Room it's not really available (confirmed) after sending a configuration, the creator has to join after
multiUserChat.sendConfigurationForm(submitForm);
so basically creator must also
multiUserChat.join(username)
(if you don't need to stay inside, perform a muc.leave() after a join)

How to use the ObdRawCommand from pires OBD-II Java API to send custom commands

Does anyone know how I can send custom commands using the ObdRawCommand in pires Java api? I have little to no experience with this api and I have contacted the creator but I haven't gotten any answer yet.
I have searched online for some project that uses the ObdRawCommand to send custom commands but I can't find anything.
So any help is appreciated!
Snippet
public void run() {
OBDcmds();
try {
ModuleVoltageCommand voltageCommand = new ModuleVoltageCommand();
OdbRawCommand command1 = new OdbRawCommand("22 40 28");
while (!Thread.currentThread().isInterrupted()) {
guiHandler(Constants.VOLTAGE_STATUS, 0, voltageCommand.getFormattedResult());
guiHandler(Constants.cmd1_STATUS, 0, command1.getFormattedResult());
Log.d("Log", "Voltage:" + voltageCommand.getFormattedResult());
Log.d("Log", "cmd1:" + command1.getFormattedResult()); //null
try {
voltageCommand.run(mmInStream, mmOutStream);
command1.run(mmInStream, mmOutStream);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("inside catch before while");
}
}
private void OBDcmds() { // execute commands
try {
new EchoOffCommand().run(mmInStream, mmOutStream);
new LineFeedOffCommand().run(mmInStream, mmOutStream);
new TimeoutCommand(125).run(mmInStream, mmOutStream);
new SelectProtocolCommand(ObdProtocols.AUTO).run(mmInStream, mmOutStream); //ISO_15765_4_CAN
new ModuleVoltageCommand().run(mmInStream, mmOutStream);
} catch (Exception e) {
Log.v("OBDcmds", "e");
// handle errors
}
}
I was right about how to send custom commands.
OdbRawCommand command1 = new OdbRawCommand("custom cmd here");

Join existing PeerGroup in JXTA/JXSE

I have a problem using JXSE.
Let's say i have a rendezVous peer and an Edge peer, not on the same local network.
The rendezVous peer create a peerGroup "test", and publish an advertisement in this group with the name "test advertisement"
Let's say i'm sure than my EdgePeer is connected to the rendezVous peer. I can find the existing group "test" with netpeerGroup.getRemoteAdvertisements().
But i don't know how to join this existing group. I tried netpeergroup.newGroup(testAdv), with testAdv = the founded peerGroupAdvertisement.
I can't find the Advertisement "test advertisement" in the "test" PeerGroup.
But if i do all thats things locally, it works. Maybe i don't understand the difference on how jxta works locally and over internet.
here the code for creating or joining a group :
public void addGroup(final String name) {
ModuleImplAdvertisement mAdv = null;
PeerGroup group = null;
temp = null;
defaultGroup.getDiscoveryService().getRemoteAdvertisements(null, DiscoveryService.GROUP,
"Name", name, 1, new DiscoveryListener() {
#Override
public void discoveryEvent(DiscoveryEvent event) {
Enumeration<Advertisement> advs = event.getResponse().getAdvertisements();
while(advs.hasMoreElements()) {
System.out.println("groupe found");
PeerGroupAdvertisement adv = (PeerGroupAdvertisement) advs.nextElement();
System.out.println("group name : " + adv.getName());
try {
temp = defaultGroup.newGroup(adv);
System.out.println("group joined");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
try {
Thread.sleep(10000);
System.out.println("waiting for group ...");
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(temp == null) {
try {
System.out.println("creating new group ..");
mAdv = defaultGroup.getAllPurposePeerGroupImplAdvertisement(); /* Getting the advertisement of implemented modules */
temp = defaultGroup.newGroup(generatePeerGroupID(name), mAdv, name, name); /* creating & publishing the group */
getDefaultGroup().getDiscoveryService().remotePublish(temp.getPeerGroupAdvertisement());
} catch (Exception e) {
e.printStackTrace();
}
}
finally found the problem. You had to start the RendezVous service on each groups, and not only the netPeerGroup.
That's why my software works locally but not on internet.

ObjectMapper append file JSON

Trying to learn about Jackson some, so I'm writing a simple program that reads a file/creates one to store some JSON in it. From the Jackson website I figured out how to read and write from the file, but in the case of my rudimentary program, i'd like to append as well. I'm basically trying to store a list of shopping lists. There is a shopping list object which has store name, amd items for that store.
The trouble is that I cannot figure a way to append another entry to the end of the file (in JSON format). Here is what I am working with so far, you can ignore the first bit it's just a silly console scanner asking for input:
public class JacksonExample {
static ObjectMapper mapper = new ObjectMapper();
static File file = new File("C:/Users/stephen.protzman/Desktop/user.json");
static List<ShoppingList> master = new ArrayList<ShoppingList>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean running = true;
while (running) {
System.out.println("[ 1 ] Add a new shopping list");
System.out.println("[ 2 ] View all shopping lists");
System.out.println("[ 3 ] Save all shopping lists");
int choice = Integer.parseInt(in.nextLine());
switch (choice) {
case 1:
getNewList();
case 2:
display();
case 3:
running = false;
}
}
in.close();
}
public static void getNewList() {
boolean more = true;
String store, temp;
List<String> items = new ArrayList<String>();
Scanner s = new Scanner(System.in);
System.out.println("Enter the store: ");
store = s.nextLine();
System.out.println("Enter each item [If done type 'DONE'] :");
while (more) {
temp = s.nextLine();
if (temp != null) {
if (temp.toUpperCase().equals("DONE")) {
more = false;
} else {
items.add(temp);
}
}
}
save(store, items);
s.close();
}
public static void display() {
try {
ShoppingList list = mapper.readValue(file, ShoppingList.class);
System.out.println(mapper.defaultPrettyPrintingWriter()
.writeValueAsString(list));
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void save(String store, List<String> items) {
//load in old one
try {
ShoppingList list = mapper.readValue(file, ShoppingList.class);
System.out.println(mapper.defaultPrettyPrintingWriter()
.writeValueAsString(list));
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//add to end of older list
ShoppingList tempList = new ShoppingList();
tempList.setStore(store);
tempList.setItems(items);
master.add(tempList);
try {
mapper.writeValue(file, master);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want to keep using ObjectMapper (considering im trying to learn Jackson) I just havent found a way to append yet is all. Any ideas?
To append content, you need to use Streaming API to create JsonGenerator; and then you can give this generator to ObjectMapper to write to. So something like:
JsonGenerator g = mapper.getFactory().createGenerator(outputStream);
mapper.writeValue(g, valueToWrite);
// and more
g.close();
Below method can be used to write objects into a json file in append mode. it first reads your existing json file and adds new java objects to JSON file.
public static void appendWriteToJson() {
ObjectMapper mapper = new ObjectMapper();
try {
// Object to JSON in file
JsonDaoImpl js = new JsonDaoImpl();
URL resourceUrl = js.getClass().getResource("/data/actionbean.json");
System.out.println(resourceUrl);
File file = new File(resourceUrl.toURI());
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true))); // append mode file writer
mapper.writeValue(out, DummyBeanObject);
} catch (Exception e) {
e.printStackTrace();
}
}

Categories

Resources