Hibernate: Error Could not locate SessionFactory in JNDI - java

I'm a newbie user of Hibernate. I've designed a database in MySQL and generated automatically the classes using HibernateTools.
For each table, HibernateTools has created 2 classes, one representing the table itself, and the other the Home object with the persist. For instance the Users table has the Users.java and UsersHome.java
User.java
public class User implements java.io.Serializable {
private Integer idUsuario;
private String nomUsuario;
private String mailUsuario;
private String pass;
private Date ultConexion;
private Date fechaAlta;
private Date ultimoIngreso;
private Date ultimoGasto;
#SuppressWarnings("rawtypes")
private Set avisoses = new HashSet(0);
#SuppressWarnings("rawtypes")
private Set conceptoses = new HashSet(0);
public User() {
}
public User(String nomUsuario, String mailUsuario, String pass, Date ultConexion, Date fechaAlta) {
this.nomUsuario = nomUsuario;
this.mailUsuario = mailUsuario;
this.pass = pass;
this.ultConexion = ultConexion;
this.fechaAlta = fechaAlta;
}
#SuppressWarnings("rawtypes")
public User(String nomUsuario, String mailUsuario, String pass, Date ultConexion, Date fechaAlta,
Date ultimoIngreso, Date ultimoGasto, Set avisoses, Set conceptoses) {
this.nomUsuario = nomUsuario;
this.mailUsuario = mailUsuario;
this.pass = pass;
this.ultConexion = ultConexion;
this.fechaAlta = fechaAlta;
this.ultimoIngreso = ultimoIngreso;
this.ultimoGasto = ultimoGasto;
this.avisoses = avisoses;
this.conceptoses = conceptoses;
}
public Integer getIdUsuario() {
return this.idUsuario;
}
public void setIdUsuario(Integer idUsuario) {
this.idUsuario = idUsuario;
}
public String getNomUsuario() {
return this.nomUsuario;
}
public void setNomUsuario(String nomUsuario) {
this.nomUsuario = nomUsuario;
}
public String getMailUsuario() {
return this.mailUsuario;
}
public void setMailUsuario(String mailUsuario) {
this.mailUsuario = mailUsuario;
}
public String getPass() {
return this.pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public Date getUltConexion() {
return this.ultConexion;
}
public void setUltConexion(Date ultConexion) {
this.ultConexion = ultConexion;
}
public Date getFechaAlta() {
return this.fechaAlta;
}
public void setFechaAlta(Date fechaAlta) {
this.fechaAlta = fechaAlta;
}
public Date getUltimoIngreso() {
return this.ultimoIngreso;
}
public void setUltimoIngreso(Date ultimoIngreso) {
this.ultimoIngreso = ultimoIngreso;
}
public Date getUltimoGasto() {
return this.ultimoGasto;
}
public void setUltimoGasto(Date ultimoGasto) {
this.ultimoGasto = ultimoGasto;
}
#SuppressWarnings("rawtypes")
public Set getAvisoses() {
return this.avisoses;
}
#SuppressWarnings("rawtypes")
public void setAvisoses(Set avisoses) {
this.avisoses = avisoses;
}
#SuppressWarnings("rawtypes")
public Set getConceptoses() {
return this.conceptoses;
}
#SuppressWarnings("rawtypes")
public void setConceptoses(Set conceptoses) {
this.conceptoses = conceptoses;
}
UserHome.java
public class UserHome {
private static final Log log = LogFactory.getLog(UserHome.class);
private final SessionFactory sessionFactory = getSessionFactory();
protected SessionFactory getSessionFactory() {
try {
return (SessionFactory) new InitialContext().lookup("SessionFactory");
} catch (Exception e) {
log.error("Could not locate SessionFactory in JNDI", e);
throw new IllegalStateException("Could not locate SessionFactory in JNDI");
}
}
public void persist(User transientInstance) {
log.debug("persisting User instance");
try {
sessionFactory.getCurrentSession().persist(transientInstance);
log.debug("persist successful");
} catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}
public void attachDirty(User instance) {
log.debug("attaching dirty User instance");
try {
sessionFactory.getCurrentSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(User instance) {
log.debug("attaching clean User instance");
try {
sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void delete(User persistentInstance) {
log.debug("deleting User instance");
try {
sessionFactory.getCurrentSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public User merge(User detachedInstance) {
log.debug("merging User instance");
try {
User result = (User) sessionFactory.getCurrentSession().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public User findById(java.lang.Integer id) {
log.debug("getting User instance with id: " + id);
try {
User instance = (User) sessionFactory.getCurrentSession().get("Usuario", id);
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
}
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
#SuppressWarnings("rawtypes")
public List findByExample(User instance) {
log.debug("finding User instance by example");
try {
List results = sessionFactory.getCurrentSession().createCriteria("User").add(Example.create(instance))
.list();
log.debug("find by example successful, result size: " + results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
}
When I do this as a tryout to see if everything goes as supposed, I get "Could not locate SessionFactory in JNDI"
UserHome uh = new UserHome();
User u = new User("nom", "Mail1#mail.com", "chsss", new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis()));
uh.persist(u);
What am I doing wrong?
Edit: The complete stacktrace of the exception
abr 21, 2016 8:47:09 AM hibernate.UsuarioHome getSessionFactory
SEVERE: Could not locate SessionFactory in JNDI
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at hibernate.UserHome.getSessionFactory(UserHome.java:27)
at hibernate.UserHome.<init>(UserHome.java:23)
at bbdd.FirstHibernate.main(FirstHibernate.java:11)
Exception in thread "main" java.lang.IllegalStateException: Could not locate SessionFactory in JNDI
at hibernate.UserHome.getSessionFactory(UserHome.java:30)
at hibernate.UserHome.<init>(UserHome.java:23)
at bbdd.FirstHibernate.main(FirstHibernate.java:11)

Do you have a initial context? Initial context will only exists when you are running your code on application server. If you are running this code on application server, please add your config files so that I can verify it is configured properly. If there is no application server and the code is being run from POJO, you need to get session factory in a different manner.Looking at your classes, I think you are running this in a POJO.
It will also help if you can paste the exception or stacktrace. Makes it easier to guess whats going wrong.

Related

Android download directory from FTP error

I have a music player that downloads a directory from the FTP server to the SD card. And the player downloads and accepts server settings (there are two versions of ME and CE), but it happens after downloading the application crashes. When I delete some folders after downloading it works normally in ME mode, but when I download it and it takes the CE mode all the time the application crashes.
public class FTPManager {
public static final String LOG_TAG = FTPManager.class.getName();
private static final String HOST = "*******";
private static final String LOGIN = "*******";
private static final String PASSWORD = "*******";
private static final int REPEAT_TIMEOUT_MILLIS = 5 * 1000;
private int mCommandAttempts;
private String host;
private String login;
private String password;
private FTPClient mFtpClient;
private FTPManager(String host, String login, String password) {
this.host = host;
this.login = login;
this.password = password;
mFtpClient = new FTPClient();
}
public FTPManager() {
this(HOST, LOGIN, PASSWORD);
}
public boolean connect() {
mCommandAttempts = 5;
return attemptConnect();
}
private boolean attemptConnect() {
try {
mFtpClient.connect(host);
mFtpClient.login(this.login, password);
mFtpClient.setPassive(true);
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
try {
TimeUnit.MILLISECONDS.sleep(REPEAT_TIMEOUT_MILLIS);
} catch (InterruptedException e1) {
Log.e(LOG_TAG, e.toString());
return false;
}
mCommandAttempts--;
if (mCommandAttempts > 0) {
return attemptConnect();
}
}
return true;
}
public List<String> listFiles() {
return listFiles(FTPFile.TYPE_FILE);
}
public List<String> listDirectores() {
return listFiles(FTPFile.TYPE_DIRECTORY);
}
private List<String> listFiles(int type) {
mCommandAttempts = 5;
return attemptListFiles(type);
}
private List<String> attemptListFiles(int type) {
ArrayList<String> names = new ArrayList<>();
try {
FTPFile[] files = mFtpClient.list();
for (FTPFile file : files) {
if (file.getType() == type) {
names.add(file.getName());
}
}
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
try {
TimeUnit.MILLISECONDS.sleep(REPEAT_TIMEOUT_MILLIS);
} catch (InterruptedException e1) {
Log.e(LOG_TAG, e.toString());
return names;
}
mCommandAttempts--;
if (mCommandAttempts > 0) {
return attemptListFiles(type);
}
}
return names;
}
public boolean downloadFile(OutputStream outputStream, String ftpName) {
mCommandAttempts = 5;
return attemptDownloadFile(outputStream, ftpName);
}
private boolean attemptDownloadFile(OutputStream outputStream, String ftpName) {
try {
mFtpClient.download(ftpName, outputStream, 0, null);
return true;
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
try {
TimeUnit.MILLISECONDS.sleep(REPEAT_TIMEOUT_MILLIS);
} catch (InterruptedException e1) {
Log.e(LOG_TAG, e.toString());
return false;
}
mCommandAttempts--;
if (mCommandAttempts > 0) {
return attemptDownloadFile(outputStream, ftpName);
}
}
return false;
}
public boolean changeDirectory(String path) {
mCommandAttempts = 5;
return attemptChangeDirectory(path);
}
private boolean attemptChangeDirectory(String path) {
try {
mFtpClient.changeDirectory(path);
return true;
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
try {
TimeUnit.MILLISECONDS.sleep(REPEAT_TIMEOUT_MILLIS);
} catch (InterruptedException e1) {
Log.e(LOG_TAG, e.toString());
return false;
}
mCommandAttempts--;
if (mCommandAttempts > 0) {
return attemptChangeDirectory(path);
}
}
return false;
}
public boolean release() {
if (mFtpClient != null) try {
mFtpClient.logout();
mFtpClient.disconnect(true);
mFtpClient = null;
return true;
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
return false;
}
return false;
}
}
And
public class FTPDirectory implements Parcelable {
private StringBuilder builder;
public FTPDirectory(String host) {
builder = new StringBuilder(host);
}
protected FTPDirectory(Parcel in) {
builder = new StringBuilder(in.readString());
}
public static final Creator<FTPDirectory> CREATOR = new Creator<FTPDirectory>() {
#Override
public FTPDirectory createFromParcel(Parcel in) {
return new FTPDirectory(in);
}
#Override
public FTPDirectory[] newArray(int size) {
return new FTPDirectory[size];
}
};
public FTPDirectory append(String path) {
builder.append("/").append(path);
return this;
}
public String getPath() {
return builder.toString();
}
public static FTPDirectory getImgDirectory() {
return new FTPDirectory("/img");
}
public static FTPDirectory getAdDirectory() {
return new FTPDirectory("/adv");
}
public static FTPDirectory getMusicDirectory() {
return new FTPDirectory("/music");
}
public static FTPDirectory getChannelDirectory(String channel, int index) {
return getChannelRootDirectory(channel)
.append(Integer.toString(index));
}
public static FTPDirectory getChannelRootDirectory(String channel) {
return getMusicDirectory()
.append(channel);
}
#Override
public String toString() {
return "FTPDirectory{" +
"Path=" + builder.toString() +
'}';
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(getPath());
}
}
I think somewhere here there may be a mistake. It turns out that one file reads and the other does not, but the format is the same. Please help to solve the problem.

Some server generated events do not get delivered to the client in production over websockets

Bottom line:
Some server generated events do not get delivered to the client in production over websockets. However, the websocket connections get established just fine.
Case study:
I open Google Chrome and connect to our server. Open the devtools. Under WS tab, I see that connection got established fine, but I receive no frames when, let’s say, server needs to update something on the page. I wait for a while and sometimes (only sometimes) I get some events with a huge amount of delay. This works as expected locally however.
Question:
Has anyone seen similar websocket behavior and has any suggestions on how to eliminate variables for this investigation.
Infrastructure:
Server: Linux Tomcat
Two servers that handle:
1. Traffic from Devices (Communicating over TCP/IP with the Server)
2. Traffic from Users
Users and Devices are many to many relationship. If a user gets connected to a server that doesn’t have a device connected. This server looks on the other server and handles the info exchange.
There is a firewall in front of the servers.
Code:
https://github.com/kino6052/websockets-issue
WebSocketServerEndpoint.java
#ServerEndpoint("/actions")
public class WebSocketServerEndpoint {
static private final org.slf4j.Logger logger = LoggerFactory.getLogger(WebSocketServerEndpoint.class);
#OnOpen
public void open(Session session) {
WebSocketSessionHandler.addSession(session);
}
#OnClose
public void close(Session session) {
WebSocketSessionHandler.removeSession(session);
}
#OnError
public void onError(Throwable error) {
//Logger.getLogger(WebSocketServerEndpoint.class.getName()).log(Level.SEVERE, null, error);
}
#OnMessage
public void handleMessage(String message, Session session) {
try (JsonReader reader = Json.createReader(new StringReader(message))) {
JsonObject jsonMessage = reader.readObject();
Long userId = null;
Long tenantId = null;
switch (WebSocketActions.valueOf(jsonMessage.getString("action"))){
case SaveUserId:
userId = getUserId(jsonMessage);
tenantId = getTenantId(jsonMessage);
Long userIdKey = WebSocketSessionHandler.saveUserId(userId, session);
Long tenantUserKey = WebSocketSessionHandler.saveTenantUser(tenantId, userId);
WebSocketSessionHandler.updateUserSessionKeys(session, tenantUserKey, userIdKey); // Needed for Making Weak Maps Keep Their Keys if Session is Currently Active
}
} catch (Exception e) {
logger.error(e.toString());
}
}
private Long getUserId(JsonObject jsonMessage) {
Long userId = null;
try {
userId = Long.parseLong(((Integer) jsonMessage.getInt("userId")).toString());
return userId;
} catch (Exception e) {
logger.error(e.getMessage());
return userId;
}
}
private Long getTenantId(JsonObject jsonMessage) {
Long tenantId = null;
try {
tenantId = Long.parseLong(((Integer) jsonMessage.getInt("tenantId")).toString());
return tenantId;
} catch (Exception e) {
logger.error(e.getMessage());
return tenantId;
}
}
}
WebSocketService.java
#Singleton
public class WebSocketService {
private static final Logger logger = LoggerFactory.getLogger(WebSocketService.class);
public enum WebSocketEvents{
OnConnection,
OnActivity,
OnAccesspointStatus,
OnClosedStatus,
OnConnectedStatus,
OnAlert,
OnSessionExpired
}
public enum WebSocketActions{
SaveUserId
}
#WebPost("/lookupWebSocketSessions")
public WebResponse lookupWebSocketSessions(#JsonArrayParam("userIds") List<Integer> userIds, #WebParam("message") String message){
try {
for (Integer userIdInt : userIds) {
Long userId = Long.parseLong(userIdInt.toString());
if (WebSocketSessionHandler.sendToUser(userId, message) == 0) {
} else {
//logger.debug("Couldn't Send to User");
}
}
} catch (ClassCastException e) {
//logger.error(e.getMessage());
return webResponseBuilder.fail(e);
} catch (Exception e) {
//logger.error(e.getMessage());
return webResponseBuilder.fail(e);
}
return webResponseBuilder.success(message);
}
#WebPost("/lookupWebSocketHistorySessions")
public WebResponse lookupWebSocketHistorySessions(#JsonArrayParam("userIds") List<Integer> userIds, #WebParam("message") String message){
try {
for (Integer userIdInt : userIds) {
Long userId = Long.parseLong(userIdInt.toString());
if (WebSocketHistorySessionHandler.sendToUser(userId, message) == 0) {
} else {
//logger.debug("Couldn't Send to User");
}
}
} catch (ClassCastException e) {
//logger.error(e.getMessage());
return webResponseBuilder.fail(e);
} catch (Exception e) {
//logger.error(e.getMessage());
return webResponseBuilder.fail(e);
}
return webResponseBuilder.success(message);
}
// Kick Out a User if Their Session is no Longer Valid
public void sendLogout(User user) {
try {
Long userId = user.getId();
List<Long> userIds = new ArrayList<>();
userIds.add(userId);
JSONObject result = new JSONObject();
result.put("userId", userId);
JSON message = WebSocketSessionHandler.createMessage(WebSocketEvents.OnSessionExpired, result);
lookOnOtherServers(userIds, message);
} catch (Exception e) {
logger.error("Couldn't Logout User");
}
}
// Send History after Processing Data
// Returns "0" if success, "-1" otherwise
public int sendHistory(Activity activity) {
try {
TimezoneService.TimeZoneConfig timeZoneConfig = timezoneService.getTimezoneConfigsByAp(null, activity.getAccesspointId());
JSONObject result = (JSONObject) JSONSerializer.toJSON(activity);
String timezoneId = timezoneService.convertTimezoneConfigToTimezoneId(timeZoneConfig);
result.put("timezoneString", timezoneId);
result.put(
"profileId",
userDao.getUserProfileId(activity.getUserId())
);
JSON message = WebSocketHistorySessionHandler.createMessage(WebSocketEvents.OnActivity, result);
List<Long> userIds = getUsersSubscribedToActivity(activity.getTenantId());
lookOnOtherServersHistory(userIds, message);
return 0;
} catch (Exception e) {
//logger.error("Couldn't Send History");
return -1;
}
}
// SendAlertUpdate after Processing Data
public void sendAlertUpdate(Alert alert) {
try {
List<Long> userIds = getUsersUnderTenantByAccesspointId(alert.getAccesspointId());
JSONObject result = JSONObject.fromObject(alert);
JSON message = WebSocketSessionHandler.createMessage(WebSocketEvents.OnAlert, result);
lookOnOtherServers(userIds, message);
} catch (Exception e) {
//logger.error("Couldn't Send Aleart");
}
}
// Send Connected Status after Processing Data
public void sendConnectedStatus(Long accesspointId, Boolean isConnected) {
try {
List<Long> userIds = getUsersUnderTenantByAccesspointId(accesspointId);
JSONObject result = new JSONObject();
result.put("accesspointId", accesspointId);
result.put("isConnected", isConnected);
JSON message = WebSocketSessionHandler.createMessage(WebSocketEvents.OnConnectedStatus, result);
lookOnOtherServers(userIds, message);
} catch (Exception e) {
//logger.error("Couldn't Send Connected Status");
}
}
public int sendHistory(CredentialActivity activity) {
try {
TimezoneService.TimeZoneConfig timeZoneConfig = timezoneService.getTimezoneConfigsByAp(null, activity.getAccesspointId());
JSONObject result = (JSONObject) JSONSerializer.toJSON(activity);
String timezoneId = timezoneService.convertTimezoneConfigToTimezoneId(timeZoneConfig);
result.put("timezoneString", timezoneId);
result.put(
"profileId",
userDao.getUserProfileId(activity.getUserId())
);
JSON message = WebSocketHistorySessionHandler.createMessage(WebSocketEvents.OnActivity, result);
List<Long> userIds = getUsersUnderTenantByAccesspointId(activity.getAccesspointId());
lookOnOtherServersHistory(userIds, message);
return 0;
} catch (Exception e) {
return -1;
}
}
public Boolean isUserSessionAvailable(Long id) {
return WebSocketSessionHandler.isUserSessionAvailable(id);
}
public void lookOnOtherServers(List<Long> userId, JSON data){
List<String> urls = awsService.getServerURLs();
for (String url : urls) {
postJSONDataToUrl(url, userId, data);
}
}
public void lookOnOtherServersHistory(List<Long> userId, JSON data){
List<String> urls = awsService.getServerURLsHistory();
for (String url : urls) {
postJSONDataToUrl(url, userId, data);
}
}
public int sendClosedStatus(AccesspointStatus accesspointStatus){
try {
JSONObject accesspointStatusJSON = new JSONObject();
accesspointStatusJSON.put("accesspointId", accesspointStatus.getAccesspointId());
accesspointStatusJSON.put("openStatus", accesspointStatus.getOpenStatus());
List<Long> userIds = getUsersUnderTenantByAccesspointId(accesspointStatus.getAccesspointId());
lookOnOtherServers(userIds, accesspointStatusJSON);
return 0;
} catch (Exception e) {
return -1;
}
}
public List<Long> getUsersSubscribedToActivity(Long tenantId) {
List<Long> userList = WebSocketSessionHandler.getUsersForTenant(tenantId);
return userList;
}
private List<Long> getUsersUnderTenantByAccesspointId(Long accesspointId) {
List<Long> userList = new ArrayList<>();
User user = userDao.getBackgroundUserByAccesspoint(accesspointId);
List<Record> recordList = tenantDao.getTenantsByUser(user, user.getId());
for (Record record : recordList) {
Long tenantId = (Long) record.get("id");
userList.addAll(getUsersSubscribedToActivity(tenantId));
}
return userList;
}
public void postJSONDataToUrl(String url, List<Long> userId, JSON data) throws AppException {
List<NameValuePair> parameters;
HttpResponse httpResponse;
HttpClientService.SimpleHttpClient simpleHttpClient = httpClientService.createHttpClient(url);
try {
parameters = httpClientService.convertJSONObjectToNameValuePair(userId, data);
} catch (Exception e) {
throw new AppException("Couldn't Convert Input Parameters");
}
try {
httpResponse = simpleHttpClient.sendHTTPPost(parameters);
} catch (Exception e) {
throw new AppException("Couldn't Get Data from the Server");
}
if (httpResponse == null) {
throw new AppException("Couldn't Send to Another Server");
} else {
//logger.error(httpResponse.getStatusLine().toString());
}
}
}
WebSocketSessionHandler.java
public class WebSocketSessionHandler {
// Apparently required to instantiate the dialogue,
// ideally it would be better to just create session map where sessions are mapped to userId,
// however, userId will be send only after the session is created.
// TODO: Investigate Instantiation of WebSocket Session Further
// WeakHashMap is Used for Automatic Memory Management (So That Removal of Keys That are no Longer Used Can be Automatically Performed)
// NOTE: However, it Requires Certain Precautions to Make Sure Their Keys Don't Expire Unexpectedly, Look for the Commented Code Below
private static final Map<Long, Set<Session>> sessionMap = new WeakHashMap<>();
private static final Map<Long, Set<Long>> tenantUserMap = new WeakHashMap<>();
public WebSocketSessionHandler() {}
public static List<Long> getUsersForTenant(Long tenantId) {
List<Long> userIds = new ArrayList<>();
Set<Long> userIdsSet = tenantUserMap.get(tenantId);
if (userIdsSet != null) {
for (Long userId : userIdsSet){
userIds.add(userId);
}
}
return userIds;
}
public static Boolean isUserSessionAvailable(Long id){
Set<Session> userSessions = sessionMap.get(id);
if (userSessions == null || userSessions.size() == 0) {
return false;
} else {
return true;
}
}
// addSession() should add "session" to "sessions" set
// returns: "0" if success and "-1" otherwise
public static int addSession(Session session) {
int output;
try {
final long ONE_DAY = 86400000;
session.setMaxIdleTimeout(ONE_DAY);
sessions.put(session, new ArrayList<>());
return sendToSession(session, createMessage(WebSocketEvents.OnConnection, "Successfully Connected"));
} catch (Exception e) {
logger.error("Couldn't Add Session");
return -1;
}
}
// removeSession() should remove "session" from "sessions" set
// Scenarios:
// sessions is null?
// returns: "0" if success and "-1" otherwise
public static int removeSession( Session session) {
try {
closeSessionProperly(session);
if (sessions.remove(session) != null) {
return 0;
} else {
return -1;
}
} catch (Exception e) {
logger.error("Couldn't Remove Session");
return -1;
}
}
private static void closeSessionProperly(Session session) {
try {
session.close();
} catch (IOException ex) {
}
}
public static Long getKeyFromMap(Map map, Long key){ // Needed for Weak Maps
Set<Long> keySet = map.keySet();
for (Long keyReference : keySet) {
if (keyReference == key) {
return keyReference;
}
}
return key; // If Not Found Return the Value Passed in
}
// saveUserId() should create an { userId -> session } entry in sessionMap
public static Long saveUserId(Long userId, Session session){
// Test Scenarios:
// Can userId be null or wrong?
// Can session be null or wrong?
try {
userId = getKeyFromMap(sessionMap, userId); // Required for Weak Maps to Work Correctly
Set<Session> sessionsForUser = sessionMap.get(userId);
if (sessionsForUser == null) {
sessionsForUser = new HashSet<>();
}
sessionsForUser.add(session);
sessionMap.put(userId, sessionsForUser);
return userId;
} catch (Exception e) {
logger.error("Couldn't Save User Id");
return null;
}
}
// saveUserId() should create an { userId -> session } entry in sessionMap
public static Long saveTenantUser(Long tenantId, Long userId){
// Test Scenarios:
// Can userId be null or wrong?
// Can session be null or wrong?
try {
tenantId = getKeyFromMap(tenantUserMap, tenantId); // Required for Weak Maps to Work Correctly
Set<Long> users = tenantUserMap.get(tenantId);
if (users == null) {
users = new HashSet<>();
}
users.add(userId);
tenantUserMap.put(tenantId, users);
return tenantId;
} catch (Exception e) {
logger.error("Couldn't Save Tenant User");
return null;
}
}
public static void updateUserSessionKeys(Session session, Long tenantId, Long userId) {
try {
List<Long> userSessionKeys = sessions.get(session);
userSessionKeys.add(0, tenantId);
userSessionKeys.add(1, userId);
} catch (Exception e) {
logger.error("Couldn't Update User Session Keys");
}
}
// removeUserId() should remove an { userId -> session } entry in sessionMap
// returns: "0" if success and "-1" otherwise
public static int removeUserId( Long userId) {
try {
sessionMap.remove(userId);
return 0;
} catch (Exception e) {
return -1;
}
}
// sendAccesspointStatus() should compose JSON message and pass it to sendToUser()
// returns: "0" if success and "-1" otherwise
public static int sendClosedStatus(Long userId, JSONObject accesspointStatus) {
try {
JSONObject accesspointStatusEventMessage = (JSONObject) createMessage(WebSocketEvents.OnClosedStatus, accesspointStatus);
sendToUser(userId, accesspointStatusEventMessage);
return 0;
} catch (Exception e) {
return -1;
}
}
// sendToUser() sends message to session that is mapped to userId
// returns: "0" if success and "-1" otherwise
public static int sendToUser( Long userId, JSON message) {
if (sessionMap.containsKey(userId)) {
Set<Session> sessionsForUser = sessionMap.get(userId);
for (Session session : sessionsForUser) {
if (!session.isOpen()) {
sessions.remove(session);
continue;
}
sendToSession(session, message);
}
return 0;
} else {
return -1;
}
}
// sendToSession() sends string message to session
// returns: "0" if success and "-1" otherwise
private static int sendToSession( Session session, JSON message){
try {
try {
Long tenantId = sessions.get(session).get(0);
((JSONObject) message).put("tenantId", tenantId);
} catch (Exception e) {
logger.error("No tenantId Found");
}
session.getBasicRemote().sendText(message.toString());
return 0;
} catch (IOException e) {
try {
session.close();
} catch (IOException ex) {
}
closeSessionProperly(session);
sessions.remove(session);
return -1;
}
}
// sendToSession() sends string message to session
// returns: "0" if success and "-1" otherwise
private static int sendToSession( Session session, String message){
try {
JSONObject newMessage = JSONObject.fromObject(message);
try {
Long tenantId = sessions.get(session).get(0);
newMessage.put("tenantId", tenantId);
} catch (Exception e) {
logger.error("No tenantId Found");
}
session.getBasicRemote().sendText(newMessage.toString());
return 0;
} catch (IOException e) {
closeSessionProperly(session);
sessions.remove(session);
return -1;
}
}
}
Probably not the only bug, but your WebSocketSessionHandler class is not thread-safe. It uses WeakHashMap internally which is not synchronized. Concurrent access to these maps may result in unexpected behavior, which may or may not cause the effects you are seeing.
Turns out this was a correct assumption. A general rule of thumb: Unexpected Behaviour ~ Race Condition
Probably not the only bug, but your WebSocketSessionHandler class is not thread-safe. It uses WeakHashMap internally which is not synchronized. Concurrent access to these maps may result in unexpected behavior, which may or may not cause the effects you are seeing.
(copied from my comment. Turns out this was the solution)

XStream registers only one converter

On my serialized XML File is only one attribute of my Object saved, although four should be saved. I think this is due to y XStream Object registering only one converter, although he should register four.
My Converters are all functioning individually. I tested them one by one.
My XML File:
<object-stream>
<model.Product>13</model.Product>
</object-stream>
My Product class which should be saved:
public class Product implements Externalizable, Serializable {
private static final long serialVersionUID = -8437751114305532162L;
#XStreamConverter(converter.NameConverter.class)
private SimpleStringProperty name;
#XStreamConverter(converter.PriceConverter.class)
private SimpleDoubleProperty price;
#XStreamConverter(converter.CountConverter.class)
private SimpleIntegerProperty quantity;
#XStreamConverter(converter.IDConverter.class)
private long id;
public Product(String name, int quantity, double price, long id)
{
this.name=new SimpleStringProperty(name);
this.quantity=new SimpleIntegerProperty(quantity);
this.price=new SimpleDoubleProperty(price);
this.id=id;
//Getter and Setter and implentation of Externalizable
My XStream class
XStream xstream;
ObjectInputStream ois;
ObjectOutputStream oos;
#Override
public void close() throws IOException {
if (oos != null) {
oos.close();
}
if (ois != null) {
ois.close();
}
}
#Override
public void writeObject(Product obj) throws IOException {
try {
oos.writeObject(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
public void open(InputStream input, OutputStream output) throws IOException {
xstream = createXStream(model.Product.class);
converter.ConverterManager con=new ConverterManager();
con.registerAllConverters(xstream);
if (input != null) {
if (input.available() > 0) {
ois = xstream.createObjectInputStream(input);
}
}
if (output != null) {
oos = xstream.createObjectOutputStream(output);
}
}
}
My ConverterManager:
import com.thoughtworks.xstream.XStream;
public class ConverterManager {
public void registerAllConverters(XStream xstream)
{
xstream.aliasAttribute("Product Price", "price");
xstream.registerConverter(new PriceConverter());
xstream.aliasAttribute("Product ID", "id");
xstream.registerConverter(new IDConverter());
xstream.aliasAttribute("Product Name", "name");
xstream.registerConverter(new NameConverter());
xstream.aliasAttribute("Product quantity", "quantity");
xstream.registerConverter(new CountConverter());
}
}
My writeObject, open and close methods are called from this method from another class:
private void saveModel() {
XStreamStrategy s=new XStreamStrategy();
try {
s.open(getFilePath());
} catch (IOException e) {
e.printStackTrace();
}
for(fpt.com.Product p: model)
{
try {
s.writeObject(p);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Create a generic method to combine multiple .close() connection methods

I have these 4 methods which each close a different connection type, meaning each of those has a different input object. Each method calls the close() method on the provided input object. Is there a way to combine those methods into one, taking in a generic object? I have no way to implement an interface on the provided objects or extend them.
import java.sql.Statement;
import javax.jms.Connection;
import javax.mail.Transport;
private void close(Statement stm) {
if(stm == null) {
return;
}
try {
stm.close();
} catch (SQLException ex) {
logger.error("Error while closing statement", ex);
}
}
private void close(java.sql.Connection con) {
if(con == null) {
return;
}
try {
con.close();
} catch (SQLException ex) {
logger.error("Error while closing connection", ex);
}
}
private void close(javax.jms.Connection con) {
if(con == null) {
return;
}
try {
con.close();
} catch(JMSException ex) {
logger.error("Error while closing JMS connection", ex);
}
}
private void close(Transport transport) {
if(transport == null) {
return;
}
try {
transport.close();
} catch (MessagingException ex) {
logger.error("Error while closing mail transport", ex);
}
}
EDIT:
Thank you for your answers regarding Java 1.7. Unfortunately our servers are running Java 1.6, so is there any solution for that?
You can use reflection.
First sample give you support for try() with resources:
#Test
public void testRes() throws Exception {
try(ClosableWrapper<StringWriter> rs = new ClosableWrapper<>(new StringWriter())){
Writer wr = rs.getResource();
}
}
static class ClosableWrapper<T> implements AutoCloseable{
private T resource;
private String closeMethod = "close";
public ClosableWrapper(T resource) {
this.resource = resource;
}
public ClosableWrapper(T resource, String closeMethod) {
this.resource = resource;
this.closeMethod = closeMethod;
}
public T getResource() {
return resource;
}
#Override
public void close() throws Exception {
if(resource!=null){
Method m = resource.getClass().getMethod(closeMethod);
m.invoke(resource);
}
}
}
or just one method:
public void close(Object resource) throws Exception {
if(resource!=null){
Method m = resource.getClass().getMethod("close");
m.invoke(resource);
}
}
Assuming these are your classes, use the AutoCloseable interface and put them in a try-with-resource.

Mocking constructor and a private function inside it using Mockito

I am in a scenario where I need to Unit test on class which is involving some bean formation and it require real data which I dont have, for more reference Below is the code.
the adapter class which I want to Mock
public class TIBCOAdapter {
public TIBCOAdapter(final GIAFProperties giafProperties) throws Exception {
if (giafProperties != null) {
this.giafProperties = giafProperties;
} else {
LOG.info("Error: No properties found");
}
init();
}
public void init() throws IOException {
factory = initializeQueueConnectionFactory();
requestQueue = initializeRequestQueue();
}
private QueueConnectionFactory initializeQueueConnectionFactory() {
final DurationRecord start = DurationLog.logBefore();
final JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiTemplate(new JndiTemplate(giafProperties.getProperties()));
bean.setJndiName(GIAFPropertyUtil.getPropertyString(giafProperties, "externalJndiName"));
try {
bean.afterPropertiesSet();
} catch (Exception e) {
throw new GIAFRuntimeException(e);
}
final ConnectionFactory targetConnectionFactory = (ConnectionFactory) bean
.getObject();
LOG.info("Got target connection factory: " + targetConnectionFactory);
final MultiCachingConnectionFactory factoryLocal = new MultiCachingConnectionFactory(
targetConnectionFactory, giafProperties);
DurationLog.logAfter(start);
return factoryLocal;
}
private Queue initializeRequestQueue() {
final JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiTemplate(new JndiTemplate(giafProperties.getProperties()));
bean.setJndiName(GIAFPropertyUtil.getPropertyString(giafProperties,
"request-queue"));
try {
bean.afterPropertiesSet();
} catch (Exception e) {
throw new GIAFRuntimeException(e);
}
return (Queue) bean.getObject();
}
}
The actual class where its object is created, which I don't want and that's why I want to mock creation of TIBCOAdapter
public class SomeClass {
public String getResponse(TestClientFilter testClientFilter) throws ICAException {
if (!filterValid(testClientFilter)) {
return null;
}
try {
Properties properties = new Properties(); // Sucess
GIAFProperties giafProperties = new GIAFProperties(properties, null); // sucess
addProperties(properties, testClientFilter); // sucess
TIBCOAdapter tibcoAdapter = new TIBCOAdapter(giafProperties); // ERROR This is the line which I want to mock
return (String) tibcoAdapter.invokeRequestResponse(testClientFilter.getMessage());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw new ICAException(e);
}
}
}
and this is my TEST
public class TestClientBusinessTest {
#Mock
private TIBCOAdapter tibco;
#InjectMocks
#Autowired
private SomeClass test;
#BeforeClass
public void setUp() throws NamingException {
MockitoAnnotations.initMocks(this);
}
private String returnStatement;
#Test(dataProvider = "getTestClientResponseBusiness", dataProviderClass = StaticDataProvider.class)
public void getResponse(TestClientFilter testClientFilter) throws Exception {
when(tibco.invokeRequestResponse(Matchers.any(TestClientFilter.class))).thenReturn(new Object());
test.getResponse(testClientFilter);
tibco.invokeRequestResponse(testClientFilter.getMessage());
}
}
These lines of code are making problem from TIBCOAdapters internal functions.
bean.setJndiTemplate(new JndiTemplate(giafProperties.getProperties()));
bean.setJndiName(GIAFPropertyUtil.getPropertyString(giafProperties, "externalJndiName"));

Categories

Resources