HTTPFileConduit.java

00001 /*
00002  * OpenMobileIS - a free Java(TM) Framework for mobile applications Java(TM)
00003  * Copyright (C) 2006-2009 Ubikis
00004  * All rights reserved.
00005  * Contact: pdelrieu@openmobileis.org
00006  *
00007  * This library is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or any later version.
00011  *
00012  * This library is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with this library; if not, write to the Free Software
00019  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
00020  * USA
00021  *
00022  *  Author : Philippe Delrieu
00023  *  
00024  *  Modifications :
00025  *  Creation P.Delrieu
00026  * 
00027  */
00028 package org.openmobileis.common.util.file;
00029 
00030 import java.io.BufferedReader;
00031 import java.io.ByteArrayOutputStream;
00032 import java.io.File;
00033 import java.io.FileOutputStream;
00034 import java.io.FileReader;
00035 import java.io.IOException;
00036 import java.io.InputStream;
00037 import java.io.OutputStream;
00038 import java.io.OutputStreamWriter;
00039 import java.net.ServerSocket;
00040 import java.net.Socket;
00041 
00042 import javax.net.SocketFactory;
00043 
00044 import org.openmobileis.common.util.PropertiesManager;
00045 import org.openmobileis.common.util.log.LogManager;
00046 import org.openmobileis.common.util.log.LogServices;
00047 import org.openmobileis.embedded.webserver.ServeInputStream;
00048 
00066 public final class HTTPFileConduit {
00067         private int port;
00068         private String dirpath = "";
00069         private String filename;
00070         private static byte[] ENDLINE = { '\r', '\n' };
00071         private String server; // server address. Format is <serveradresse>:<port>
00072         private boolean debugOn = false;
00073         private int waitFileTimeout;
00074 
00075         class TestMakeQuery implements Runnable {
00076                 public void run() {
00077                         while (true) {
00078                                 File file = new File(dirpath + File.separator + filename + ".in");
00079                                 if (file.exists()) {
00080                                         try {
00081                                                 BufferedReader readbuff = new BufferedReader(new FileReader(file));
00082                                                 String server = readbuff.readLine();
00083                                                 int index = server.indexOf(":");
00084                                                 String sadr = server.substring(0, index);
00085                                                 String sport = server.substring(index + 1, server.length());
00086                                                 int port = Integer.parseInt(sport);
00087                                                 // byte[] tosend = FileUtilities.readFile(file);
00088                                                 Socket socket = SocketFactory.getDefault().createSocket(sadr, port);
00089                                                 OutputStream out = socket.getOutputStream();
00090                                                 char[] buffer = new char[1024];
00091                                                 int char_read = -1;
00092                                                 OutputStreamWriter outw = new OutputStreamWriter(out);
00093                                                 while ((char_read = readbuff.read(buffer)) != -1) {
00094                                                         outw.write(buffer, 0, char_read);
00095                                                 }
00096                                                 outw.flush();
00097                                                 InputStream in = socket.getInputStream();
00098                                                 FileOutputStream outfile = new FileOutputStream(dirpath + File.separator + filename + ".out.tmp");
00099                                                 byte[] bufferb = new byte[1024];
00100                                                 int readbyte = -1;
00101                                                 while ((readbyte = in.read(bufferb, 0, buffer.length)) != -1) {
00102                                                         outfile.write(bufferb, 0, readbyte);
00103                                                 }
00104                                                 outfile.flush();
00105                                                 outfile.close();
00106                                                 in.close();
00107                                                 out.close();
00108                                                 outw.close();
00109                                                 socket.close();
00110 
00111                                                 File newfile = new File(dirpath + File.separator + filename + ".out.tmp");
00112                                                 newfile.renameTo(new File(dirpath + File.separator + filename + ".out"));
00113                                                 file.delete();
00114 
00115                                         } catch (Throwable ex) {
00116                                                 LogManager.traceError(0, "Test HTTPFileConduit Error :" + ex.toString());
00117                                                 try {
00118                                                         FileOutputStream outfile = new FileOutputStream(dirpath + File.separator + filename + ".out");
00119                                                         outfile.write("HTTP/1.1 500 Internal Error".getBytes());
00120                                                         outfile.flush();
00121                                                         outfile.close();
00122                                                 } catch (IOException exi) {
00123                                                         LogManager.traceError(0, "Test HTTPFileConduit Error :" + exi.toString());
00124                                                 }
00125                                                 return;
00126                                         }
00127                                 }
00128                                 try {
00129                                         Thread.currentThread().sleep(1000);
00130                                 } catch (Throwable exi) {
00131                                         LogManager.traceError(0, "Test HTTPFileConduit Error :" + exi.toString());
00132                                 }
00133                         }
00134                 }
00135 
00136         }
00137 
00138         class LocalServer implements Runnable {
00139 
00140                 public LocalServer() {
00141                 }
00142 
00143                 public void run() {
00144                 //      LogManager.traceDebug(0, "HTTPFileConduit START QUERY HTTP");
00145                 ServerSocket serverSocket = null;
00146                         ByteArrayOutputStream outarray = new ByteArrayOutputStream();
00147                         try { // accept request from clients
00148                                 // write serveur address. Format is <serveradresse>:<port>
00149                                 outarray.write(server.getBytes());
00150                                 outarray.write(ENDLINE);
00151 
00152                                 serverSocket = new ServerSocket(port, 1000);
00153                                         Socket socket = serverSocket.accept();
00154                                         OutputStream out = socket.getOutputStream();
00155                                         try {
00156                                                 // write file here.
00157                                                 ServeInputStream input = new ServeInputStream(socket.getInputStream());
00158                                                 String line = null;
00159                                                 int contentLenght = -1;
00160                                                 String contentType = null;
00161                                                 while ((line = input.readLine()) != null) {
00162                                                         outarray.write(line.getBytes());
00163                                                         outarray.write(ENDLINE);
00164                                                         if (line.indexOf("Content-Length") != -1) {
00165                                                                 int index = line.indexOf(":");
00166                                                                 contentLenght = Integer.parseInt(line.substring(index + 1, line.length()).trim());
00167                                                         } else if (line.indexOf("Content-Type") != -1) {
00168                                                                 int index = line.indexOf(":");
00169                                                                 contentType = line.substring(index + 1, line.length()).trim();
00170                                                         }
00171                                                         if (line.length() == 0)
00172                                                                 break;
00173                                                 }
00174                                                 input.setReturnedAsReader(true);
00175                                                 if (contentType != null && contentType.equals("application/x-www-form-urlencoded") && contentLenght > 0) {
00176                                                         // contentLenght = contentLenght-outarray.toByteArray().length;
00177                                                         byte[] postedBytes = new byte[contentLenght];
00178                                                         int offset = 0;
00179 
00180                                                         do {
00181                                                                 int inputLen = input.read(postedBytes, offset, contentLenght - offset);
00182                                                                 if (inputLen <= 0) {
00183                                                                         throw new IllegalArgumentException("Bag HTTP application/x-www-form-urlencoded query.");
00184                                                                 }
00185                                                                 offset += inputLen;
00186                                                         } while ((contentLenght - offset) > 0);
00187                                                         outarray.write(postedBytes);
00188                                                 }
00189                                                 outarray.flush();
00190                                                 outarray.close();
00191                                                 // LogManager.traceDebug(0, outarray.toString());
00192                                                 // write to a file.
00193                                                 ReadWriteFileTransfertManager writer = new ReadWriteFileTransfertManager(dirpath);
00194                                                 writer.setTimeout(waitFileTimeout);
00195                                                 byte[] b = writer.sendReadWriteCommand(outarray.toByteArray(), filename + ".in", filename + ".out", null);
00196                                                 out.write(b);
00197                                         } finally {
00198                                                 out.flush();
00199                                                 socket.close();
00200                                                 // delete out file et in file if exist
00201                                                 File ff = new File(dirpath + File.separator + filename + ".out");
00202                                                 if (ff.exists())
00203                                                         ff.delete();
00204                                                 ff = new File(dirpath + File.separator + filename + ".in");
00205                                                 if (ff.exists())
00206                                                         ff.delete();
00207                                         }
00208                                 //      LogManager.traceDebug(0, "HTTPFileConduit END QUERY HTTP");
00209                         } catch (Throwable e) {
00210                                 // if an error occurs try to restart the connexion one time.
00211                                 LogManager.traceError(0, e);
00212                         } finally {
00213                                 try {
00214                                         if (serverSocket != null)
00215                                                 serverSocket.close();
00216                                 } catch (Exception e) {
00217                                         LogManager.traceError(LogServices.WEBSERVICE, e);
00218                                 }
00219                         }
00220                 }
00221         }
00222 
00227         public HTTPFileConduit(int port, String file) {
00228 //              LogManager.traceDebug(0, "HTTPFileConduit verson 1");
00229                 this.port = port;
00230                 int index = file.lastIndexOf(File.separator);
00231                 if (index != -1) {
00232                         dirpath = file.substring(0, index);
00233                 }
00234                 filename = file.substring(index + 1, file.length());
00235                 this.waitFileTimeout = 300000;
00236                 String time = PropertiesManager.getManager().getProperty("org.openmobileis.common.HTTPFileConduit.timeout");
00237                 if (time != null)       {
00238                         try     {
00239                                 this.waitFileTimeout = Integer.parseInt(time);
00240                         } catch (Throwable ex){
00241                                 LogManager.traceError(0, "HTTPFileConduit, org.openmobileis.common.HTTPFileConduit.timeout propery is not an integer :"+time+" . Set 600 second timeout.");
00242                         }
00243                 }
00244                 
00245         }
00246 
00247         public void startListening(String sendServerAddress) {
00248                 // start test
00249         //      LogManager.traceDebug(0, "HTTPFileConduit startListening");
00250                 this.server = sendServerAddress;
00251                 if (this.isDebugOn()) {
00252                         TestMakeQuery test = new TestMakeQuery();
00253                         Thread thtest = new Thread(test);
00254                         thtest.start();
00255                 }
00256 
00257                 LocalServer server = new LocalServer();
00258                 Thread th = new Thread(server);
00259                 th.start();
00260                 try {
00261                         Thread.currentThread().sleep(500); // wait to be sure the LocalServer
00262                         // socket is littening
00263                 } catch (Throwable ex) {
00264                         LogManager.traceError(0, "HTTPFileConduit Error :" + ex.toString());
00265                 }
00266         }
00267 
00268         public boolean isDebugOn() {
00269                 return debugOn;
00270         }
00271 
00272         public void setDebugOn(boolean debugOn) {
00273                 this.debugOn = debugOn;
00274         }
00275 
00276 }

Generated on Mon Jan 11 21:19:15 2010 for OpenMobileIS by  doxygen 1.5.4