I'm trying to make some functional tests for my webapplication that is using Play 2.1.4 and Socialsecure. Before using securesocial the tests where pretty straight forward but now im having troubles figuering out how i can make tests on the secured actions.
#Test
public void createNewNote() {
Result result;
// Should return bad request if no data is given
result = callAction(
controllers.routes.ref.Notes.newNote(),
fakeRequest().withFormUrlEncodedBody(
ImmutableMap.of("title", "", "text",
"")));
assertThat(status(result)).isEqualTo(BAD_REQUEST);
result = callAction(
controllers.routes.ref.Notes.newNote(),
fakeRequest().withFormUrlEncodedBody(
ImmutableMap.of("title", "My note title", "text",
"My note content")));
// Should return redirect status if successful
assertThat(status(result)).isEqualTo(SEE_OTHER);
assertThat(redirectLocation(result)).isEqualTo("/notes");
Note newNote = Note.find.where().eq("title", "My note title")
.findUnique();
// Should be saved to DB
assertNotNull(newNote);
assertEquals("My note title", newNote.title);
assertEquals("My note content", newNote.text);
}
As of right now i got a user in the test yml file:
- !!models.User
id: 1234567890
username: Pingu
provider: Twitter
firstName: Pingu
lastName: Pingusson
email: pingu#note.com
password: password
My user is pretty straight forward...:
#Table(
uniqueConstraints=
#UniqueConstraint(columnNames={"username"}))
#Entity
public class User extends Model {
private static final long serialVersionUID = 1L;
#Id
public String id;
public String provider;
public String firstName;
public String lastName;
public String email;
public String password;
#MinLength(5)
#MaxLength(20)
public String username;
public static Finder<String, User> find = new Finder<String, User>(
String.class, User.class);
public static User findById(String id) {
return find.where().eq("id", id).findUnique();
}
public static User findByEmail(String email) {
return find.where().eq("email", email).findUnique();
}
#Override
public String toString() {
return this.id + " - " + this.firstName;
}
}
and the UserService:
public class UserService extends BaseUserService {
public UserService(Application application) {
super(application);
}
#Override
public void doDeleteExpiredTokens() {
if (Logger.isDebugEnabled()) {
Logger.debug("deleteExpiredTokens...");
}
List<LocalToken> list = LocalToken.find.where().lt("expireAt", new DateTime().toString()).findList();
for(LocalToken localToken : list) {
localToken.delete();
}
}
#Override
public void doDeleteToken(String uuid) {
if (Logger.isDebugEnabled()) {
Logger.debug("deleteToken...");
Logger.debug(String.format("uuid = %s", uuid));
}
LocalToken localToken = LocalToken.find.byId(uuid);
if(localToken != null) {
localToken.delete();
}
}
#Override
//public Identity doFind(UserId userId) {
public Identity doFind(IdentityId identityId){
if (Logger.isDebugEnabled()) {
Logger.debug(String.format("finding by Id = %s", identityId.userId()));
}
User localUser = User.find.byId(identityId.userId());
Logger.debug(String.format("localUser = " + localUser));
if(localUser == null) return null;
SocialUser socialUser = new SocialUser(new IdentityId(localUser.id, localUser.provider),
localUser.firstName,
localUser.lastName,
String.format("%s %s", localUser.firstName, localUser.lastName),
Option.apply(localUser.email),
null,
new AuthenticationMethod("userPassword"),
null,
null,
Some.apply(new PasswordInfo("bcrypt", localUser.password, null))
);
if (Logger.isDebugEnabled()) {
Logger.debug(String.format("socialUser = %s", socialUser));
}
return socialUser;
}
#Override
public Identity doFindByEmailAndProvider(String email, String providerId) {
List<User> list = User.find.where().eq("email", email).eq("provider", providerId).findList();
if(list.size() != 1){
Logger.debug("found a null in findByEmailAndProvider...");
return null;
}
User localUser = list.get(0);
SocialUser socialUser =
new SocialUser(new IdentityId(localUser.email, localUser.provider),
localUser.firstName,
localUser.lastName,
String.format("%s %s", localUser.firstName, localUser.lastName),
Option.apply(localUser.email),
null,
new AuthenticationMethod("userPassword"),
null,
null,
Some.apply(new PasswordInfo("bcrypt", localUser.password, null))
);
return socialUser;
}
#Override
public Token doFindToken(String token) {
if (Logger.isDebugEnabled()) {
Logger.debug("findToken...");
Logger.debug(String.format("token = %s", token));
}
LocalToken localToken = LocalToken.find.byId(token);
if(localToken == null) return null;
Token result = new Token();
result.uuid = localToken.uuid;
result.creationTime = new DateTime(localToken.createdAt);
result.email = localToken.email;
result.expirationTime = new DateTime(localToken.expireAt);
result.isSignUp = localToken.isSignUp;
if (Logger.isDebugEnabled()) {
Logger.debug(String.format("foundToken = %s", result));
}
return result;
}
#Override
public Identity doSave(Identity user) {
if (Logger.isDebugEnabled()) {
Logger.debug("save...!_!");
Logger.debug(String.format("user = %s", user));
}
User localUser = null;
localUser = User.find.byId(user.identityId().userId());
Logger.debug("id = " + user.identityId().userId());
Logger.debug("provider = " + user.identityId().providerId());
Logger.debug("firstName = " + user.firstName());
Logger.debug("lastName = " + user.lastName());
Logger.debug(user.fullName() + "");
Logger.debug("email = " + user.email());
Logger.debug(user.email().getClass() + "");
if (localUser == null) {
Logger.debug("adding new...");
localUser = new User();
localUser.id = user.identityId().userId();
localUser.provider = user.identityId().providerId();
localUser.firstName = user.firstName();
localUser.lastName = user.lastName();
//Temporary solution for twitter which does not have email in OAuth answer
if(!(user.email().toString()).equals("None")){
localUser.email = user.email().get();
}
if(!(user.passwordInfo() + "").equals("None")){
localUser.password = user.passwordInfo().get().password();
}
localUser.save();
} else {
Logger.debug("existing one...");
localUser.id = user.identityId().userId();
localUser.provider = user.identityId().providerId();
localUser.firstName = user.firstName();
localUser.lastName = user.lastName();
//Temporary solution for twitter which does not have email in OAuth answer
if(!(user.email().toString()).equals("None")){
localUser.email = user.email().get();
}
if(!(user.passwordInfo() + "").equals("None")){
localUser.password = user.passwordInfo().get().password();
}
localUser.update();
}
return user;
}
#Override
public void doSave(Token token) {
LocalToken localToken = new LocalToken();
localToken.uuid = token.uuid;
localToken.email = token.email;
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
localToken.createdAt = df.parse(token.creationTime.toString("yyyy-MM-dd HH:mm:ss"));
localToken.expireAt = df.parse(token.expirationTime.toString("yyyy-MM-dd HH:mm:ss"));
} catch (ParseException e) {
Logger.error("UserService.doSave(): ", e);
}
localToken.isSignUp = token.isSignUp;
localToken.save();
}
}
As of my understanding i should in someway set the session so the user is logged in by using the .withsession method on the fakerequest and maybe also set some value on the serverside.
Tried searching the web for examples using securesocial and play but found no tests at all.
How can i login in my user so i can preform the tests?
Best regards
Rawa
Thanks to David Weinbergs comment i was able to solve this after some trail and error. (:
I started out my LocalUser implementation from this reply:
https://stackoverflow.com/a/18589402/1724097
This is how i solved it:
To make unit tests i created a local user in the database, using the test-data.yml file:
- !!models.LocalUser
id: 1234567890
username: Username
provider: userpass
firstName: firstName
lastName: lastName
email: user#example.com
#hash for "password"
password: $2a$10$.VE.rwJFMblRv2HIqhZM5.CiqzYOhhJyLYrKpMmwXar6Vp58U7flW
Then i made a test utils class that create my fakeCookie.
import models.LocalUser;
import play.Logger;
import securesocial.core.Authenticator;
import securesocial.core.IdentityId;
import securesocial.core.SocialUser;
import securesocial.core.PasswordInfo;
import scala.Some;
import securesocial.core.AuthenticationMethod;
import scala.Option;
import scala.util.Right;
import scala.util.Either;
import play.mvc.Http.Cookie;
public class Utils {
public static Cookie fakeCookie(String user){
LocalUser localUser = LocalUser.findByEmail(user);
Logger.debug("Username: " + localUser.username +" - ID: " + localUser.id);
SocialUser socialUser = new SocialUser(new IdentityId(localUser.id, localUser.provider),
localUser.firstName,
localUser.lastName,
String.format("%s %s", localUser.firstName, localUser.lastName),
Option.apply(localUser.email),
null,
new AuthenticationMethod("userPassword"),
null,
null,
Some.apply(new PasswordInfo("bcrypt", localUser.password, null))
);
Either either = Authenticator.create(socialUser);
Authenticator auth = (Authenticator) either.right().get();
play.api.mvc.Cookie scalaCookie = auth.toCookie();
//debug loggig
Logger.debug("Cookie data:");
Logger.debug("Name: " + "Value: " + auth.cookieName() + " | Class: " + auth.cookieName().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("Value: " + "Value: " + scalaCookie.value() + " | Class: " + scalaCookie.value().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("MaxAge: " + "Value: " + scalaCookie.maxAge() + " | Class: " + scalaCookie.maxAge().getClass() + " | Should be type: " + "int");
Logger.debug("Path: " + "Value: " + scalaCookie.path() + " | Class: " + scalaCookie.path().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("Domain: " + "Value: " + scalaCookie.domain() + " | Class: " + auth.cookieDomain().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("Secure: " + "Value: " + auth.cookieSecure() + " | Class: " + "Boolean" + " | Should be type: " + "boolean");
Logger.debug("HttpOnly: " + "Value: " + auth.cookieHttpOnly() + " | Class: " + "Boolean" + " | Should be type: " + "boolean");
// secureSocial doesnt seem to set a maxAge or Domain so i set them myself.
Cookie fakeCookie = new Cookie(auth.cookieName(), scalaCookie.value(), 120, scalaCookie.path(), "None", auth.cookieSecure(), auth.cookieHttpOnly());
return fakeCookie;
}
}
And then i simply use my cookie to in the fakeRequest so im logged in:
Cookie cookie = Utils.fakeCookie("user#example.com");
Result result = callAction(
controllers.routes.ref.yourSampleClass.yourSecuredFucntion(),
fakeRequest().withFormUrlEncodedBody(
ImmutableMap.of("Value", "Some input value")).withCookies(cookie));
// Should return redirect status if successful
assertThat(status(result)).isEqualTo(SEE_OTHER);
assertThat(redirectLocation(result)).isEqualTo("/yourWantedResult");
Hope this helps others!
Related
I want to post new data to server with this JSON:
{
"tgl_Lahir": "1990-12-18 00:00:00",
"nama": "Joe",
"keterangan": "Employee",
"tempatLahir": "Los Angeles",
"noPegawai": "111111",
"golDarah": "0",
"statusNikah": "0",
"hubungans": {
"id": "10"
},
"agama": {
"id_Agama": "1"
},
"jeniskelamin": {
"jenisKelamin": "1"
}
}
Here's my ApiClientPOST.java:
public class ApiClientPOST {
private static Retrofit retrofit = null;
public static Retrofit getClient(String url){
if(retrofit == null){
retrofit = new Retrofit.Builder().baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Here's my APIUtils.java:
public class APIUtils {
private APIUtils(){
};
public static final String API_URL = "IPAddress/employee/family/add";
public static MainInterface getUserService(){
return ApiClientPOST.getClient(API_URL).create(MainInterface.class);
}
}
Here's my familylistresponsePOST.java:
public class familylistresponsePOST {
#SerializedName("noPegawai")
private String noPegawai;
#SerializedName("date_otor")
private Object dateOtor;
#SerializedName("jeniskelamin")
private Jeniskelamin jeniskelamin;
#SerializedName("keterangan")
private String keterangan;
#SerializedName("hubungans")
private Hubungans hubungans;
#SerializedName("tgl_Lahir")
private String tglLahir;
#SerializedName("nama")
private String nama;
#SerializedName("agama")
private Agama agama;
#SerializedName("statusNikah")
private String statusNikah;
#SerializedName("tempatLahir")
private String tempatLahir;
#SerializedName("id")
private int id;
#SerializedName("golDarah")
private String golDarah;
public void setNoPegawai(String noPegawai){
this.noPegawai = noPegawai;
}
public String getNoPegawai(){
return noPegawai;
}
public void setDateOtor(Object dateOtor){
this.dateOtor = dateOtor;
}
public Object getDateOtor(){
return dateOtor;
}
public void setJeniskelamin(Jeniskelamin jeniskelamin){
this.jeniskelamin = jeniskelamin;
}
public Jeniskelamin getJeniskelamin(){
return jeniskelamin;
}
public void setKeterangan(String keterangan){
this.keterangan = keterangan;
}
public String getKeterangan(){
return keterangan;
}
public void setHubungans(Hubungans hubungans){
this.hubungans = hubungans;
}
public Hubungans getHubungans(){
return hubungans;
}
public void setTglLahir(String tglLahir){
this.tglLahir = tglLahir;
}
public String getTglLahir(){
return tglLahir;
}
public void setNama(String nama){
this.nama = nama;
}
public String getNama(){
return nama;
}
public void setAgama(Agama agama){
this.agama = agama;
}
public Agama getAgama(){
return agama;
}
public void setStatusNikah(String statusNikah){
this.statusNikah = statusNikah;
}
public String getStatusNikah(){
return statusNikah;
}
public void setTempatLahir(String tempatLahir){
this.tempatLahir = tempatLahir;
}
public String getTempatLahir(){
return tempatLahir;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setGolDarah(String golDarah){
this.golDarah = golDarah;
}
public String getGolDarah(){
return golDarah;
}
#Override
public String toString(){
return
"ListUserResponse2{" +
"noPegawai = '" + noPegawai + '\'' +
",date_otor = '" + dateOtor + '\'' +
",jeniskelamin = '" + jeniskelamin + '\'' +
",keterangan = '" + keterangan + '\'' +
",hubungans = '" + hubungans + '\'' +
",tgl_Lahir = '" + tglLahir + '\'' +
",nama = '" + nama + '\'' +
",agama = '" + agama + '\'' +
",statusNikah = '" + statusNikah + '\'' +
",tempatLahir = '" + tempatLahir + '\'' +
",id = '" + id + '\'' +
",golDarah = '" + golDarah + '\'' +
"}";
}
}
I've tried to create this method and use it on my Button.setOnClickListener:
public void addFamily(String noPegawai,String agama, String hubungan, String jenisKelamins, String tgl_Lahir, String nama, String keterangan, String tempatLahir, String golDarah, String statusNikah){
SharedPreferences preferences = getSharedPreferences("MyPref",0);
String tokens = preferences.getString("userToken",null);
Call<familylistresponse> call = apiService.addFams(noPegawai,agama, hubungan, jenisKelamins, tgl_Lahir , nama, keterangan, tempatLahir, golDarah, statusNikah, "Bearer" + tokens);
call.enqueue(new Callback<familylistresponse>() {
#Override
public void onResponse(Call<familylistresponse> call, Response<familylistresponse> response) {
// if (response.isSuccessful()){
familylistresponse resultsData = new familylistresponse();
resultsData= response.body();
Toast.makeText(TambahDataKeluarga.this,"Data Berhasil Ditambahkan!" + resultsData, Toast.LENGTH_SHORT).show();
// }
}
#Override
public void onFailure(Call<familylistresponse> call, Throwable t) {
Log.e("ERROR: ", t.getMessage());
}
});
}
This one is my tambah Button:
tambah.setOnClickListener(v -> {
SharedPreferences preferences = getSharedPreferences("MyPref",0);
String noPegawai = preferences.getString("noPegawai",null);
String snopeg = etNoPegawai.getText().toString().trim();
String snama = etNama.getText().toString().trim();
String stmpLahir = etTmptLahir.getText().toString().trim();
String stglLahir = etTglLahir.getText().toString().trim();
String sketerangan = etKeterangan.getText().toString().trim();
String sgoldar = etGoldar.getText().toString().trim();
String sstatusnikah = etStatusNikah.getText().toString().trim();
valueJenisKelamin = jeniskelamin.getSelectedItem().toString();
valueHubungan = spHubungans.getSelectedItem().toString();
valueAgama = spAgama.getSelectedItem().toString();
familylistresponse f = new familylistresponse();
f.setNoPegawai(snopeg);
agamas.setAgama(spAgama.getSelectedItem().toString().trim());
jks.setJenisKelamin(jeniskelamin.getSelectedItem().toString().trim());
hubungans.setHubungan(spHubungans.getSelectedItem().toString().trim());
addFamily(snopeg, valueAgama, valueHubungan, valueJenisKelamin, stglLahir, snama, sketerangan, stmpLahir, sgoldar, sstatusnikah);
Log.d(f.getNama(),f.getGolDarah());
Toast.makeText(TambahDataKeluarga.this,"No pegawai "+ noPegawai + " Nama Pegawai "+ snama+ " Tgl Lahir "+ stglLahir
+ " Agama " + valueAgama
+ " Hubungan " + valueHubungan
+ " Jenis Kelamin " + valueJenisKelamin
+ " Tgl Lahir " + stglLahir
+ " Keterangan " + sketerangan
+ " Tempat Lahir " + stmpLahir
+ " Goldar " + sgoldar
+ " Status Nikah " + sstatusnikah,Toast.LENGTH_LONG).show();
});
The toast says that the data is successfully stored but in fact, it isn't. The toast also says that response.body() is null and there is no error in logcat even in the debugger. Please kindly help me. Thanks in advance for any help
I do not see where you are defining Hubungans, Agama and Jeniskelamin classes although you are using it as datatype inside your familylistresponsePOST.java
After creating these three classes, I hope your issue will be solved.
I'm getting familiar with BitcoinJ. So now there is a function for user that registers for the first time and there should be created address for him. But it doesn't work. It says there is already some money.
// USER HAS NEVER USED COIN_ATLAS ( IT IS THE FIRST TIME )
public void addUser()
{
DBObject dbUser;
WalletAppKit kit = new WalletAppKit(TestNet3Params.get(), new File("."), "forwarding-service-testnet");
params = TestNet3Params.get();
Debug.Log("Wait a bit...");
kit.startAsync();
kit.awaitRunning();
BlockChain chain = null;
my_wallet = kit.wallet(); // Wallet created for that user
try {
chain = new BlockChain(params, my_wallet,
new MemoryBlockStore(params));
} catch (BlockStoreException e) {
e.printStackTrace();
}
PeerGroup peerGroup = new PeerGroup(params, chain);
peerGroup.addPeerDiscovery(new DnsDiscovery(params));
peerGroup.addWallet(my_wallet);
peerGroup.startAsync();
Debug.Log("WALLET: " + my_wallet.currentReceiveAddress());
Debug.Log("WALLET BALANCE: " + my_wallet.getBalance().toFriendlyString());
my_wallet.addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() {
#Override
public void onCoinsReceived(Wallet wallet, Transaction transaction, Coin coin, Coin coin1) {
send("NEW TRANSACTION:");
sendWithMarkdown("FROM: " + wallet.currentReceiveAddress() + " : " + bold(coin1.toFriendlyString()));
Coin value = transaction.getValueSentToMe(wallet);
System.out.println("Received tx for " + value.toFriendlyString() + ": " + transaction);
Futures.addCallback(transaction.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() {
#Override
public void onSuccess(#Nullable TransactionConfidence transactionConfidence) {
send(bold("Transaction confirmed!"));
send(bold(value.toFriendlyString() + " is deposited!"));
}
#Override
public void onFailure(Throwable throwable) {
}
});
}
});
peerGroup.downloadBlockChain();
peerGroup.stopAsync();
dbUser = new BasicDBObject("_id", bot_user.getId())
.append("firstName", bot_user.getFirstName())
.append("password", bot_user.getPassword())
.append("address", my_wallet.currentReceiveAddress().toString())
.append("BTC", (double)my_wallet.getBalance().getValue());
collection.insert(dbUser);
}
There is what I get in output:
WALLET: mtrjbnpq5wDzoywrKqod63tpB7ZUFrr7q5
WALLET BALANCE: 1.21503904 BTC
But if I check this address in blockchain, it shows 0.
So how to create wallet the right way?
I am implementing Chat application just like facebook.
one to one chat is complete with sounds, notifications and message counter.
but at some point during chat I meetup with this error
Here is my ChatSocket.js class
var chatsocket = function() {
var messageReceive = "";
var ws;
var messageSend = function(message) {
var buildMessage = "<div class='row msg_container base_sent'>"
+ "<div class='col-md-10 col-xs-10'> "
+ "<div class='messages msg_sent'>" + "<p>" + message + "</p>"
+ "<time datetime='2009-11-13T20:00'>Timothy • 51 min</time>"
+ "</div>" + "</div>" + "";
var imgMessage = "<div class='col-md-2 col-xs-2 avatar'>"
+ "<img src='http://www.bitrebels.com/wp-content/uploads/2011/02/Original-Facebook-Geek-Profile-Avatar-1.jpg'class='img-responsive ' />"
+ "</div>" + "</div>";
return buildMessage + imgMessage;
};
var messageReceive = function(message) {
var imgMessage = "<div class='row msg_container base_receive'>" +
"<div class='col-md-2 col-xs-2 avatar'>"
+ "<img src='http://www.bitrebels.com/wp-content/uploads/2011/02/Original-Facebook-Geek-Profile-Avatar-1.jpg'class='img-responsive ' />"
+ "</div>";
var buildMessage = "<div class='col-md-10 col-xs-10'> "
+ "<div class='messages msg_receive'>" + "<p>" + message + "</p>"
+ "<time datetime='2009-11-13T20:00'>Timothy • 51 min</time>"
+ "</div>" + "</div>" + "</div>";
return imgMessage + buildMessage;
};
var connect = function() {
var user = $("#user").val();
try{
ws = new WebSocket("ws://localhost:8080/EnterpriceChat/chat/" + user);
} catch(err) {
console.log("error");
}
ws.onmessage = function(event) {
var message = JSON.parse(event.data);
//Refresh the list since there is a user which is online/offline now
if(message.content == 'refreshContact') {
loadUserContactList();
} else {
var idSuffix = getElementIdSuffix(message.from);
var status = createNewChatBox(message.from);
if(!status) {
var msg_panel_id = getMsgPanelId(idSuffix);
$("#"+msg_panel_id).append(messageReceive(message.content));
}
scrollToBottom(message.from);
updateNotification(message.from);
}
};
};
var sendMessage = function(element) {
var inputElementId = element.attr("data-id");
var to = element.attr("data-id-email");
var msg_panel_id = element.attr("data-id-msg-panel");
//Validating the inputs
var content = $("#"+inputElementId).val();
//Reset the input fields
$("#"+inputElementId).val('');
if(!content) {
return;
}
var json = JSON.stringify({
"to" : to,
"content" : content
});
ws.send(json);
$("#"+msg_panel_id).append(messageSend(content));
};
var eventClick = function() {
$('.btn-chat-send').unbind('click');
$('.chat_input').unbind('keypress');
$('.chat_input').unbind('focus');
$('#userListCategory').find('li').unbind('click');
$('.user_list_entry').unbind('click');
$('.btn-chat-send').click(function() {
console.log();
sendMessage($(this));
var to = $(this).closest('.input-group').find('.btn-chat-send').attr("data-id-email");
scrollToBottom(to);
});
$('.chat_input').keypress(function(e) {
if(e.which == 13) {
$(this).closest('.input-group').find('.btn-chat-send').click();
}
});
$('#userListCategory').find('li').click(function() {
var type = $(this).attr("data-id");
$('#userListCategory').attr("data-current-selection", type);
loadUserContactList(type);
});
$('.user_list_entry').click(function() {
var selectedUserEmail = $(this).attr('data-id-email');
createNewChatBox(selectedUserEmail);
var id = getChatWindowId(getElementIdSuffix(selectedUserEmail));
$('#'+id).find('.chat_input').focus();
});
$('.chat_input').focus(function() {
var to = $(this).closest('.input-group').find('.btn-chat-send').attr("data-id-email");
var notificationId = getChatUserNotificationId(getElementIdSuffix(to));
if($('#'+notificationId).text() != '0') {
markMessagesAsRead(to);
}
});
};
return {
initEvent : function() {
connect();
}, initAction : function() {
eventClick();
}
}
}();
I don't know that why I am getting this exception, the exception is null pointer Exception and it's not pointing me to my code,
I have a Question that,
1- What's the role of deflator in websockets and if we face some of them, how to resolve? how to resolve?
and here is my ChatEndPoint.java
package com.chat.config;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.logging.Logger;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.chat.core.dao.ex.SQLException;
import com.chat.core.repository.MessageRepository;
import com.chat.core.repository.impl.MessageRepositoryImpl;
import com.chat.core.util.Constants;
#ServerEndpoint(value = "/chat/{username}", decoders = MessageDecoder.class, encoders = MessageEncoder.class)
public class ChatEndPoint {
private final Logger log = Logger.getLogger(getClass().getName());
private static MessageRepository messageRespoitory = MessageRepositoryImpl.getInstance();
private Session session;
private String username;
private static final Set<ChatEndPoint> chatEndpoints = new CopyOnWriteArraySet<>();
private static HashMap<String, String> users = new HashMap<>();
#OnOpen
public void onOpen(Session session, #PathParam("username") String username) throws IOException, EncodeException {
log.info(session.getId() + " connected!");
this.session = session;
this.username = username;
chatEndpoints.add(this);
users.put(session.getId(), username);
broadcastRefreshContact();
System.out.println("Active endpoints count : " + chatEndpoints.size());
System.out.println("Active endpoints : " + chatEndpoints);
}
#OnMessage
public void onMessage(Session session, Message message) throws IOException, EncodeException {
log.info(message.toString());
System.out.println("onMessage : " + message.toString());
message.setFrom(users.get(session.getId()));
persistMessage(message);
sendMessageToOneUser(message);
}
private static void persistMessage(Message message) {
try {
messageRespoitory.create(message.getFrom(), message.getTo(), message.getContent());
} catch (SQLException e) {
System.out.print("Unable to persist message");
e.printStackTrace();
}
}
#OnClose
public void onClose(Session session) throws IOException, EncodeException {
log.info(session.getId() + " disconnected!");
chatEndpoints.remove(this);
broadcastRefreshContact();
}
#OnError
public void onError(Session session, Throwable throwable) throws IOException, EncodeException {
broadcastRefreshContact();
log.warning(throwable.toString());
}
private static void broadcastRefreshContact() throws IOException, EncodeException {
Message message = new Message();
message.setContent(Constants.REFRESH_CONTACT);
broadcast(message);
}
private static void broadcast(Message message) throws IOException, EncodeException {
for (ChatEndPoint endpoint : chatEndpoints) {
synchronized (endpoint) {
endpoint.session.getBasicRemote().sendObject(message);
}
}
}
private static void sendMessageToOneUser(Message message) throws IOException, EncodeException {
for (ChatEndPoint endpoint : chatEndpoints) {
synchronized (endpoint) {
if (endpoint.session.getId().equals(getSessionId(message.getTo()))) {
endpoint.session.getBasicRemote().sendObject(message);
}
}
}
}
private static String getSessionId(String to) {
if (users.containsValue(to)) {
for (String sessionId : users.keySet()) {
if (users.get(sessionId).equals(to)) {
return sessionId;
}
}
}
return null;
}
public static Set<String> getOnlineUsers() {
Set<String> users = new TreeSet<String>();
for(ChatEndPoint enpoint : chatEndpoints) {
users.add(enpoint.username);
}
return users;
}
#Override
public String toString() {
return "ChatEndPoint [session=" + session + ", username=" + username
+ "]";
}
}
Thanks!!!
I found the root cause for that exception, actually there was a cache maintained at the backend. Which was not getting updated properly when the user did a refresh.
I am new to Google Contact Api. i am trying to retrieve all my contacts using Google Contact API. For this I used Oauth authentication and Google Contact API.
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.gdata.client.Query;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.authn.oauth.OAuthParameters.OAuthType;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.Link;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.contacts.GroupMembershipInfo;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.ExtendedProperty;
import com.google.gdata.data.extensions.Im;
import com.google.gdata.data.extensions.Name;
import com.google.gdata.util.ServiceException;
public class GoogleContactsAccess{
/* This method will authenticate the user credentials passed to it and returns an instance of ContactService class.*/
public ContactsService authenticateId(){
GoogleOAuthParameters oAuthParameters = null;
ContactsService contactService = null;
try{
contactService = new ContactsService("API Project");
oAuthParameters = new GoogleOAuthParameters();
oAuthParameters.setOAuthConsumerKey("ConsumerKey");
oAuthParameters.setOAuthConsumerSecret("ConsumerKey");
oAuthParameters.setScope("https://www.google.com/m8/feeds");
oAuthParameters.setOAuthType(OAuthType.TWO_LEGGED_OAUTH);
oAuthParameters.addCustomBaseParameter("xoauth_requestor_id", "my ID#gmail.com");
contactService.setOAuthCredentials(oAuthParameters,new OAuthHmacSha1Signer());
contactService.getRequestFactory().setHeader("GData-Version", "3.0");
}catch(Exception e){
e.printStackTrace();
}
return contactService;
}
/* This method will print details of all the contacts available in that particular Google account. */
public void printAllContacts(ContactsService myService)throws ServiceException, IOException {
// Request the feed
URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full?v=3.0&alt=json'");
// The query that will retrieve all contacts
Query myQuery = new Query(feedUrl);
ContactFeed resultFeed = myService.getFeed(myQuery, ContactFeed.class);
// Print the results
System.out.println(resultFeed.getTitle().getPlainText());
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
ContactEntry entry = resultFeed.getEntries().get(i);
if (entry.hasName()) {
Name name = entry.getName();
if (name.hasFullName()) {
String fullNameToDisplay = name.getFullName().getValue();
if (name.getFullName().hasYomi()) {
fullNameToDisplay += " (" + name.getFullName().getYomi() + ")";
}
System.out.println("\t\t" + fullNameToDisplay);
} else {
System.out.println("\t\t (no full name found)");
}
if (name.hasNamePrefix()) {
System.out.println("\t\t" + name.getNamePrefix().getValue());
} else {
System.out.println("\t\t (no name prefix found)");
}
if (name.hasGivenName()) {
String givenNameToDisplay = name.getGivenName().getValue();
if (name.getGivenName().hasYomi()) {
givenNameToDisplay += " (" + name.getGivenName().getYomi() + ")";
}
System.out.println("\t\t" + givenNameToDisplay);
} else {
System.out.println("\t\t (no given name found)");
}
if (name.hasAdditionalName()) {
String additionalNameToDisplay = name.getAdditionalName().getValue();
if (name.getAdditionalName().hasYomi()) {
additionalNameToDisplay += " (" + name.getAdditionalName().getYomi() + ")";
}
System.out.println("\t\t" + additionalNameToDisplay);
} else {
System.out.println("\t\t (no additional name found)");
}
if (name.hasFamilyName()) {
String familyNameToDisplay = name.getFamilyName().getValue();
if (name.getFamilyName().hasYomi()) {
familyNameToDisplay += " (" + name.getFamilyName().getYomi() + ")";
}
System.out.println("\t\t" + familyNameToDisplay);
} else {
System.out.println("\t\t (no family name found)");
}
if (name.hasNameSuffix()) {
System.out.println("\t\t" + name.getNameSuffix().getValue());
} else {
System.out.println("\t\t (no name suffix found)");
}
} else {
System.out.println("\t (no name found)");
}
System.out.println("Email addresses:");
for (Email email : entry.getEmailAddresses()) {
System.out.print(" " + email.getAddress());
if (email.getRel() != null) {
System.out.print(" rel:" + email.getRel());
}
if (email.getLabel() != null) {
System.out.print(" label:" + email.getLabel());
}
if (email.getPrimary()) {
System.out.print(" (primary) ");
}
System.out.print("\n");
}
System.out.println("IM addresses:");
for (Im im : entry.getImAddresses()) {
System.out.print(" " + im.getAddress());
if (im.getLabel() != null) {
System.out.print(" label:" + im.getLabel());
}
if (im.getRel() != null) {
System.out.print(" rel:" + im.getRel());
}
if (im.getProtocol() != null) {
System.out.print(" protocol:" + im.getProtocol());
}
if (im.getPrimary()) {
System.out.print(" (primary) ");
}
System.out.print("\n");
}
System.out.println("Groups:");
for (GroupMembershipInfo group : entry.getGroupMembershipInfos()) {
String groupHref = group.getHref();
System.out.println(" Id: " + groupHref);
}
System.out.println("Extended Properties:");
for (ExtendedProperty property : entry.getExtendedProperties()) {
if (property.getValue() != null) {
System.out.println(" " + property.getName() + "(value) = " +
property.getValue());
} else if (property.getXmlBlob() != null) {
System.out.println(" " + property.getName() + "(xmlBlob)= " +
property.getXmlBlob().getBlob());
}
}
Link photoLink = entry.getContactPhotoLink();
String photoLinkHref = photoLink.getHref();
System.out.println("Photo Link: " + photoLinkHref);
if (photoLink.getEtag() != null) {
System.out.println("Contact Photo's ETag: " + photoLink.getEtag());
}
System.out.println("Contact's ETag: " + entry.getEtag());
}
}
public static void main(String args[]){
try {
GoogleContactsAccess googleContactsAccess = new GoogleContactsAccess();
ContactsService contactSrv = googleContactsAccess.authenticateId();
googleContactsAccess.printAllContacts(contactSrv);
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
i tried the above code. i am getting the below exception
java.lang.NullPointerException: No authentication header information
at com.google.gdata.util.AuthenticationException.initFromAuthHeader(AuthenticationException.java:96)
at com.google.gdata.util.AuthenticationException.(AuthenticationException.java:67)
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:608)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:564)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536)
at com.google.gdata.client.Service.getFeed(Service.java:1135)
at com.google.gdata.client.Service.getFeed(Service.java:1077)
at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:676)
at com.google.gdata.client.Service.getFeed(Service.java:1034)
at com.cohere.getcontacts.GoogleContactsAccess.printAllContacts(GoogleContactsAccess.java:59)
at com.cohere.getcontacts.GoogleContactsAccess.main(GoogleContactsAccess.java:197)
so any one help me to resolve the problem thanks in advance
It looks like you are using ConsumerKey as both key and secret in your code :
oAuthParameters.setOAuthConsumerKey("ConsumerKey");
oAuthParameters.setOAuthConsumerSecret("ConsumerKey");
You need to use the correct ConsumerSecret of your app
I have a JSON object like this:
{
"user1": {
"timeSpent": "20.533333333333335h",
"worklog": [
{
"date": "06/26/2013",
"issues": [
{
"issueCode": "COC-2",
"comment": "\ncccccc",
"timeSpent": "20.533333333333335h"
}
],
"dayTotal": "20.533333333333335h"
}
]
},
"admin": {
"timeSpent": "601.1h",
"worklog": [
{
"date": "06/25/2013",
"issues": [
{
"issueCode": "COC-1",
"comment": "",
"timeSpent": "113.1h"
}
],
"dayTotal": "113.1h"
},
{
"date": "06/26/2013",
"issues": [
{
"issueCode": "COC-1",
"comment": "",
"timeSpent": "8h"
},
{
"issueCode": "COC-2",
"comment": "",
"timeSpent": "480h"
}
],
"dayTotal": "488h"
}
]
}
}
and trying to parse it with Gson:
Gson gson = new Gson();
Book responseBean = gson.fromJson(jsonString, Book.class);
But the 'responceBean' is always 'null'
Here are all the other classes:
public class Book {
private List<User> user = new LinkedList<User>();
public List<User> getUser() {
return user;
}
public void setUser(List<User> user) {
this.user = user;
}
}
public class User {
private String timeSpent;
private List<WorkLog> worklogs = new LinkedList<WorkLog>();;
public List<WorkLog> getWorklogs() {
return worklogs;
}
public void setWorklogs(List<WorkLog> worklogs) {
this.worklogs = worklogs;
}
public String getTimeSpent() {
return timeSpent;
}
public void setTimeSpent(String timeSpent) {
this.timeSpent = timeSpent;
}
}
public class WorkLog{
private String date;
private String dayTotal;
private List<Issues> issues;
public String getDate(){
return this.date;
}
public void setDate(String date){
this.date = date;
}
public String getDayTotal(){
return this.dayTotal;
}
public void setDayTotal(String dayTotal){
this.dayTotal = dayTotal;
}
public List<Issues> getIssues(){
return this.issues;
}
public void setIssues(List<Issues> issues){
this.issues = issues;
}
}
public class Issues{
private String comment;
private String issueCode;
private String timeSpent;
public String getComment(){
return this.comment;
}
public void setComment(String comment){
this.comment = comment;
}
public String getIssueCode(){
return this.issueCode;
}
public void setIssueCode(String issueCode){
this.issueCode = issueCode;
}
public String getTimeSpent(){
return this.timeSpent;
}
public void setTimeSpent(String timeSpent){
this.timeSpent = timeSpent;
}
}
This is my latest attempt. Somehow I cannot figure out the right way. Will be very appreciative for any help.
Your JSON model does not match your object model.
You need an intermediate layer to fill the gap: a TypeAdapter.
Moreover there is no naming information for the user.
And finally there is a name mismatch: "worklog" in JSON, "worklogs" in Java.
Here is a fixed version:
Java model:
class User {
private String timeSpent;
#SerializedName("worklog")
private List<WorkLog> worklogs = new LinkedList<WorkLog>();
private String name;
public List<WorkLog> getWorklogs() {
return worklogs;
}
public void setWorklog(List<WorkLog> worklogs) {
this.worklogs = worklogs;
}
public String getTimeSpent() {
return timeSpent;
}
public void setTimeSpent(String timeSpent) {
this.timeSpent = timeSpent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The plumbing to fill the gap:
class BookTypeAdapter implements JsonSerializer<Book>, JsonDeserializer<Book>
{
Gson gson = new Gson();
public JsonElement serialize(Book book, Type typeOfT, JsonSerializationContext context)
{
JsonObject json = new JsonObject();
for (User user : book.getUser())
{
json.addProperty(user.getName(), gson.toJson(user));
}
return json;
}
public Book deserialize(JsonElement element, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
JsonObject json = element.getAsJsonObject();
Book book = new Book();
for (Entry<String, JsonElement> entry : json.entrySet())
{
String name = entry.getKey();
User user = gson.fromJson(entry.getValue(), User.class);
user.setName(name);
book.getUser().add(user);
}
return book;
}
}
And a roundtrip:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Book.class, new BookTypeAdapter());
Gson gson = builder.create();
Book book = gson.fromJson("{" +
" \"user1\": {" +
" \"timeSpent\": \"20.533333333333335h\"," +
" \"worklog\": [" +
" {" +
" \"date\": \"06/26/2013\"," +
" \"issues\": [" +
" {" +
" \"issueCode\": \"COC-2\"," +
" \"comment\": \"\ncccccc\"," +
" \"timeSpent\": \"20.533333333333335h\"" +
" }" +
" ]," +
" \"dayTotal\": \"20.533333333333335h\"" +
" }" +
" ]" +
" }," +
" \"admin\": {" +
" \"timeSpent\": \"601.1h\"," +
" \"worklog\": [" +
" {" +
" \"date\": \"06/25/2013\"," +
" \"issues\": [" +
" {" +
" \"issueCode\": \"COC-1\"," +
" \"comment\": \"\"," +
" \"timeSpent\": \"113.1h\"" +
" }" +
" ]," +
" \"dayTotal\": \"113.1h\"" +
" }," +
" {" +
" \"date\": \"06/26/2013\"," +
" \"issues\": [" +
" {" +
" \"issueCode\": \"COC-1\"," +
" \"comment\": \"\"," +
" \"timeSpent\": \"8h\"" +
" }," +
" {" +
" \"issueCode\": \"COC-2\"," +
" \"comment\": \"\"," +
" \"timeSpent\": \"480h\"" +
" }" +
" ]," +
" \"dayTotal\": \"488h\"" +
" }" +
" ]" +
" }" +
"}", Book.class);
String json = gson.toJson(book);
Have a look at my tutorial to get an idea of what is possible with Gson: Java/JSON mapping with Gson
Enjoy! :)
I had some problem before a month. As far as I remember it was because, same as you, I forgot to make "new" to objects. I mean that it should look:
public class User {
private String timeSpent;
private List<WorkLog> worklogs = new List < WorkLog >();
}
Try this and I hope that it will help.
P.S.
Also as Erik Pragt said you have array of Users, not just single one. So you will have to make 1 more class that contains a List < Users >.