I'm trying to read a CSV file from a given URL and print in. I can't find where I was wrong but it doesn't print me anything. Can someone please help me to find what I need to fix so this program will work? Thanks.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Main {
public static void main(String[] args) throws IOException {
URL url = new URL("http://gist.githubusercontent.com/yonbergman/7a0b05d6420dada16b92885780567e60/raw/114aa2ffb1c680174f9757431e672b5df53237eb/data.csv");
URLConnection connection = url.openConnection();
InputStreamReader input = new InputStreamReader(connection.getInputStream());
BufferedReader buffer = null;
String line = "";
String csvSplitBy = ",";
try {
buffer = new BufferedReader(input);
while ((line = buffer.readLine()) != null) {
String[] room = line.split(csvSplitBy);
System.out.println(line);
System.out.println("room [capacity =" + room[0] + " , price=" + room[1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (buffer != null) {
try {
buffer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
this is late, just happen to find this post, while it did not work for user, we got some pointers from it, and wanted to post what worked for us:
//...
//Java IO File imports
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
//Java SQL imports
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
// ...
// Button code
public void doBrowserReadFromTwitterPHP() {
// ...
// Entering try catch
try {
// ...
// Connect to DB2 to access Twitter table(s)
Connection connection = DB2TWConnector.getConnection();
// ...
// make available CSV in URL
URL urlCSV = new URL(
"http://www.yourweburl.com/AppDevFolder/resttwitterpubpostcsv.php");
// ...
// establish connection to file in URL
URLConnection urlConn = urlCSV.openConnection();
// ...
InputStreamReader inputCSV = new InputStreamReader(
((URLConnection) urlConn).getInputStream());
// ...
BufferedReader br = new BufferedReader(inputCSV);
// ...
// Declare String to hold file to Split from URL
String line;
String RoleNameVal = RoleNameValue.toString();
String UserNameVal = UserNameValue.toString();
String PageIDVal = PageID.toString();
// ...
// Read file accordingly
while ((line = br.readLine()) != null) {
// ...
// Split file based on Delimiter in question "MyStrToMyDotoboseSectoid"
String[] values = line.split(" MyStrToMyDotoboseSectoid "); // separator
// ...
// Declare and plug values obtained from Split
String strPostID = values[0];
String strPostName = values[1];
String strPostMessage = values[2];
String strPostDate = values[3];
String strPostURL = values[4];
String strPostStamp = values[5];
// ...
// Plug in App generated Info
String strRoleID = RoleNameVal.trim();
String strUserName = UserNameVal.trim();
String strPageID = PageIDVal.trim();
//DEBUG Purposes, comment out in prod
System.out.println("strPostID = " +strPostID);
System.out.println("strPostName = " +strPostName);
System.out.println("strPostMessage = " +strPostMessage);
System.out.println("strPostDate = " +strPostDate);
System.out.println("strPostURL = " +strPostURL);
System.out.println("strPostStamp = " +strPostStamp);
System.out.println("strRoleID = " +strRoleID);
System.out.println("strUserName = " +strUserName);
System.out.println("strPageID = " +strPageID);
// ...
System.out.println("Entering DB2 query...");
// ...
PreparedStatement prep = connection
.prepareStatement("insert into DB2ADMIN.TWITTER_WEB_POST values(?,?,?,?,?,?,?,?,?)");
// ... ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
System.out.println("Loading values values to Columns...");
// ...
// make avail expected value
prep.setString(1, strPostID);
prep.setString(2, strPostDate);
prep.setString(3, strPostName);
prep.setString(4, strPostURL);
prep.setString(5, strPostMessage);
prep.setString(6, strPostStamp);
prep.setString(7, strRoleID);
prep.setString(8, strUserName);
prep.setString(9, strPageID);
connection.setAutoCommit(false);
prep.execute();
connection.setAutoCommit(true);
// ...
System.out.println("DB2 Twitter values added...");
}
// clean stuff up
br.close();
connection.close();
} catch (Exception e) {
SQLException e2 = ((SQLException) e).getNextException();
String more = "";
if (e2 != null)
more = " : " + e2.getMessage();
try {
throw new SQLException("Connecting to DB, using: "
+ UserNameValue + " account: " + e.getMessage() + more);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
The problem with your url.
Github uses specific policies in the request header to prevent getting content of your data.
See here how to get content from github
Related
I have this issue:
I have a function that works fine but takes longer than I can handle for closing the window. So I have another function that checks with tasklist calls if the other window is finished.
It only checks it once so I need to have it check it again and again until finished.
The check function:
private int getWin() {
Process Checkprocess;
try {
String Checkcommand = "cmd /c tasklist /V /FI \"WINDOWTITLE eq Admin:*\"";
Checkprocess = Runtime.getRuntime().exec(Checkcommand);
String Checkline;
String Checkval="PID";
is = new BufferedReader(new InputStreamReader(Checkprocess.getInputStream()));
while((Checkline = is.readLine()) != null) {
retval = Checkline.contains(Checkval);
if (retval)
test = 1;
else
test = 0;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return test;
}
that should return 0 if false or 1 if there is a window with that title.
The whole source:
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
public class RunCommand extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 5711290708294275382L;
String commands= null;
//this could be set to a specific directory, if desired
File dir = null;
BufferedReader is = null;
BufferedReader es = null;
boolean retval;
int test;
private BufferedReader outfile;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
performTask(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
performTask(request, response);
}
private int getWin() {
Process Checkprocess;
try {
String Checkcommand = "cmd /c tasklist /V /FI \"WINDOWTITLE eq Admin:*\"";
Checkprocess = Runtime.getRuntime().exec(Checkcommand);
String Checkline;
String Checkval="PID";
is = new BufferedReader(new InputStreamReader(Checkprocess.getInputStream()));
while((Checkline = is.readLine()) != null) {
retval = Checkline.contains(Checkval);
if(retval)
test = 1;
else
test = 0;
System.out.println("HERE test" + retval);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return test;
}
private void performTask (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out= response.getWriter();
try
{
String commandbuild = request.getParameter("commandinput");
String commandfilename = request.getParameter("commandfile");
final SimpleDateFormat datefor = new SimpleDateFormat("ddMMyyyy_HHmmss");
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String timeadd = datefor.format(timestamp);
System.out.println(timeadd);
String completefilename = "C:\\tmp\\" + commandfilename +"_"+ timeadd + ".txt ";
String commandfull = "db2 -tvz "+ completefilename + commandbuild ;
commands= "cmd /c db2cwadmin.bat " + commandfull;
//System.out.println(commands);
Process process;
if (dir != null)
process = Runtime.getRuntime().exec(commands, null, dir);
else
process = Runtime.getRuntime().exec(commands);
String line;
StringBuilder data = new StringBuilder();
is = new BufferedReader(new InputStreamReader(process.getInputStream()));
data.append("Command: " + commands);
data.append("\n\n\n");
while((line = is.readLine()) != null) {
//System.out.println(line);
data.append(line);
data.append("\n");
}
es = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while((line = es.readLine()) != null)
System.err.println(line);
int exitCode = process.waitFor();
if (exitCode == 0) {
System.out.println("It worked");
while(test != 1) {
getWin();
if (test == 1)
break;
}
Process EndProcess;
String Endcommands = "taskkill /F /FI \"WINDOWTITLE eq Admin:*\"";
EndProcess = Runtime.getRuntime().exec(Endcommands);
int exitCodeEnd = EndProcess.waitFor();
System.out.println(exitCodeEnd);
//TimeUnit.SECONDS.sleep(10);
data.append("Window closed!");
data.append("\n");
data.append("\n");
outfile = new BufferedReader(new FileReader(completefilename));
String outfilelines;
while( (outfilelines = outfile.readLine()) != null ) {
data.append(outfilelines);
data.append("\n");
}
request.setAttribute("data", data);
out.append(data);
RequestDispatcher dispatcher= request.getRequestDispatcher("runCommand.jsp");
dispatcher.forward(request, response);
}
else
System.out.println("Something bad happend. Exit code: " + exitCode);
} //try
catch(Exception e)
{
System.out.println("Something when wrong: " + e.getMessage());
e.printStackTrace();
} //catch
finally
{
if (is != null)
try { is.close(); } catch (IOException e) {}
if (es != null)
try { es.close(); } catch (IOException e) {}
} //finally
}}
The problem ist that even if the getWin returns true (there is a println() to check that) the while loop is not exited and the prog is not going on. Furthermore it returns true than goes on and returns a couple of false and than true again and so on
How can I have the while loop quit when test is 1?
Thanks
How can I have the while loop quit when test is 1?
You can use break
if (retval){
test = 1;
break; //exit loop
}else{
test = 0;
}
I am trying to control a GPIO pin in my program to turn on a simple relay all of the code works apart from one issue; the GPIO pin code to send the signal high isn't working, and isn't causing any errors either, i am using the pi4j libraries to control the pins on the RaspberryPi Board.
Here is my code:
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.sql.Timestamp;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Calendar;
public class FileWatch {
static String clkID;
static String clkID2;
static String ts;
static String ts1;
static boolean done = false;
static boolean REdone = false;
static boolean finished = false;
static boolean ready;
static String host ="jdbc:mysql://localhost/dancers";
static String username ="root";
static String password ="beaker19";
public static void main(String[] args) throws IOException,
InterruptedException {
// create gpio controller
final GpioController gpio = GpioFactory.getInstance();
// provision gpio pin #01 as an output pin and turn on
final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "MyLED", PinState.LOW);
while (true) {
done = false;
REdone=false;
checkFile();
System.out.println("worked");
pin.high();
Thread.sleep(3000);
REcheckFile();
Thread.sleep(500);
//Thread.
if (clkID.equals(clkID2)) {
uploadTimes();
}
else {
System.out.println("Wrong matching ID's");
}
Thread.sleep(1000);
pin.low();
}
}
// Thread th = new Thread(new FileWatch());
// th.start();
// checkFile();
// REcheckFile();
// if (clkID2.equals(clkID2)){
// System.out.println("worked");
// }
// else {
// System.out.println("not worked");
// }
//
public static void check() throws InterruptedException{
checkFile();
Thread.sleep(3000);
REcheckFile();
Thread.sleep(500);
}
public String getClkId() {
return clkID;
}
public static void connection() {
// while(!finished){
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("worked");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
}
public static void checkFile() {
while (!done) {
try {
WatchService watcher = FileSystems.getDefault()
.newWatchService();
Path dir = Paths.get("/home/pi/rpi2ardu");
dir.register(watcher, ENTRY_MODIFY);
System.out.println("Watch Service registered for dir: "
+ dir.getFileName());
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException ex) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
#SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path fileName = ev.context();
System.out.println(kind.name() + ": " + fileName);
if (kind == ENTRY_MODIFY
&& fileName.toString().equals("example.txt")) {
System.out.println("My source file has changed!!!");
String sCurrentLine = null;
try (BufferedReader br = new BufferedReader(
new FileReader("/home/pi/rpi2ardu/example.txt"))) {
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
clkID = sCurrentLine;
System.out.println(clkID);
java.util.Date date = new java.util.Date();
date = new Timestamp(date.getTime());
// System.out.println(new
// Timestamp(date.getTime()));
ts = date.toString();
System.out.println(ts);
}
} catch (IOException e) {
e.printStackTrace();
}
File inputFile = new File("/home/pi/rpi2ardu/example.txt"); // Your
// file
File tempFile = new File("/home/pi/rpi2ardu/temp.txt");// temp
// file
BufferedReader reader = new BufferedReader(
new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(
new FileWriter(tempFile));
String currentLine;
while ((currentLine = reader.readLine()) != null) {
currentLine = ("");
writer.write(currentLine);
}
writer.close();
reader.close();
done = true;
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
}
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
public static void REcheckFile() {
while (!REdone) {
try {
WatchService watcher = FileSystems.getDefault()
.newWatchService();
Path dir = Paths.get("/home/pi/rpi2ardu");
dir.register(watcher, ENTRY_MODIFY);
System.out.println("Watch Service registered for dir: "
+ dir.getFileName());
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException ex) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
#SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path fileName = ev.context();
System.out.println(kind.name() + ": " + fileName);
if (kind == ENTRY_MODIFY
&& fileName.toString().equals("example.txt")) {
System.out.println("My source file has changed!!!");
String sCurrentLine = null;
try (BufferedReader br = new BufferedReader(
new FileReader("/home/pi/rpi2ardu/example.txt"))) {
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
clkID2 = sCurrentLine;
System.out.println(clkID2);
java.util.Date date1 = new java.util.Date();
date1 = new Timestamp(date1.getTime());
// System.out.println(new
// Timestamp(date.getTime()));
String ts1 = date1.toString();
System.out.println(ts1);
}
} catch (IOException e) {
e.printStackTrace();
}
File inputFile = new File("/home/pi/rpi2ardu/example.txt"); // Your
// file
File tempFile = new File("/home/pi/rpi2ardu/temp.txt");// temp
// file
BufferedReader reader = new BufferedReader(
new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(
new FileWriter(tempFile));
String currentLine;
while ((currentLine = reader.readLine()) != null) {
currentLine = ("");
writer.write(currentLine);
}
writer.close();
reader.close();
REdone = true;
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
}
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
public static void uploadTimes(){
try
{
String host ="jdbc:mysql://localhost/dancers";
String username ="root";
String password ="beaker19";
connection();
Connection conn = DriverManager.getConnection(host, username, password);
System.out.println("Connected:");
String t1= ts;
String t2 =ts1;
String id =clkID;
// the mysql insert statement
String query = " insert into test (id, ts, ts1)"
+ " values (?, ?, ?)";
// create the mysql insert preparedstatement
java.sql.PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, id);
preparedStmt.setString (2, t1);
preparedStmt.setString (3, t2);
// execute the preparedstatement
preparedStmt.execute();
System.out.println("worked");
conn.close();
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}
Im not sure why it isnt sending the gpio signal high and i am not seeing any results its just ommits the code like it wasnt there.
Any help would be great thanks!
Two things:
Make sure you are using the correct GPIO pin number. The pin numbering of Pi4J is different than the usual two ways of numbering in python. Take a look at this link: http://pi4j.com/pins/model-2b-rev1.html
Relays usually require high current to switch. The current provided by a GPIO pin is not enough to trigger most relays. Hook up an LED and resistor to that GPIO pin to test whether the problem is the pin not turning high or whether it is the relay requiring more current than the pin can supply.
I am creating a socket connection with a client utilizing android studio. I can successfully make a connection between the mobile device and the server, and my first debug message (Log.d("While Debugger", line)) successfully shows the input data from the server. However, the arraylist does not appear to adding the results, and my other debug messages are not providing any output!
To clarify further, when I call the returnData() method the temperature array is returned as null.
Any help will be much appreciated, and I will do my best to answer any questions asked of what I've written. Thanks!
package com.mycompany.myfirstapp;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
/**
* Created by seank on 15/07/2015.
*/
public class SocketExample {
ArrayList<Double> temperature = new ArrayList<Double>();
public SocketExample() throws IOException {
String serverHostname = new String ("192.168.1.143");
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 10007.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
Log.d("Here", "Got to the streams");
try {
echoSocket = new Socket(serverHostname, 10007);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
Log.e("Here","Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
Log.e("Here","Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
String line;
while( (line = in.readLine()) != null ) {
Log.d("While Debugger", line);
Double value = Double.parseDouble(line);
temperature.add(value);
}
if(temperature.size() == 0) {
Log.d("Numbers", "size = 0");
}
else {
Log.d("Numbers", String.valueOf(temperature.size()));
}
if(String.valueOf(temperature.size()) == null) {
Log.e("Numbers", "The temperature size is a null value");
}
// Close our streams
in.close();
out.close();
echoSocket.close();
}
public ArrayList<Double> returnData() {
return temperature;
}
public static void main(String[] args) throws IOException {
SocketExample socket = new SocketExample();
}
}
I think that, your program is blocking in the while loop, so your next debug is not executed.
You can try to add below code into the your while loop
if(temperature.size() == 0) {
Log.d("Numbers", "size = 0");
}
else {
Log.d("Numbers", String.valueOf(temperature.size()));
}
Okay, so I have an http server, pretty basic, which implements http 1.0, and it functions perfectly, except for a colossal flaw, when returning a zip file or it seems any compressed format, there is data corruption. What is confusing me is that there is only corruption when I call the writerHeader() method in my HeaderHandler class, so when I do not call this method, and just return the request without sending response headers to the client, all the data is intact and functional. Another confusing aspect of this is that when I compare the corrupt file's size with the good file's size, they are both exactly the same, down to the last byte.
package com.tinyhttp.core;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
import java.nio.file.Files;
public class Connection implements Runnable{//soon try to implement http 1.1
private Socket sock;
private BufferedReader in;
private HeaderHandler handler;
private OutputStream out;
public static final String DEFAULT_FILE = "test.zip";
public Connection(Socket sock){
this.sock = sock;
try{
out = sock.getOutputStream();
}catch(IOException e){
}
}
public void run(){
ReceiveRequest();
if(sock.isClosed())
return;
RequestHandel();
}
private void RequestHandel(){
if(handler.getMethod().equals("GET")){
File file = new File(handler.getRequest());
if(file.exists()){
try {
handler.writeHeader(out, file.length(), "200 OK", Files.probeContentType(file.toPath()));
} catch (IOException e) {
e.printStackTrace();
}
ReturnFile(handler.getRequest());
}else if(file.toString().equals("") || file.toString().equals("/")){
try {
handler.writeHeader(out, file.length(), "200 OK", Files.probeContentType(new File(DEFAULT_FILE).toPath()));//works without this line...
ReturnFile(DEFAULT_FILE);
} catch (IOException e) {
e.printStackTrace();
}
}
else{
returnNotFound();
System.out.println("404 NOT FOUND");
}
}
else
ReturnNotImplemented();
close();
}
private void ReceiveRequest(){
try {
handler = new HeaderHandler();
in = new BufferedReader(new InputStreamReader(sock.getInputStream(), "UTF-8"));
String line;
try{
while(!(line = in.readLine()).equals("")){
handler.append(line);
}
}catch(NullPointerException a){
close();
}
}catch (IOException e) {
e.printStackTrace();
}
System.out.println(sock.getInetAddress() + ":\n" + handler.getRequestLine());
}
private void ReturnFile(String req){
FileInputStream in = null;
try {
in = new FileInputStream(req);
} catch (FileNotFoundException e) {
System.out.println("The file " + req +" was not found");
return;
}
try {
byte[] buff = new byte[64*1024];
for(int read; (read = in.read(buff)) > -1;)
out.write(buff, 0, read);;
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void close(){
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void returnNotFound(){
try {
Writer out = new OutputStreamWriter(this.out, "UTF-8");
out.write("HTTP/1.1 404 NOT FOUND\n\rServer: " + Init.SERVER_ID + "\n\r\n\r");
out.write("<!DOCTYPE html>\n<html>\n<body>\n<h1>404 NOT FOUND</h1>" + handler.returnRawHead() + "\n</body>\n</html>");
close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void ReturnNotImplemented(){
Writer out = null;
try {
out = new OutputStreamWriter(this.out, "UTF-8");
out.write("HTTP/1.1 501 Not Implemented\n\rServer: " + Init.SERVER_ID + "\n\r\n\r");
out.write("<!DOCTYPE html>\n<html>\n<body>\n<h1>501 NOT IMPLEMENTED</h1>" + handler.returnRawHead() + "\n</body>\n</html>");
out.flush();
close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and the handler...
package com.tinyhttp.core;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HeaderHandler {
private ArrayList<String> list = new ArrayList<String>();
private String[] sortedheader;
public void append(String line){
list.add(line);
}
private void storeLine(){
sortedheader = new String[list.size()];
sortedheader = list.toArray(sortedheader);
}
public String getRequestLine(){
if(sortedheader == null)
storeLine();
try{
return sortedheader[0];
}catch(ArrayIndexOutOfBoundsException e){
}
return null;
}
public String getFileExtension(String file){
Pattern pat = Pattern.compile("\\..*\\z");
Matcher mat = pat.matcher(file);
mat.find();
try{
return mat.group().substring(1);
}catch(IllegalStateException e){
}
return null;
}
public String getConnectionType(){
if(sortedheader == null)
storeLine();
String headerstring = null;
for(int i = 0; i < sortedheader.length; i++){
Pattern pat = Pattern.compile("[Cc][Oo][Nn][Nn][Ee][Cc][Tt][Ii][Oo][Nn]");
Matcher mat = pat.matcher(sortedheader[i]);
mat.find();
try{
mat.group();
headerstring = sortedheader[i];
break;
}catch(IllegalStateException e){
}
}
return headerstring.substring(11).trim();
}
public float checkVersion(){
if(sortedheader == null)
storeLine();
String line;
try{
line = sortedheader[0];
}catch(ArrayIndexOutOfBoundsException e){
return -1;
}
Pattern pat = Pattern.compile("\\d\\.\\d");
Matcher mat = pat.matcher(line);
mat.find();
return Float.parseFloat(mat.group());
}
public String returnRawHead(){
if(sortedheader == null) storeLine();
StringBuilder sb = new StringBuilder("");
for(int i = 0; i < sortedheader.length; i++){
sb.append(sortedheader[i] + "\n");
}
return sb.toString();
}
public void writeHeader(OutputStream out, long length, String responsecode, String type){
Writer writer = null;
try {
writer = new OutputStreamWriter(out, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try{
writer.write("HTTP/" + Init.HTTP_IMPLEMENTATION + " " + responsecode + "\n\r");
writer.write("Content-Length: " + length + "\n\r");
writer.write("Server: " + Init.SERVER_ID + "\n\r");
writer.write("Content-Type: " + type + "\n\r");
writer.write("Connection: " + Init.CONNECTION_TYPE + "\n\r");//getting odd results wiv the flushing
writer.flush();
}catch(IOException e){
e.printStackTrace();
}
}
public String getMethod(){
if(sortedheader == null)
storeLine();
Pattern pat = Pattern.compile("[A-Z]{3,6}\\s");
Matcher mat = pat.matcher(sortedheader[0]);
mat.find();
String fin = mat.group();
return fin.substring(0, (fin.length() - 1));
}
public String getRequest(){
if(sortedheader == null)
storeLine();
Pattern pat = Pattern.compile("/.*\\s");
Matcher mat = pat.matcher(sortedheader[0]);
mat.find();
String req = mat.group();
return req.substring(1, (req.length() - 1));
}
public void printProcessed(){
if(sortedheader == null) storeLine();
for(int i = 0; i < sortedheader.length; i++){
System.out.println(sortedheader[i]);
}
}
}
Thanks for any help, Jake
So, basically it works, but it doesn't. It doesn't throw any errors, it just doesn't finish writing the file. It does read all of the lines in the file and they are all formatted correctly. I've tried debugging all of that. When debugging the "currentLine" all of the lines show up and are formatted correctly; However if I check my file that I'm writing to, it writes some of them perfectly, and then will just cut off at the end. Like the program didn't have enough time before killing itself.
My guess would be that writing takes awhile, and the program is being terminated before the file finishes writing, if that's the case, how can I avoid that?
Here's the code.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
BufferedReader fileReader;
BufferedWriter fileWriter;
private Main() {
try {
fileReader = new BufferedReader(new FileReader("File/spawn-config.cfg"));
fileWriter = new BufferedWriter(new FileWriter("Dumped/world_npcs.json"));
loadFile();
} catch (IOException e) {
e.printStackTrace();
}
}
private void loadFile() {
String currentLine;
try {
fileWriter.write("[\n");
while((currentLine = fileReader.readLine()) != null) {
if(!currentLine.startsWith("//") && !currentLine.startsWith("[")
&& !currentLine.startsWith("/*")) {
System.err.println(currentLine);
String[] array = currentLine.split("\\t");
String npcID = array[0].substring(7);
String xPos = array[1];
String yPos = array[2];
String zPos = array[3];
String walk = "false";
String radius = "0";
//-----------------------
fileWriter.write("{\n");
fileWriter.write("\"npc-id\": "+npcID+"\n");
fileWriter.write("\"position\": {\n");
fileWriter.write("\"x\": " + xPos + "\n");
fileWriter.write("\"y\": " + yPos + "\n");
fileWriter.write("\"z\": " + zPos + "\n");
fileWriter.write("},\n");
fileWriter.write("\"walking-policy\": {\n");
fileWriter.write("\"coordinate\": false, \"radius\": 0\n");
fileWriter.write("}\n},");
}
}
fileWriter.write("]");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] params) {
new Main();
}
}
If you are ready with writing flush and close the outputstream
fileWriter.flush();
fileWriter.close();