I'm currently developping a bungeecord plugin for my server but It's two days that I'm searching for a problem and any forum have the answer.
My problem:
I don't want to create a spigot/bukkit plugin that I have to place in all my server.
My problem is that I want that a player that have a permission like VelocityPerm.Legend when he write something on the chat the format is :
PlayerName [LEGEND] What the player write
This is my code :
#EventHandler
public void onChat(ChatEvent e) {
String line = e.getMessage();
if(!line.startsWith("/")){
ProxiedPlayer p = (ProxiedPlayer) e.getSender();
String message = e.getMessage();
if(p.hasPermission("VelocityPerm.Founder")) {
e.setMessage(ChatColor.DARK_RED + "[FOUNDER]: " + ChatColor.WHITE + message);
}
}
}
How to do it ?.
You have to create a bungee event on your bungee plugin like that :
#EventHandler
public void onChat(ChatEvent e) {
ProxiedPlayer p = (ProxiedPlayer) e.getSender();
if(e.isCommand()) { // check if it's a command, to cancel it or not
// here you can manage when it's a command.
// but when we are here, it's NOT a chat message.
} else { // it's a chat message
if(p.hasPermission("VelocityPerm.Legend")) { // check if has permission
e.setMessage("[Legend] " + p.getName() + ": " + ChatColor.WHITE + e.getMessage()); // change message
}
}
}
Don't forget to register your event :
#Override
public void onEnable() {
getProxy().getPluginManager().registerListener(this, new MyChatEvent());
}
I am using Mobile Hub (amazon) in my android project and for sign-in providers i am using cognito and I have their sample code which they provide and I modify the code and the Login with Facebook is working but the issue which I am facing is onSuccess method when user login successfully called twice and I debugg it but I can not Figure it out how to fix that issue.
SplashActivity.java
public class SplashActivity extends AppCompatActivity implements SignInResultHandler {
IdentityManager identityManager;
private LottieAnimationView animationView;
private static final String LOG_TAG = SplashActivity.class.getSimpleName() + " : ";
private final StartupAuthResultHandler authResultHandler = new StartupAuthResultHandler() {
#Override
public void onComplete(final StartupAuthResult authResult) {
identityManager = authResult.getIdentityManager();
if (authResult.isUserSignedIn()) {
// User has successfully signed in with an identity provider.
final IdentityProvider provider = identityManager.getCurrentIdentityProvider();
Logger.d(LOG_TAG + "Signed in with " + provider.getDisplayName());
} else if (authResult.isUserAnonymous()) {
// User has an unauthenticated anonymous (guest) identity, either because the user never previously
// signed in with any identity provider or because refreshing the provider credentials failed.
// Optionally, you can check whether refreshing a previously signed in provider failed.
final StartupAuthErrorDetails errors = authResult.getErrorDetails();
if (errors.didErrorOccurRefreshingProvider()) {
final AuthException providerAuthException = errors.getProviderRefreshException();
Logger.d(LOG_TAG + String.format(
"Credentials for Previously signed-in provider %s could not be refreshed." +
providerAuthException.getProvider().getDisplayName()) +
providerAuthException);
}
Logger.d(LOG_TAG + "Continuing with unauthenticated (guest) identity.");
} else {
// User has no identity because authentication was unsuccessful due to a failure.
final StartupAuthErrorDetails errors = authResult.getErrorDetails();
Logger.e(LOG_TAG + "No Identity could be obtained. Continuing with no identity.",
errors.getUnauthenticatedErrorException());
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
animationView = (LottieAnimationView) findViewById(R.id.animation_view);
identityManager = AWSMobileClient.defaultMobileClient().getIdentityManager();
identityManager.doStartupAuth(this, authResultHandler);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (identityManager.isUserSignedIn()) {
goMain();
} else {
goSignIn();
}
}
}, 2000);
}
#Override
public void onStart() {
super.onStart();
animationView.setProgress(0f);
animationView.playAnimation();
}
#Override
public void onStop() {
super.onStop();
animationView.cancelAnimation();
}
/**
* Go to the main activity.
*/
private void goMain() {
startActivity(new Intent(this, MainActivity.class));
}
private void goSignIn() {
identityManager.signInOrSignUp(this, this);
finish();
}
/* This method is called two times and I also search in code it inoke only one time*/
#Override
public void onSuccess(Activity callingActivity, IdentityProvider provider) {
callingActivity.finish();
if(provider != null) {
IdentityProfile identityProfile = identityManager.getIdentityProfile();
Logger.d(LOG_TAG + " Name : " + identityProfile.getUserName());
Logger.d(LOG_TAG + " Email : " + identityProfile.getUserEmailAddress());
Logger.d(LOG_TAG + " ImageLink : " + identityProfile.getUserImageUrl());
Logger.d(LOG_TAG + " provider : " + provider.getProviderType());
}
goMain();
}
/**
* User cancelled signing in with a provider on the sign-in activity.
* Note: The user is still on the sign-in activity when this call is made.
*
* #param provider the provider the user canceled with.
*/
public void onIntermediateProviderCancel(Activity callingActivity, IdentityProvider provider) {
Logger.d(LOG_TAG + "onIntermediateProviderCancel() called with: callingActivity = " +
"[" + callingActivity + "], provider = [" + provider + "]");
}
/**
* User encountered an error when attempting to sign-in with a provider.
* Note: The user is still on the sign-in activity when this call is made.
*
* #param provider the provider the user attempted to sign-in with that encountered an error.
* #param ex the exception that occurred.
*/
public void onIntermediateProviderError(Activity callingActivity, IdentityProvider provider, Exception ex) {
Logger.d(LOG_TAG + "onIntermediateProviderError() called with: callingActivity = [" + callingActivity + "], " +
"provider = [" + provider + "], errorMesage = [" + ex.getMessage() + "]");
}
#Override
public boolean onCancel(Activity callingActivity) {
return false;
}
}
SignInActivity.java
public class SignInActivity extends AppCompatActivity {
private static final String LOG_TAG = SignInActivity.class.getSimpleName() + " : ";
private SignInManager signInManager;
/**
* SignInProviderResultHandlerImpl handles the final result from sign in.
*/
private class SignInProviderResultHandlerImpl implements SignInProviderResultHandler {
/**
* Receives the successful sign-in result and starts the main activity.
*
* #param provider the identity provider used for sign-in.
*/
#Override
public void onSuccess(final IdentityProvider provider) {
Logger.d(LOG_TAG + String.format("Sign-in with %s succeeded.", provider.getDisplayName()));
// The sign-in manager is no longer needed once signed in.
SignInManager.dispose();
final IdentityManager identityManager = signInManager.getIdentityManager();
final SignInResultHandler signInResultsHandler = signInManager.getResultHandler();
// Load user name and image.
identityManager.loadUserIdentityProfile(provider, new Runnable() {
#Override
public void run() {
// Call back the results handler.
signInResultsHandler.onSuccess(SignInActivity.this, provider);
finish();
}
});
}
/**
* Receives the sign-in result indicating the user canceled and shows a toast.
*
* #param provider the identity provider with which the user attempted sign-in.
*/
#Override
public void onCancel(final IdentityProvider provider) {
Logger.i(LOG_TAG + String.format("Sign-in with %s canceled.", provider.getDisplayName()));
signInManager.getResultHandler().onIntermediateProviderCancel(SignInActivity.this, provider);
}
/**
* Receives the sign-in result that an error occurred signing in and shows a toast.
*
* #param provider the identity provider with which the user attempted sign-in.
* #param ex the exception that occurred.
*/
#Override
public void onError(final IdentityProvider provider, final Exception ex) {
Logger.d(LOG_TAG + String.format("Sign-in with %s caused an error." +
provider.getDisplayName()) + ex);
signInManager.getResultHandler().onIntermediateProviderError(SignInActivity.this, provider, ex);
}
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
List<String> readPermissions = new ArrayList<>();
readPermissions.add("public_profile");
readPermissions.add("email");
loginButton.setReadPermissions(readPermissions);
signInManager = SignInManager.getInstance();
signInManager.setProviderResultsHandler(this, new SignInProviderResultHandlerImpl());
signInManager.initializeSignInButton(IdentityProviderType.FACEBOOK, loginButton);
}
#Override
public void onRequestPermissionsResult(final int requestCode, #NonNull final String permissions[],
#NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
signInManager.handleRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
signInManager.handleActivityResult(requestCode, resultCode, data);
}
#Override
public void onBackPressed() {
if (signInManager != null) {
if (signInManager.getResultHandler().onCancel(this)) {
super.onBackPressed();
// Since we are leaving sign-in via back, we can dispose the sign-in manager, since sign-in was cancelled.
SignInManager.dispose();
}
}
finish();
}
}
I am developing chat application by using Openfire XMPP server. I can text chat between two user. But i want to know Typing status when some one is typing message. So i created a class :-
public class typingStatus implements ChatStateListener {
#Override
public void processMessage(Chat arg0, Message arg1) {
// TODO Auto-generated method stub
}
#Override
public void stateChanged(Chat arg0, ChatState arg1) {
// TODO Auto-generated method stub
System.out.println(arg0.getParticipant() + " is " + arg1.name());
}
}
But i am confuse so that How will it work? I know that i need a packet where i can it in Listener. But i am unable to find that packet.
Please any one suggest, How will it work?
and also what is difference between Smack and asmack?
Thank you!
To enable ChatStateListener you need to create a custom MessageListener Class
public class MessageListenerImpl implements MessageListener,ChatStateListener {
#Override
public void processMessage(Chat arg0, Message arg1) {
System.out.println("Received message: " + arg1);
}
#Override
public void stateChanged(Chat arg0, ChatState arg1) {
if (ChatState.composing.equals(arg1)) {
Log.d("Chat State",arg0.getParticipant() + " is typing..");
} else if (ChatState.gone.equals(arg1)) {
Log.d("Chat State",arg0.getParticipant() + " has left the conversation.");
} else {
Log.d("Chat State",arg0.getParticipant() + ": " + arg1.name());
}
}
}
Then you create MessageListener object
MessageListener messageListener = new MessageListenerImpl();
And then pass this in the create chat method
Chat newChat = chatmanager.createChat(jabber_id_of_friend, messageListener);
what is difference between Smack and asmack? <-- Check This
finally I got the solution. I need to use chat listener along with chat manager and also I need to use in built sendcomposingnotification function. No need to use Messageeventrequestlistener interface or any other custom class for this. I added the following lines,,
connection.getChatManager().addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(final Chat arg0, final boolean arg1) {
// TODO Auto-generated method stub
arg0.addMessageListener(new MessageListener()
{
#Override
public void processMessage(Chat arg0, Message arg1)
{
// TODO Auto-generated method stub
Log.d("TYpe Stat",title[0] + " is typing......");
Toast.makeText(getApplicationContext(),title[0] + " is typing......",Toast.LENGTH_SHORT).show();
}
}
});
}
});
and also need to send notification like this..
mem.sendComposingNotification(etRecipient.getText().toString(), message.getPacketID());
System.out.println("Sending notification");
where mem is type of MessageEventManger.
Ref: http://www.igniterealtime.org/builds/smack/docs/latest/javadoc/org/jivesoftware/smackx/MessageEventManager.html
ChatManager chatManager = ChatManager.getInstanceFor(connection);
Chat chat= chatManager.createChat(to, new ChatStateListener() {
#Override
public void stateChanged(Chat chat, ChatState state) {
switch (state){
case active:
Log.d("state","active");
break;
case composing:
Log.d("state","composing");
break;
case paused:
Log.d("state","paused");
break;
case inactive:
Log.d("state","inactive");
break;
case gone:
Log.d("state","gone");
break;
}
}
#Override
public void processMessage(Chat chat, Message message) {
Log.d("processMessage","processMessage");
}
});
use this code.hope so will work
i am using chat state listener :
Chat chat = chatManager.createChat(jid,
new ChatStateChangedListener());
bind the chatstatelistener with each jid like above , then :
public class ChatStateChangedListener implements ChatStateListener {
public ChatStateChangedListener() {
printLog("Chat State Changed Listner Constructor");
}
#Override
public void processMessage(Chat arg0, Message arg1) {
}
#Override
public void stateChanged(Chat chat, ChatState state) {
if (state.toString().equals(ChatState.composing.toString())) {
tvLastSeen.setText("Typing...");
} else if (state.toString().equals(ChatState.paused.toString())) {
tvLastSeen.setText("paused...");
} else {
tvLastSeen.setText("nothing");
}
}
}
}
Create On Class MMessageListener to listen incoming messages
private class MMessageListener implements MessageListener, ChatStateListener {
public MMessageListener(Context contxt) {
}
#Override
public void stateChanged(Chat chat, ChatState chatState) {
mStatus = "Online";
if (ChatState.composing.equals(chatState)) {
mStatus = chat.getParticipant() + " is typing..";
Log.d("Chat State", chat.getParticipant() + " is typing..");
} else if (ChatState.gone.equals(chatState)) {
Log.d("Chat State", chat.getParticipant() + " has left the conversation.");
mStatus = chat.getParticipant() + " has left the conversation.";
} else if (ChatState.paused.equals(chatState)){
Log.d("Chat State", chat.getParticipant() + ": " + chatState.name());
mStatus = "Paused";
}else if (ChatState.active.equals(chatState)){
mStatus = "Online";
}
// do whatever you want to do once you receive status
}
#Override
public void processMessage(Message message) {
}
#Override
public void processMessage(Chat chat, Message message) {
}
}
Add Listener to your chat object
Chat Mychat = ChatManager.getInstanceFor(connection).createChat(
"user2#localhost"),
mMessageListener);
Send status to receiving user on edittext text change
ChatStateManager.getInstance(connection).setCurrentState(ChatState.composing, Mychat);
This works fine for me.
Your or another xmpp client which you use, should sending chat state for You can catch the state.
Like This;
try {
ChatStateManager.getInstance(GlobalVariables.xmppManager.connection).setCurrentState(ChatState.composing, chat);
} catch (XMPPException e) {
e.printStackTrace();
}
or
try {
ChatStateManager.getInstance(GlobalVariables.xmppManager.connection).setCurrentState(ChatState.gone, chat);
} catch (XMPPException e) {
e.printStackTrace();
}
However you can get it from ProcessPacket also.
there you will get a Message object, after you can extract xml portion from there and handle them its contain specific chatstate or not.
Message message = (Message) packet;
String msg_xml = message.toXML().toString();
if (msg_xml.contains(ChatState.composing.toString())) {
//handle is-typing, probably some indication on screen
} else if (msg_xml.contains(ChatState.paused.toString())) {
// handle "stopped typing"
} else {
// normal msg
}
now handle as per your requirement.
Just add ChatStateManager after ChatManager intalization:
chatManager = ChatManager.getInstanceFor(getXmpptcpConnection());
ChatStateManager.getInstance(getXmpptcpConnection());
Then you need to add ChatStateListener during createChat(to,chatMesageListener):
chatManager.createChat(message.getTo(), chatMessageListener).sendMessage(message);
private ChatStateListener chatMessageListener = new ChatStateListener() {
#Override
public void stateChanged(Chat chat, ChatState state) {
//State Change composing,active,paused,gone,etc
Log.d(TAG, "ChatStateListener:::stateChanged -> " + chat.toString() + " \n -> " + state.toString());
}
#Override
public void processMessage(Chat chat, Message message) {
//Incoming Message
Log.d(TAG, "ChatStateListener:::processMessage -> " + chat.toString() + " \n -> " + message.toString());
}
};
I used cometd to realize notification push, but i found out the following issue :
After log in the system, at the beginning, the client can receive message from server, but after wait pretty long time or do some other operation, the client may not receive message from server any more. Did anyone else encountered this problem? Thanks in Advance.
Blow is my code :
1. Client Code
var cometd = dojox.cometd;cometd.websocketEnabled = false;
cometd.init(url);
cometd.subscribe("/foo/new", function(message) {
......The business logic......
}
);
2. The ServletContextAttributeListener that integrate with AbstractService
public class BayeuxInitializerListener implements ServletContextAttributeListener {
private static final String CLIENT_CHANNEL = "/foo/new";
#Override
public void attributeAdded(ServletContextAttributeEvent event) {
if(BayeuxServer.ATTRIBUTE.equals(event.getName())) {
BayeuxServer bayeuxServer = (BayeuxServer) event.getValue();
boolean isCreated = bayeuxServer.createIfAbsent(CLIENT_CHANNEL, new ConfigurableServerChannel.Initializer() {
#Override
public void configureChannel(ConfigurableServerChannel channel) {
channel.setPersistent(true);
}
});
new MyService(bayeuxServer);
}
}
3. Service
public class MyService extends AbstractService {
private static final Logger logger = Logger.getLogger(MyService .class);
private static final String CLIENT_CHANNEL = "/foo/new";
private static final String LISTENER_CHANNEL = "/service/notification";
public MyService(BayeuxServer bayeuxServer) {
super(bayeuxServer, "notification");
this.addService(LISTENER_CHANNEL, "processNotification");
}
public void processNotification(ServerSession serverSession, Map<String, Object> data) {
LocalSession localSession = this.getLocalSession();
if(logger.isDebugEnabled()) {
logger.debug("Local Session : " + localSession.getId() + ".");
}
ServerChannel serverChannel = this.getBayeux().getChannel(CLIENT_CHANNEL)
Set<ServerSession> subscribers = serverChannel.getSubscribers();
if(0 == subscribers.size()) {
logger.info("There are no subcribers for " + CLIENT_CHANNEL + ".");
}
for(ServerSession subscriber : subscribers) {
logger.info("The subscriber for " + CLIENT_CHANNEL + " : " + subscriber.getId() + ".");
}
serverChannel.publish(localSession, data, null);
}
Here is my code, how do I use oauth to get the data such as user_id or first and last name of the user and sign them to fields? Should I implement them in the onSuccess method?
private void addFacebookAuth(){
loginButton.addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
final AuthRequest req = new AuthRequest(FACEBOOK_AUTH_URL, FACEBOOK_APP_ID).withScopes(
FACEBOOK_EMAIL_SCOPE,
FACEBOOK_BIRTHDAY_SCOPE,
FACEBOOK_USERID_SCOPE,
FACEBOOK_USER_LAST_NAME_SCOPE,
FACEBOOK_USER_FIRST_NAME_SCOPE).withScopeDelimiter(",");
AUTH.login(req, new Callback<String, Throwable>(){
#Override
public void onFailure(Throwable reason) {
Window.alert("Error:\n" + reason.getMessage());
}
#Override
public void onSuccess(String token) {
// Window.alert("Got an OAuth token:\n" + token + "\n"
// + "Token expires in " + AUTH.expiresIn(req) + " ms\n");
RootPanel.get().remove(loginButton);
}
});
}
});
RootPanel.get().add(loginButton);
}