Commit 578723b1 authored by nargessalehi98's avatar nargessalehi98

Pre-end

parent aefab250
url: http://yahoo.com | method: GET | headers: null: null |
bodyredirect
headers{X-Frame-Options=[SAMEORIGIN], null=[HTTP/1.1 301 Moved Permanently], Cache-Control=[no-store, no-cache], Server=[ATS], Content-Security-Policy=[frame-ancestors 'self' https://*.techcrunch.com https://*.yahoo.com https://*.aol.com https://*.huffingtonpost.com https://*.oath.com https://*.verizonmedia.com https://*.publishing.oath.com; sandbox allow-forms allow-same-origin allow-scripts allow-popups allow-popups-to-escape-sandbox allow-presentation; report-uri https://csp.yahoo.com/beacon/csp?src=ats&site=frontpage&region=US&lang=en-US&device=featurephone&yrid=&partner=;], Connection=[keep-alive], Content-Length=[8], Date=[Fri, 12 Jun 2020 09:04:02 GMT], Content-Language=[en], Location=[https://us.yahoo.com/], Content-Type=[text/html]}
takedTime3.336
statusCode301
statusMassageMoved Permanently
byteCount8
\ No newline at end of file
import com.sun.net.httpserver.Headers;
import java.io.*;
import java.util.Scanner;
/**
* Manage requests files
* @author Narges Salehi
*/
public class Files {
//creat 2 path for response and requests
static final String PATH1 = "./requests/";
static final String PATH2 = "./response/";
//creat static variable to keep value of requests
static String Body; //body of massage
static String byteCount; //byte of request
static String takedTime; //time of request
static String statusCode; //status code of request
static String statusMassage; //status massage of request
static String HeadersOfMassage; //Headers of request
/*
* static constructor to creat directories
*/
static {
File directory1 = new File(PATH1);
directory1.mkdirs();//create directory for request
File directory2 = new File(PATH2);
directory2.mkdirs(); //create directory for response
}
/**
* Creat new directory by user request
* @param name of directory
*/
public static void makeDirectory(String name) {
//creat a path in root folder
final String PATH = "./requests/" + name;
File directory = new File(PATH);// new file in given path
directory.mkdirs(); //create directory
}
/**
* Write response if asked for
* @param content of response
* @param fileName name of file
* @throws IOException
*/
public static void fileWriterResponse(String content, String fileName) throws IOException {
OutputStream out = new FileOutputStream(PATH2 + fileName + ".txt/"); //create a stream
out.write(content.getBytes()); //write content on file
out.flush();
}
/**
* Write all the information of request
* @param content of request
* @param directory to save in
* @param fileName path
* @throws IOException
*/
public static void fileWriterRequest(String content, String directory, String fileName) throws IOException {
OutputStream out = new FileOutputStream(PATH1 + directory + "/" + fileName + ".txt/"); //creat a stream
out.write(content.getBytes()); //write content on file
out.flush();
}
/**
* Read file if asked
* @param file to be read
* @return content of file
*/
public static String fileReader(File file) {
StringBuilder line = new StringBuilder(); //create a string builder
try (InputStream in = new FileInputStream(file)) {
int content;
while ((content = in.read()) != -1) {
line.append((char) content);
}
} catch (Exception e) {
e.printStackTrace();
}
return line.toString();
}
/**
* List all the directory
* @return File[] of directories
*/
public static File[] showDirectories() {
File directories = new File(PATH1);
File[] listOfDirectories = directories.listFiles(); //creat a list of file in given directory
assert listOfDirectories != null; //check if directory is not empty
return listOfDirectories;
}
/**
* show all the requests in a directory
* @param name of directory
* @return list of requests
*/
public static File[] showList(String name) {
File requests = new File(PATH1 + name);
File[] listOfRequests = requests.listFiles();
assert listOfRequests != null;
return listOfRequests;
}
/**
* check if the given name is a directory name or no
* @param name of directory
* @return true or false
*/
public static boolean isDirectory(String name) {
File directories = new File(PATH1);
File[] listOfDirectories = directories.listFiles();
assert listOfDirectories != null;
for (File file : listOfDirectories) //check out in directory to find given file name
if (file.getName().equals(name))
return true;
return false;
}
/**
* show options list of requests
* @param Directory given directory
* @throws FileNotFoundException
*/
public static void showRequestList(String Directory) throws FileNotFoundException {
File requests = new File(PATH1 + Directory);
File[] listOfRequests = requests.listFiles();
assert listOfRequests != null;
if (listOfRequests.length == 0)
System.out.println("No Request yet");
for (int i = 1; i <= listOfRequests.length; i++) { //count from 1 to the size of file list
for (File file : listOfRequests) { //check if present file has the same number as previous loop
if (file.getName().contains(String.valueOf(i))) {
Scanner scanner = new Scanner(new FileInputStream(file));
String line = scanner.nextLine().trim();
System.out.println(i + " . " + line);
}
}
}
}
/**
* Give number of file in a directory
* @param directory to check number of file in it
* @return number of file
*/
public static int numberOfFiles(String directory) {
File requests = new File(PATH1 + directory); //Get file in given path
File[] listOfRequests = requests.listFiles(); //make list of files in given path
return listOfRequests.length + 1; //return number of file
}
/**
* Show information of a requests
* @param number Of request in shown list
* @param directory Directory of request
*/
public static void showRequest(Integer number, String directory) {
File requests = new File(PATH1 + directory);
File[] listOfRequests = requests.listFiles();
assert listOfRequests != null;
for (File file : listOfRequests) {
if (file.getName().equals(String.valueOf(number) + ".txt")) {
System.out.println(fileReader(file));
}
}
}
/**
* Read different value of a requests in a file
* @param filePath given file address
* @throws FileNotFoundException
*/
public static void setMassageValues(String filePath) throws FileNotFoundException {
File file = new File(filePath);
Scanner scanner = new Scanner(new FileInputStream(file));
String line = scanner.nextLine();
line = scanner.nextLine();
while (!line.startsWith("headers")) { //read from body word till header
if (scanner.hasNextLine()) {
Body += line + "\n";
line = scanner.nextLine();
} else
break;
}
Body=Body.replace("body",""); //remove body word
Body=Body.replace("null","");
while (!line.startsWith("takedTime")) { //read from headers till takedTime word
if (scanner.hasNextLine()) {
HeadersOfMassage += line + "\n"; //set headers
line = scanner.nextLine();
} else
break;
}
HeadersOfMassage=HeadersOfMassage.replace("headers","");//remove headers word
HeadersOfMassage=HeadersOfMassage.replace("null","");
takedTime = line.replace("takedTime", ""); //set takedTime
statusCode = scanner.nextLine().replace("statusCode", ""); //set statusCode
statusMassage=scanner.nextLine().replace("statusMassage",""); //set statusMassage
byteCount=scanner.nextLine().replace("byteCount",""); //set byteCount
}
}
import com.sun.net.httpserver.Headers;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* present GUI of insomnia
*
* @author Narges Salehi
*/
public class GUI {
......@@ -31,7 +42,14 @@ public class GUI {
JPanel header;
JTabbedPane tab;
JPanel jPanel;
JLabel error;
JLabel tt;
JTree jTree;
JMenuBar data;
JTextArea massageBody;
DefaultMutableTreeNode node1;
JTextArea nameValue;
JTextField urlField;
//check if system tray is on or not
boolean checkSystemTray = false;
//go to next line to add component - count lines
......@@ -43,8 +61,12 @@ public class GUI {
//check how many time we use system tray
static int runOnce;
//check theme
static boolean checkTheme=false;
static boolean checkTheme = false;
static String method = "GET";
static String statusCode;
String Body;
String URL = "http://";
String directory = "narges";
/**
* creat a new GUI
......@@ -89,25 +111,25 @@ public class GUI {
//set accelerator for item
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.SHIFT_MASK));
//item to set theme
JMenuItem theme=new JMenuItem("Dark/Light");
JMenuItem theme = new JMenuItem("Dark/Light");
theme.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, ActionEvent.SHIFT_MASK));
//add action listener for set theme
theme.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//boolean checks present theme
if(!checkTheme){
if (!checkTheme) {
jPanel.setBackground(Color.white);
jTree.setBackground(Color.white);
middle.setBackground(Color.white);
right.setBackground(Color.white);
checkTheme=true;
}else{
checkTheme = true;
} else {
jPanel.setBackground(Color.darkGray);
jTree.setBackground(Color.darkGray);
middle.setBackground(Color.darkGray);
right.setBackground(Color.darkGray);
checkTheme=false;
checkTheme = false;
}
}
});
......@@ -169,7 +191,7 @@ public class GUI {
//creat and adding component
JLabel Insomnia = new JLabel(" Insomnia");
Insomnia.setFont(new Font("Arial", 14, 20));
Insomnia.setPreferredSize(new Dimension(0,50));
Insomnia.setPreferredSize(new Dimension(0, 50));
Insomnia.setForeground(Color.white);
jMenuBar.add(Insomnia, BorderLayout.LINE_START);
JMenu jMenu = new JMenu("▾");
......@@ -223,11 +245,31 @@ public class GUI {
jPanel = new JPanel();
jPanel.setLayout(new GridLayout(0, 1));
//creating JTree and nodes to grouping request
DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("My Folder");
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Get My Request");
node1.add(node2);
node1 = new DefaultMutableTreeNode("Requests");
updateJTree(node1, Files.showDirectories());
//creat tree
jTree = new JTree(node1);
jTree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
if (e.getPath().toString().contains(".txt")) {
String oldPath = e.getPath().toString();
String path = oldPath.replace(", ", "/");
path = path.replace("[", "./");
path = path.replace("]", "");
try {
Files.setMassageValues(path);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
massageBody.setText(Files.Body);
nameValue.setText(Files.HeadersOfMassage);
error.setText(Files.statusCode+" "+Files.statusMassage+ " ");
tt.setText(Files.takedTime+" s " +Files.byteCount + " B");
}
}
});
jTree.setBackground(Color.DARK_GRAY);
gbc.gridy = 3;
gbc.weightx = 1;
......@@ -250,15 +292,39 @@ public class GUI {
JMenuBar URL = new JMenuBar();
URL.setPreferredSize(new Dimension(0, 50));
//text field to get URL
JTextField urlField = new JTextField();
urlField = new JTextField();
urlField.setPreferredSize(new Dimension(0, 20));
//creating and adding item to JMenu
JMenu methods = new JMenu(" Get ▾");
JMenuItem get = new JMenuItem("GET");
get.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
method = "GET";
}
});
JMenuItem post = new JMenuItem("POST");
post.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
method = "POST";
}
});
JMenuItem put = new JMenuItem("PUT");
put.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
method = "Put";
}
});
JMenuItem patch = new JMenuItem("PATCH");
JMenuItem delete = new JMenuItem("DELETE");
delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
method = "DELETE";
}
});
JMenuItem options = new JMenuItem("OPTIONS");
JMenuItem head = new JMenuItem("HEAD");
JMenuItem cm = new JMenuItem("Custom Method");
......@@ -346,13 +412,22 @@ public class GUI {
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.fill = GridBagConstraints.BOTH;
middle.add(tab, gbc);
send.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (urlField.getText() != null) {
sendRequest();
((DefaultTreeModel) jTree.getModel()).reload();
}
}
});
//**************************************************************************************************************
//right side of insomnia
//designing right panel
//set gridBagLayout for panel
right.setLayout(new GridBagLayout());
//creat a menu bar to keep statusCode statusMassage and Time
JMenuBar data = new JMenuBar();
data = new JMenuBar();
//set size for menu bar
data.setPreferredSize(new Dimension(0, 50));
//set layout for menu bar
......@@ -362,11 +437,11 @@ public class GUI {
//add item to menu bar
data.add(time, BorderLayout.LINE_END);
//creat item to keep statusMassage
JLabel error = new JLabel("Error ");
error = new JLabel("Error ");
//add item to menu bar
data.add(error, BorderLayout.LINE_START);
//creat item to keep statusCode
JLabel tt = new JLabel("0 ms 0 B");
tt = new JLabel(" 0 ms 0 B");
//add item to menu bar
data.add(tt, BorderLayout.CENTER);
//set gridBagConstrains for add menu bar to right panel
......@@ -388,7 +463,8 @@ public class GUI {
//set layout for panel
preview.setLayout(new GridBagLayout());
//creat a text area for massage body
JTextArea massageBody = new JTextArea();
massageBody = new JTextArea();
JScrollPane jScrollPane = new JScrollPane(massageBody);
massageBody.setBackground(Color.darkGray);
//add panel to tabbedPane
tab1.add("Preview", preview);
......@@ -411,7 +487,7 @@ public class GUI {
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
//add text area to panel
preview.add(massageBody, gbc);
preview.add(jScrollPane, gbc);
//creat a panel for header
JPanel header2 = new JPanel();
header2.setBackground(Color.darkGray);
......@@ -420,7 +496,7 @@ public class GUI {
//add header to tabbedPane
tab1.add("Header", header2);
//add item to header
JLabel name = new JLabel("Name");
JLabel name = new JLabel("Name value");
name.setForeground(Color.gray);
JLabel value = new JLabel("value");
value.setForeground(Color.gray);
......@@ -428,18 +504,39 @@ public class GUI {
gbc.gridy = 0;
gbc.gridx = 0;
gbc.weightx = 1;
gbc.weighty = 0;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.NORTHWEST;
header2.add(name, gbc);
gbc.gridx = 1;
header2.add(value, gbc);
JButton copyToClipboard = new JButton("Copy to Clipboard");
// header2.add(value, gbc);
nameValue = new JTextArea();
nameValue.setBackground(Color.darkGray);
JScrollPane jScrollPane1 = new JScrollPane(nameValue);
jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
gbc.gridy = 1;
gbc.gridx = 1;
gbc.gridx = 0;
gbc.weightx = 1;
gbc.weighty = 12;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.WEST;
header2.add(jScrollPane1, gbc);
JButton copyToClipboard = new JButton("Copy to Clipboard");
copyToClipboard.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
nameValue.selectAll();
nameValue.copy();
}
});
gbc.gridy = 2;
gbc.gridx = 0;
gbc.weightx = 0;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.NONE;
header2.add(copyToClipboard, gbc);
//creat other panel
JPanel cookies = new JPanel();
......@@ -469,10 +566,30 @@ public class GUI {
//add splitPane to window
window.add(jSplitPane1);
}
//end of GUI
//end of GUI *******************************************************************************************************
public void updateJTree(DefaultMutableTreeNode baseNode, File[] FileList) {
baseNode.removeAllChildren();
for (File file : FileList) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(file.getName());
if (Files.showList(file.getName()) != null) {
for (File file1 : Files.showList(file.getName())) {
node.add(new DefaultMutableTreeNode(file1.getName()));
}
baseNode.add(node);
}
}
}
public void updateComboBox(JComboBox comboBox, File[] FileList) {
for (File file : FileList) {
comboBox.addItem(file.getName());
}
}
/**
* creat a panel with given data
*
* @param jPanel JPanel
* @param color of panel
* @param border of panel
......@@ -486,8 +603,10 @@ public class GUI {
}
//------------------------------------------------------------------------------------------------------------------
/**
* set JTree render
*
* @return defaultTreeCellRenderer
* copied from stack over flow
*/
......@@ -502,6 +621,7 @@ public class GUI {
/**
* check JTree focus lost of gained
*
* @param tree JTree
* @return new FocusListener
*/
......@@ -522,6 +642,7 @@ public class GUI {
/**
* check if outside of JTree has clicked - clear selections
*
* @param tree JTree
* @return new MouseListener
*/
......@@ -558,6 +679,7 @@ public class GUI {
};
}
//------------------------------------------------------------------------------------------------------------------
/**
* class perform listener for top menu
*/
......@@ -667,7 +789,7 @@ public class GUI {
gbc.anchor = GridBagConstraints.NORTHWEST;
JLabel info1 = new JLabel(" Requests in Insomnia are saved in groups.");
smallFrame.add(info1, gbc);
JLabel name = new JLabel(" Request Name :");
JLabel name = new JLabel(" Group Name :");
gbc.gridy = 1;
gbc.gridx = 0;
gbc.weightx = 1;
......@@ -686,19 +808,45 @@ public class GUI {
gbc.weighty = 1;
smallFrame.add(info2, gbc);
JComboBox groups = new JComboBox();
updateComboBox(groups, Files.showDirectories());
gbc.gridy = 4;
gbc.gridx = 0;
gbc.weightx = 1;
gbc.weighty = 1;
smallFrame.add(groups, gbc);
JButton creat = new JButton("Creat +");
JButton creat = new JButton("Create");
creat.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = requestName.getText();
Files.makeDirectory(name);
updateJTree(node1, Files.showDirectories());
((DefaultTreeModel) jTree.getModel()).reload();
directory = name;
smallFrame.dispatchEvent(new WindowEvent(smallFrame, WindowEvent.WINDOW_CLOSING));
}
});
gbc.gridy = 5;
gbc.gridx = 0;
gbc.weightx = 1;
gbc.weightx = 3;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.SOUTHEAST;
smallFrame.add(creat, gbc);
JButton save = new JButton("Save");
save.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
directory = (String) groups.getSelectedItem();
smallFrame.dispatchEvent(new WindowEvent(smallFrame, WindowEvent.WINDOW_CLOSING));
}
});
gbc.gridy = 5;
gbc.gridx = 1;
gbc.weightx = 1;
gbc.weighty = 1;
smallFrame.add(save, gbc);
}
}
}
......@@ -845,5 +993,28 @@ public class GUI {
System.out.println("TrayIcon could not be added.");
}
}
}
public void sendRequest() {
String URL = "http://" + urlField.getText();
try {
if(method.equals("PUT") || method.equals("POST")){
Body = HTTPClient.Request(URL, true, false, true, false,
true, method, null, null, null, directory);
}
Body = HTTPClient.Request(URL, true, false, true, false,
false, method, null, null, null, directory);
massageBody.setLineWrap(true);
massageBody.setText(Body);
massageBody.setForeground(Color.white);
error.setText(String.valueOf(HTTPClient.getStatusCode())+" "+HTTPClient.statusMassage);
tt.setText(" " + HTTPClient.getTakedTime() + " s " + HTTPClient.takedByte+ "B");
for (Map.Entry<String, List<String>> entry : HTTPClient.map.entrySet()) {
String temp = nameValue.getText();
nameValue.setText(temp + "\n" + entry.getKey() + " : " + entry.getValue());
}
nameValue.setForeground(Color.lightGray);
} catch (IOException ex) {
System.out.println("wrong URL");
}
}
}
\ No newline at end of file
import java.io.*;
import java.net.*;
import java.net.http.HttpClient;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
* Provide a console http-request-app
*
* @author Narges Salehi
*/
public class HTTPClient {
HttpClient client = HttpClient.newHttpClient(); //creat a http client to connect
boolean showHeaders; //creat a boolean to check if headers are going to be shown
boolean saveResponse; //creat a boolean to check if response are going to be saved
boolean saveRequest; //creat a boolean to check if request are going to be saved
boolean formData; //creat a boolean to check if request are going to be formData
boolean setHeaders; //creat a boolean to check if headers are going to be set
boolean listIsOn = false; //creat a boolean to check if request are showing
static int statusCode; //save status code
static String statusMassage; // save status massage
static String takedTime; // save taked time
static String takedByte; // save taked byte
static Map<String, List<String>> map; //save Header of request
static HashMap<String, String> Headers; // save given header by user
static String stringOfData; // save given data by user as a string
static HashMap<String, String> Data; //save given data as HashMap
static String word1; //save url with out 'http://'
/**
* Creat a console app
*
* @throws IOException
* @throws InterruptedException
*/
public HTTPClient() throws IOException, InterruptedException {
Headers = new HashMap<>();
Data = new HashMap<>();
Scanner scanner = new Scanner(System.in);
while (true) {
String method = "GET"; //set default method as get
String key = null;
String value = null;
String name = null;
String directory = null;
String command = scanner.nextLine(); //creat a scanner to scan commands
String[] line = (command.split(" ")); //spilt commands in " "
ArrayList<String> words = new ArrayList<String>(Arrays.asList(line)); //put commands in an ArrayList
String URL = "http://" + words.get(1); //save real url
word1 = words.get(1); //save raw url
if (words.get(0).equals("jurl")) { //check if given command start with jurl or no
if (words.get(1).equals("--help") || words.get(1).equals("-h")) {
listIsOn = false;
System.out.println(
"-M or --method " + "," + "select method , can be deleted for GET " +
"\n" + "-H or --headers" + "," + "set request headers " +
"\n" + "-O or --output" + "," + "save body in file" +
"\n" + "-S or --save" + "," + "save request in file " +
"\n" + "-d or --data" + "," + "set massage body as form data " +
"\n" + "-i" + " ," + "showing headers of response " +
"\n" + "end" + " ," + "Exit program " +
"\n" + "create" + " , " + "create a new directory"
);
continue;
} else if (words.get(1).equals("list")) {
if (Files.isDirectory(words.get(2))) {
Files.showRequestList(words.get(2));
listIsOn = true;
} else
System.out.println("This directory is not true");
continue;
} else if (words.get(1).equals("fire") && Files.isDirectory(words.get(2)) && listIsOn) {
for (int i = 3; i < words.size(); i++) {
if (isInteger(words.get(i))) {
int number = Integer.valueOf(words.get(i));
Files.showRequest(number, words.get(2));
} else {
System.out.println("No more Number");
break;
}
}
continue;
} else if (words.get(1).equals("end")) {
System.exit(0);
} else if (words.get(1).equals("create")) {
String PathName = words.get(2);
Files.makeDirectory(PathName);
continue;
} else {
listIsOn = false;
if (true) {
for (String word : words) {
switch (word) {
case "-i":
showHeaders = true;
break;
case "-O":
int indexOfName = words.indexOf("-O");
if (words.size() - 1 > indexOfName) {
indexOfName++;
if (!words.get(indexOfName).startsWith("-"))
name = words.get(indexOfName);
else {
Date date = new Date();
name = "output_" + date.toString();
}
} else {
Date date = new Date();
name = "output_" + date.toString();
}
saveResponse = true;
break;
case "--output":
indexOfName = words.indexOf("-O");
if (words.size() - 1 > indexOfName) {
indexOfName++;
if (!words.get(indexOfName).startsWith("-"))
name = words.get(indexOfName);
else {
Date date = new Date();
name = "output_" + date.toString();
}
} else {
Date date = new Date();
name = "output_" + date.toString();
}
saveResponse = true;
break;
case "-S":
int indexOfDirectory = words.indexOf("-S");
indexOfDirectory++;
directory = words.get(indexOfDirectory);
saveRequest = true;
break;
case "--save":
indexOfDirectory = words.indexOf("--save");
indexOfDirectory++;
directory = words.get(indexOfDirectory);
saveRequest = true;
break;
case "-d":
int indexOfData = words.indexOf("-d");
indexOfData++;
String temp = words.get(indexOfData);
stringOfData = temp;
temp = temp.replace("\"", "");
String[] data1 = temp.split("&");
ArrayList<String> data2 = new ArrayList<String>(Arrays.asList(data1));
for (String s : data2) {
String[] keyValue = s.split("=");
ArrayList<String> keyValue2 = new ArrayList<String>(Arrays.asList(keyValue));
Data.put(keyValue2.get(0), keyValue2.get(1));
}
formData = true;
break;
case "--data":
indexOfData = words.indexOf("--data");
indexOfData++;
temp = words.get(indexOfData);
stringOfData = temp;
temp = temp.replace("\"", "");
data1 = temp.split("&");
data2 = new ArrayList<String>(Arrays.asList(data1));
for (String s : data2) {
String[] keyValue = s.split("=");
ArrayList<String> keyValue2 = new ArrayList<String>(Arrays.asList(keyValue));
Data.put(keyValue2.get(0), keyValue2.get(1));
}
formData = true;
break;
case "-H":
int indexOfHeader = words.indexOf("-H");
indexOfHeader++;
temp = words.get(indexOfHeader);
temp = temp.replace("\"", "");
String[] header1 = temp.split(";");
ArrayList<String> header2 = new ArrayList<String>(Arrays.asList(header1));
for (String s : header2) {
String[] keyValue = s.split(":");
ArrayList<String> keyValue2 = new ArrayList<String>(Arrays.asList(keyValue));
Headers.put(keyValue2.get(0), keyValue2.get(1));
}
setHeaders = true;
break;
case "--headers":
indexOfHeader = words.indexOf("--headers");
indexOfHeader++;
temp = words.get(indexOfHeader);
temp = temp.replace("\"", "");
header1 = temp.split(";");
header2 = new ArrayList<String>(Arrays.asList(header1));
for (String s : header2) {
String[] keyValue = s.split(":");
ArrayList<String> keyValue2 = new ArrayList<String>(Arrays.asList(keyValue));
Headers.put(keyValue2.get(0), keyValue2.get(1));
}
setHeaders = true;
break;
case "-M":
int indexOfMethod = words.indexOf("-M");
indexOfMethod++;
method = words.get(indexOfMethod);
break;
case "--method":
indexOfMethod = words.indexOf("--method");
indexOfMethod++;
method = words.get(indexOfMethod);
break;
default:
break;
}
}
} else {
System.out.println("2 command not found" + "try 'jurl --help' or 'jurl -h' for more information");
continue;
}
}
} else {
System.out.println("3 command not found" + "try 'jurl --help' or 'jurl -h' for more information");
continue;
}
//send request
Request(URL, showHeaders, setHeaders, saveRequest, saveResponse, formData, method, key, value, name, directory);
//set value to default for new request
showHeaders = false;
setHeaders = false;
saveRequest = false;
saveResponse = false;
formData = false;
}
}
/**
* check if given string is url or not
* @param url given string
* @return true of false
*/
public boolean isURL(String url) {
try {
(new java.net.URL(url)).openStream().close();
return true;
} catch (Exception ignored) {
}
return false;
}
/**
* check if given string is a integer or not
* @param s given string
* @return true of false
*/
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException | NullPointerException e) {
return false;
}
return true;
}
/**
* Get taked time of request
* @return taked time
*/
public static String getTakedTime() {
return takedTime;
}
/**
* Get status code of request
* @return status code
*/
public static int getStatusCode() {
return statusCode;
}
/**
* Send a HTTPRequest with given data
*
* @param URL url
* @param showHeaders
* @param setHeaders
* @param saveRequest
* @param saveResponse
* @param formData
* @param method method of request
* @param key header key
* @param value header value
* @param name name of file
* @param directory to save request in
* @return string of body
* @throws IOException
*/
public static String Request(String URL, boolean showHeaders, boolean setHeaders,
boolean saveRequest, boolean saveResponse, boolean formData, String method,
String key, String value, String name, String directory) throws IOException {
long start = System.currentTimeMillis();//start counting time
URL url = new URL(URL); //creat a url
HttpURLConnection yc = (HttpURLConnection) url.openConnection(); //open connection
if (!method.equals("null") && !method.equals("GET")) { //set method default is get
yc.setRequestMethod(method); //set method
yc.setDoOutput(true);
}
if (setHeaders) { //if set headers is true set given headers by user as headers
for (String Key : Headers.keySet()) {
for (String Value : Headers.values()) {
if (Headers.get(Key).equals(Value)) {
yc.setRequestProperty(Key, Value);
}
}
}
}
if (formData) { // if user give data
if (word1.contains("urlencoded")) { //check if its url data
try {
int data = stringOfData.getBytes(StandardCharsets.UTF_8).length; //get bytes of data
yc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //set properties
yc.setRequestProperty("charset", "utf-8");
yc.setRequestProperty("Content-Length", Integer.toString(data));
try (OutputStream os = yc.getOutputStream()) { //creat stream to write values
os.write(stringOfData.getBytes(StandardCharsets.UTF_8));
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
yc.disconnect();
}
}
if (word1.contains("formdata")) { //if it is form data
try {
yc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "1111"); //set properties
BufferedOutputStream request = new BufferedOutputStream(yc.getOutputStream()); //creat a stream
bufferOutFormData(Data, "1111", request); //call method of form data set values
} catch (IOException e) {
e.printStackTrace();
}
}
}
//start reading body
StringBuilder Body = new StringBuilder(); // to build body as a string
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream())); //stream to get body
String inputLine; //line to keep body lines
while ((inputLine = in.readLine()) != null) { //check end of body
System.out.println(inputLine); //print body in console
Body.append(inputLine); //creat body
Body.append("\n");
}
in.close(); //close stream
map = yc.getHeaderFields(); //get headers of request
if (showHeaders) { //if show headers is true set map value as headers of request
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
System.out.println(entry.getKey()
+ " : " + entry.getValue());
}
}
//count byte of a request
int byteCount = 0;
int headerIndex = 0;
while (true) {
String key2 = yc.getHeaderFieldKey(headerIndex);
if (key == null)
break;
String value2 = yc.getHeaderField(headerIndex++);
byteCount += key.getBytes(StandardCharsets.US_ASCII).length
+ value.getBytes(StandardCharsets.US_ASCII).length + 2;
}
byteCount += yc.getHeaderFieldInt("Content-Length", Integer.MIN_VALUE);
takedByte = String.valueOf(byteCount);
long end = System.currentTimeMillis();
takedTime = String.valueOf((end - start) / 1000);
takedTime += ".";
takedTime += String.valueOf((end - start) % 1000);
if (saveRequest) {//if save request is true save request as below pattern
//first line of file show 'option view' in list
String topLine = "url: " + URL + " | " + "method: " + method + " | " + "headers: " + key + ": " + value + " | ";
String content = topLine + "\n" +
"body" + Body +
"headers" + map + "\n" +
"takedTime" + takedTime + "\n" +
"statusCode" + yc.getResponseCode() + "\n" +
"statusMassage" + yc.getResponseMessage() + "\n" +
"byteCount" + byteCount;
Files.fileWriterRequest(content, directory, String.valueOf(Files.numberOfFiles(directory)));//write content in given directory
}
if (saveResponse) { //if save response is true save response of request
Files.fileWriterResponse(Body.toString(), name);
}
System.out.println(yc.getResponseCode());//print status code
statusCode = yc.getResponseCode();//set status code
statusMassage = yc.getResponseMessage();//set status massage
return Body.toString();//return string of body
}
/**
* Set Values as data im form data
*
* @param body set of values
* @param boundary boundary
* @param bufferedOutputStream stream to write values
* @throws IOException
*/
public static void bufferOutFormData(HashMap<String, String> body, String boundary, BufferedOutputStream bufferedOutputStream) throws IOException {
for (String key : body.keySet()) {
bufferedOutputStream.write(("--" + boundary + "\r\n").getBytes());
if (key.contains("file")) {
bufferedOutputStream.write(("Content-Disposition: form-data; filename=\"" +
(new File(body.get(key))).getName() + "\"\r\nContent-Type: Auto\r\n\r\n").getBytes());
try {
BufferedInputStream tempBufferedInputStream = new BufferedInputStream(new FileInputStream(new File(body.get(key))));
byte[] filesBytes = tempBufferedInputStream.readAllBytes();
bufferedOutputStream.write(filesBytes);
bufferedOutputStream.write("\r\n".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
} else {
bufferedOutputStream.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n").getBytes());
bufferedOutputStream.write((body.get(key) + "\r\n").getBytes());
}
}
bufferedOutputStream.write(("--" + boundary + "--\r\n").getBytes());
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
}
......@@ -2,6 +2,7 @@ import javax.swing.*;
/**
* Run the program
*
* @author Narges Salehi
*/
public class Main {
......@@ -20,4 +21,9 @@ public class Main {
//creat a new GUI
GUI gui=new GUI();
}
// public static void main(String[] args) throws IOException, InterruptedException {
// HTTPClient h = new HTTPClient();
//
// }
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment