Send automatic message on a given date - java

I have made a SMS application with Java that works like a charm. I want the application to send SMS on a given date. I am using the Quartz Job Scheduling for that. First I need these two applications to be connected to each other. Then I need Quartz to collect a date and time from a list (can be excel list) and send a message. Is this possible? Appreciate any help.
Here is the message application:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.codec.binary.Base64;
public class SMSApplication {
public static void main(String[] args) {
try {
String phoneNumber = "+XXXXXXXXX";
String appKey = "XXXXXXX";
String appSecret = "XXXXXXXX";
String message = "Hello world!";
URL url = new URL("https://messagingapi.sinch.com/v1/sms/" + phoneNumber);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
String userCredentials = "application\\" + appKey + ":" + appSecret;
byte[] encoded = Base64.encodeBase64(userCredentials.getBytes());
String basicAuth = "Basic " + new String(encoded);
connection.setRequestProperty("Authorization", basicAuth);
String postData = "{\"Message\":\"" + message + "\"}";
OutputStream os = connection.getOutputStream();
os.write(postData.getBytes());
StringBuilder response = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ( (line = br.readLine()) != null)
response.append(line);
br.close();
os.close();
System.out.println(response.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is the Quartz job class:
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class QuartzJob implements Job{
#Override
public void execute(JobExecutionContext jec) throws JobExecutionException {
System.out.println("Hello");
System.out.println(new Date())
}
}
And here is the Quartz main class:
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.ScheduleBuilder;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzMain {
public static void main(String[] args) throws SchedulerException {
JobDetail job = JobBuilder.newJob(QuartzJob.class).build();
Trigger tl = TriggerBuilder.newTrigger().withIdentity("SimpleTrigger").startNow().build();
Scheduler sc = StdSchedulerFactory.getDefaultScheduler();
sc.start();
sc.scheduleJob(job, tl);
}}

To start at a given date:
In the trigger replace .startNow() with .startAt(date) with date being a java.util.Date that represents the date and time it should start.
To connect:
In your Quartz job class call your sendSMS() method (currently your main method in SMSApplication) any variables (such as the phone number) should be passed to the job class in the job builer with .usingJobData("key","value"). See http://www.quartz-scheduler.org/documentation/quartz-2.3.0/ and read through the Tutorials and Cookbook for more information.

Related

Mock an instance method call of another class that takes a URL and File object and writes a file to a HTTP connection

I'm trying to write UTs for a file called DocumentStoreAccessor.java. Here is the class below:
package com.company.main.accessor;
import com.company.main.dagger.component.AccessorComponent;
import com.company.main.dagger.component.DaggerAccessorComponent;
import com.company.main.util.aws.s3.AWSS3Util;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
#Slf4j
#RequiredArgsConstructor
public class DocumentStoreAccessor {
private final DocumentStore documentStoreClient; //Comes from Dagger
public DocumentStoreAccessor() {
AccessorComponent accessorComponent = DaggerAccessorComponent.create();
this.documentStoreClient = accessorComponent.provideDocumentStoreClient();
}
private int putContentsIntoS3(CreateUploadS3UrlResult createUploadS3UrlResponse,
#NonNull File file) {
int uploadStatusCode = 0;
try {
URL url = new URL(createUploadS3UrlResponse.getS3Url());
uploadStatusCode = new AWSS3Util().upload(url, file); //Instance comes from a util class
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return uploadStatusCode;
}
public String uploadFile(File file, DocumentFileExtension fileExtension) throws Exception {
String documentId = null;
CreateUploadS3UrlResult createUploadS3Urlresult = documentStoreClient.createUploadS3Url(new CreateUploadS3UrlRequest());
int putContentsStatusCode = putContentsIntoS3(createUploadS3Urlresult, file);
if (putContentsStatusCode == 200) {
CreateDocumentRequest createDocumentRequest = new CreateDocumentRequest()
CreateDocumentResult document = documentStoreClient.createDocument(createDocumentRequest);
documentId = document.getDocumentId();
} else {
throw new Exception("Status code is: " + putContentsStatusCode);
}
return documentId;
}
}
Inside this file I do new AWSS3Util().upload(url, file).
And here is the AWSS3Util.java
package com.company.main.util.aws.s3;
import com.company.main.exception.DataAccessException;
import com.company.main.exception.RetriableDataAccessException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
#Slf4j
#AllArgsConstructor
#Builder
public class AWSS3Util {
private static final String PUT_REQUEST_METHOD = "PUT";
public int upload(#NonNull final URL url, #NonNull final File file) throws IOException {
final InputStream inputStream = new FileInputStream(file);
final Reader fileReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
final BufferedReader br = new BufferedReader(fileReader);
HttpURLConnection connection = null;
int responseCode = 0;
try {
// Create the connection and use it to upload the new object using the pre-signed URL.
connection = create(url);
connection.setDoOutput(true);
connection.setRequestMethod(PUT_REQUEST_METHOD);
final OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
String st;
while ((st = br.readLine()) != null) {
out.write(st);
}
out.close();
responseCode = connection.getResponseCode();
} catch (IOException e) {
throw new RetriableDataAccessException(String.format("S3 upload request failed with request: %s", url.toString()), e);
} finally {
inputStream.close();
fileReader.close();
br.close();
}
return responseCode;
}
private HttpURLConnection create(URL url) throws IOException {
return (HttpURLConnection) url.openConnection();
}
}
I want to make new AWSS3Util().upload(url, file) return a 200..
I'm unable to do so.. I keep getting a NullPointerException. Here is what I have for the past day:
package com.company.main.accessor;
import com.company.main.util.aws.s3.AWSS3Util;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
#ExtendWith(MockitoExtension.class)
public class DocumentStoreAccessorTest {
#Mock
private DocumentStore mockDocumentStoreClient;
#Mock
private HttpURLConnection httpURLConnection;
#Mock
private OutputStream outputStream;
#InjectMocks
private DocumentStoreAccessor classUnderTest;
private URL url;
private AWSS3Util awss3Util;
private CreateUploadS3UrlRequest dummyCreateUploadS3UrlRequest;
private CreateUploadS3UrlResult dummyCreateUploadS3UrlResult;
private CreateDocumentRequest dummyCreateDocumentRequest;
private CreateDocumentResult dummyCreateDocumentResult;
#BeforeEach
void setUp() throws IOException {
awss3Util = new AWSS3Util();
url = getMockUrl(httpURLConnection);
dummyCreateUploadS3UrlRequest = new CreateUploadS3UrlRequest();
dummyCreateUploadS3UrlResult = new CreateUploadS3UrlResult().withS3Url("http://foo.io://:99");
dummyCreateDocumentRequest = new CreateDocumentRequest();
dummyCreateDocumentResult = new CreateDocumentResult().withDocumentId("foo");
}
#Test
void uploadSuccess() throws IOException {
when(mockDocumentStoreClient.createUploadS3Url(dummyCreateUploadS3UrlRequest)).thenReturn(dummyCreateUploadS3UrlResult);
AWSS3Util aSpy = Mockito.spy(awss3Util);
Mockito.when(aSpy.upload(url, getDataToUpload())).thenReturn(200);
when(mockDocumentStoreClient.createDocument(dummyCreateDocumentRequest)).thenReturn(dummyCreateDocumentResult);
String id = classUnderTest.uploadFile(getDataToUpload(), DocumentFileExtension.XLSX);
assertEquals(id, "foo");
verify(mockDocumentStoreClient, times(1)).createUploadS3Url(dummyCreateUploadS3UrlRequest);
}
private File getDataToUpload() {
return new File("TestFileName.xlsx");
}
/**
* We cannot directly use Mockito to mock URL. This helper method, helps us to create the mock url.
* <p>
* https://stackoverflow.com/questions/565535/mocking-a-url-in-java
*/
private URL getMockUrl(HttpURLConnection httpURLConnection) throws IOException {
final URLStreamHandler handler = new URLStreamHandler() {
#Override
protected URLConnection openConnection(final URL arg0)
throws IOException {
return httpURLConnection;
}
};
final URL url = new URL("http://foo.io", "foo.io", 80, "", handler);
return url;
}
}
I'm unable to mock the URL class, so I followed a another Stackoverflow post..
The AWSS3Util cannot come through Dagger, it is a util class that we're all using so this must not change.
I'm not sure if I'm going in the right direction.. I've tried "spying" on that AWSS3Util class. I want this method to return a 200 or any status code of my choice to cover them in UTs by asserting a String return as seen in the example below
I can change the the upload method inside AWSS3Util to static if it helps UTs
Cannot use PowerMockito (this is a last resort)
Try incorporating Yan's comments:
#Test
void verifyCreateUploadS3UrlInvocation() throws Exception {
when(mockDocumentStoreClient.createUploadS3Url(dummyCreateUploadS3UrlRequest)).thenReturn(dummyCreateUploadS3UrlResult);
when(httpURLConnection.getOutputStream()).thenReturn(outputStream);
when(httpURLConnection.getResponseCode()).thenReturn(200);
when(awss3Util.upload(url, getDataToUpload())).thenReturn(200);
when(mockDocumentStoreClient.createDocument(dummyCreateDocumentRequest)).thenReturn(dummyCreateDocumentResult);
String id = classUnderTest.uploadFile(getDataToUpload(), DocumentFileExtension.XLSX);
assertEquals(id, "foo");
verify(mockDocumentStoreClient, times(1)).createUploadS3Url(dummyCreateUploadS3UrlRequest);
}
I get a 405 thrown when I specifically want it to send a 200, and therefore java.lang.Exception: Status code is: 405 thrown from my function.
Firstly I would change a little bit AWSS3Util, because reading binary files as string can lead to very interesting results.
import lombok.NonNull;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class AWSS3Util {
private static final String PUT_REQUEST_METHOD = "PUT";
public int upload(#NonNull final URL url, #NonNull final File file) throws IOException {
HttpURLConnection connection = create(url);
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
connection.setDoOutput(true);
connection.setRequestMethod(PUT_REQUEST_METHOD);
try (BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream())) {
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) > 0) {
bos.write(buffer, 0, len);
}
}
return connection.getResponseCode();
}
}
private HttpURLConnection create(URL url) throws IOException {
return (HttpURLConnection) url.openConnection();
}
}
Test for upload method could be like this:
import org.junit.jupiter.api.Test;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.nio.file.Files;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MyTest {
#Test
public void test() throws IOException {
final HttpURLConnection mockUrlCon = mock(HttpURLConnection .class);
URLStreamHandler stubUrlHandler = new URLStreamHandler() {
#Override
protected URLConnection openConnection(URL u) throws IOException {
return mockUrlCon;
}
};
URL url = new URL("http://foo.io", "foo.io", 80, "", stubUrlHandler);
when(mockUrlCon.getResponseCode()).thenReturn(200);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
when(mockUrlCon.getOutputStream()).thenReturn(outputStream);
File file = new File("c:\\anyFile.png");
int responseCode = new AWSS3Util().upload(url, file);
assertEquals(200, responseCode);
byte[] expectedBytes = Files.readAllBytes(file.toPath());
byte[] actualBytes = outputStream.toByteArray();
assertArrayEquals(expectedBytes, actualBytes);
}
}
I had to violate the second rule - I had to DependencyInject it via Dagger
package com.company.main.dagger.module;
import com.company.main.util.aws.s3.AWSS3Util;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;
#Module
public class AWSS3UtilModule {
#Provides
#Singleton
public static AWSS3Util provideAwss3Util() {
return new AWSS3Util();
}
}
and then in my component
import javax.inject.Singleton;
#Singleton
#Component(modules = {
ShipDocsDMSAccessorModule.class,
AWSS3UtilModule.class
})
public interface AccessorComponent {
ShipDocsDMS provideShipDocsDMSClient();
AWSS3Util provideAwss3Util();
}
and then in my main class
#Slf4j
#RequiredArgsConstructor
public class ShipDocsDMSAccessor {
private final ShipDocsDMS shipDocsDMSClient;
private final AWSS3Util awss3Util;
public ShipDocsDMSAccessor() {
AccessorComponent accessorComponent = DaggerAccessorComponent.create();
this.shipDocsDMSClient = accessorComponent.provideShipDocsDMSClient();
this.awss3Util = accessorComponent.provideAwss3Util();
}
.
.
.
.
and then in my test, I can freely mock AWSS3Util dependency and carry ahead and force out the required response.

Sending XML message to JMS queue

am working with a project in which I am trying to call a Servlet that will push XML message to a JMS queue running in my local machine, using java code. You can find the actual Servlet code below, which actually sends the message to the queue.
import java.io.IOException;
import java.io.PrintWriter;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MessageSender
extends HttpServlet
{
private static final long serialVersionUID = 1L;
static PrintWriter out;
public static final String CNN_FACTORY = "jms/alert/connectionFactory";
public static final String QUEUE_NAME = "jms/alert/amlScreenQueue";
public static String currentQueueName;
public static String JMSConnectionFactory;
private QueueConnection qcon;
private QueueSession qsession;
private static QueueSender qsender;
private Queue queue;
private static ObjectMessage om;
private static MessageProducer messageProducer;
public MessageSender() {}
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try
{
String JMSQueueName = request.getParameter("JMSQueueName");
currentQueueName = JMSQueueName;
JMSConnectionFactory = request.getParameter("JMSConnectionFactory");
out = response.getWriter();
InitialContext ic = getInitialContext();
init(ic, JMSQueueName);
doPost(request, response);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void init(Context ctx, String queueName)
throws NamingException, JMSException
{
QueueConnectionFactory qconFactory = (QueueConnectionFactory)ctx.lookup(JMSConnectionFactory);
this.qcon = qconFactory.createQueueConnection();
this.qsession = this.qcon.createQueueSession(false, 1);
queue = ((Queue)ctx.lookup(queueName));
QueueConnection qcon = qconFactory.createQueueConnection();
qcon.start();
QueueSession qsession = qcon.createQueueSession(false, 1);
qsender = qsession.createSender(queue);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String textMessage = request.getParameter("textMessage");
try
{
TextMessage msg = qsession.createTextMessage(textMessage);
msg.setStringProperty("JMSXGroupID", "1");
msg.setIntProperty("JMSXGroupSeq", 1);
msg.setBooleanProperty("JMS_IBM_Last_Msg_In_Group", false);
qsender.send(msg);
out.println("Message sent to queue " + currentQueueName);
out.println("");
out.println(msg.getText());
}
catch (JMSException e)
{
e.printStackTrace();
out.println(e.getErrorCode());
try
{
qsender.close();
qcon.close();
}
catch (JMSException e) {
e.printStackTrace();
}
}
finally
{
try
{
qsender.close();
qcon.close();
}
catch (JMSException e) {
e.printStackTrace();
}
}
}
private static InitialContext getInitialContext() throws NamingException
{
return new InitialContext();
}
}
This is the java code that I am using to call the servlet,
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map.Entry;
public class SendMessage {
public static void main(String[] args) throws URISyntaxException{
String line;
StringBuffer buffer = new StringBuffer();
String data = null;
try
{
String filePath = "data/payload.xml";
File dataFile = new File(filePath);
if(dataFile.exists()){
data = new String(Files.readAllBytes(Paths.get(filePath)));
}else{
System.out.println("Not Available");
}
String localUrl = "http://localhost:8080/SimulationTool/MessageSender";
String params = "JMSQueueName=jms/alert/amlScreenQueue&"
+ "JMSConnectionFactory=jms/alert/connectionFactory&"
+ "textMessage=" + data;
System.out.println("PARAMS:::" + params);
URL url = new URL(localUrl);
System.out.println("URL FOUND:::" + url.toURI());
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.connect();
System.out.println("Response Code:::" + ((HttpURLConnection)conn).getResponseCode());
BufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ));
out.write(params);
out.flush();
out.close();
// Response code
System.out.println("Response Code:::" + ((HttpURLConnection)conn).getResponseCode());
// Response values
for (Entry<String, List<String>> header : ((HttpURLConnection)conn).getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
String response;
while ( (response = in.readLine()) != null ) {
System.out.println( response );
}
in.close();
}
catch ( MalformedURLException ex ) {
ex.printStackTrace();
}
catch ( IOException ex ) {
ex.printStackTrace();
}
}
}
The problem is its failing with below exception,
Response Code:::200
java.net.ProtocolException: Cannot write output after reading input.
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1312)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1291)
at servlettests.SendMessage.main(SendMessage.java:63)
Its shows response code as 200, so the connection was successful but it fails while getting the outputstream, which is being created to send message to the queue. Pls help me on resolving this issue.

Yandex Api not translating properly in eclipse

Here is my code in TranslateAPI.java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
public class TranslateAPI {
public static final String API_KEY = "pdct.1.1.20180924T090857Z.3e14b8b207704aef.9bdc409229b123003526815bb7062ed42616f26a";
private static String request(String URL) throws IOException {
URL url = new URL(URL);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
InputStream inStream = urlConn.getInputStream();
String recieved = new BufferedReader(new InputStreamReader(inStream)).readLine();
System.setProperty("http.agent", "Chrome");
String agent = java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("http.agent"));
inStream.close();
return recieved;
}
public static Map<String, String> getLangs() throws IOException {
String langs = request("https://translate.yandex.net/api/v1.5/tr.json/getLangs?key=" + API_KEY + "&ui=en");
langs = langs.substring(langs.indexOf("langs")+7);
langs = langs.substring(0, langs.length()-1);
String[] splitLangs = langs.split(",");
Map<String, String> languages = new HashMap<String, String>();
for (String s : splitLangs) {
String[] s2 = s.split(":");
String key = s2[0].substring(1, s2[0].length()-1);
String value = s2[1].substring(1, s2[1].length()-1);
languages.put(key, value);
}
return languages;
}
public static String translate(String text, String sourceLang, String targetLang) throws IOException {
String response = request("https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + API_KEY + "&text=" + text + "&lang=" + sourceLang + "-" + targetLang);
return response.substring(response.indexOf("text")+8, response.length()-3);
}
AND in workerthread.java:
String s=TranslateAPI.detectLanguage(abc);
System.out.println(s);
However,I am getting the follwing errror:
Server returned HTTP response code: 403 for URL: https://translate.yandex.net/api/v1.5/tr.json/detect?key=pdct.1.1.20180924T090857Z.3e14b8b207704aef.9bdc409229b123003526815bb7062ed42616f26a&text=cat
Can you please help? Thanks in advance
You are getting a 401 Error thus Your API Key is Invalid,
You can always go to Yandex's Developers page to get a new one.
Its always great to publish your private API here :D

JSONException Twitter client side application

I am currently trying to build a client application for twitter. One of the functionalities of the app is to search tweet (including historical tweet). I tried to modify the code that I got from Github. However, when I tried to debug the code, I got JSONException cause by null value. Here is my code:
package thematicanalysis;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import twitter4j.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import twitter4j.JSONException;
/**
*
* #author adichris
*/
public class TweetManager {
private static String getURLResponse(String since, String until, String querySearch, String scrollCursor,int counter) throws Exception{
String appendQuery = " ";
if(since!=null)
appendQuery+= " since:"+since;
if(until!=null)
appendQuery+= " until:"+until;
if(querySearch!=null)
appendQuery+= " "+querySearch;
String url = String.format("https://twitter.com/search?src=typd&q=%s&scroll_cursor=%s", URLEncoder.encode(appendQuery, "UTF-8"),scrollCursor);
System.out.println("URL: "+ url);
URL obj = new URL (url);
HttpURLConnection con = (HttpURLConnection)obj.openConnection();
con.setRequestMethod("GET");
//StringBuilder response;
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while((inputLine=in.readLine())!=null)
response.append(inputLine);
in.close();
con.disconnect();
//System.out.println(response.toString());
saveToFile(response.toString(),counter);
return response.toString();
}
private static void saveToFile(String content,int counter) throws IOException
{
try (PrintWriter pw = new PrintWriter("newOutput"+counter+".txt","UTF-8")) {
pw.printf("%s\n",content);
pw.close();
}
}
public static void getTweets (String since, String until, String querySearch) throws JSONException, Exception{
try{
String refreshCursor = null;
int counter = 1;
while(true)
{
String response = getURLResponse(since,until,querySearch,refreshCursor,counter);
JSONObject json = new JSONObject(response);
if(json.equals(null))
System.out.println("hereeee");
counter++;
System.out.println(counter);
refreshCursor = json.getString("scroll_cursor");
Document doc = Jsoup.parse((String)json.get("items_html"));
Elements tweets = doc.select("div.js-stream-tweet");
System.out.println(tweets.size());
if (tweets.isEmpty()){
break;
}
for (Element tweet: tweets){
String userName = tweet.select("span.username.js-action-profile-name b").text();
String text = tweet.select("p.js-tweet-text").text().replaceAll("[^\\u0000-\\uFFFF]", "");
long dateMs = Long.valueOf(tweet.select("small.time span.js-short-timestamp").attr("data-time-ms"));
Date date = new Date(dateMs);
System.out.println(userName);
//saveToFile(text);
}
}
}catch(JSONException e){
e.printStackTrace();
}
}
}

Execution stops automatically at getOutputStream() function Push notification using servlets

I have a problem while getting a push notification on the server side. I am using C2DM sever connection to achieve the push notification. Its working fine on android but not in the Java Servecr. I'm able to get the registration ID and authentication code but the handling stops when it comes to the line:
OutputStream out = conn.getOutputStream();
It does not throw anything, just stops.
If anyone has a solution for this then please guide me. I am adding the whole code so you can go through and tell me where I'm wrong in getting the result.
import org.apache.http.client.methods.HttpPost;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.print.DocFlavor.INPUT_STREAM;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class Server {
private static String key=null;
// private final static String AUTH = "authentication";
private static final String UPDATE_CLIENT_AUTH = "Update-Client-Auth";
public static final String PARAM_REGISTRATION_ID = "registration_id";
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
private static final String UTF8 = "UTF-8";
private static String Authcode = null;
// Registration is currently hardcoded
private final static String YOUR_REGISTRATION_STRING = "reg id";
public void getAuthentification() {
System.out.println("check");
//HttpPost post = new HttpPost("http://www.google.com/accounts/ClientLogin");
try {
System.getProperties().put("proxySet", true);
System.getProperties().put("proxyHost","proxy" );
System.getProperties().put("proxyPort","8080");
System.out.println("getAuthentication method called****************************");
URL url=new URL("https://www.google.com/accounts/ClientLogin");
URLConnection connection=url.openConnection();
connection.setDoOutput(true);
HttpURLConnection conn=(HttpURLConnection)connection;
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(true);
StringBuilder content = new StringBuilder();
content.append("Email=").append("xyz#gmail.com");
content.append("&Passwd=").append("asdfgt");
content.append("&service=").append("ac2dm");
content.append("&source=").append("MY_APP-V0.1");
content.append("&accountType=").append("HOSTED_OR_GOOGLE");
OutputStream out = conn.getOutputStream();
out.write(content.toString().getBytes("UTF-8"));
out.close();
int res = conn.getResponseCode();
System.out.println(res + "Success");
StringBuffer resp = new StringBuffer();
if(res == HttpsURLConnection.HTTP_OK){
InputStream in = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
System.out.println("inside");
if (line.startsWith("Auth=")) {
Authcode = line.substring(5);
resp.append(line.substring(5));
System.out.println(line.substring(5));
System.out.println("something to be done here..");
}
}
rd.close();
}
}
}
public void sendMessage() {
try {
System.out.println(YOUR_REGISTRATION_STRING);
System.out.println("Authcode = " + Authcode);
System.getProperties().put("proxySet", true);
System.getProperties().put("proxyHost","proxy" );
System.getProperties().put("proxyPort","8080");
URL url1 = new URL("https://android.apis.google.com/c2dm/send");
System.out.println("here2.5");
HttpURLConnection conn1 = (HttpURLConnection) url1.openConnection();
System.out.println("here2.6");
conn1.setDoInput(true);
conn1.setDoOutput(true);
conn1.setUseCaches(false);
conn1.setRequestMethod("POST");
conn1.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn1.setRequestProperty("Authorization", "GoogleLoginauth="+ Authcode);
System.out.println("here2.7");
OutputStream out = conn1.getOutputStream();
System.out.println("send Message method.");
String auth_key="n/a";
if(key!=null) {
auth_key=Authcode;
}
System.out.println("here");
// Send a sync message to this Android device.
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append(PARAM_REGISTRATION_ID)
.append("=").append(YOUR_REGISTRATION_STRING);
System.out.println("here1");
postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY)
.append("=").append("0");
System.out.println("here2");
postDataBuilder.append("&").append("data.payload")
.append("=").append(URLEncoder.encode("Lars war hier", UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
conn1.setRequestProperty("Content-Length",
Integer.toString(postData.length));
// Hit the dm URL.
System.out.println("out created");
out.write(postData);
System.out.println("data written");
out.close();
System.out.println("here3");
int responseCode = conn1.getResponseCode();
System.out.println(String.valueOf(responseCode));
// Validate the response code
if (responseCode == 401 || responseCode == 403) {
// The token is too old - return false to retry later, will
// fetch the token
// from DB. This happens if the password is changed or token
// expires. Either admin
// is updating the token, or Update-Client-Auth was received by
// another server,
// and next retry will get the good one from database.
System.out.println("C2DM, Unauthorized - need token");
}
} catch (Exception ignore) {
// the editor that corrected the indentation of the code could not find any code here so he closed all methods to have a syntactically correct class.
}
}
}
Make sure that you are posting message to url from background thread not from the UI thread.
I hope after this change it will work. Good Luck!!!

Categories