Why is my google app engine project not sending an email? - java

I have uploaded a test html page and servlet following this article exactly. This works and will send me an email. However, when I copy this code almost exactly into my SendEmail method in the code shown below it does not send an email. I know when I run this locally that it gets to the SendEmail method just fine (but you cannot send emails using the development server in GAE). When I deploy it there are no errors on the page or in the logs so it plain old seems like it is just not sending the email. Anyone see a reason why?
public class EmailService {
private static SimpleDateFormat dateFormatter = new SimpleDateFormat ("MM/dd/yyyy");
public static void SendDeadlineEmails() {
PersistenceManager pm = getPersistenceManager();
try {
List<DeadlineEmailObject> studentsWithDeadlineToday = populateEmailList(pm);
sendEmails(studentsWithDeadlineToday);
} finally {
pm.close();
}
}
private static List<DeadlineEmailObject> populateEmailList(PersistenceManager pm) {
List<Student> students = getStudents(pm);
List<DeadlineEmailObject> studentsWithDeadlineToday = new ArrayList<DeadlineEmailObject>();
String today = dateFormatter.format(System.currentTimeMillis());
for(Student student : students) {
Set<Charge> charges = student.getCharges();
if(charges != null) {
for(Charge charge : charges) {
String deadline = dateFormatter.format(charge.getDeadline());
if(deadline.equals(today)) {
studentsWithDeadlineToday.add(new DeadlineEmailObject(student, charge));
}
}
}
}
return studentsWithDeadlineToday;
}
#SuppressWarnings("unchecked")
private static List<Student> getStudents(PersistenceManager pm) {
return (List<Student>) pm.newQuery(Student.class).execute();
}
private static void sendEmails(List<DeadlineEmailObject> studentsWithDeadlineToday) {
for(DeadlineEmailObject emailObj : studentsWithDeadlineToday) {
sendEmail(emailObj);
System.out.println("Student: " + emailObj.getStudent().getFullName() + "\nAmount: " + emailObj.getCharge().getAmount() +
"\nDeadline: " + dateFormatter.format(emailObj.getCharge().getDeadline()));
}
}
private static void sendEmail(DeadlineEmailObject emailObj) {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("njbuwm#gmail.com", "Admin"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(emailObj.getStudent().getEmail(), emailObj.getStudent().getFullName()));
msg.setSubject("Deadline Reached");
msg.setText(buildMessage(emailObj));
Transport.send(msg);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String buildMessage(DeadlineEmailObject emailObj) {
String email = "";
email += "Dear " + emailObj.getStudent().getFullName() + " ,\n";
email += "You owe us money. This much: $" + emailObj.getCharge().getAmount() + ".\n";
email += "For this reason: " + emailObj.getCharge().getReason() + ".\n";
email += "The deadline is today and I advise you to pay it or you will be deported to Idontpaymybills Island forever.\n";
email += "Thank you,\n Automated Emailer";
return email;
}
private static PersistenceManager getPersistenceManager() {
return JDOHelper.getPersistenceManagerFactory("transactions-optional").getPersistenceManager();
}
}

Change your call to setFrom() to use an email address permitted in the Developers Guide:
To set the sender address, the app calls the setFrom() method on the
MimeMessage object. The sender address must be one of the following
types:
The address of a registered administrator for the application
The address of the user for the current request signed in with a Google Account. You can determine the current user's email address with the Users API. The user's account must be a Gmail account, or be on a domain managed by Google Apps.
Any valid email receiving address for the app (such as xxx#APP-ID.appspotmail.com).

Related

Android management API service file allocation

I am testing android managment API using localhost as call back url. I followed each and every step following this url Android Management API Sample.
Now i m stuck on place.. according to this guide, i download the json file from service account. Now i copy that json file and save in app folder of my project.
This is my enterprise.json file
Screenshot of json file in android studio
and i just give folder location as enterprise.json in location string
This is my code
private static final String PROJECT_ID = "enterprise-271814";
private static final String SERVICE_ACCOUNT_CREDENTIAL_FILE =
"enterprise.json";
private static final String POLICY_ID = "samplePolicy";
/** The package name of the COSU app. */
private static final String COSU_APP_PACKAGE_NAME =
"com.ariaware.devicepoliceycontroller";
/** The OAuth scope for the Android Management API. */
private static final String OAUTH_SCOPE =
"https://www.googleapis.com/auth/androidmanagement";
private static final String APP_NAME = "Device Policey Controller";
private final AndroidManagement androidManagementClient;
public Sample(AndroidManagement androidManagementClient) {
this.androidManagementClient = androidManagementClient;
}
public void run() throws IOException {
// Create an enterprise. If you've already created an enterprise, the
// createEnterprise call can be commented out and replaced with your
// enterprise name.
String enterpriseName = createEnterprise();
System.out.println("Enterprise created with name: " + enterpriseName);
// Set the policy to be used by the device.
setPolicy(enterpriseName, POLICY_ID, getCosuPolicy());
// Create an enrollment token to enroll the device.
String token = createEnrollmentToken(enterpriseName, POLICY_ID);
System.out.println("Enrollment token (to be typed on device): " + token);
// List some of the devices for the enterprise. There will be no devices for
// a newly created enterprise, but you can run the app again with an
// existing enterprise after enrolling a device.
List<Device> devices = listDevices(enterpriseName);
for (Device device : devices) {
System.out.println("Found device with name: " + device.getName());
}
// If there are any devices, reboot one.
if (devices.isEmpty()) {
System.out.println("No devices found.");
} else {
rebootDevice(devices.get(0));
}
}
public static AndroidManagement getAndroidManagementClient()
throws IOException, GeneralSecurityException {
try (FileInputStream input =
new FileInputStream(SERVICE_ACCOUNT_CREDENTIAL_FILE)) {
GoogleCredential credential =
GoogleCredential.fromStream(input)
.createScoped(Collections.singleton(OAUTH_SCOPE));
return new AndroidManagement.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
credential)
.setApplicationName(APP_NAME)
.build();
}
}
private String createEnterprise() throws IOException {
// Initiate signup process.
System.out.println("Creating signup URL...");
SignupUrl signupUrl =
androidManagementClient
.signupUrls()
.create()
.setProjectId(PROJECT_ID)
.setCallbackUrl("https://localhost:9999")
.execute();
System.out.print(
"To sign up for a new enterprise, open this URL in your browser: ");
System.out.println(signupUrl.getUrl());
System.out.println(
"After signup, you will see an error page in the browser.");
System.out.print(
"Paste the enterpriseToken value from the error page URL here: ");
String enterpriseToken =
new BufferedReader(new InputStreamReader(System.in)).readLine();
// Create the enterprise.
System.out.println("Creating enterprise...");
return androidManagementClient
.enterprises()
.create(new Enterprise())
.setProjectId(PROJECT_ID)
.setSignupUrlName(signupUrl.getName())
.setEnterpriseToken(enterpriseToken)
.execute()
.getName();
}
private Policy getCosuPolicy() {
List<String> categories = new ArrayList<>();
categories.add("android.intent.category.HOME");
categories.add("android.intent.category.DEFAULT");
return new Policy()
.setApplications(
Collections.singletonList(
new ApplicationPolicy()
.setPackageName(COSU_APP_PACKAGE_NAME)
.setInstallType("FORCE_INSTALLED")
.setDefaultPermissionPolicy("GRANT")
.setLockTaskAllowed(true)))
.setPersistentPreferredActivities(
Collections.singletonList(
new PersistentPreferredActivity()
.setReceiverActivity(COSU_APP_PACKAGE_NAME)
.setActions(
Collections.singletonList("android.intent.action.MAIN"))
.setCategories(categories)))
.setKeyguardDisabled(true)
.setStatusBarDisabled(true);
}
private void setPolicy(String enterpriseName, String policyId, Policy policy)
throws IOException {
System.out.println("Setting policy...");
String name = enterpriseName + "/policies/" + policyId;
androidManagementClient
.enterprises()
.policies()
.patch(name, policy)
.execute();
}
private String createEnrollmentToken(String enterpriseName, String policyId)
throws IOException {
System.out.println("Creating enrollment token...");
EnrollmentToken token =
new EnrollmentToken().setPolicyName(policyId).setDuration("86400s");
return androidManagementClient
.enterprises()
.enrollmentTokens()
.create(enterpriseName, token)
.execute()
.getValue();
}
private List<Device> listDevices(String enterpriseName) throws IOException {
System.out.println("Listing devices...");
ListDevicesResponse response =
androidManagementClient
.enterprises()
.devices()
.list(enterpriseName)
.execute();
return response.getDevices() ==null
? new ArrayList<Device>() : response.getDevices();
}
private void rebootDevice(Device device) throws IOException {
System.out.println(
"Sending reboot command to " + device.getName() + "...");
Command command = new Command().setType("REBOOT");
androidManagementClient
.enterprises()
.devices()
.issueCommand(device.getName(), command)
.execute();
}
Moreover i m using android management api for the first time and i dont know its proper implementation. Anyone who has experience on this kinllt guide me a little bit. I found a lot about this but i didn't found any userful tutorial
For Android, you have to store the service account file either in the assets folder or raw folder.
This thread provides code on a number of ways to load the json data into an InputStream depending on the location you selected.

How to assign roles with a Discord bot made in Java?

I'm trying to get my Meeseeks bot to assign and remove roles on discord for my personal server. I'm not all too familiar with the special methods and commands, and I've had no luck looking for it!
This is my code right now;
package discord.meeseeksBot;
import discord.meeseeksBot.Ref2;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.MessageChannel;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
public class App extends ListenerAdapter
{
public static void main(String[] args) throws Exception
{
JDA jda = new
JDABuilder(AccountType.BOT).setToken(Ref2.token).buildBlocking();
jda.addEventListener(new App());
}
#Override
public void onMessageReceived(MessageReceivedEvent evt)
{
User objUser = evt.getAuthor();
MessageChannel objMsgCh = evt.getChannel();
Message objMsg = evt.getMessage();
//the prefix to which the bot responds to is "Mr.Meeseeks, "
if(objMsg.getContentRaw().equalsIgnoreCase(Ref2.prefix+"I need
help"))
{
objMsgCh.sendMessage("Hi, " + objUser.getAsMention() + ", " + "
I'm Mr.Meeseeks! Look at me! How can I help?").queue();
objMsgCh.sendMessage("You can tell me to **ADD** you to a role,
or **REMOVE** you from a role!").queue();
}
}
}
I'm working to get the bot to where he'll reply to "Mr.Meeseeks, I need help"
with a list of title roles (these roles serve no hierarchical purpose, nor do they appear separately from online members!) you can choose from, and apply to yourself. I'd also like him to be able to remove yourself from a role.
And example for what I had in mind was a role for gender pronouns, (i.e. "she/her" or "he/him") so that when a profile is clicked on in the server, you'd be able to see what they'd be called.
So you could say, "Mr.Meeseeks, add me to "she/her" pronouns!" and he'd do that for you, or "Mr.Meeseeks, remove me from "she/her" pronouns!".
I can't seem to figure it out for Java.
I am not too familiar with JDA, as Discord4J is better, but I can point you in the right direction.
You want to use regex to test for "Mr", "Meeseeks", "add", and "me" all in the same message. Then you can test for the gender pronouns:
#Override
public void onMessageReceived(MessageReceivedEvent evt) {
User objUser = evt.getAuthor();
MessageChannel objMsgCh = evt.getChannel();
Message objMsg = evt.getMessage();
String content = objMsg.getContentRaw();
Guild guild = evt.getGuild();
//the prefix to which the bot responds to is "Mr.Meeseeks, "
if (objMsg.getContentRaw().equalsIgnoreCase(Ref2.prefix + "I need help")) {
objMsgCh.sendMessage("Hi, " + objUser.getAsMention() + ", " + " I'm Mr.Meeseeks! Look at me! How can I help?").queue();
objMsgCh.sendMessage("You can tell me to **ADD** you to a role, or **REMOVE** you from a role!").queue();
// Test for "Mr", "Meeseeks", "add", and "me".
} else if (content.matches("^(?=.*\\badd\\b)(?=.*\\bme\\b)(?=.*\\bto\\b)(?=.*\\bMr\\b)(?=.*\\bMeeseeks\\b).+")) {
// Test for pronouns (Assuming your roles names are "he/him" and "she/her")
Role group = content.matches("((she)|(her))") ? guild.getRolesByName("she/her", true).get(0) :
content.matches("((he)|(him))") ? guild.getRolesByName("he/him", true).get(0) : null;
if (group == null) {
// Let the user know if they used an invalid pronoun.
objMsgCh.sendMessage("Sorry " + objUser.getAsMention() + ", I can't find that role!").queue();
} else {
// Assign the role.
guild.getController().addRolesToMember​(guild.getMember(objUser), group);
objMsgCh.sendMessage("Added " + objUser.getAsMention() + " to " + group.getName() + "!").queue();
}
}
}

How to get user credentials from request?

I am working on Restlet tutorial example concerning coarse-grained authorization:
public class MyApiWithRoleAuthorization extends Application {
//Define role names
public static final String ROLE_USER = "user";
public static final String ROLE_OWNER = "owner";
#Override
public Restlet createInboundRoot() {
//Create the authenticator, the authorizer and the router that will be protected
ChallengeAuthenticator authenticator = createAuthenticator();
RoleAuthorizer authorizer = createRoleAuthorizer();
Router router = createRouter();
Router baseRouter = new Router(getContext());
//Protect the resource by enforcing authentication then authorization
authorizer.setNext(Resource0.class);
authenticator.setNext(baseRouter);
//Protect only the private resources with authorizer
//You could use several different authorizers to authorize different roles
baseRouter.attach("/resourceTypePrivate", authorizer);
baseRouter.attach("/resourceTypePublic", router);
return authenticator;
}
private ChallengeAuthenticator createAuthenticator() {
ChallengeAuthenticator guard = new ChallengeAuthenticator(
getContext(), ChallengeScheme.HTTP_BASIC, "realm");
//Create in-memory users with roles
MemoryRealm realm = new MemoryRealm();
User user = new User("user", "user");
realm.getUsers().add(user);
realm.map(user, Role.get(this, ROLE_USER));
User owner = new User("owner", "owner");
realm.getUsers().add(owner);
realm.map(owner, Role.get(this, ROLE_OWNER));
//Attach verifier to check authentication and enroler to determine roles
guard.setVerifier(realm.getVerifier());
guard.setEnroler(realm.getEnroler());
return guard;
}
private RoleAuthorizer createRoleAuthorizer() {
//Authorize owners and forbid users on roleAuth's children
RoleAuthorizer roleAuth = new RoleAuthorizer();
roleAuth.getAuthorizedRoles().add(Role.get(this, ROLE_OWNER));
roleAuth.getForbiddenRoles().add(Role.get(this, ROLE_USER));
return roleAuth;
}
private Router createRouter() {
//Attach Server Resources to given URL
Router router = new Router(getContext());
router.attach("/resource1/", Resource1.class);
router.attach("/resource2/", Resource2.class);
return router;
}
public static void main(String[] args) throws Exception {
//Attach application to http://localhost:9000/v1
Component c = new Component();
c.getServers().add(Protocol.HTTP, 9000);
c.getDefaultHost().attach("/v1", new MyApiWithRoleAuthorization());
c.start();
}
}
I create a class for checking user credentials:
public class Resource1 extends ServerResource{
#Get
public String represent() throws Exception {
User user = getRequest().getClientInfo().getUser();
String identifier = user.getIdentifier();
char[] pass = user.getSecret();
return this.getClass().getSimpleName() + " found ! User: " + identifier +
"; password = " + charArrayToString(pass) ;
}
private String charArrayToString(char[] chars ) {
String result = "";
for (char c : chars){
result += c;
}
return result;
}
}
When I go to resource http://localhost:9000/v1/resourceTypePublic/resource1/ the application asks for credentials and I input "user", "user" (or "owner", "owner"). But I get internal server error. The reason is that variable pass in return statement
return this.getClass().getSimpleName() + " found ! User: " + identifier +
"; password = " + charArrayToString(pass) ;
has null value. The statement without this variable works ok:
return this.getClass().getSimpleName() + " found ! User: " + identifier;
and returns user login. But what about the secret? Why it returns null value despite the user secret had been inputted?
User object created with statement
User user = getRequest().getClientInfo().getUser();
does not contain information about password despite it has a field secret. There is another way to get user credentials:
char[] pass = getChallengeResponse().getSecret();

Java - OpenID (Login with Steam)

I have recently had to some trouble trying to get OpenID to work in Java (servlet). I'm trying to make a user able to login to my website using their Steam account. I've tried mutliple libraries but some of them are outdated and for others is almost no documentation available so the library I'm trying right now is JOpenID. It works as expected until I need to verify the information sent back by Steam (http://steamcommunity.com/openid). This is my Servlet:
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private OpenIdManager manager;
static final long ONE_HOUR = 3600000L;
static final long TWO_HOUR = ONE_HOUR * 2L;
static final String ATTR_MAC = "openid_mac";
static final String ATTR_ALIAS = "openid_alias";
public LoginServlet() {
super();
}
#Override
public void init() throws ServletException {
super.init();
manager = new OpenIdManager();
manager.setRealm("http://localhost:8080/TestServletProject/LoginServlet");
manager.setReturnTo("http://localhost:8080/TestServletProject/LoginServlet?login=verify");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String login = request.getParameter("login");
if(login != null){
if(login.equals("steam")){
out.print("<h2>Redirecting</h2>");
Endpoint endpoint = manager.lookupEndpoint("http://steamcommunity.com/openid");
Association association = manager.lookupAssociation(endpoint);
request.getSession().setAttribute(ATTR_MAC, association.getRawMacKey());
request.getSession().setAttribute(ATTR_ALIAS, endpoint.getAlias());
String url = manager.getAuthenticationUrl(endpoint, association);
response.sendRedirect(url);
}else if(login.equals("verify")){
checkNonce(request.getParameter("openid.response_nonce"));
byte[] mac_key = (byte[]) request.getSession().getAttribute(ATTR_MAC);
String alias = (String) request.getSession().getAttribute(ATTR_ALIAS);
Authentication authentication = manager.getAuthentication(request, mac_key, alias);
response.setContentType("text/html; charset=UTF-8");
showAuthentication(response.getWriter(), authentication);
return;
}else if(login.equals("logout")){
out.print("<h2>Loggin out</h2>");
}
return;
}
String id = (String) request.getSession().getAttribute("steamid");
if (id != null) {
out.print("<h2>Welcome ");
out.print(id);
out.print("</h2>");
out.print("Logout");
} else {
out.print("Login");
}
}
void showAuthentication(PrintWriter pw, Authentication auth) {
pw.print("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><title>Test JOpenID</title></head><body><h1>You have successfully signed on!</h1>");
pw.print("<p>Identity: " + auth.getIdentity() + "</p>");
pw.print("<p>Email: " + auth.getEmail() + "</p>");
pw.print("<p>Full name: " + auth.getFullname() + "</p>");
pw.print("<p>First name: " + auth.getFirstname() + "</p>");
pw.print("<p>Last name: " + auth.getLastname() + "</p>");
pw.print("<p>Gender: " + auth.getGender() + "</p>");
pw.print("<p>Language: " + auth.getLanguage() + "</p>");
pw.print("</body></html>");
pw.flush();
}
void checkNonce(String nonce) {
// check response_nonce to prevent replay-attack:
if (nonce==null || nonce.length()<20)
throw new OpenIdException("Verify failed.");
// make sure the time of server is correct:
long nonceTime = getNonceTime(nonce);
long diff = Math.abs(System.currentTimeMillis() - nonceTime);
if (diff > ONE_HOUR)
throw new OpenIdException("Bad nonce time.");
if (isNonceExist(nonce))
throw new OpenIdException("Verify nonce failed.");
storeNonce(nonce, nonceTime + TWO_HOUR);
}
private Set<String> nonceDb = new HashSet<String>();
// check if nonce is exist in database:
boolean isNonceExist(String nonce) {
return nonceDb.contains(nonce);
}
// store nonce in database:
void storeNonce(String nonce, long expires) {
nonceDb.add(nonce);
}
long getNonceTime(String nonce) {
try {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.parse(nonce.substring(0, 19) + "+0000")
.getTime();
}
catch(ParseException e) {
throw new OpenIdException("Bad nonce time.");
}
}
}
I'm getting a org.expressme.openid.OpenIdException: Invalidate handle on line 65: Authentication authentication = manager.getAuthentication(request, mac_key, alias);
While doing some research I found out that this had to do with the Assosiaction sent to steam being expired. This is the JOpenID class that causes the OpenIdException: https://github.com/michaelliao/jopenid/blob/master/src/main/java/org/expressme/openid/OpenIdManager.java
Does anybody know how I can get this to work, or alternatively, know a better library to use. I'm quite new to this and I'm not sure if I'm using the right library or if there's better ways to do this.
So for anyone still wondering: I looked into the JOpenID code and it seems like the code in the getAuthentication() method that goes before the code that throws the exception is enough to retrieve the Steam ID (which is what I tried to get from Steam). So instead of Authentication authentication = manager.getAuthentication(request, mac_key, alias); I now just put String identity = request.getParameter("openid.identity");. This returns http://steamcommunity.com/openid/id/76561198206376959, last part being the Steam ID.

MultipleChatUser XMPP asmack join

I am new to this OpenFire and asmack, i want the user to have a functionality of Multi Users Chatting so i searched around and i found MUC i have implemented this for creating a room and sending invitation to other users these works, other user receives the invitation but the other user is not able to join the room.
I am doing this on other user invitation receiving
Here connection is the connection of this user and room is the room name that we getting in invitation.
MultiUserChat muc3 = new MultiUserChat(connection,room);
muc3.join("testbot3");
testbot3 is just some random name.
But this throws 404 error.
Do i need to join the user before sending the invitation i.e if A user sending invitation to B , before invitation sent do A needs to join these users by default to room and then it depends on B to decline or just keep quite.
What i am doing is B receives invitation from A in that InvitationListner of B i am trying to join with the above code.
I have been trying for long now i am not sure what is going wrong, some one can give a sample code of how to do this it would be great help for me.
Thanks
Here is more information on my issue
As i go and check on Openfire i can see the room created by the user and he has been added himself as an owner so i dont think so it would be an issue with room getting created.
May be this can be an issue with room getting locked, as i have read through the room is locked when the room is not completely created , i guess this is an issue with form filling when we create the room, i am not filling in the password in the form can this be an issue ?
Please see the following code below inside the handler i am calling a method "checkInvitation" which does the same as above code posted still i get 404. Can you please tell me what i wrong in my code.
Do the nickname that needs to be added can be anything or it needs to something user specific ?
public void createChatroom(){
MultiUserChat muc = null;
try {
muc = new MultiUserChat(connection, "myroom#conference.localhost");
muc.create("testbot");
// Get the the room's configuration form
Form form = muc.getConfigurationForm();
// Create a new form to submit based on the original form
Form submitForm = form.createAnswerForm();
// Add default answers to the form to submit
for (Iterator fields = form.getFields(); fields.hasNext();) {
FormField field = (FormField) fields.next();
if (!FormField.TYPE_HIDDEN.equals(field.getType()) && field.getVariable() != null) {
// Sets the default value as the answer
submitForm.setDefaultAnswer(field.getVariable());
}
}
// Sets the new owner of the room
List owners = new ArrayList();
owners.add("admin#localhost");
submitForm.setAnswer("muc#roomconfig_roomowners", owners);
// Send the completed form (with default values) to the server to configure the room
muc.sendConfigurationForm(submitForm);
muc.join("d");
muc.invite("b#localhost", "Meet me in this excellent room");
muc.addInvitationRejectionListener(new InvitationRejectionListener() {
public void invitationDeclined(String invitee, String reason) {
// Do whatever you need here...
System.out.println("Initee "+invitee+" reason"+reason);
}
});
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setConnection(XMPPConnection connection) {
this.connection = connection;
if (connection != null) {
// Add a packet listener to get messages sent to us
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message
.getFrom());
Log.i("XMPPClient", "Got text [" + message.getBody()
+ "] from [" + fromName + "]");
messages.add(fromName + ":");
messages.add(message.getBody());
// Add the incoming message to the list view
mHandler.post(new Runnable() {
public void run() {
setListAdapter();
checkInvitation();
}
});
}
}
}, filter);
mHandler.post(new Runnable() {
public void run() {
checkInvitation();
}
});
}
}
The 404 error indicates that:
404 error can occur if the room does not exist or is locked
So, ensure that your room is not locked or existed! The code below is how I join the room when there's an in-comming invitation:
private void setChatRoomInvitationListener() {
MultiUserChat.addInvitationListener(mXmppConnection,
new InvitationListener() {
#Override
public void invitationReceived(Connection connection,
String room, String inviter, String reason,
String unKnown, Message message) {
//MultiUserChat.decline(mXmppConnection, room, inviter,
// "Don't bother me right now");
// MultiUserChat.decline(mXmppConnection, room, inviter,
// "Don't bother me right now");
try {
muc.join("test-nick-name");
Log.e("abc","join room successfully");
muc.sendMessage("I joined this room!! Bravo!!");
} catch (XMPPException e) {
e.printStackTrace();
Log.e("abc","join room failed!");
}
}
});
}
Hope this helps your error!
Edit:this is how I config the room:
/*
* Create room
*/
muc.create(roomName);
// muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
Form form = muc.getConfigurationForm();
Form submitForm = form.createAnswerForm();
for (Iterator fields = form.getFields(); fields.hasNext();) {
FormField field = (FormField) fields.next();
if (!FormField.TYPE_HIDDEN.equals(field.getType())
&& field.getVariable() != null) {
show("field: " + field.getVariable());
// Sets the default value as the answer
submitForm.setDefaultAnswer(field.getVariable());
}
}
List<String> owners = new ArrayList<String>();
owners.add(DataConfig.USERNAME + "#" + DataConfig.SERVICE);
submitForm.setAnswer("muc#roomconfig_roomowners", owners);
submitForm.setAnswer("muc#roomconfig_roomname", roomName);
submitForm.setAnswer("muc#roomconfig_persistentroom", true);
muc.sendConfigurationForm(submitForm);
// submitForm.
show("created room!");
muc.addMessageListener(new PacketListener() {
#Override
public void processPacket(Packet packet) {
show(packet.toXML());
Message mess = (Message) packet;
showMessageToUI(mess.getFrom() + ": " + mess.getBody());
}
});
With this cofiguration, I can join a room easily without password.
You may use the code snippet to join the chat:
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();
}
}
Invite a friend:
/**
* Invites another user to this room.
*
* #param userAddress the address of the user to invite to the room.(one
* may also invite users not on their contact list).
* #param reason a reason, subject, or welcome message that would tell
* the the user why they are being invited.
*/
public void invite(String userAddress, String reason)
{
multiUserChat.invite(userAddress, reason);
}

Categories