Saturday, 15 May 2010

sockets - How to access a file on a Client from a Server without transferring the file from the Client to the Server in Java -



sockets - How to access a file on a Client from a Server without transferring the file from the Client to the Server in Java -

i programming first java socket application uses client/server paradigm.

i have next classes: socketserver socketclient

the objective of application have user input file path .csv file on client console/file system:

1. create server programme uses socket. a. server receives csv path/filename located on client client. b. server accesses client csv file , converts xml file. c. server streams xml file contents, not xml path/file name, client.

create client programme uses socket. utilize same port server.

a. prompt user path/filename of csv file.

b. send path/filename server processing.

c. receive xml file stream server socket.

d. save xml file stream file stored on client.

e. store generated xml file anywhere on client.

i have written code connecting sockets on both server , client converting .csv .xml, however, struggling with:

step 1b.the server accesses client csv file , converts xml file.

can access .csv file located on client straight server or have transfer file path server client, transfer file server conversion, transfer new xml document back?

based on instructions, sounds there should way access file server.

here code have written.

clientcontroller.java

public class clientcontroller extends consolecontroller { // debug private static final boolean debug = true; private static final boolean debug_store = false; private static final boolean debug_prompt = false; private static final boolean debug_values = true; // constants public static final string prompt_message = "enter filepath '.csv' file convert '.xml' file: "; // members private string userfilepath; private socketclient mclient; // constructors public clientcontroller() { super(); mclient = null; } // life-cycle methods @override public void oncreate() { // setup connection server mclient = setupserverconnection(); // path csv file conversion requestpathtocsvfile(); // effort transfer file seek { sendpathtoserver(userfilepath); } grab (exception e) { system.out.println("failed transfer file!"); system.out.println("exception: "); e.printstacktrace(); } // effort send message 50 times mclient.sendsomemessages(3); } // convenience methods private socketclient setupserverconnection() { string hostname = "localhost"; int port = 54321; byte[] info = "hello server".getbytes(); homecoming new socketclient(hostname, port, data); } private void requestpathtocsvfile() { // debug vars boolean isempty = true; boolean isdefaultmessage = true; boolean iscsv = false; while (true){ if (!isempty && !isdefaultmessage && iscsv) break; // prompt user userfilepath = promptuser(prompt_message); system.out.println(userfilepath); // debugging isempty = userfilepath.isempty(); isdefaultmessage = userfilepath.equals(default_message); iscsv = iscsvpath(userfilepath); // output debugging if (debug && debug_values) { if (userfilepath != null) { system.out.println("debug userfilepath: " + userfilepath); } else { system.out.println("debug userfilepath: isnull"); } system.out.println("isempty: " + (isempty? "true":"false")); system.out.println("debug userfilepath:" + (isdefaultmessage? "true":"false")); system.out.println("iscsvpath: " + (iscsvpath(userfilepath)? "true":"false")); } } } private void sendpathtoserver(string path) { // send filepath server mclient.sendmessage(path); } private boolean iscsvpath(string path) { homecoming regex.hasextension(path, "csv"); } }

socketserver.java

import java.io.bufferedinputstream; import java.io.file; import java.io.fileinputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.net.serversocket; import java.net.socket; // illustration of simple socket server. public class socketserver { // constants private static final boolean debug = true; private static final boolean debug_nodes = true; // flags private static final int flag_message = 0; private static final int flag_convert_csv_to_xml = 1; // constants private static final string temporary_folder_path = "/tmp"; private static final string temp_csv_filename = "csvtoconverttoxml.csv"; private static final string temp_xml_filename = "xmlofcsv.xml"; // members private int serverport; private serversocket mserversocket = null; private socket msocket; private inputstream msocketinput; private outputstream msocketoutput; private int msocketflag; private string mpathtocsv; public socketserver(int serverport) { this.serverport = serverport; seek { mserversocket = new serversocket(serverport); } grab (ioexception e) { e.printstacktrace(system.err); } } public void waitforconnections() { msocket = null; msocketinput = null; msocketoutput = null; while (true) { // open socket on server , wait connection opensocket(); // todo code flagging msocketflag = 1; switch (msocketflag) { case flag_message: handleconnection(); break; case flag_convert_csv_to_xml: handlefileconversionconnection(); break; } // close socket. closesocket(); } } // method wait bytes // connection, read them, write them again, until // socket closed other side. public void handlefileconversionconnection() { while(true) { byte[] buffer = new byte[1024]; int bytes_read = 0; seek { // phone call read() wait forever, until // programme on other side either sends data, // or closes socket. bytes_read = msocketinput.read(buffer, 0, buffer.length); // if socket closed, sockinput.read() homecoming -1. if(bytes_read < 0) { system.err.println("tried read socket, read() returned < 0, closing socket."); return; } // set mpathtocsv mpathtocsv = new string(buffer, 0, bytes_read); // log recieved info system.out.println("server received "+ bytes_read +" bytes, data=" + mpathtocsv); system.out.println("mpathtocsv: " + mpathtocsv); // path supplied client , save in /temp folder on server string pathtotempcsv = getfilefromclient(mpathtocsv,temporary_folder_path, temp_csv_filename); // convert csv xml string pathtoxmlforclient = convertcsvtoxml(pathtotempcsv, temporary_folder_path, temp_xml_filename); // transfer new xml document client //transfer(pathtoxmlforclient); // msocketoutput.write(buffer, 0, bytes_read); // phone call flush() optional - we're saying go // ahead , send info instead of buffering it. msocketoutput.flush(); } grab (exception e) { system.err.println("exception reading from/writing socket, e="+e); e.printstacktrace(system.err); return; } } } // method wait bytes // connection, read them, write them again, until // socket closed other side. public void handleconnection() { while(true) { byte[] buffer = new byte[1024]; int bytes_read = 0; seek { // phone call read() wait forever, until // programme on other side either sends data, // or closes socket. bytes_read = msocketinput.read(buffer, 0, buffer.length); // if socket closed, sockinput.read() homecoming -1. if(bytes_read < 0) { system.err.println("tried read socket, read() returned < 0, closing socket."); return; } system.out.println("server received "+ bytes_read +" bytes, data=" + (new string(buffer, 0, bytes_read))); msocketoutput.write(buffer, 0, bytes_read); // phone call flush() optional - we're saying go // ahead , send info instead of buffering it. msocketoutput.flush(); } grab (exception e) { system.err.println("exception reading from/writing socket, e="+e); e.printstacktrace(system.err); return; } } } public void opensocket() { seek { // method call, accept(), blocks , waits // (forever if necessary) until other programme // opens socket connection our server. when // other programme opens connection our server, // accept() creates new socket represent // connection , returns. msocket = mserversocket.accept(); system.err.println("have accepted new socket."); // point on, no new socket connections can // made our server until accept() called again. msocketinput = msocket.getinputstream(); msocketoutput = msocket.getoutputstream(); } grab (ioexception e) { e.printstacktrace(system.err); } } public void closesocket() { seek { system.err.println("closing socket."); msocket.close(); } grab (exception e) { system.err.println("exception while closing socket."); e.printstacktrace(system.err); } system.err.println("finished socket, waiting next connection."); } // convenience methods public void transfer(string sfile) throws ioexception { if (debug && debug_nodes) system.out.println("enter transfer(string sfile)"); // create new file object file myfile = new file(sfile); while (true) { byte[] mybytearray = new byte[(int) myfile.length()]; bufferedinputstream bis = new bufferedinputstream(new fileinputstream(myfile)); bis.read(mybytearray, 0, mybytearray.length); // outputstream socket msocketoutput.write(mybytearray, 0, mybytearray.length); msocketoutput.flush(); // close socket bis.close(); } } public string getfilefromclient(string pathtofile, string destinationdirectory, string newfilename) { if (debug && debug_nodes) system.out.println("enter getfilefromclient(string pathtofile, string destinationdirectory, string newfilename)"); string pathtonewfile = destinationdirectory + "/" + newfilename; // todo file client if (debug && debug_nodes) system.out.println("exit getfilefromclient(string pathtofile, string destinationdirectory, string newfilename)"); homecoming pathtonewfile; } public string convertcsvtoxml(string pathtocsv, string pathtodestinationdirectory, string newfilename) { if (debug && debug_nodes) system.out.println("enter convertcsvtoxml(string pathtocsv, string pathtodestinationdirectory, string newfilename)"); string pathtonewfile = pathtodestinationdirectory + "/" + newfilename; // todo create new file , convert csv xml xmlwriter xmlfile = new xmlwriter(pathtocsv, pathtonewfile); xmlfile.csvtoxml(); if (debug && debug_nodes) system.out.println("exit convertcsvtoxml(string pathtocsv, string pathtodestinationdirectory, string newfilename)"); homecoming pathtonewfile; } public static void main(string argv[]) { int port = 54321; socketserver server = new socketserver(port); server.waitforconnections(); } }

socketclient.java

import java.io.bufferedoutputstream; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.net.socket; public class socketclient { // constants public static final int transfer_size_1kb = 1024; // members private string mserverhostname = null; private int mserverport = 0; private byte[] info = null; private socket msocket = null; private inputstream msocketinput = null; private outputstream msocketoutput = null; public socketclient(string serverhostname, int serverport) { this(serverhostname, serverport, null); } public socketclient(string mserverhostname, int mserverport, byte[] data) { this.mserverhostname = mserverhostname; this.mserverport = mserverport; this.data = data; } public void transfer( string outfile ) throws exception { // open socket opensocket(); // create new byte array size of 1kb byte[] bytearray = new byte[transfer_size_1kb]; // create bufferedoutputstream outfile path fileoutputstream fos = new fileoutputstream(outfile); bufferedoutputstream bos = new bufferedoutputstream(fos); // testing fos.tostring(); // initialize values 0 int bytesread = 0; int count = 0; system.out.println("got here"); // transfer 'outfile' 1kb (1024 bytes) increments, each pass 1kb chunk of files while ((bytesread = msocketinput.read(bytearray, 0, bytearray.length)) != -1) { system.out.println("got here"); // send info server bos.write(bytearray, 0, bytesread); // if less 1kb, finish transfer using flush() bos.flush(); system.out.println(++count); } // log console system.out.println("finished transferring " + outfile); // close bufferedoutputstream bos.close(); // close socket closesocket(); } public void sendsomemessages(int iterations) { // open socket opensocket(); byte[] buf = new byte[data.length]; int bytes_read = 0; for(int x=1; x<=iterations; x++) { seek { msocketoutput.write(data, 0, data.length); bytes_read = msocketinput.read(buf, 0, buf.length); } grab (ioexception e) { e.printstacktrace(system.err); } if( bytes_read != data.length ) { system.out.println("run: sent "+ data.length +" bytes, server should have sent them back, read "+bytes_read+" bytes, not same number of bytes."); } else { system.out.println("client sent "+bytes_read+" bytes server , received them again, msg = "+(new string(data))); } // sleep bit action doesn't happen fast - // purely reasons of demonstration, , not required technically. seek { thread.sleep(50);} grab (exception e) {}; } system.err.println("done reading/writing to/from socket, closing socket."); // close socket closesocket(); } public void sendmessage(string str) { // open socket opensocket(); // convert string byte array byte[] info = str.getbytes(); // create buffer object size of info byte array byte[] buf = new byte[data.length]; int bytes_read = 0; // effort send info on network seek { msocketoutput.write(data, 0, data.length); bytes_read = msocketinput.read(buf, 0, buf.length); } grab (ioexception e) { e.printstacktrace(system.err); } if( bytes_read != data.length ) { system.out.println("run: sent "+ data.length +" bytes, server should have sent them back, read "+bytes_read+" bytes, not same number of bytes."); } else { system.out.println("client sent "+bytes_read+" bytes server , received them again, msg = "+(new string(data))); } // sleep bit action doesn't happen fast - // purely reasons of demonstration, , not required technically. seek { thread.sleep(50);} grab (exception e) {}; system.err.println("done reading/writing to/from socket, closing socket."); // close socket closesocket(); } public void opensocket() { // open socket system.err.println("opening connection "+mserverhostname+" port "+mserverport); seek { msocket = new socket(mserverhostname, mserverport); msocketinput = msocket.getinputstream(); msocketoutput = msocket.getoutputstream(); } grab (ioexception e) { e.printstacktrace(system.err); return; } system.err.println("about start reading/writing to/from socket."); } public void closesocket() { // close socket seek { msocket.close(); } grab (ioexception e) { system.err.println("exception closing socket."); e.printstacktrace(system.err); } system.err.println("exiting."); } // getters & setters public string getserverhostname() { homecoming mserverhostname; } public void setserverhostname(string serverhostname) { this.mserverhostname = mserverhostname; } public int getserverport() { homecoming mserverport; } public void setserverport(int serverport) { this.mserverport = mserverport; } public socket getsocket() { homecoming msocket; } public void setsocket(socket socket) { this.msocket = msocket; } public inputstream getsocketinput() { homecoming msocketinput; } public void setsocketinput(inputstream socketinput) { this.msocketinput = msocketinput; } public outputstream getsocketoutput() { homecoming msocketoutput; } public void setsocketoutput(outputstream socketoutput) { this.msocketoutput = msocketoutput; } }

supporting classes

consolecontroller.java

import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstreamreader; import java.util.comparator; @suppresswarnings("unused") public abstract class consolecontroller { // debug private static final boolean debug = false; private static final boolean debug_store = false; private static final boolean debug_prompt = false; private static final boolean debug_values = false; // constants protected static final string default_message = "no input recieved"; // members private string mrecentinput; // constructors public consolecontroller() { mrecentinput = default_message; } // life-cycle methods abstract public void oncreate(); public string promptuser(string userprompt) { system.out.println(userprompt); try{ // create bufferedreader read console bufferedreader bufferread = new bufferedreader(new inputstreamreader(system.in)); // read line console mrecentinput = bufferread.readline(); if (mrecentinput.equalsignorecase("exit")) exit(); } catch(ioexception e) { e.printstacktrace(); } homecoming mrecentinput; } public string getinput() { homecoming mrecentinput; } public void exit() { //system.out.println("quiting"); system.exit(0); } }

regex.java

import java.util.regex.matcher; import java.util.regex.pattern; @suppresswarnings("unused") public class regex { public static final boolean debug = false; public static final boolean debug_has_ext = true; public static boolean hasextension(string path, string extension) { // match numberic , hexadecimal values pattern exttest = pattern.compile("\\.(" + extension.trim() + ")$"); matcher values = exttest.matcher(path); if (debug && debug_has_ext) { system.out.println("regex - extension matches"); system.out.println("search string: " + path); system.out.println("pattern: " + exttest.pattern()); system.out.print("match: "); } // returns true if there anothermatch remaining, returns false if no matches remain boolean anothermatch = values.find(); if (anothermatch == true) { while(anothermatch) { // if here, there match // log if (debug && debug_has_ext) system.out.println(values.group()); // check see if there anothermatch anothermatch = values.find(); } homecoming true; } else { if (debug && debug_has_ext) system.out.println("there no match"); homecoming false; } } }

xmlwriter.java

import java.io.*; import org.w3c.dom.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; public class xmlwriter { // members private document mdocumentforoutput; private string minfilepath; private string moutfilepath; // constructors public xmlwriter(string filepathforconversion, string filepathforoutput) { minfilepath = filepathforconversion; moutfilepath = filepathforoutput; seek { mdocumentforoutput = createdocument(); } grab (exception e) { system.out.println("exception: "); e.printstacktrace(); } } public document createdocument() throws ioexception, parserconfigurationexception { documentbuilderfactory builderfactory = documentbuilderfactory.newinstance(); documentbuilder docbuilder = builderfactory.newdocumentbuilder(); document doc = docbuilder.newdocument(); homecoming doc; } public void processdocument(string delimeter) throws exception { // file object inpath file infile = new file(minfilepath); // create bufferedreader file bufferedreader reader = new bufferedreader(new filereader(infile)); // read line file string sline = reader.readline(); // string[] sheaders = sline.split(delimeter); sline = reader.readline(); string[] snodes = sline.split(delimeter); element aroot; element achild; aroot = mdocumentforoutput.createelement(sheaders[0].trim()); mdocumentforoutput.appendchild(aroot); while ((sline=reader.readline()) != null) { achild = mdocumentforoutput.createelement(sheaders[1].trim()); string[] sdata = sline.split(delimeter); (int x=0; x<snodes.length; ++x) { element c = mdocumentforoutput.createelement(snodes[x].trim()); c.appendchild(mdocumentforoutput.createtextnode(sdata[x].trim())); achild.appendchild(c); } aroot.appendchild(achild); } } public void createxml() throws exception { //transformerfactory instance used create transformer objects. transformerfactory mill = transformerfactory.newinstance(); transformer transformer = factory.newtransformer(); transformer.setoutputproperty(outputkeys.indent, "yes"); // create string xml tree stringwriter sw = new stringwriter(); streamresult result = new streamresult(sw); domsource source = new domsource(mdocumentforoutput); transformer.transform(source, result); string xmlstring = sw.tostring(); file file = new file(moutfilepath); bufferedwriter bw = new bufferedwriter(new outputstreamwriter(new fileoutputstream(file))); bw.write(xmlstring); bw.flush(); bw.close(); } public void createxmldocument(string delimeter) throws exception { processdocument(delimeter); createxml(); } public void csvtoxml() { seek { createxmldocument(","); } grab (exception e) { system.out.print("exception: "); e.printstacktrace(); } } public static void testwriter(string csvfile) { seek { seek { xmlwriter xmlwriter = new xmlwriter(csvfile, "output.xml"); xmlwriter.csvtoxml(); } grab (exception e) { system.out.println("'" + csvfile + "' not exist in given directory! please check have entered filepath"); } system.out.println("<b>xml file created successfully</b>"); } catch(exception e) { system.out.println(e); } } }

java sockets

No comments:

Post a Comment