GPIO not going high and code being ignored when running PI4J - java

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.

Related

Servlet Loop function call until result with while loop

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;
}

Reading CSV file from url in Java

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

Not getting Joblog from JES SPOOL using Java

I have written one Java class to submit JCL to Mainframe JES using FTP. The code is able to submit the JCL but it is not retrieving the JOB log from JES SPOOL.
package com.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
public class MVSSpool {
private FTPClient ftp = null;
private String fUserId,fPassword,fHost,fJobPerfix,replyText;
public MVSSpool(String fUserId, String fPassword,
String fHost, String fJobPerfix) {
this.fUserId = fUserId;
this.fPassword = fPassword;
this.fHost = fHost;
this.fJobPerfix = fJobPerfix;
ftp = new FTPClient();
}
public String getfUserId() {
return fUserId;
}
public void setfUserId(String fUserId) {
this.fUserId = fUserId;
}
public void setfPassword(String fPassword) {
this.fPassword = fPassword;
}
public String getfHost() {
return fHost;
}
public void setfHost(String fHost) {
this.fHost = fHost;
}
public String getfJobPerfix() {
return fJobPerfix;
}
public void setfJobPerfix(String fJobPerfix) {
this.fJobPerfix = fJobPerfix;
}
public void submitJobToSpool(String jobName) throws Exception{
if (jobName != null){
connectMVSFtp();
InputStream is = null;
BufferedReader br = null;
String currentLine = null;
try{
ftp.retrieveFileStream("'"+jobName.trim()+"'");
replyText = ftp.getReplyString();
System.out.println("some " + replyText);
String[] replies = ftp.getReplyStrings();
String remoteFileName = replies[replies.length - 1].split(" ")[2]+ ".2";
for(String rep :replies){
System.out.println("checking .. " + rep);
}
Thread.sleep(10000);
System.out.println("getting sysout of the file " + remoteFileName);
is = ftp.retrieveFileStream(remoteFileName);
replies = ftp.getReplyStrings();
for(String rep :replies){
System.out.println("checking 2 .. " + rep);
}
if (is != null){
br = new BufferedReader(new InputStreamReader(is));
while((currentLine = br.readLine()) != null){
System.out.println(currentLine);
}
}
ftp.completePendingCommand();
System.out.println("Done...");
}catch(Exception e){
e.printStackTrace();
throw new Exception("Error in submitting Job from spool");
}finally{
ftp.disconnect();
if(br != null){
br.close();
}
if(is != null){
is.close();
}
}
}
}
/**
* #throws SocketException
* #throws IOException
*/
private void connectMVSFtp() throws SocketException, IOException {
// check if the required parameters are set already
if (fUserId == null | fPassword == null | fHost == null){
}else{
ftp.connect(fHost);
replyText = ftp.getReplyString();
System.out.println(replyText);
// login using user name and password
ftp.login(fUserId, fPassword);
replyText = ftp.getReplyString();
System.out.println(replyText);
// point the FTP to JES spool
ftp.site("filetype=jes");
replyText = ftp.getReplyString();
System.out.println(replyText);
}
}
}
I am getting below messages
230 XXXXX is logged on. Working directory is "XXXXX.".
200 SITE command was accepted
some 125-Submitting job 'XXXXX.XXXX.JCLLIB(ALIAS)' FIXrecfm 80
125 When JOB07591 is done, will retrieve its output
checking .. 125-Submitting job 'XXXXX.XXXX.JCLLIB(ALIAS)' FIXrecfm 80
checking .. 125 When JOB07591 is done, will retrieve its output
getting sysout of the file JOB07591.2
checking 2 .. 550 No spool files available for JOB07591, JesPutGet aborted
Done...enter code here

I want to create a text file with name coming from user and the write in it?

I wrote this program for my uni Assignment. The main idea is when ever the addItem is invoked it creates a text file and write order from the user on that file. But how ever it only creates the file but prints nothing on the inside.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
public class OrderedFood extends Food {
private int quantity;
private boolean isSet;
private SetDrink setDrink;
public OrderedFood(){
quantity = 0;
isSet = false;
setDrink = null;
}
public OrderedFood(String foodCode, String foodName,boolean isSet, SetDrink setDrink, int quantity){
super(foodCode, foodName);
this.isSet = isSet;
this.quantity = quantity;
this.setDrink = setDrink;
}
public int getquantity(){
return quantity;
}
public void setquantity(int quantity){
this.quantity = quantity;
}
public boolean getIsSet(){
return isSet;
}
public void setisSet(boolean isSet){
this.isSet = isSet;
}
public SetDrink getsetDrink(){
return setDrink;
}
public void setsetDrink(SetDrink setDrink){
this.setDrink = setDrink;
}
public void addItem (String foodCode, int TabNum)throws IOException{
clearScreen(); // invoking the clearScreen method
String filename = Integer.toString(TabNum);
try
{
//this blocks creates a table by the table num
File file = new File("/tmp", filename);
System.out.println("path=" + file.getAbsolutePath());
file.createNewFile();
System.out.println("File created");
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Failed to create file");
}
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "utf-8")))
{
writer.write("foodCode"); // this syntax prints the order
writer.close();
}
}
public void deleteItem(String foodCode , int TabNum)throws IOException{
clearScreen();
String Tab = Integer.toString(TabNum);
remove(Tab,foodCode);// we just invoke the remove method, which will then remove the item from the .txt file
}
public static void clearScreen() { // this method clears the screen.
System.out.print("\033[H\033[2J");
System.out.flush();
}
public void remove(String file, String lineToRemove)throws IOException {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader buff = new BufferedReader(new FileReader(file));
PrintWriter kap = new PrintWriter(new FileWriter(tempFile));
String line = null;
while ((line = buff.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
kap.println(line);
kap.flush();
}
}
kap.close();
buff.close();
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
There is a logical mistake when you are creating a file you are not telling the extension also when opening the file for writing you used filename but it contains only the tabnumber not the full path to file use the below code
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
public class OrderedFood extends Food {
private int quantity;
private boolean isSet;
private SetDrink setDrink;
public OrderedFood(){
quantity = 0;
isSet = false;
setDrink = null;
}
public OrderedFood(String foodCode, String foodName,boolean isSet, SetDrink setDrink, int quantity){
super(foodCode, foodName);
this.isSet = isSet;
this.quantity = quantity;
this.setDrink = setDrink;
}
public int getquantity(){
return quantity;
}
public void setquantity(int quantity){
this.quantity = quantity;
}
public boolean getIsSet(){
return isSet;
}
public void setisSet(boolean isSet){
this.isSet = isSet;
}
public SetDrink getsetDrink(){
return setDrink;
}
public void setsetDrink(SetDrink setDrink){
this.setDrink = setDrink;
}
public void addItem (String foodCode, int TabNum)throws IOException{
clearScreen(); // invoking the clearScreen method
String filename = Integer.toString(TabNum);
try
{
//this blocks creates a table by the table num
File file = new File("/tmp", filename);
System.out.println("path=" + file.getAbsolutePath());
file.createNewFile();
filename = file.getAbsolutePath(); //here the actual address is updated to use later
System.out.println("File created");
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Failed to create file");
}
try
{
//now here we need that address updated earlier not just the tabnumber
PrintWriter writer = new PrintWriter(filename, "UTF-8");
writer.print("food code");
riter.close();
}
}
public void deleteItem(String foodCode , int TabNum)throws IOException{
clearScreen();
String Tab = Integer.toString(TabNum);
remove(Tab,foodCode);// we just invoke the remove method, which will then remove the item from the .txt file
}
public static void clearScreen() { // this method clears the screen.
System.out.print("\033[H\033[2J");
System.out.flush();
}
public void remove(String file, String lineToRemove)throws IOException {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader buff = new BufferedReader(new FileReader(file));
PrintWriter kap = new PrintWriter(new FileWriter(tempFile));
String line = null;
while ((line = buff.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
kap.println(line);
kap.flush();
}
}
kap.close();
buff.close();
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

http server has a tenancy to corrupt zips, mp4s and other compressed formats

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

Categories

Resources