jboss eap 7 - Post message to IBM MQ with resource adapter - jboss

I have installed WMQ JMS resource adapter (9.0.4) to my JBOSS EAP 7 standalone-full.xml & created connection factory and admin object to it.
/subsystem=resource-adapters/resource-adapter=ibm-mq-resource-adapter:add(archive=wmq.jmsra-9.0.4.0.rar, transaction-support=NoTransaction)
/subsystem=resource-adapters/resource-adapter=ibm-mq-resource-adapter/admin-objects=queue-ao1:add(class-name=com.ibm.mq.connector.outbound.MQQueueProxy, jndi-name=java:jboss/outbound)
/subsystem=resource-adapters/resource-adapter=ibm-mq-resource-adapter/admin-objects=queue-ao1/config-properties=baseQueueName:add(value=TEST1)
/subsystem=resource-adapters/resource-adapter=ibm-mq-resource-adapter/admin-objects=queue-ao1/config-properties=baseQueueManagerName:add(value=TESTMANAGER)
Connection definition:
<connection-definition class-name="com.ibm.mq.connector.outbound.ManagedConnectionFactoryImpl" jndi-name="java:jboss/mqSeriesJMSFactoryoutbound" tracking="false" pool-name="mq-cd">
<config-property name="channel">
SYSTEM.DEF.XXX
</config-property>
<config-property name="hostName">
XX-XXX
</config-property>
<config-property name="transportType">
CLIENT
</config-property>
<config-property name="queueManager">
TESTMANAGER
</config-property>
<config-property name="port">
1414
</config-property>
</connection-definition>
In my understanding, If I post a message to the outbound queue from the connection factory mqSeriesJMSFactoryoutbound, I should be able to reach IBM MQ. I tried with below code to look up connection factory but I am getting naming notfound exception. Please help
public class TestQueueConnection {
// Set up all the default values
private static final String DEFAULT_MESSAGE = "Hello, World! successfull";
private static final String DEFAULT_CONNECTION_FACTORY = "java:jboss/mqSeriesJMSFactoryoutbound";
private static final String DEFAULT_DESTINATION = "java:jboss/outbound";
private static final String DEFAULT_MESSAGE_COUNT = "1";
private static final String DEFAULT_USERNAME = "jmsuser";
private static final String DEFAULT_PASSWORD = "jmsuser123";
private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
private static final String PROVIDER_URL = "http-remoting://127.0.0.1:8070";
public static void main(String[] args) throws JMSException {
Context namingContext = null;
try {
String userName = System.getProperty("username", DEFAULT_USERNAME);
String password = System.getProperty("password", DEFAULT_PASSWORD);
// Set up the namingContext for the JNDI lookup
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
namingContext = new InitialContext(env);
// Perform the JNDI lookups
String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY);
namingContext.lookup(connectionFactoryString);
QueueConnectionFactory connectionFactory = (QueueConnectionFactory)
JMSContext jmsContext = connectionFactory.createContext(DEFAULT_USERNAME, DEFAULT_PASSWORD);
Queue destination = (Queue) namingContext.lookup(DEFAULT_DESTINATION);
jmsContext.createProducer().send(destination, DEFAULT_MESSAGE);
System.out.println("><><><><><><>< MESSAGE POSTED <><><><><><><>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" );
} catch (NamingException e) {
e.printStackTrace();
} finally {
if (namingContext != null) {
try {
namingContext.close();
} catch (NamingException e) {
}
}
}
}

Made couple of changes to the above.
In connection-definition, instead of com.ibm.mq.connector.outbound.ManagedConnectionFactoryImpl, used ManagedQueueConnectionFactoryImpl to avoid class cast exception at runtime.
Connection factories created by RA are not accessible outside of its JVM. Written a servlet to access these connection factory. I am able to connect with below piece of code.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
Context namingContext = null;
String connectionFactoryString = "mqSeriesJMSFactoryoutbound";
String queueName = "outbound";
MessageProducer producer = null;
Session session = null;
Connection conn =null;
try {
namingContext = new InitialContext();
QueueConnectionFactory connectionFactory = (QueueConnectionFactory) namingContext.lookup(connectionFactoryString);
Queue destination = (Queue) namingContext.lookup(queueName);
conn = connectionFactory.createConnection();
session = conn.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(destination);
TextMessage message = session.createTextMessage();
message.setText(msg);
producer.send(message,
Message.DEFAULT_DELIVERY_MODE,
Message.DEFAULT_PRIORITY,
Message.DEFAULT_TIME_TO_LIVE);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
// Close the message producer
try {
if (producer != null) producer.close();
}
catch (JMSException e) {
System.err.println("Failed to close message producer: " + e);
}
// Close the session
try {
if (session != null) session.close();
}
catch (JMSException e) {
System.err.println("Failed to close session: " + e);
}
// Close the connection
try {
if(conn != null)
conn.close();
}
catch (JMSException e) {
System.err.println("Failed to close connection: " + e);
}
}
}

Related

ConnectionFactory throwing errors when shared

I've a very simple application that adds messages to a queue and reads them using a MessagerListener.
Edit: I was testing this on a single instance of Artemis that had been setup as part of a two instance cluster on docker.
I want to create the ConnectionFactory once and reuse it for all producers and consumers in the application.
I have created the ConnectionFactory and stored it in a static variable (singleton) so it can be accessed from anywhere.
The aim is that the client use this shared connection factory to create a new connection when required.
However, I have noticed that doing this causes a "Failed to create session factory" when trying to create a new connection.
javax.jms.JMSException: Failed to create session factory
at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.createConnectionInternal(ActiveMQConnectionFactory.java:886)
at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.createConnection(ActiveMQConnectionFactory.java:299)
at com.test.artemistest.jms.QueueTest2.getMessagesFromQueue(QueueTest2.java:137)
at com.test.artemistest.jms.QueueTest2.access$000(QueueTest2.java:61)
at com.test.artemistest.jms.QueueTest2$1.run(QueueTest2.java:75)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: ActiveMQNotConnectedException[errorType=NOT_CONNECTED message=AMQ219007: Cannot connect to server(s). Tried with all available servers.]
at org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl.createSessionFactory(ServerLocatorImpl.java:690)
at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.createConnectionInternal(ActiveMQConnectionFactory.java:884)
If I create a connection factory per call this error does not occur.
Doing this seems very inefficient.
I've recreated a similar issue below.
If I create the connection factory in the main method the error occurs.
However if created just before use in a method it works as expected.
If I add two listeners the error occurs even though they are in separate threads. Could it be linked to the fact the connections are not closed in the consumers but are in the producers?
Why is this the case and do you recommend sharing the connection factory?
Thanks
public class QueueTest2 {
private static boolean shutdown = false;
private static ConnectionFactory cf;
public static void main(String[] args) {
// uncomment below for error to occur
// QueueTest2.getConnectionFactory("localhost", 61616);
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new Runnable() {
#Override
public void run() {
getMessagesFromQueue("localhost", 61616);
while (!shutdown) {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("getMessagesFromQueue shutdown");
}
});
addMessagesToQueue("localhost", 61616);
// uncommenting below also causes the issue
// executor.execute(new Runnable() {
// #Override
// public void run() {
// getMessagesFromQueue("localhost", 61616);
// while (!shutdown) {
// try {
// Thread.sleep(1000L);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// System.out.println("getMessagesFromQueue shutdown");
// }
// });
addMessagesToQueue("localhost", 61616);
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
shutdown = true;
executor.shutdownNow();
}
private static void addMessagesToQueue(String host, int port) {
ConnectionFactory cf2 = getConnectionFactory(host, port);
Connection connection = null;
Session sessionQueue = null;
try {
connection = cf2.createConnection("artemis", "password");
connection.setClientID("Producer");
sessionQueue = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
Queue orderQueue = sessionQueue.createQueue("exampleQueue");
MessageProducer producerQueue = sessionQueue.createProducer(orderQueue);
connection.start();
// send 100 messages
for (int i = 0; i < 100; i++) {
TextMessage message = sessionQueue.createTextMessage("This is an order: " + i);
producerQueue.send(message);
}
} catch (JMSException ex) {
Logger.getLogger(QueueTest2.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (sessionQueue != null) {
sessionQueue.close();
}
} catch (JMSException ex) {
Logger.getLogger(QueueTest2.class.getName()).log(Level.SEVERE, null, ex);
}
try {
if (connection != null) {
connection.close();
}
} catch (JMSException ex) {
Logger.getLogger(QueueTest2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private static void getMessagesFromQueue(String host, int port) {
ConnectionFactory cf2 = getConnectionFactory(host, port);
Connection connection2 = null;
Session sessionQueue2;
try {
connection2 = cf2.createConnection("artemis", "password");
connection2.setClientID("Consumer2");
sessionQueue2 = connection2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
Queue orderQueue = sessionQueue2.createQueue("exampleQueue");
MessageConsumer consumerQueue = sessionQueue2.createConsumer(orderQueue);
consumerQueue.setMessageListener(new MessageHandlerTest2());
connection2.start();
Thread.sleep(5000);
} catch (JMSException ex) {
Logger.getLogger(QueueTest2.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(QueueTest2.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static ConnectionFactory getConnectionFactory(String host, int port) {
if (cf == null) {
Map<String, Object> connectionParams2 = new HashMap<String, Object>();
connectionParams2.put(TransportConstants.PORT_PROP_NAME, port);
connectionParams2.put(TransportConstants.HOST_PROP_NAME, host);
TransportConfiguration transportConfiguration = new TransportConfiguration(NettyConnectorFactory.class
.getName(), connectionParams2);
cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, transportConfiguration);
}
return cf;
}
}
class MessageHandlerTest2 implements MessageListener {
#Override
public void onMessage(Message message) {
try {
System.out.println("new message: " + ((TextMessage) message).getText());
message.acknowledge();
} catch (JMSException ex) {
Logger.getLogger(MessageHandlerTest2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I've run your code, but I don't see any errors. My guess is that there may be a timing issue related to concurrency. Try adding synchronized to your getConnectionFactory method since it can theoretically be called concurrently by multiple threads in your application, e.g.:
private synchronized static ConnectionFactory getConnectionFactory(String host, int port)
I have found a solution that works on a clustered environment and docker.
It involves using the "pooled-jms" connection pool. Something I had planned to use anyway.
Although it does not explain the issues I was seeing above, it is at least a work around until I can investigate further.
The "WARN: AMQ212064: Unable to receive cluster topology " mentioned above appears to have been a red herring as it went away as quickly as it appeared.

Send email in specific time with Quartz

Hello i would like to ask your help concerning how to send email in quartz executor. That is my code
public class SchedulerJob implements Job{
#EJB
private ParticipationTaskDao participationTaskDao;
public void sendEmail() throws AddressException, MessagingException {
List<ParticipationTask> participantTasks=participationTaskDao.listParticipantTask();
for(ParticipationTask participantTask:participantTasks){
String subject="Task";
String message="You take part to the task "+participant.getTask().getName()+" from "+participant.getTask().getDateStart()+" to "+participant.getTask().getDateEnd()+". Description:"
+ participantTask.getTask().getDescription();
String receiver=participantTask.getUser().getEmail();
System.out.println("Email sent initialisation... ");
try {
final String username="mymail#gmail.com";
final String password="mypassword";
String host = "smtp.gmail.com";
String from = "mymail#gmail.com";
String pass = "mypassword";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "false");
props.put("mail.debug", "true");
Session session = Session.getInstance(props, new GMailAuthenticator(username, password));
MimeMessage message = new MimeMessage(session);
Address fromAddress = new InternetAddress(from);
Address toAddress = new InternetAddress(receiver);
message.setFrom(fromAddress);
message.setRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(subject);
message.setText(message);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
message.saveChanges();
Transport.send(message);
transport.close();
}catch(Exception ex){
System.out.println("<html><head></head><body>");
System.out.println("ERROR: " + ex);
System.out.println("</body></html>");
}
System.out.println(""Email sent successfully);
}
}
#Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
try {
sendEmail();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
When i start my server, i don't see nothing but if i decide to test the below code all things runs correctly
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("Quartz runs correctly");
}

Use apache httpclient as backend for jersey client base on PoolingHttpClientConnectionManager

i try to use apache httpclient as backend for jersey client to handle cookie automatically and here is my code
class ClientHelper {
public static HttpClientConnectionManager customConnectionManager() throws Exception {
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
throws CertificateException {
System.out.println("========checkClientTrusted=========");
}
#Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
throws CertificateException {
System.out.println("========checkServerTrusted==========");
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}}, new SecureRandom());
SSLConnectionSocketFactory
sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslContext);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnectionSocketFactory)
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager phcc = new PoolingHttpClientConnectionManager(registry);
return phcc;
}
public static Client createClient() {
HttpClient apacheClient = null;
try {
apacheClient =
HttpClientBuilder.create().setConnectionManager(customConnectionManager()).build();
} catch (Exception e) {
e.printStackTrace();
}
Client client = new Client(new ApacheHttpClient4Handler(apacheClient,
new BasicCookieStore(),
true));
return client;
}
}
I try to use the apache httpclient as the backend of jersey client (in order to handle the cookie)
Then, I create a simple class to test client,
import com.sun.jersey.api.client.Client;
....
public class ApiTest {
private static Client client;
public String getAuth(String username, String passwd) {
Map<String, String> formParams = new HashMap<String, String>();
formParams.put("username", String.valueOf(username));
formParams.put("passwd", String.valueOf(passwd));
try {
String basePath = "https://xyzhost/login";
if (client == null) {
client = ClientHelper.createClient();
client.addFilter(new LoggingFilter(System.out));
}
WebResource webResource = client.resource(basePath);
ClientResponse response = webResource.type("application/x-www-form-urlencoded").accept("application/json")
.post(ClientResponse.class, processFormParams(formParams));
if (response != null) {
String authRes = response.getEntity(String.class);
response.close();
return authRes;
} else {
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public String getSummary(){
try {
String basePath = "https://xyzhost/summary";
if (client == null) {
client = ClientHelper.createClient();
}
WebResource webResource = client
.resource(basePath);
ClientResponse response = webResource.type("application/x-www-form-urlencoded").accept("application/json")
.post(ClientResponse.class, processFormParams(formParams));
if (response != null) {
String serviceRes = response.getEntity(String.class);
response.close();
return serviceRes;
} else {
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) throws ApiException {
String username = "testuser";
String passwd = "testpasswd";
AuthApi apiTest = new ApiTest();
String auth =apiTest.getAuth(username, passwd);
String reslut1 = apiTest.getSummary();
String result2 = apiTest.getSummary();
String result3 = apiTest.getSummary();
String result4 = apiTest.getSummary();
}
}
So, I use the same client to hit the service under the same host.
I can success get the response for "auth" and "result1" but the client stuck in "result2" in the following part
ClientResponse response = webResource.type("application/x-www-form-urlencoded").accept("application/json")
.post(ClientResponse.class, processFormParams(formParams));
I try to modify the following part:
PoolingHttpClientConnectionManager phcc= new PoolingHttpClientConnectionManager(registry);
phcc.setDefaultMaxPerRoute(10);
then, ApiTest works, won't stuck. I guess there is some issue about the connection, since by default, the max per route for poolingHttpClientConnectionManager is 2, so my ApiTest will stuck in the 3rd request. I think the connection has been release since I have consume the response entity ,
if (response != null) {
String serviceRes = response.getEntity(String.class);
response.close();
return serviceRes;
}
but it seems not work at all, the connection seems not released.
anyone can help ? Appreciate!
I get one solution: switch the version of jersey-client from 1.17 to 1.18 , then problem solved!
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18</version>
<scope>compile</scope>
</dependency>

Use a TemporaryQueue on client-side for synchronous Request/Reply JMS with a JBoss server bean

I have a MDB running on JBoss 7.1, and a simple Java application as a client on another machine. The goal is the following:
the client sends a request (ObjectMessage) to the server
the server processes the request and sends back a response to the client (ObjectMessage again)
I thought to use a TemporaryQueue on the client to listen for the response (because I don't know how to do it asynchronously), and the JMSReplyTo Message's property to correctly reply back because I should support multiple independent clients.
This is the client:
public class MessagingService{
private static final String JBOSS_HOST = "localhost";
private static final int JBOSS_PORT = 5455;
private static Map connectionParams = new HashMap();
private Window window;
private Queue remoteQueue;
private TemporaryQueue localQueue;
private ConnectionFactory connectionFactory;
private Connection connection;
private Session session;
public MessagingService(Window myWindow){
this.window = myWindow;
MessagingService.connectionParams.put(TransportConstants.PORT_PROP_NAME, JBOSS_PORT);
MessagingService.connectionParams.put(TransportConstants.HOST_PROP_NAME, JBOSS_HOST);
TransportConfiguration transportConfiguration = new TransportConfiguration(NettyConnectorFactory.class.getName(), connectionParams);
this.connectionFactory = (ConnectionFactory) HornetQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, transportConfiguration);
}
public void sendRequest(ClientRequest request) {
try {
connection = connectionFactory.createConnection();
this.session = connection.createSession(false, QueueSession.AUTO_ACKNOWLEDGE);
this.remoteQueue = HornetQJMSClient.createQueue("testQueue");
this.localQueue = session.createTemporaryQueue();
MessageProducer producer = session.createProducer(remoteQueue);
MessageConsumer consumer = session.createConsumer(localQueue);
ObjectMessage message = session.createObjectMessage();
message.setObject(request);
message.setJMSReplyTo(localQueue);
producer.send(message);
ObjectMessage response = (ObjectMessage) consumer.receive();
ServerResponse serverResponse = (ServerResponse) response.getObject();
this.window.dispatchResponse(serverResponse);
this.session.close();
} catch (JMSException e) {
// TODO splittare e differenziare
e.printStackTrace();
}
}
Now I'm having troubles writing the server side, as I cannot figure out how to establish a Connection to a TemporaryQueue...
public void onMessage(Message message) {
try {
if (message instanceof ObjectMessage) {
Destination replyDestination = message.getJMSReplyTo();
ObjectMessage objectMessage = (ObjectMessage) message;
ClientRequest request = (ClientRequest) objectMessage.getObject();
System.out.println("Queue: I received an ObjectMessage at " + new Date());
System.out.println("Client Request Details: ");
System.out.println(request.getDeparture());
System.out.println(request.getArrival());
System.out.println(request.getDate());
System.out.println("Replying...");
// no idea what to do here
Connection connection = ? ? ? ? ? ? ? ?
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer replyProducer = session.createProducer(replyDestination);
ServerResponse serverResponse = new ServerResponse("TEST RESPONSE");
ObjectMessage response = session.createObjectMessage();
response.setObject(serverResponse);
replyProducer.send(response);
} else {
System.out.println("Not a valid message for this Queue MDB");
}
} catch (JMSException e) {
e.printStackTrace();
}
}
I cannot figure out what am I missing
You are asking the wrong question here.. You should look at how to create a Connection inside any Bean.
you need to get the ConnectionFactory, and create the connection accordingly.
For more information, look at the javaee examples on the HornetQ download.
In specific look at javaee/mdb-tx-send/ when you download hornetq.
#MessageDriven(name = "MDBMessageSendTxExample",
activationConfig =
{
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
#ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/testQueue")
})
public class MDBMessageSendTxExample implements MessageListener
{
#Resource(mappedName = "java:/JmsXA")
ConnectionFactory connectionFactory;
public void onMessage(Message message)
{
Connection conn = null;
try
{
// your code here...
//Step 11. we create a JMS connection
conn = connectionFactory.createConnection();
//Step 12. We create a JMS session
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
//Step 13. we create a producer for the reply queue
MessageProducer producer = sess.createProducer(replyDestination);
//Step 14. we create a message and send it
producer.send(sess.createTextMessage("this is a reply"));
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if(conn != null)
{
try
{
conn.close();
}
catch (JMSException e)
{
}
}
}
}

Socket closed after a while

I have my socket closed or reset by peer after a while,I think garbage collection problem through its reader or writer.
Asynctask for handling responses:
#Override
protected Void doInBackground(Void... params) {
//Log.e("NEW LISTENER THREAD NAME", name);
//initializations
try{
clientSocket = new Socket();
//clientSocket.setTcpNoDelay(true);
clientSocket.connect(new InetSocketAddress(serverURL, dataServerPort));
requestSender = new PrintWriter(new PrintStream(clientSocket.getOutputStream(), true,"UTF-8"));
Sender.Init();
}catch(Exception e){
e.printStackTrace();
}
gsonObj = new GsonBuilder().create();//This the object that handels every comming response
finish = false;
try{
listener = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}catch (IOException e) {
Log.e("FROM CREATING LISTENER", "FROM CREATING LISTENER ========> ");
e.printStackTrace();
}
LOGGED_IN = StaticArea.getLoggedIn(cnt);
if(LOGGED_IN){
USER = StaticArea.getUserName(cnt);
Sender.ResumeUser();
/*********DELEGATING CONNECTING TO SERVER TO BE USED IN SERVICE*************/
Message connectionMsg = new Message();
connectionMsg.obj = Boolean.valueOf(true);
serviceHandler.handleMessage(connectionMsg);
/*********END DELEGATING CONNECTING TO SERVER*************/
}else{
/*********DELEGATING CONNECTING TO SERVER TO BE USED IN SERVICE*************/
Message connectionMsg = new Message();
connectionMsg.obj = Boolean.valueOf(false);
serviceHandler.handleMessage(connectionMsg);
/*********END DELEGATING CONNECTING TO SERVER*************/
}
GoOnline();
while(!finish){
try{
answerS = listener.readLine();
if(answerS != null )//to avoid any null response
if(answerS.contains(Response.MYRESPONSE){
if(MyService.theHandler != null){
Message msg = new Message();
msg.obj = answerS;
MyService.theHandler.sendMessage(msg);
The Sender class is class that has a static methods and uses my sockets output:
public class Sender {
private static Gson gsonObj;
public static void Init() {
gsonObj = new GsonBuilder().create();
}
public static void SendTestRequest(){
try{
Request req = new Request();
req.setR_TYPE(Request.TEST);
String reqString = gsonObj.toJson(req);
requestSender.println(reqString);
requestSender.flush();
}catch(Exception e){
}
}//end method