I can't get any output from this program. Do you know why? I am using NetBeans 8.1 and wamp server. I design database named assignments online. Can you also suggest if I am using true drivers?
package managmentSystem;
import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
/**
*
* #author DiyaBangesh
*/
public class ManagmentSystem {
//PreparedStatement pst = null;
//Statement st= null;
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
try{
ResultSet rs;
Connection conn;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/assignment","root","");
JOptionPane.showMessageDialog(null,"Connection to database is established");
//return conn;
Statement st = conn.createStatement();
String sql ="SELECT * FROM userdetails";
rs = st.executeQuery(sql);
while(rs.next()){
String nam = rs.getString("name");
String uid = rs.getString("user_id");
String pwd = rs.getString("password");
String eid = rs.getString("email_id");
String con = rs.getString("contact");
String ut = rs.getString("usertype");
System.out.println(nam + " " + uid + " " + pwd + " "+ eid + " " + con + " " + ut );
}
conn.close();
}
catch (Exception sqlEx){
System.out.println(sqlEx);
}
}
}
mysql-connector-java-bin.jar is the one needeed and you have already used it. Make sure that you used correct database name & correct password. Replace 'yourpassword' with your database password. And make sure that server is running.
Follow as below.
public class ManagmentSystem {
Connection con;
Statement s;
PreparedStatement ps;
ResultSet rs;
ManagmentSystem()
{
try
{ Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/assignment?user=root&password=yourpassword");
}
catch(SQLException s)
{
System.out.println("Error in DB Connection");
s.printStackTrace();
}
catch(ClassNotFoundException c)
{
System.out.println("Driver not Found");
}
}
}
I am using SockJs Java client to connect with websocket running on different server. Every thing works fine like server publishes message and my Java client receives it,but if server is restarted then I am not able to receive any reply.But when I restart the client then again everything work ok. So I want to implement the re-connection logic with restarting the SockJs Java client. My code is as below:
#SpringBootApplication
public class Application {
private final static WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
private static Logger logger = Logger.getLogger(Application.class);
public static void main(String[] args) throws InterruptedException, ExecutionException {
SpringApplication.run(Application.class, args);
Transport webSocketTransport = new WebSocketTransport(new StandardWebSocketClient());
List<Transport> transports = Collections.singletonList(webSocketTransport);
SockJsClient sockJsClient = new SockJsClient(transports);
sockJsClient.setMessageCodec(new Jackson2SockJsMessageCodec());
WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
String url = "ws://{host}:{port}/hello";
ListenableFuture<StompSession> f = stompClient.connect(url, headers, new MyWebSocketHandler(), "localhost", 9090);
StompSession stompSession = f.get();
logger.info("Subscribing to greeting topic using session " + stompSession);
subscribeGreetings(stompSession);
}
public static void subscribeGreetings(StompSession stompSession) throws ExecutionException, InterruptedException {
stompSession.subscribe("/topic/greetings", new StompFrameHandler() {
public Type getPayloadType(StompHeaders stompHeaders) {
return byte[].class;
}
public void handleFrame(StompHeaders stompHeaders, Object o) {
logger.info("Received greeting " + new String((byte[]) o));
}
});
}
}
Some of my java code, but is for a raw websocket, dont using STOMP.
Based on this javascript recconnecting implementation: https://github.com/joewalnes/reconnecting-websocket
Java code:
/**
*
* Problemas conocidos:
*
* Si se realiza la instancia dos veces consecutivas, se generan dos conexiones. Esto es debido a que el Executor
* crea dos tareas y no limita.
* Una posible solucion seria convertir esta API de reconexion en un Singleton, sin embargo hacer eso significa solo
* poder crear una coneccion.
* Una forma de solucionar esto es crear una fabrica de websockets. Y por otro lado tener la API como un singleton.
*
* Para reproducir el problema:
*
* ReconnectWebsocket ws = new ReconnectWebsocket(new LogicWsExternal() {
#Override
public void onOpen(Session session) {
} // This is myPersonalEndPoint
},uri, settings
);
ws = new ReconnectWebsocket(new LogicWsExternal() {
#Override
public void onOpen(Session session) {
} // This is myPersonalEndPoint
},uri, settings
);
// .. dos conexiones...
*
*
*
* #author gas
*
*/
public class ReconnectWebsocket implements ReconnectObserver{
private final Logger LOG = LoggerFactory.getLogger(ReconnectWebsocket.class);
//http://stackoverflow.com/questions/5762491/how-to-print-color-in-console-using-system-out-println
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_WHITE = "\u001B[37m";
// private static ReconnectWebsocketTest instance = null;
Boolean debug;
Boolean automaticOpen;
Integer reconnectInterval;
Integer maxReconnectionInterval;
Float reconnectDecay;
Integer timeoutInterval;
Integer maxConnectAttempts;
String binaryType;
// These should be treated as read-only properties
/** The URL as resolved by the constructor. This is always an absolute URL. Reas only. */
URI path;
/** The number of attempted reconnects since starting, or the last successful connection. Read only. */
int connectAttemptsCount;
/**
* The current state of the connection.
* Can be one of: WebSocket.CONNECTING, WebSocket.OPEN, WebSocket.CLOSING, WebSocket.CLOSED
* Read only.
*/
WebSocketStates readyState = WebSocketStates.CLOSED;
/**
* A string indicating the name of the sub-protocol the server selected; this will be one of
* the strings specified in the protocols parameter when creating the WebSocket object.
* Read only.
*/
// TODO
//this.protocol = null;
// Private state variables
//ReconnectWebsocket self = this;
Session session; // In Javascript implementation is ws variable.
boolean forcedClose = false;
boolean timeOutFlag = false;
Future<Boolean> timerReconnectionFuture; // Usado para controlar el timer para las reconexnes.
//private ReconnectObservable observable;
LogicWsExternal logicExternal;
ClientManager client;
LogicWs wsLogic;
static ScheduledExecutorService executor;
static ScheduledExecutorService executor2;
Future openFuture;
AtomicBoolean openFlag;
/*
*
* Tyrus estates:
* org.glassfish.tyrus.core.TyrusWebSocket.State
*
* */
public static enum WebSocketStates { // Tyrus:
CONNECTING("CONNECTING",0) // NEW
,OPEN("OPEN",1) // CONNECTED
,CLOSING("CLOSING",2) // CLOSING
,CLOSED("CLOSED",3) // CLOSED
;
String desc;
Integer statusInt;
WebSocketStates(String desc,Integer statusInt){
this.desc=desc;
this.statusInt=statusInt;
}
public String getDescription() {
return desc;
}
public Integer getStatusInt() {
return statusInt;
}
public void printDescription(){
System.out.println("PrinterStatus: "+desc);
}
}
public ReconnectWebsocket(URI path) throws DeploymentException, IOException {
this(new LogicWsExternal(){
#Override
public void onOpen(Session session) { }},path, null);
}
// Consturctor whith Only package visivility
public ReconnectWebsocket(LogicWsExternal logicWsExernal, URI path) throws DeploymentException, IOException {
this(logicWsExernal,path, null);
}
public ReconnectWebsocket(LogicWsExternal logicWsExternal, URI path, ReconnectSettings settings) {
// Default setting
// Overwrite and define settings with options if they exist.
/** Wheter this instance should log debug mesages. */
this.debug = settings.getDebug()!=null ? settings.getDebug() : true;
/** Wheter or not the websocket should attempt to connect immediately upon instantiation. */
this.automaticOpen = settings.getAutomaticOpen() !=null ? settings.getAutomaticOpen() : true;
/** The number of milliseconds to delay before attempting to reconnect. */
this.reconnectInterval = settings.getReconnectInterval()!=null ? settings.getReconnectInterval() : 1000;
/** The maximum number of milliseconds to delay a reconnection attempt. Timeout to reconnect */
this.maxReconnectionInterval = settings.getMaxReconnectionInterval()!=null ? settings.getMaxReconnectionInterval() : 10000;
/** The rate of increase of the reconnect delay. Allows reconnect attemps to back off when problems persist. */
this.reconnectDecay = settings.getReconnectDecay()!=null ? settings.getReconnectDecay() : (float) 1.3;
/** The maximum time in milliseconds to wait for a connection to succeed before closing and retrying */
this.timeoutInterval = settings.getTimeoutInterval()!=null ? settings.getTimeoutInterval() : 5000;
/** The number of connection attempts to make before to stop. Unlimited if value is zero.
**/
this.maxConnectAttempts = settings.getMaxConnectAttempts()!=null ? settings.getMaxConnectAttempts() : 0;
/** The binary type, possible values 'blob' or 'arraybuffer', default 'blob'. */
this.binaryType = settings.getBinaryType()!=null ? settings.getBinaryType() : "blob";
//settings.put("idStateEvenbusChannel", "false");
//settings.put("idStateEvenbusChannel", "false");
// These should be treated as read-only properties
/** The URL as resolved by the constructor. This is always an absolute URL. Reas only. */
this.path = path;
/** The number of attempted reconnects since starting, or the last successful connection. Read only. */
this.connectAttemptsCount = 0;
/**
* The current state of the connection.
* Can be one of: WebSocket.CONNECTING, WebSocket.OPEN, WebSocket.CLOSING, WebSocket.CLOSED
* Read only.
*/
this.readyState = WebSocketStates.CLOSED;
/**
* A string indicating the name of the sub-protocol the server selected; this will be one of
* the strings specified in the protocols parameter when creating the WebSocket object.
* Read only.
*/
// TODO
// "has a" rather than "is a" observable
//observable = new ReconnectObservable();
this.logicExternal = logicWsExternal;
wsLogic = new LogicWs();
//client = ClientManager.createClient();//GLiszli lient by default
// Java 7 cient.
client = ClientManager.createClient(JdkClientContainer.class.getName());
wsLogic.addObserver(this);
// By default initialize the executors.
executor = Executors.newScheduledThreadPool(1);
executor2 = Executors.newScheduledThreadPool(1);
openFlag = new AtomicBoolean(true);
// Wheher or not to create a websocket upon instantiation
if (this.automaticOpen) {
//this.open();
this.open();
}
}
public void open() {
if (readyState == WebSocketStates.CONNECTING || readyState == WebSocketStates.OPEN ) {
return;
}
if (executor.isShutdown()) {
executor = Executors.newScheduledThreadPool(1);
}
if (executor2.isShutdown()) {
/*
* Este poolthread se apaga cuando se manda a llamar la funcion close() de la API.
* El apagado se realiza porque se considera que ya no se va o volver a conectar.
*/
executor2 = Executors.newScheduledThreadPool(1);
}
/*
* Resetear variables
*/
AtomicInteger counter = new AtomicInteger(0);
connectAttemptsCount = 0;
readyState = WebSocketStates.CONNECTING;
// Ejecutar funciones en metodo OnConnecting
//String reconnectReason = e.getMessage();
//self.update(new InternalMessageWs(WsEventType.ONCONNECTING,new OnConnectingEvent(reconnectReason)));
update(new InternalMessageWs(WsEventType.ONCONNECTING,new OnConnectingEvent("First Connect")));
Runnable openRun = () -> {
do{
if (debug) {
System.out.println("DEBUG: ReconnectingWebSocket attempt-connect# "+(connectAttemptsCount+1)+" of "+(maxConnectAttempts==0?"infinite":maxConnectAttempts)+" URI="+path.getPath());
}
Callable<Session> task1 = new Callable<Session>() {
#Override
public Session call() throws Exception {
// Avizar al API que se esta intentando realizar una reconexión. Patron productor-consumidor.
// TODO Deberia de ser un hilo?? ESto ya que podria se r que algo en el metodo externo sea de tipo bloqueante.
watcherReconnectionTry();
Session session = client.connectToServer(wsLogic,path);
//self.session = client.connectToServer(wsLogic,self.path);
//System.out.println("ReconnectWebsocket:: client.connectToServer(...) is null:"+(session==null?"true":"false"));
//System.out.println("ReconnectWebsocket:: client.connectToServer(...) is open:"+session.isOpen());
return session;
}
};
Future<Session> future = executor.submit(task1);
try {
// Tiempo de espera antes de interrumpir volver a intentarlo.
//Session s = future.get(self.timeoutInterval,TimeUnit.MILLISECONDS);
//Session s = future.get(30,TimeUnit.SECONDS);
//return s;
//self.session = future.get(30,TimeUnit.SECONDS);
session = future.get(timeoutInterval,TimeUnit.MILLISECONDS);
break;
} catch (InterruptedException | ExecutionException | TimeoutException e) {
// TODO Auto-generated catch block
//e.printStackTrace(); //For debug only
// Calculate Back off time.
/*
*
*/
float timeout = (float) (reconnectInterval * Math.pow(reconnectDecay,connectAttemptsCount));
connectAttemptsCount++;
if (maxConnectAttempts > 0 && ( connectAttemptsCount >= maxConnectAttempts )) {
break;
}
int maxTimeReconnect = (int) (timeout > maxReconnectionInterval ? maxReconnectionInterval : timeout);
counter.set(maxTimeReconnect/1000);
Callable<Boolean> timerReconnection = new Callable<Boolean>() {
#Override
public Boolean call() {
System.out.println("counter.get()="+counter.get());
while(counter.get() >= 0) {
System.out.println("Time next reconection: "+counter.get()+" seconds");
System.out.println("ThreadId: "+Thread.currentThread().getId() );
// Avizar a la API el tiempo para la sig. reconexión.. Patron productor-consumidor.
// TODO Deberia de ser un hilo?? ESto ya que podria se r que algo en el metodo externo sea de tipo bloqueante.
watcherTimeLeft(counter.get());
if (counter.get() == 0 && debug ) {
System.out.println("DEBUG: ReconnectingWebSocket connection-timeout: "+path.getPath());
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
counter.decrementAndGet();
}
return false;
}
};
/*
* scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS)
*
* 0 -> initialDelay, this time is includen in the backoff algorithm calc, then this value is zero.
* timeout -> the delay between the termination of one execution and the commencement of the next
*/
timerReconnectionFuture = executor.submit(timerReconnection);
try {
Boolean delayTime = timerReconnectionFuture.get();
} catch (InterruptedException | ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}while (!Thread.currentThread().isInterrupted()); //END while
//while (openFlag.get()); //END while
};// END Runnable
openFuture = executor2.submit(openRun);
}//
public void send(String str) {
// Convertir el texto a objeto Message para enviarlo.
if (readyState == WebSocketStates.OPEN) {
if (debug) {
LOG.debug("Sending to URL:\"{}\", Data:\n\"{}\" ",path.getPath(),JsonWriter.formatJson(str));
//System.out.println("DEBUG: ReconnectingWebSocket sending to "+path.getPath()+": "+str);
}
//session.getBasicRemote().sendText(data);
try {
session.getBasicRemote().sendText(str);
} catch (IOException e) {
LOG.error("Sending to URL:\"{}\", Data:\"{}\" {}",path.getPath(),str,e);
//e.printStackTrace();
}
}
}
/**
*
* #param j objeto Json a enviar por Websocket.
* #throws EncodeException
* #throws IOException
*/
public void send(Json j) {
//System.out.println("ReconnectWebsocket:: send(Json INI)");
send(new Message(j));
//System.out.println("ReconnectWebsocket:: send(Json END)");
}
/**
* Transmits data to the server over Websocket connection.
*
* #param data a text string, ArrayBuffer or Blob to send to the server.
* #throws IOException
* #throws EncodeException
*/
public void send(Message data) {
//System.out.println("ReconnectWebsocket:: send(Message INI)");
if (readyState == WebSocketStates.OPEN) {
if (debug) {
System.out.println("DEBUG: ReconnectingWebSocket send "+path.getPath()+": "+data);
}
//System.out.println("ReconnectWebSocket::send(Message msg - Before)" );
//System.out.println("ReconnectWebSocket::send(Message msg - Before - session is null="+(session==null?"true":"false" ));
//System.out.println("ReconnectWebSocket::send(Message msg - Before - session is open="+session.isOpen());
//session.getBasicRemote().sendText(data);
try {
session.getBasicRemote().sendObject(data);
LOG.debug("Sending to URL:\"{}\", Data:\"{}\" ",path.getPath(),data);
//System.out.println("REconnectWebSocket::send(Message msg - After)" );
} catch (IOException | EncodeException e) {
//e.printStackTrace();
LOG.error("Sending to URL:\"{}\", Data:\"{}\" {}",path.getPath(),data,e);
}
}
// Deberia de detenerse la reconeccion en estos casos?, es decir detener despues de intentar enviar una
// cadena de texto pero que ha fallado.
//System.out.println("ReconnectWebsocket:: send(Message END)");
}
public void close(String reason) {
close(CloseReason.CloseCodes.NORMAL_CLOSURE,reason);
}
public void close() {
close(CloseReason.CloseCodes.NORMAL_CLOSURE,null);
}
public void close(CloseReason.CloseCodes code) {
close(code,null);
}
/** Closes the Websocket connection or connection attempt, if any.
* If the connection is already CLOSED, this method does nothing.
*/
public void close(CloseReason.CloseCodes code, String reason) {
if (readyState == WebSocketStates.CLOSED) {
return;
}
CloseReason closeReason;
forcedClose = true;
/*
* Status code: 1000
* Name: CLOSE_NORMAL
* Description: The connection successfully completed whatever purpose for
* which it was created.
* https://developer.mozilla.org/es/docs/Web/API/CloseEvent
*/
// Default CLOSE_NORMAL code
if (code==null) {
closeReason = new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE,"ReconnectingWebSocket STOP");
} else if (reason!=null) {
closeReason = new CloseReason(code,reason);
} else {
closeReason = new CloseReason(code,"ReconnectingWebSocket STOP");
}
if ( (readyState == WebSocketStates.OPEN || readyState == WebSocketStates.CONNECTING) ) {
// Change readyState status:
readyState = WebSocketStates.CLOSED;
if (session==null) {
/*
* readyState == WebSocketStates.CONNECTING && session == null
*
* This ocurr when the server is off and the client is in a loop trying to connect.
*/
timerReconnectionFuture.cancel(true);
//openFuture.cancel(true);
} else {
/*
* readyState == WebSocketStates.OPEN && session != null
* or
* readyState == WebSocketStates.CONNECTING && session != null
*/
try { // Permanent close. Called via the Close method.
if (session.isOpen()) {
/*
* Session is previously closed when has connected at less one time, after the server shutdown
* and the reconnection beging. During the reconnection if you try to close (forced close)
* then session.close will thorwn a error.
* To fix we have verificate if the session is closed.
*/
session.close(closeReason);
}
executor.shutdown();
executor2.shutdown();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.error("Error cerrando sesion. {}",e);
}
}
//openFuture.cancel(true);
}
}
/**
* Additional public API method to refresh the connection if still is open.
* After close, the websocket will try to reconnect.
* For example, if the app suspects bad data / missed heart beats, it can try to refresh.
*/
public void refresh() {
if (readyState == WebSocketStates.OPEN) {
try {
session.close(new CloseReason(CloseCodes.SERVICE_RESTART, "refresh!!"));
} catch (IOException e) {
//e.printStackTrace();
LOG.error("Error cerrando sesion. {}",e);
}
} else {
// Stop timer of reconnection.
if (readyState == WebSocketStates.CONNECTING) {
//timerReconnectionFuture.cancel(true);
close(CloseCodes.SERVICE_RESTART, "refresh!!");
// Reset variables.
connectAttemptsCount = 0;
open();
}
}
}
public Session getSession(){
return session;
}
public WebSocketStates getReadyState() {
return readyState;
}
/**
* El observador de los cambios en el clente Websocket interno.
*/
#Override
public void update(InternalMessageWs msg) {
switch (msg.getType()) {
case ONOPEN:
// Cambiar estado de la conexión
readyState = WebSocketStates.OPEN;
if (debug ) {
System.out.println("DEBUG: ReconnectingWebSocket onOpen: "+path.getPath());
}
// Ejecutar las funciones onOPen que el usuario ha definido.
logicExternal.onOpen( ((OnOpenEvent)msg.getEvent()).getSession() );
break;
case ONMESSAGE:
if (debug) {
System.out.println("DEBUG: ReconnectingWebSocket onMessage: "+path.getPath());
}
OnMessageEvent evtMsg = (OnMessageEvent)msg.getEvent();
// Ejecutar las funciones OnMessage que el usuario ha definido.
logicExternal.onMessage(evtMsg.getSession(),evtMsg.getMessage());
break;
case ONCLOSE:
if (debug ) {
System.out.println("DEBUG: ReconnectingWebSocket onClose: "+path.getPath()+" forcedClose="+forcedClose);
}
// Cambiar estado de la conexión
readyState = WebSocketStates.CLOSED;
OnCloseEvent evtClose = (OnCloseEvent)msg.getEvent();
// Ejecutar las funciones OnClose que el usuario ha definido.
logicExternal.onClose(evtClose.getSession(),evtClose.getReason());
/*
* Determinar si se debe vlver a conectar o no.
* Si forcedClose = true, entonces detener.
* Si forcedClose = false, entonces reconectar.
*/
if (!forcedClose) {
this.open();
}
else{
if (debug ) {
System.out.println("DEBUG: ReconnectingWebSocket STOP Reconnectiing: "+path.getPath());
}
forcedClose = false;
}
break;
case ONERROR:
if (debug ) {
System.out.println("DEBUG: ReconnectingWebSocket onError: "+path.getPath());
}
// Cambiar estado de la conexión
readyState = WebSocketStates.CLOSED;
OnErrorEvent evtError = (OnErrorEvent)msg.getEvent();
// Ejecutar las funciones OnError que el usuario ha definido.
logicExternal.onError(evtError.getSession(),evtError.getT());
// Volver a iniciar secuencia de conectar.
this.open();
// Algunos prfieren cerrar la conexion.
//this.close(CloseCodes.CLOSED_ABNORMALLY,evtError.getT().getMessage());
break;
case ONCONNECTING:
if (debug ) {
System.out.println("DEBUG: ReconnectingWebSocket onConnecting: "+path.getPath());
}
OnConnectingEvent evtConnecting = (OnConnectingEvent)msg.getEvent();
// Ejecutar las funciones OnConnecting que el usuario ha definido.
logicExternal.onConnecting(evtConnecting.getReason());
break;
default:
break;
}
}
#Override
public void watcherReconnectionTry() {
logicExternal.watcherReconnectionTry();
}
#Override
public void watcherTimeLeft(int timeLeft) {
logicExternal.watcherTimeLeft(timeLeft);
}
}
One interface:
public interface ReconnectObserver {
public void update(InternalMessageWs msg);
public void watcherReconnectionTry();
public void watcherTimeLeft(int timeLeft);
}
ReconnectObservable class:
import java.util.ArrayList;
public class ReconnectObservable implements ReconnectSubject {
private ArrayList<ReconnectObserver> observers;
public ReconnectObservable() {
observers = new ArrayList<ReconnectObserver>();
}
#Override
public void addObserver(ReconnectObserver observer) {
observers.add(observer);
}
#Override
public void notifyObservers(InternalMessageWs msg) {
for(ReconnectObserver observer : observers) {
observer.update(msg);
}
}
}
ReconnectSubject interface:
public interface ReconnectSubject {
public void addObserver(ReconnectObserver observer);
//public void notifyObservers();
public void notifyObservers(InternalMessageWs msg);
}
InternalMessageWs class:
import javax.websocket.CloseReason;
import javax.websocket.Session;
public class InternalMessageWs {
WsEventType type;
Object event;
InternalMessageWs(WsEventType type) {
this.type = type;
this.event = null;
}
InternalMessageWs(WsEventType type, Object event) {
this.type = type;
this.event=event;
}
public WsEventType getType() {
return type;
}
public void setType(WsEventType type) {
this.type = type;
}
public Object getEvent() {
return event;
}
public void setEvent(Object event) {
this.event = event;
}
}
class OnOpenEvent {
Session session;
public OnOpenEvent(Session session) {
this.session = session;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
}
class OnMessageEvent {
Message message;
Session session;
public OnMessageEvent(Session session, Message message) {
this.message = message;
this.session = session;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
}
class OnCloseEvent {
Session session;
CloseReason reason;
public OnCloseEvent(Session session, CloseReason reason) {
this.session = session;
this.reason = reason;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public CloseReason getReason() {
return reason;
}
public void setReason(CloseReason reason) {
this.reason = reason;
}
}
class OnErrorEvent {
Session session;
Throwable t;
public OnErrorEvent(Session session,Throwable t) {
this.t = t;
this.session=session;
}
public Throwable getT() {
return t;
}
public void setT(Throwable t) {
this.t = t;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
}
class OnConnectingEvent {
String reason;
public OnConnectingEvent(String reason) {
this.reason = reason;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
}
enum WsEventType {
ONOPEN,ONMESSAGE,ONCLOSE,ONERROR,
ONCONNECTING // Using in Reconnecting state of the Websocket client.
}
You need use Java 8 JDK because im usign callables, etc.
You can implement a proxy pattern. I do a reconnect using this Java pattern.
But my implementation is for a raw Websocket java client.
A proxy pattern involve the funcionality of original object. You need add a reconnect() and onReconnect() methods to the cicle life of websocket. Websocket only have onError, onConnect, OnMessage, OnClose methods.
I will implement a recconnector for a SockJS Java client, then I will post the code if you want.
I use the IsolatingStorageSetting to store a collection of objects. It works great when my app is running but when I restart it...the collection is empty...Why does it not keep my object collection in memory.?
private void llsElements_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LongListSelector llselement = null;
listElementCollection.Clear();
if (sender != null)
llselement =(LongListSelector)sender;
if(llselement.SelectedItem!=null)
{
BdeskElement bdelement=(BdeskElement)llselement.SelectedItem;
if (bdelement.TypeElement == BdeskElement.BdeskTypeElement.File)
{
if (!IsolatedStorageSettings.ApplicationSettings.Contains(bdelement.URLElement))//IsCached? =>NON
{
if (IsolatedStorageSettings.ApplicationSettings.Count >= 100)//Si la liste des fichiers en cache est pleine
{
string KeyOldestElement = IsolatedStorageSettings.ApplicationSettings.Last().Key;
IsolatedStorageSettings.ApplicationSettings.Remove(KeyOldestElement);//on supprime le dernier élément de la liste
if (IsolatedStorageOperations.IsFileSaved(KeyOldestElement+bdelement.Extension))
IsolatedStorageOperations.DeleteFile(KeyOldestElement+bdelement.Extension);
}
IsolatedStorageSettings.ApplicationSettings.Add(bdelement.URLElement, bdelement);//on ajoute notre élément
DownloadAndReadFile(bdelement);
}
else //Si le fichier est deja présent dans la liste (donc déja en cache)
{
if (IsFileModified(bdelement, IsolatedStorageSettings.ApplicationSettings[bdelement.URLElement]))//compare la version téléchargée et la version en cache/ les versions sont identiques
{
string FileNameFormated = bdelement.URLElement.Replace("/", "_").Substring(7, bdelement.URLElement.Length - 7);
if (IsolatedStorageOperations.IsFileSaved(FileNameFormated))
{
MessageBox.Show("Le fichier est lu dans le cache");
byte[] Encryptedbytefile = IsolatedStorageOperations.GetFile((FileNameFormated));
byte [] UnCryptedByteFile=EncryptedString.DecryptDataToData(Encryptedbytefile);
IsolatedStorageOperations.SaveToFile(UnCryptedByteFile, "FileToRead" + bdelement.Extension);
IsolatedStorageOperations.ReadFile("FileToRead"+bdelement.Extension);
}
}
else//les versions sont différentes
{
IsolatedStorageSettings.ApplicationSettings.Remove(bdelement.URLElement);//supprime l'ancienne version
IsolatedStorageSettings.ApplicationSettings.Add(bdelement.URLElement, bdelement);//ajoute la nouvelle
DownloadAndReadFile(bdelement);
}
}
}
else if (bdelement.TypeElement == BdeskElement.BdeskTypeElement.Folder)
{
//l'élément cliqué devient l'élément courant
App.CurrentFolder = bdelement;
//On raffiche la page
NavigationService.Navigate(new Uri(String.Format("/Views/BDocs/FolderView.xaml?id={0}", Guid.NewGuid().ToString()), UriKind.Relative));
}
}
IsolatedStorageSettings.ApplicationSettings.Save(); //EDITED
}
EDIT
ISSUE I HAVE ON THE SAVE METHOD
Informations supplémentaires : Type 'System.Windows.Media.ImageSource' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.
Probably it's because you aren't saving it - try to use IsolatedStorageSettings.ApplicationSettings.Save() when you finsh with it.
Of course it won't work when you restart the Emulator - after restarting it is a fresh instance.
EDIT - after OP's edit
You cannot serialize ImageSource - similar question is here. Instead consider serializing ImagePath.
I am using OpenNLP but it is not giving me exact name,location,organization entity. How to extract entity using stanford parser?
My code might help you.
Here is my Code
public class stanfrdIntro {
public static void main(String[] args) throws IOException, SAXException,
TikaException {
String serializedClassifier = "classifiers/english.all.3class.distsim.crf.ser.gz";
AbstractSequenceClassifier<CoreLabel> classifier = CRFClassifier
.getClassifierNoExceptions(serializedClassifier);
if (args.length > 1) {
String fileContents = IOUtils.slurpFile(args[1]);
List<List<CoreLabel>> out = classifier.classify(fileContents);
for (List<CoreLabel> sentence : out) {
for (CoreLabel word : sentence) {
System.out.print(word.word() + '/' +
word.get(CoreAnnotations.AnswerAnnotation.class) + ' ');
}
System.out.println();
}
out = classifier.classifyFile(args[1]);
for (List<CoreLabel> sentence : out) {
for (CoreLabel word : sentence) {
System.out.print(word.word() + '/' +
word.get(CoreAnnotations.AnswerAnnotation.class) + ' ');
}
System.out.println();
}
} else {
String s1 = "Good afternoon Rahul Kulhari, how are you today?";
String s2 =
"I go to school at Stanford University, which is located in California.";
stanfrdIntro si = new stanfrdIntro();
String s1 = si.contentEx();
s1 = s1.replaceAll("\\s+", " ");
System.out.println(s1);
String t=classifier.classifyWithInlineXML(s1);
System.out.println(Arrays.toString(getTagValues(t).toArray()));
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//PERSON/text()");
Object value = expr.evaluate(doc, XPathConstants.STRING);
System.out.println(t);
System.out.println(classifier.classifyToString(s1));
Set<String> s=classifier.;
for(String s13: s)
{
System.out.println(s13);
}
System.out.println(classifier.classifyWithInlineXML(s1));
System.out.println(classifier.classifyToString(s1, "xml", true));
int i=0;
for (List<CoreLabel> lcl : classifier.classify(s2)) {
for (CoreLabel cl : lcl) {
System.out.println(i++ + ":");
System.out.println(cl);
}
}
}
}
}
I currently have this huge and slow code that takes forever to run.... Im in the process of refactoring it to make it somewhat more readable and overall provide a faster experience...
Basically I have a folder in my server where text files are stored with a LOT of data.. this script will read from this files and through EF add elements to the database... this takes a long time to load.
public class ScriptMetabolicoController : Controller
{
private IPortalAdministradorServices _servicioPortalAdministrador = new PortalAdministradorServices();
IRepositorio<Historia> historiarepo = new Repositorio<Historia>();
IRepositorio<Indicador_Metabolico> indicadorrepo = new Repositorio<Indicador_Metabolico>();
[Authorize(Roles = "Administrador")]
public ActionResult Index()
{
DirectoryInfo myDir = new DirectoryInfo(Server.MapPath("labtelFTP"));
ViewData["sinActualizacionesPendientes"] = false;
if (myDir.GetFiles().Count() != 0)
{
try
{
foreach (FileInfo file in myDir.GetFiles())
{
if (file.Extension != ".aspx")
{
StreamReader stream;
stream = file.OpenText();
while (stream.Peek() != -1)
{
string linea = stream.ReadLine();
string cedula = linea.Substring(2, 18).Trim();
Historia historia;
if (historiarepo.ObtenerTodos().Where(h => h.Cedula == cedula).Count() == 1)
{
//Se obtiene la historia por la cédula del participante
historia = historiarepo.ObtenerTodos().Where(h => h.Cedula == cedula).First();
//Se inicializan las fechas de solicitud y las fechas de reporte del examen que se lee del archivo
var numero = historia.Examenes_Metabolicos.Count();
int anor = Convert.ToInt32(linea.Substring(216, 4));
int mesr = Convert.ToInt32(linea.Substring(220, 2));
int diar = Convert.ToInt32(linea.Substring(222, 2));
DateTime fecha_reporte = new DateTime(anor, mesr, diar);
int anos = Convert.ToInt32(linea.Substring(202, 4));
int mess = Convert.ToInt32(linea.Substring(206, 2));
int dias = Convert.ToInt32(linea.Substring(208, 2));
DateTime fecha_solicitud = new DateTime(anos, mess, dias);
//Variable que tendrá el examen en cuestión
Examen_Metabolico examen;
//Si es el primer indicador de un examen nuevo en la historia del participante se crea una instancia nueva
if (historia.Examenes_Metabolicos.Where(e => e.Fecha_Solicitud == fecha_solicitud).Count() == 0)
{
examen = new Examen_Metabolico();
examen.Fecha_Reporte = fecha_reporte;
examen.Fecha_Solicitud = fecha_solicitud;
historia.Examenes_Metabolicos.Add(examen);
//Se crea en base de datos el examen vacío para luego agregarle valores metabólicos asociados a el.
//historiarepo.GuardarTodo();
}
//Si el indicador no es el primero de un examen nuevo entonces se le asigna a la variable 'examen' la referencia del mismo
else
{
examen = historia.Examenes_Metabolicos.Where(e => e.Fecha_Solicitud == fecha_solicitud).First();
}
//Se lee el código del indicador metabólico
string codigo = linea.Substring(236, 6).Trim();
//Si en efecto el indicador presente en la línea que se está leyendo existe se prosigue a anexarlos al examen
if (indicadorrepo.ObtenerTodos().Where(i => i.Codigo == codigo).Count() != 0)
{
//Se carga el indicador con el que se está trabajando en una línea específica
Indicador_Metabolico indicador = indicadorrepo.ObtenerTodos().Where(i => i.Codigo == codigo).First();
//Se crea una nueva instancia de valor metabólico
Valor_Metabolico val = new Valor_Metabolico();
//Se obtienen los valores del indicador de la línea del archivo que se está leyendo
string rango_alto = linea.Substring(194, 6).Trim();
string rango_bajo = linea.Substring(188, 6).Trim();
string unidades = linea.Substring(178, 10).Trim();
bool alerta = false;
string al = linea.Substring(200, 2).Trim();
if (al != "")
alerta = true;
string valor = linea.Substring(118, 60).Trim();
//Se inicializan los atributos del valor metabólico
//val.Examen_Metabolico_Id = examen.Id;
//val.Indicador_Metabolico_Id = indicador.Id;
val.Unidades = unidades;
val.Rango_Alto = rango_alto;
val.Rango_Bajo = rango_bajo;
val.Valor = valor;
val.Alerta = alerta;
val.Indicador_Metabolico = indicador;
examen.Valores_Metabolicos.Add(val);
historiarepo.GuardarTodo();
}
}
}
stream.Close();
file.MoveTo(Path.Combine(Server.MapPath("BackuplabtelFTP"), file.Name));
}
}
}
catch (Exception e)
{
ViewData["Error"] = true;
return View();
}
ViewData["Error"] = false;
return View();
}
else
{
ViewData["sinActualizacionesPendientes"] = true;
return View();
}
}
}
I know there is a feature called asynchronous controllers but Im not sure if they are meant for this case...
Please give me some advice on how to make this better.
ps. I would also like this script to be called regularly (once an hour) but Im not sure how to that either..
Does this need to be done in MVC? It seems like this could maybe be done by something like a windows service (which could be kind of a pain) or some other kind of scheduled app, maybe even a console application. For repeating tasks that just do things with either file systems or the DB, I use a console application that uses System.Threading.Timers. You let the background timer threads work and your web app is free to do, well, web things :)
If it needs to be web based, here's a handy post for how to do simple repeating tasks.
https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/
If you wanted to turn your action into an asynchronous action then your controller would look something like this:
public class ScriptMetabolicoController : AsyncController
{
private IPortalAdministradorServices _servicioPortalAdministrador = new PortalAdministradorServices();
IRepositorio<Historia> historiarepo = new Repositorio<Historia>();
IRepositorio<Indicador_Metabolico> indicadorrepo = new Repositorio<Indicador_Metabolico>();
[Authorize(Roles = "Administrador")]
public void IndexAsync()
{
AsyncManager.OutstandingOperations.Increment();
DirectoryInfo myDir = new DirectoryInfo(Server.MapPath("labtelFTP"));
AsyncManager.Parameters["sinActualizacionesPendientes"] = false;
if (myDir.GetFiles().Count() != 0)
{
try
{
foreach (FileInfo file in myDir.GetFiles())
{
if (file.Extension != ".aspx")
{
StreamReader stream;
stream = file.OpenText();
while (stream.Peek() != -1)
{
string linea = stream.ReadLine();
string cedula = linea.Substring(2, 18).Trim();
Historia historia;
if (historiarepo.ObtenerTodos().Where(h => h.Cedula == cedula).Count() == 1)
{
//Se obtiene la historia por la cédula del participante
historia = historiarepo.ObtenerTodos().Where(h => h.Cedula == cedula).First();
//Se inicializan las fechas de solicitud y las fechas de reporte del examen que se lee del archivo
var numero = historia.Examenes_Metabolicos.Count();
int anor = Convert.ToInt32(linea.Substring(216, 4));
int mesr = Convert.ToInt32(linea.Substring(220, 2));
int diar = Convert.ToInt32(linea.Substring(222, 2));
DateTime fecha_reporte = new DateTime(anor, mesr, diar);
int anos = Convert.ToInt32(linea.Substring(202, 4));
int mess = Convert.ToInt32(linea.Substring(206, 2));
int dias = Convert.ToInt32(linea.Substring(208, 2));
DateTime fecha_solicitud = new DateTime(anos, mess, dias);
//Variable que tendrá el examen en cuestión
Examen_Metabolico examen;
//Si es el primer indicador de un examen nuevo en la historia del participante se crea una instancia nueva
if (historia.Examenes_Metabolicos.Where(e => e.Fecha_Solicitud == fecha_solicitud).Count() == 0)
{
examen = new Examen_Metabolico();
examen.Fecha_Reporte = fecha_reporte;
examen.Fecha_Solicitud = fecha_solicitud;
historia.Examenes_Metabolicos.Add(examen);
//Se crea en base de datos el examen vacío para luego agregarle valores metabólicos asociados a el.
//historiarepo.GuardarTodo();
}
//Si el indicador no es el primero de un examen nuevo entonces se le asigna a la variable 'examen' la referencia del mismo
else
{
examen = historia.Examenes_Metabolicos.Where(e => e.Fecha_Solicitud == fecha_solicitud).First();
}
//Se lee el código del indicador metabólico
string codigo = linea.Substring(236, 6).Trim();
//Si en efecto el indicador presente en la línea que se está leyendo existe se prosigue a anexarlos al examen
if (indicadorrepo.ObtenerTodos().Where(i => i.Codigo == codigo).Count() != 0)
{
//Se carga el indicador con el que se está trabajando en una línea específica
Indicador_Metabolico indicador = indicadorrepo.ObtenerTodos().Where(i => i.Codigo == codigo).First();
//Se crea una nueva instancia de valor metabólico
Valor_Metabolico val = new Valor_Metabolico();
//Se obtienen los valores del indicador de la línea del archivo que se está leyendo
string rango_alto = linea.Substring(194, 6).Trim();
string rango_bajo = linea.Substring(188, 6).Trim();
string unidades = linea.Substring(178, 10).Trim();
bool alerta = false;
string al = linea.Substring(200, 2).Trim();
if (al != "")
alerta = true;
string valor = linea.Substring(118, 60).Trim();
//Se inicializan los atributos del valor metabólico
//val.Examen_Metabolico_Id = examen.Id;
//val.Indicador_Metabolico_Id = indicador.Id;
val.Unidades = unidades;
val.Rango_Alto = rango_alto;
val.Rango_Bajo = rango_bajo;
val.Valor = valor;
val.Alerta = alerta;
val.Indicador_Metabolico = indicador;
examen.Valores_Metabolicos.Add(val);
historiarepo.GuardarTodo();
}
}
}
stream.Close();
file.MoveTo(Path.Combine(Server.MapPath("BackuplabtelFTP"), file.Name));
}
}
AsyncManager.Parameters["Error"] = false;
}
catch (Exception e)
{
AsyncManager.Parameters["Error"] = true;
}
}
else
{
AsyncManager.Parameters["sinActualizacionesPendientes"] = true;
}
AsyncManager.OutstandingOperations.Decrement();
}
public ActionResult IndexCompleted(bool error, bool sinActualizacionesPendientes )
{
ViewData["sinActualizacionesPendientes"] = sinActualizacionesPendientes;
ViewData["Error"] = error;
return View();
}
}
And here's the MS article that could help you out:
http://msdn.microsoft.com/en-us/library/ee728598.aspx
Hope this helps!
Check this out it may help http://quartznet.sourceforge.net/ . I plan on using it in my current project to schedule up some longer running tasks.