Kasutajaliidesed lab 2 java server example
Allikas: Lambda
import java.io.*; import java.net.*; import java.util.StringTokenizer; import javax.xml.transform.*; import javax.xml.transform.stream.*; /** * This class implements a multithreaded simple HTTP * server that supports the GET request method. * It listens on port 8080, waits client requests, and * serves documents. */ public class HttpServer { // The port number which the server // will be listening on public static final int HTTP_PORT = 8080; public ServerSocket getServer() throws Exception { return new ServerSocket(HTTP_PORT); } // multi-threading -- create a new connection // for each request public void run() { ServerSocket listen; try { listen = getServer(); while(true) { Socket client = listen.accept(); ProcessConnection cc = new ProcessConnection(client); } } catch(Exception e) { System.out.println("Exception: "+e.getMessage()); } } // main program public static void main(String argv[]) throws Exception { HttpServer httpserver = new HttpServer(); httpserver.run(); } } class ProcessConnection extends Thread { Socket client; BufferedReader is; DataOutputStream os; public ProcessConnection(Socket s) { // constructor client = s; try { is = new BufferedReader(new InputStreamReader (client.getInputStream())); os = new DataOutputStream(client.getOutputStream()); } catch (IOException e) { System.out.println("Exception: "+e.getMessage()); } this.start(); // Thread starts here...this start() will call run() } public void run() { try { // get a request and parse it. String request = is.readLine(); System.out.println( "Request uus: "+request ); StringTokenizer st = new StringTokenizer( request ); if ( (st.countTokens() >= 2) && st.nextToken().equals("GET") ) { if ( (request = st.nextToken()).startsWith("/") ) request = request.substring( 1 ); if ( request.equals("") ) request = request + "index.html"; System.out.println( "listing: "+request ); // check request String[] tmp; tmp=split(request,"?"); if (tmp.length>1) { //System.out.println("tmp: "+tmp); tmp=split(tmp[1],"&"); System.out.println("tmp1: "+tmp[0]); addparty(os,tmp); } // if (request.equals("listing")) { listing(os); } else if (request.equals("allparties")) { allparties(os); } else if (request.equals("addparty")) { addparty(os,tmp); } else { File f = new File(request); shipDocument(os, f); } } else { os.writeBytes( "400 Bad Request" ); } client.close(); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } } /** * Read the requested file and ship it * to the browser if found. */ public static void shipDocument(DataOutputStream out, File f) throws Exception { try { DataInputStream in = new DataInputStream(new FileInputStream(f)); int len = (int) f.length(); byte[] buf = new byte[len]; in.readFully(buf); in.close(); out.writeBytes("HTTP/1.0 200 OK\r\n"); out.writeBytes("Content-Length: " + f.length() +"\r\n"); out.writeBytes("Content-Type: text/html\r\n\r\n"); out.write(buf); out.flush(); } catch (Exception e) { out.writeBytes("<html><head><title>error</title></head><body>\r\n\r\n"); out.writeBytes("HTTP/1.0 400 " + e.getMessage() + "\r\n"); out.writeBytes("Content-Type: text/html\r\n\r\n"); out.writeBytes("</body></html>"); out.flush(); } finally { out.close(); } } public static void listing(DataOutputStream out) { String ls_str; String res=""; try { out.writeBytes("HTTP/1.0 200 OK\r\n"); Process myprocess = Runtime.getRuntime().exec("trydir.bat"); DataInputStream ls_in = new DataInputStream( myprocess.getInputStream()); try { while ((ls_str = ls_in.readLine()) != null) { res+=("<a href=\"redigeeri.cgi?"); res+=(ls_str); res+=("\">"); res+=("R</a> "); res+=("<a href=\""); res+=(ls_str); res+=("\">"); res+=(ls_str); res+=("</a>"); res+=("<br>"); } } catch (IOException e) { System.out.println("miski viga!"); e.printStackTrace(); } } catch (Exception err) { err.printStackTrace(); } try { out.writeBytes("Content-Length: " + res.length() +"\r\n"); out.writeBytes("content-type: text/html\r\n"); out.writeBytes("\r\n"); out.writeBytes(res); out.close(); } catch (Exception e) { } } public static void allparties(DataOutputStream out) throws Exception { URL yahoo = new URL("http://dijkstra.cs.ttu.ee:7777/xstone/xfuns/party_all"); BufferedReader in = new BufferedReader( new InputStreamReader( yahoo.openStream())); String inputLine; // create File and Stream objects //File dataFile = new File("fruit.xml"); // data File styleFile = new File("parties.xsl"); // stylesheet //InputStream dataStream = new FileInputStream(dataFile); InputStream styleStream = new FileInputStream(styleFile); // create XSLT Source and Result objects Source data = new StreamSource(in); Source style = new StreamSource(styleStream); Result output = new StreamResult(out); // create Transformer and perform the tranfomation Transformer xslt = TransformerFactory.newInstance().newTransformer(style); xslt.transform(data, output); /* while ((inputLine = in.readLine()) != null) { out.writeBytes(inputLine); } */ in.close(); } public static void addparty(DataOutputStream out, String[] splitargs) throws Exception { String xstone; String args; System.out.println("addp starts"); xstone="http://dijkstra.cs.ttu.ee:7777/xstone/xfuns/party_insert?"; args="1&2&"+splitargs[0]+"&"+splitargs[1]+ "&16-05-1965&17-05-1965&7&8&9&10&11&12"; xstone=xstone+args; System.out.println(xstone); URL yahoo = new URL(xstone); BufferedReader in = new BufferedReader( new InputStreamReader( yahoo.openStream())); String inputLine; // create File and Stream objects //File dataFile = new File("fruit.xml"); // data File styleFile = new File("insert_party_result.xsl"); // stylesheet //InputStream dataStream = new FileInputStream(dataFile); InputStream styleStream = new FileInputStream(styleFile); // create XSLT Source and Result objects Source data = new StreamSource(in); Source style = new StreamSource(styleStream); Result output = new StreamResult(out); // create Transformer and perform the tranfomation Transformer xslt = TransformerFactory.newInstance().newTransformer(style); xslt.transform(data, output); /* while ((inputLine = in.readLine()) != null) { out.writeBytes(inputLine); } */ in.close(); } public static String[] split(String input, String separator) { int len; int count; int pos; //String separator=","; int ws; int we; String[] words; /* count the number of separators: then we know the required size of the array */ len=input.length(); count=0; pos=-1; for(;;) { // loop over all occurrences of separator in input pos=input.indexOf(separator,pos+1); // search from last pos found! if (pos<0) break; // none found after pos count++; } // let us print some useful debug information //System.out.println("\nFound "+count+" separators "+separator); // make a suitable array words=new String[count+1]; // loop again over the input, this time collecting strings ws=0; // word start we=ws+1; // word end count=0; pos=-1; for(;;) { // again, loop over all occurrences of separator in input pos=input.indexOf(separator,pos+1); // search from last pos found! if (pos<0) { // no separator found after pos: take to end of string we=input.length(); } else { // separator found we=pos; } words[count]=input.substring(ws,we).trim(); // take substring, remove spaces ws=pos+separator.length(); // this is where the next word will start count++; if (pos<0) break; } return words; } }