Error in retrieving messages from Gmail server using javaxmail - jakarta-mail

This code is for retrieving mails from gmail server it works only for one minutes then it stops why ?
ActionListener displayNotification = new ActionListener() {
int oldn=0, newn=0;Folder f = s.getmailFolder();
public void actionPerformed(ActionEvent ae) {
try{
f=s.getmailFolder();
newn=f.getUnreadMessageCount();
}catch(Exception e){}
if (oldn!=newn)
s.getNotification(f);
oldn=newn;
}
};
Timer t = new Timer (10000,displayNotification);
t.start();

Related

BaseX parrallel Client

I have client like this :
import org.basex.api.client.ClientSession;
#Slf4j
#Component(value = "baseXAircrewClient")
#DependsOn(value = "baseXAircrewServer")
public class BaseXAircrewClient {
#Value("${basex.server.host}")
private String basexServerHost;
#Value("${basex.server.port}")
private int basexServerPort;
#Value("${basex.admin.password}")
private String basexAdminPassword;
#Getter
private ClientSession session;
#PostConstruct
private void createClient() throws IOException {
log.info("##### Creating BaseX client session {}", basexServerPort);
this.session = new ClientSession(basexServerHost, basexServerPort, UserText.ADMIN, basexAdminPassword);
}
}
It is a singleton injected in a service which run mulitple queries like this :
Query query = client.getSession().query(finalQuery);
return query.execute();
All threads query and share the same session.
With a single thread all is fine but with multiple thread I get some random (and weird) error, like the result of a query to as a result of another.
I feel that I should put a synchronized(){} arround query.execute() or open and close session for each query, or create a pool of session.
But I don't find any documentation how the use the session in parrallel.
Is this implementation fine for multithreading (and my issue is comming from something else) or should I do it differently ?
I ended creating a simple pool by adding removing the client from a ArrayBlockingQueue and it is working nicely :
#PostConstruct
private void createClient() throws IOException {
log.info("##### Creating BaseX client session {}", basexServerPort);
final int poolSize = 5;
this.resources = new ArrayBlockingQueue < ClientSession > (poolSize) {
{
for (int i = 0; i < poolSize; i++) {
add(initClient());
}
}
};
}
private ClientSession initClient() throws IOException {
ClientSession clientSession = new ClientSession(basexServerHost, basexServerPort, UserText.ADMIN, basexAdminPassword);
return clientSession;
}
public Query query(String finalQuery) throws IOException {
ClientSession clientSession = null;
try {
clientSession = resources.take();
Query result = clientSession.query(finalQuery);
return result;
} catch (InterruptedException e) {
log.error("Error during query execution: " + e.getMessage(), e);
} finally {
if (clientSession != null) {
try {
resources.put(clientSession);
} catch (InterruptedException e) {
log.error("Error adding to pool : " + e.getMessage(), e);
}
}
}
return null;
}

JMS Request Reply Pattern, No Output

TestRequestresponse:
public static void main(String args[]) throws JMSException {
TibjmsConnectionFactory connectionFactory = new TibjmsConnectionFactory(
"tcp://localhost:7222");
Connection con = connectionFactory.createConnection("admin", "");
con.start();
Session s = con.createSession();
System.out.println("Successfully created JMS Connection and Session!");
Queue q1 = s.createQueue("train.ems.queue.test");
System.out.println(q1);
System.out.println("Queue created!");
TemporaryQueue tq = s.createTemporaryQueue();
MessageProducer mp = s.createProducer(q1);
MessageConsumer mc = s.createConsumer(tq);
TextMessage tm = s.createTextMessage("Hi this is ABHISHEK!");
tm.setStringProperty("Country", "IN");
tm.setJMSCorrelationID("SENDER");
tm.setJMSReplyTo(tq);
mp.setTimeToLive(30000);
mp.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
mp.setPriority(Message.DEFAULT_PRIORITY);
mp.send(tm);
Message recv = mc.receive(60000);
if (recv != null) {
System.out.println(recv.getBody(String.class));
}
mp.close();
s.close();
con.close();
}
TestAsyncReceiveMessage:
public class TestAsyncReceiveMessage implements MessageListener {
Session s;
Queue q1;
MessageProducer mp;
public static void main(String ars[]) throws JMSException {
TestAsyncReceiveMessage obj = new TestAsyncReceiveMessage();
obj.createSession();
obj.createQueue();
obj.msgConsumer();
}
private void msgConsumer() throws JMSException {
// TODO Auto-generated method stub
MessageConsumer mc = s.createConsumer(q1, "Country='IN'");
mc.setMessageListener(new TestAsyncReceiveMessage());
}
private void createQueue() throws JMSException {
// TODO Auto-generated method stub
q1 = s.createQueue("train.ems.queue.test");
// t1=s.createTopic("train.ems.topic.test");
}
private void createSession() throws JMSException {
// TODO Auto-generated method stub
TibjmsConnectionFactory connectionFactory = new TibjmsConnectionFactory(
"tcp://localhost:7222");
Connection con = connectionFactory.createConnection("admin", "");
s = con.createSession();
System.out.println("Successfully created JMS Connection and Session!");
}
public void onMessage(Message arg0) {
try {
System.out.println(arg0.getBody(String.class));
TextMessage tm = s.createTextMessage("ACk");
Queue t = (Queue) arg0.getJMSReplyTo();
mp = s.createProducer(t);
mp.send(tm);
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Well First it showed me NullPointerException when creating TextMessage in onMessage, i changed something and theres no more exception, but theres no putput either. Help! :)
You have not called Connection.Start() method after creating it in TestAsyncReceiveMessage code. Application has to call Connection.Start() to inform the messaging provider to start delivering messages. Otherwise messages will not be delivered to consumer.
Connection.Start is typically called after consumer is created and any message listeners are attached to consumer so that the consumer is ready to receive messages.

javaFX : How to periodically load information from db and show it on a Label?

I want to execute a method periodically, this method get informations from database it show it into a label, I tried the following code :
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//update information
miseAjour();
}
}, 0, 2000);
when i run the main program, the background service run also normaly but when the informations changes on db i get this exception:
Exception in thread "Timer-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = Timer-0
And this is the code of method miseAjour :
public void miseAjour(){
try {
dbConnection db = new dbConnection();
Connection connect = db.connectiondb();
connect.setAutoCommit(false);
Statement stmt= connect.createStatement();
ResultSet rs = stmt.executeQuery("SELECT count(*) as nbrAderent FROM gss_aderent ");
int nbrAderent = rs.getInt("nbrAderent");
rs.close();
stmt.close();
connect.commit();
connect.close();
main_nbrAdrTot.setText(nbrAderent + "");
} catch (SQLException ex) {
Logger.getLogger(SimpleController.class.getName()).log(Level.SEVERE, null, ex);
}
}
You can Timer for this, but I would recommend to use the JavaFX provided API called as ScheduledService.
ScheduledService is made to execute the same Task at regular intervals and since it creates a Task internally, there are API which help you to bind the value to the UI controls.
ScheduledService<Object> service = new ScheduledService<Object>() {
protected Task<Object> createTask() {
return new Task<Object>() {
protected Object call() {
// Call the method and update the message
updateMessage(miseAjour());
return object; // Useful in case you want to return data, else null
}
};
}
};
service.setPeriod(Duration.seconds(10)); //Runs every 10 seconds
//bind the service message properties to your Label
label.textProperty().bind(service.messageProperty()); // or use your label -> main_nbrAdrTot
Inside the dbcall method miseAjour, return the value that you have fetched and you want to update the label with :
public String miseAjour(){
String nbrAderent = null;
try {
dbConnection db = new dbConnection();
Connection connect = db.connectiondb();
connect.setAutoCommit(false);
Statement stmt= connect.createStatement();
ResultSet rs = stmt.executeQuery("SELECT count(*) as nbrAderent FROM gss_aderent ");
nbrAderent = String.valueOf(rs.getInt("nbrAderent"));
connect.commit();
} catch (SQLException ex) {
Logger.getLogger(SimpleController.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
rs.close();
stmt.close();
connect.close();
}
return nbrAderent;
}
Finnaly i resolved the problem ,here is the code :
public class TimerServiceApp {
public void start() throws Exception {
TimerService service = new TimerService();
service.setPeriod(Duration.seconds(10));
service.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent t) {
main_nbrAdrTot.setText(t.getSource().getMessage());
}
});
service.start();
}
private class TimerService extends ScheduledService<Integer> {
private final StringProperty nbrTotAderent = new SimpleStringProperty();
public final void setTotalAderentNumber(String value ) {
nbrTotAderent.set(value);
}
public String getTotalAderentNumber() throws SQLException {
String nbrAderent = null;
ResultSet rs=null;
Statement stmt=null;
Connection connect=null;
try {
dbConnection db = new dbConnection();
connect = db.connectiondb();
connect.setAutoCommit(false);
stmt= connect.createStatement();
rs = stmt.executeQuery("SELECT count(*) as nbrAderent FROM gss_aderent ");
nbrAderent = String.valueOf(rs.getInt("nbrAderent"));
connect.commit();
} catch (SQLException ex) {
Logger.getLogger(SimpleController.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
rs.close();
stmt.close();
connect.close();
}
System.out.println(" Total aderent number updated to :" + nbrAderent + " Aderents ");
return nbrAderent;
}
protected Task<Integer> createTask() {
return new Task<Integer>() {
protected Integer call() throws SQLException {
nbrTotAderent.setValue(getTotalAderentNumber());
updateMessage(getTotalAderentNumber());
return Integer.parseInt(getTotalAderentNumber());
}
};
}
}
} `
and i called this service by :
TimerServiceApp s = new TimerServiceApp();
s.start();
i dont know if the solution is optimised but it work :) thank you #ItachiUchiha i took the solution from yout answer in the following link

I am unable build up a query in Solr

I am trying to form a query in solr for data import but could not able to do so.
I need to form the below query:
http://salsa23q-XXX-08.XXX.XXX.com:8080/solr/#/geoloc_replica1/dataimport/?command=full-import&clean=true
The code I am trying:
public class SolrJDB
{
public static String url = "http://salsa23q-XXX-08.XXX.XXX.com:8080/solr:8080/solr";
public static SolrServer localserver;
public static CloudSolrServer cloudserver;// = new CloudSolrServer("url");
public static SolrQuery que;
public static SolrInputDocument doc;
public static SolrDocumentList list;
public static QueryResponse response;
public static String serverurl = "http://salsa23q-XXX-08.XXX.XXX.com:8080/solr";
public static void main(String[] args) throws MalformedURLException, SQLException, SolrServerException {
try{
System.out.println("+++++++++++++ Starting here +++++++++++++++++++++");
//Cloud Server
String url = "salsa23q-XXX-08.XXX.XXX.com:8080/solr";
cloudserver = new CloudSolrServer(url);
SolrQuery parameters = new SolrQuery();
parameters.set("qt","/geoloc_replica1");
parameters.set("qt","//dataimport");
parameters.set("command","full-import");
System.out.println("Query to be Executed ============"+parameters.toString());
QueryResponse response = cloudserver.query(parameters);
SolrDocumentList list = response.getResults();
}
catch(SolrServerException e){
System.out.println(e.toString());
e.printStackTrace();
}
catch(Exception e){
System.out.println(e.toString());
e.printStackTrace();
}
}
}
I am getting following error:
org.apache.solr.client.solrj.SolrServerException: Error executing query
at org.apache.solr.client.solrj.request.QueryRequest.process(QueryRequest.java:98)
at org.apache.solr.client.solrj.SolrServer.query(SolrServer.java:301)
at SolrJDB.main(SolrJDB.java:37)
Caused by: java.lang.RuntimeException
at org.apache.solr.common.cloud.SolrZkClient.<init>(SolrZkClient.java:115)
at org.apache.solr.common.cloud.SolrZkClient.<init>(SolrZkClient.java:83)
at org.apache.solr.common.cloud.ZkStateReader.<init>(ZkStateReader.java:138)
at org.apache.solr.client.solrj.impl.CloudSolrServer.connect(CloudSolrServer.java:140)
at org.apache.solr.client.solrj.impl.CloudSolrServer.request(CloudSolrServer.java:165)
at org.apache.solr.client.solrj.request.QueryRequest.process(QueryRequest.java:90)
... 2 more
You are mixing up things in your code. You want to perform a request to run a DataImportHandler. But you are constructing a SolrQuery. The latter represents a search request.
What you need to run a DataImportHandler via the Java API is an UpdateRequest.
public int runDataImportHandler() throws Exception {
// fill in the parameters you want to run your import with
ModifiableSolrParams tmpParams = new ModifiableSolrParams();
tmpParams.set("command", "full-import");
tmpParams.set("clean", true);
tmpParams.set("commit", true);
tmpParams.set("optimize", true);
// create the update request
UpdateRequest tmpRequest = new UpdateRequest("/dataimport");
tmpRequest.setParams(tmpParams);
SolrServer tmpServer = getServer();
tmpRequest.process(tmpServer);
ModifiableSolrParams tmpStatusParams = new ModifiableSolrParams();
tmpStatusParams.set("command", "status");
String tmpStatus = "busy";
int tmpProcessed = 0;
do {
System.out.println("waiting for import to finish, status was " + tmpStatus);
Thread.sleep(500);
UpdateRequest tmpStatusRequest = new UpdateRequest("/dataimport");
tmpStatusRequest.setParams(tmpStatusParams);
UpdateResponse tmpStatusResponse = tmpStatusRequest.process(tmpServer);
tmpStatus = tmpStatusResponse.getResponse().get("status").toString();
Map tmpMessages = (Map) tmpStatusResponse.getResponse().get("statusMessages");
System.out.println("import status is " + tmpStatus);
if (tmpMessages.get("Total Documents Processed") != null) {
tmpProcessed = Integer.valueOf(tmpMessages.get("Total Documents Processed").toString());
}
} while ("busy".equals(tmpStatus));
System.out.println("import done");
return tmpProcessed;
}
As I can see your code the exception is related to how CloudSolrServer instance is created :-
To make instance of CloudSolrServer you need to have Solr in Cloud mode and the URL used here will be zookeeper address. CloudSolrServer creates zkStateReader which gets live nodes and collection from which it query.
Following is the exact way how you would be creating the code for dataimport:-
public static void main(String[] args) throws SolrServerException, IOException {
ModifiableSolrParams params = new ModifiableSolrParams();
params.set(UpdateParams.COLLECTION, "collection1");
params.set(CommonParams.QT, "/dataimport");
params.set("command", "full-import");
params.set("claen", true);
params.set(UpdateParams.COMMIT, true);
params.set(UpdateParams.OPTIMIZE, true);
String url = "localhost:9983"; /*Zookeeper Address*/
CloudSolrServer cloudserver = new CloudSolrServer(url, true);
cloudserver.setDefaultCollection("test");/*This is necessary in case if you are not specifying any collection name in dataimport*/
cloudserver.query(params);
}

Send JSon from Server to Client in GCM

I am Using GCM (Google Cloud Messaging).In that what i want i want to send J Son from the server side .On Client side I want to receive that for simple message i have done but i am stucked how could i pass J Son from the server side to the client side.
Please help me to resolve this.
This is my Server side code
public class GCMBroadcast extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String SENDER_ID = "";
private static final String ANDROID_DEVICE = "";
private List<String> androidTargets = new ArrayList<String>();
public GCMBroadcast() {
super();
androidTargets.add(ANDROID_DEVICE);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String collapseKey = "";
String userMessage = "";
try {
userMessage = request.getParameter("Message");
collapseKey = request.getParameter("CollapseKey");
} catch (Exception e) {
e.printStackTrace();
return;
}
Sender sender = new Sender(SENDER_ID);
Message message = new Message.Builder()
.collapseKey(collapseKey)
.addData("message", userMessage)
.build();
try {
MulticastResult result = sender.send(message, androidTargets, 1);
System.out.println("Response: " + result.getResults().toString());
if (result.getResults() != null) {
int canonicalRegId = result.getCanonicalIds();
if (canonicalRegId != 0) {
System.out.println("response " +canonicalRegId );
}
} else {
int error = result.getFailure();
System.out.println("Broadcast failure: " + error);
}
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("CollapseKey", collapseKey);
request.setAttribute("Message", userMessage);
request.getRequestDispatcher("XX.jsp").forward(request, response);
}
}
Your payload (added to the Message by calls to addData) can only be name/value pairs. If you want to send a JSON, you can put a JSON string in the value of such name/value pair. Then you'll have to parse that JSON yourself in the client side.
For example :
.addData("message","{\"some_json_key\":\"some_json_value\"}")

Resources