How to generate JUnit Test case in Java? - java

I am practising JUnit test cases and currently working on a problem which is as follows:
To read HTML from any website say "http://www.google.com" ( Candidate can use any API of inbuilt APIs in Java like URLConnection ).
Print on console the HTML from the URL above and save it to a file ( web-content.txt) in local machine.
Write JUnit test cases for the above program.
I've successfully achieved first steps but when I am running JUnit Test Case its showing Failure.
ReadFile.java
package com.test;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ReadFile
{
static void display(String input,OutputStream fos)
{
try
{
URL url = new URL(input);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
Reader reader = new InputStreamReader(stream);
int data=0;
while((data=reader.read())!=-1)
{
System.out.print((char)data);
fos.write((char)data);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String[] args)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input =null;
FileOutputStream fos =null;
System.out.println("Please enter any url");
try
{
input = reader.readLine();
fos = new FileOutputStream("src/web-context.txt");
display(input,fos);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
ReadFileTest.java
package com.test;
import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import org.junit.Test;
public class ReadFileTest {
#Test
public void test() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ReadFile.display("http://google.co.in", baos);
assertTrue(baos.toString().contains("http://google.co.in"));
}
}
I am getting following error while running JUnit Test in Eclipse:
java.lang.AssertionError
java.lang.AssertionError at org.junit.Assert.fail(Assert.java:86) at org.junit.Assert.assertTrue(Assert.java:41) at org.junit.Assert.assertTrue(Assert.java:52) at com.test.ReadFileTest.test(ReadFileTest.java:15) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown
I want that the JUnit Test Case will return true.

What's not working here is :
assertTrue(baos.toString().contains("http://google.co.in"));
and what would work is
assertTrue(baos.toString().contains("google.co.in")); // note the difference

Make something like that:
static String display(String input) {
try {
URL url = new URL(input);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
Reader reader = new InputStreamReader(stream);
int data = 0;
StringBuilder builder = new StringBuilder();
while ((data = reader.read()) != -1) {
builder.append((char) data);
}
return builder.toString();
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
I don't know why you use ByteArrayOutputStream
And now for your test case:
#Test
public void test() {
String data = ReadFile.display("http://google.co.in");
assertTrue(data != null);
assertTrue(data.contains("http://google.co.in"));
}

Related

HttpURLConnection returns 400, but request body is correct

I'm trying to connect a java application to the json api of betaface.
I ran into a weird problem I hope you guys can help me with.
I have the (ugly) code to connect to the api. This code is just to test what kind of responses I get and what to do with it.
I build a request body, print the request body to the console, and then write the request body to the api. The problem is that the responsecode is 400.
The weird thing is, when I copy the request body and execute it through Advanced Rest Client it will return a 200 and the expected body. I think the problem is not in the body but somewhere in the HTTPUrlConnection.
I've added my test class to illustrate the problem, you guys would only need a small image to reproduce the problem. The API keys are the free to use api keys of betaface.
Thank you very much for any help you can give me.
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import javax.imageio.ImageIO;
public class APITest {
/**
* #param args
*/
public static void main(String[] args) {
try
{
new APITest();
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public APITest() throws MalformedURLException, IOException {
String api_key = "d45fd466-51e2-4701-8da8-04351c872236";
String api_secret = "171e8465-f548-401d-b63b-caf0dc28df5f";
String urlToConnect = "http://www.betafaceapi.com/service_json.svc/UploadNewImage_File";
File fileToUpload = new File("C:\\test.jpg");
byte[] t = getImageBase64ByteArray(fileToUpload);
String body = "";
body += "{\"api_key\":\"";
body += api_key;
body += "\",\"api_secret\":\"";
body += api_secret;
body += "\",\"detection_flags\":\"\",\"imagefile_data\":[";
for(int i = 0; i < t.length; i++) {
body += t[i];
if(i < t.length - 1)
body += ",";
}
body += "],\"original_filename\":\"Test.jpg\"}";
System.out.println(body);
HttpURLConnection connection = (HttpURLConnection)new URL(urlToConnect).openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
BufferedWriter writer =
new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
writer.write(body);
writer.newLine();
writer.flush();
writer.close();
int responseCode = connection.getResponseCode();
System.out.println(responseCode); // Should be 200
InputStream errorstream = connection.getErrorStream();
BufferedReader br = null;
if (errorstream == null){
InputStream inputstream = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(inputstream));
}else{
br = new BufferedReader(new InputStreamReader(errorstream));
}
String response = "";
String line;
while ((line = br.readLine()) != null){
response += line;
}
System.out.println(response);
}
public byte[] getImageBase64ByteArray(File file) {
BufferedImage bufferedImage;
try
{
bufferedImage = ImageIO.read(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String encoded = "";
try {
ImageIO.write(bufferedImage, "jpg", bos);
byte[] imageBytes = bos.toByteArray();
encoded = Base64.getEncoder().encodeToString(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return encoded.getBytes();
}
catch(IOException e)
{
e.printStackTrace();
}
return new byte[0];
}
}

getting the check if twitch stream is live

I have been working with java to make it where i check if a certain user if live and it will say true or false if the user is streaming...im working with minimal json.
here is my code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import com.eclipsesource.json.JsonObject;
public class hostbot {
public static void main(String[] args) throws Exception {
Twitchbot bot = new Twitchbot();
bot.setVerbose(true);
bot.connect("irc.twitch.tv", 6667, "something");
}
public boolean isStreamLive()
{
try
{
URL url = new URL("https://api.twitch.tv/kraken/streams/rexephon");
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader( new InputStreamReader( conn.getInputStream() ));
String inputLine = br.readLine();
br.close();
JsonObject jsonObj = JsonObject.readFrom(inputLine);
return ( jsonObj.get("stream").isNull() )?false:true;
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}
}
when i return false is that suppose to print in the log the word false? or something else?

Bugzilla-Query using Java - Getting HTML instead of XML

When I type this following URL into my browser, Bugzilla answers with XML:
http://bugzilla.mycompany.local/buglist.cgi?ctype=rdf&bug_status=CONFIRMED&product=MyProduct
I want to process this XML in a Java program. But when I use the exact same URL in my Java program, Bugzilla answers with HTML instead of XML.
This is my program:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Test {
public static void main(String[] args)
throws IOException {
URL url = new URL("http://bugzilla.mycompany.local/buglist.cgi?ctype=rdf&bug_status=CONFIRMED&product=MyProduct");
URLConnection connection = url.openConnection();
final StringBuilder response = new StringBuilder(1024);
try(InputStreamReader isr = new InputStreamReader(connection.getInputStream())) {
try(BufferedReader reader = new BufferedReader(isr)) {
String inputLine = null;
while((inputLine = reader.readLine()) != null) {
response.append(inputLine);
response.append('\n');
}
}
}
System.out.println(response);
}
}
What am I doing wrong?
The resulting HTML is not the result of the query. It's Bugzillas log-in form. Duh!

Java code downloading data from this url

So I am new to java programming and I am supposed to download data from the URL below every 5 minute.
host: 204.8.38.210
Get:/Iowa.Sims.AllSites.C2C/IADOT_SIMS_AllSites_C2C.asmx/OP_ShareTrafficDetectorData?MSG_TrafficDetectorDataRequest=string%20HTTP/1.1
I get this error-"Server returned HTTP response code : 400 " using this code below
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class JavaDownload {
public static void main(String[] args) throws IOException{
String fileName = "file3x.html";
URL link = new URL("http://204.8.38.210/Iowa.Sims.AllSites.C2C/IADOT_SIMS_AllSites_C2C.asmx/OP_ShareTrafficDetectorData?MSG_TrafficDetectorDataRequest=string%20HTTP/1.1");
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n=0;
while(-1!=(n=in.read(buf)))
{
out.write(buf,0,n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
System.out.println("Finished");
}
}

Socket write error while using ObjectOutputStream's writeObject method

I am trying to implement FTP protocol using socket programing in java. I am using the ObjectOutputStream to write the data requested to the socket in the server side but i am getting the following error on the console window..
Software caused connection abort: socket write error
Here is the implementation of my program
Server side:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class FTPServer {
public static void main(String[] args) {
try {
#SuppressWarnings("resource")
ServerSocket ss = new ServerSocket(4550);
while(true) {
Socket socket = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
FileInstance file = new FileInstance();
System.out.println(file.srcDir = br.readLine());
System.out.println(file.destDir = br.readLine());
System.out.println(file.filename = file.srcDir.substring(file.srcDir.lastIndexOf("/") + 1));
File f = new File(file.srcDir);
byte[] bytes = new byte[(int)f.length()];
FileInputStream fis = new FileInputStream(f);
fis.read(bytes);
file.FILE_SIZE = bytes.length;
file.fileData = bytes;
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(file);
System.out.println("Success");
oos.close();
fis.close();
br.close();
}
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
Client Side:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class FTPClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 4550);
BufferedReader sbr = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the path of requested file");
String path = sbr.readLine();
System.out.println(path);
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Enter Destination");
path = path + "\n" + sbr.readLine();
System.out.println(path);
pw.write(path);
pw.close();
sbr.close();
// receive file
ObjectInputStream ois= new ObjectInputStream(socket.getInputStream());
FileInstance file = (FileInstance)ois.readObject();
ois.close();
if(!new File(file.destDir).exists())
new File(file.destDir).mkdir();
File nfile = new File(file.destDir + "/" + file.filename);
FileOutputStream fos = new FileOutputStream(nfile);
fos.write(file.fileData);
fos.close();
socket.close();
System.out.println("Success");
} catch(IOException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
this is the FileInstance class......
import java.io.Serializable;
public class FileInstance implements Serializable {
private static final long serialVersionUID = 1L;
public String destDir;
public String srcDir;
public String filename;
public long FILE_SIZE;
public byte[] fileData;
public String status;
}
You have two problems in FTPClient
You are closing the socket prematurely. At line 22 pw.close() needs to be pw.flush()
Even after you fix the first issue the server will hang. You need to add a newline to the end of the path string you send so the server, using readLine(), can read entire lines; otherwise it waits forever for a complete line that never arrives.
This was trivial to debug in Eclipse. If you want to be a good developer, debugging skills are crucial. Set more than one breakpoint and see what happens. Experiment. Play. Learn.

Categories