Project

General

Profile

« Previous | Next » 

Revision 799

Added by Matt Jones over 23 years ago

Completely removed the socket-server feature that used to provide
file upload. It is now replaced by multipart/form-data over http.

View differences:

src/edu/ucsb/nceas/metacat/DataFileUploadInterface.java
1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: An abstract class that is a template for a data transfer class
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Chad Berkley
7
 *    Release: @release@
8
 *
9
 *   '$Author$'
10
 *     '$Date$'
11
 * '$Revision$'
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
 */
27

  
28
package edu.ucsb.nceas.metacat;
29

  
30
import java.net.*;
31
import java.io.*;
32
import java.util.Properties;
33
import java.util.Date;
34
import java.text.SimpleDateFormat;
35
import java.sql.*;
36

  
37
abstract class DataFileUploadInterface extends Thread 
38
{
39
  private MetaCatUtil util = new MetaCatUtil();
40
  private static String filedir = "";
41
  private String user = null;
42
  private String sess_id = null;
43
  private int port;
44
  protected Socket s;
45
  
46
  /**
47
   * Sets the port, user and sess_id
48
   */
49
  DataFileUploadInterface(int port, String user, String sess_id) 
50
  {
51
    this.sess_id = sess_id;
52
    this.user = user;
53
    this.port = port;
54
    filedir = util.getOption("datafilepath");
55
  }
56
  
57
  /**
58
   * Override this method with the code to handle the socket connection to 
59
   * the port specified in the constructor.
60
   */
61
  abstract void getFile(int port, String user, String sess_id);
62
  
63
  /**
64
   * This method is invoked when this class is broken off into a new thread
65
   */
66
  public void run () 
67
  {
68
    getFile(port, user, sess_id);
69
  }
70
  
71
  /**
72
   * attempts to connect a socket, returns null if it is not successful
73
   * returns the connected socket if it is successful.
74
   */
75
  public static Socket getSocket(String host, int port)
76
  {
77
    Socket s = null;
78
    try
79
    {
80
      s = new Socket(host, port);
81
      //we could create a socket on this port so the port is not available
82
      //System.out.println("socket connnected");
83
      return s;
84
    }
85
    catch(UnknownHostException u)
86
    {
87
      System.out.println("unknown host in DataFileUploadInterface.getSocket");
88
    }
89
    catch(IOException i)
90
    {
91
      //an ioexception is thrown if the port is not in use
92
      //System.out.println("socket not connected");
93
      return s;
94
    }
95
    return s;
96
  }
97
  
98
  /**
99
   * returns true if the port specified is not in use.  false otherwise
100
   */
101
  public static boolean portIsAvailable(int port)
102
  {
103
    Socket s;
104
    String host = "localhost";
105
    try
106
    {
107
      s = new Socket(host, port);
108
      //s.close();
109
      //we could create a socket on this port so the port is not available
110
      //System.out.println("socket not available");
111
      return false;
112
    }
113
    catch(UnknownHostException u)
114
    {
115
      System.out.println("unknow host error in " + 
116
                         "DataFileUploadInterface.portIsAvailable");
117
    }
118
    catch(IOException i)
119
    {
120
      //an ioexception is thrown if the port is not in use
121
      //System.out.println("socket available");
122
      return true;
123
    }
124
    return true;
125
  }
126
  
127
  /**
128
   * Updates xml_documents with the new data document information
129
   * @param accnum the accession number of the new data file
130
   * @param filename the filename of the new data file
131
   * @param userOwner the document's owner's username
132
   */
133
  public void updateDB(String accnum, String filename, String userOwner)
134
  {
135
    SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
136
    java.util.Date localtime = new java.util.Date();
137
    String dateString = formatter.format(localtime);
138
    
139
    String sqlDateString = "to_date('" + dateString + "', 'YY-MM-DD HH24:MI:SS')";
140
    
141
    StringBuffer sql = new StringBuffer();
142
    sql.append("insert into xml_documents (docid, docname, doctype, ");
143
    sql.append("user_owner, user_updated, server_location, rev, date_created");
144
    sql.append(", date_updated, public_access) values ('");
145
    sql.append(accnum).append("','").append(filename).append("','BIN','");
146
    sql.append(userOwner).append("','").append(userOwner).append("','1','");
147
    sql.append("1',").append(sqlDateString).append(",");
148
    sql.append(sqlDateString).append(",'0')");
149
    //System.out.println("sql: " + sql.toString());
150
    try
151
    {
152
      Connection conn = util.openDBConnection();
153
      PreparedStatement pstmt = conn.prepareStatement(sql.toString());
154
      pstmt.execute();
155
      pstmt.close();
156
      conn.close();
157
    }
158
    catch(Exception e)
159
    {
160
      System.out.println("error with db connection in DataFileServer.updateDB" +
161
                         ": " + e.getMessage());
162
    }
163
    
164
  }
165
}
166 0

  
src/edu/ucsb/nceas/metacat/DataStreamTest.java
1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A test driver for the DataFileServer class
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Chad Berkley
7
 *    Release: @release@
8
 *
9
 *   '$Author$'
10
 *     '$Date$'
11
 * '$Revision$'
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
 */
27

  
28
package edu.ucsb.nceas.metacat;
29

  
30
import java.io.*;
31
import java.lang.*;
32
import java.util.*;
33
import java.sql.*;
34
import java.net.*;
35
import edu.ucsb.nceas.metacat.*;
36
import javax.servlet.http.*;
37

  
38

  
39
public class DataStreamTest
40
{
41
  DataStreamTest()
42
  {
43
  
44
  }
45
  
46
  /**
47
   * sends a file to the data file server socket
48
   */
49
  public static String SendFile(String filename, String host, int port, 
50
                                String cookie) 
51
  {
52
    Socket echoSocket = null;
53
    OutputStream out = null;
54
    InputStream in = null;
55
    DataOutputStream dsout = null;
56
    InputStreamReader isr = null;
57
    
58
		String retmsg = "";
59
    
60
    System.out.println("host: " + host + " port: " + port + " filename: " +
61
                       filename + " cookie: " + cookie);
62
    try 
63
    {
64
      echoSocket = DataFileServer.getSocket(host, port); //get the socket
65
      while(echoSocket == null) 
66
      {//loop until the port is there
67
        echoSocket = DataFileServer.getSocket(host, port);
68
      }
69
      //echoSocket = new Socket(host, port);
70
      out = echoSocket.getOutputStream(); //out to the server
71
      in = echoSocket.getInputStream();   //in from server
72
      isr = new InputStreamReader(in);
73
    } 
74
    catch (UnknownHostException e) 
75
    {
76
      System.err.println("Don't know about host: " + host + 
77
                         " : error in DataStreamTest.sendFile: " + 
78
                         e.getMessage());
79
      e.printStackTrace(System.out);
80
      System.exit(1);
81
    } 
82
    catch (IOException e) 
83
    {
84
      System.err.println("IO error in DataStreamTest.sendFile: "
85
                         + "broken connection to: " + host);
86
      System.out.println("error: " + e.getMessage());
87
      e.printStackTrace(System.out);
88
      System.exit(1);
89
    }
90
	  
91
    try
92
    {  
93
      File file = new File(filename); //get the file from the local system
94
      dsout = new DataOutputStream(out); 
95
      FileInputStream fs = new FileInputStream(file);
96
      // first convert the filename to a byte array
97
      String fn = file.getName();
98
      byte[] fname = fn.getBytes();
99
      // now write the string bytes followed by a '0'
100
      for (int i=0;i<fname.length;i++) 
101
      {
102
        dsout.write(fname[i]);    
103
      }
104
      dsout.write(0);  // marks end of name info
105
      
106
      //write the session id to the stream
107
      byte[] cook = cookie.getBytes();
108
      for(int i=0; i<cook.length; i++)
109
      {
110
        dsout.write(cook[i]);
111
      }
112
      dsout.write(0); //follow it with a 0
113
      
114
      //write the length of the file followed by a 0
115
      long flength = file.length();
116
      System.out.println("file sized (B): " + flength);
117
      String sflength = String.valueOf(flength); //note that this is changed
118
                                                 //to a string
119
      
120
      byte[] fl = sflength.getBytes();
121
      for(int i=0; i<fl.length; i++)
122
      {
123
        dsout.write(fl[i]);
124
      }
125
      dsout.write(0); //following 0
126
      
127
      //dsout.write((int)flength);
128
      //dsout.write(0);
129
      dsout.flush();
130
      
131
      BufferedReader rin = new BufferedReader(isr);
132

  
133
      // now send the file data
134
      byte[] buf = new byte[1024];
135
      int cnt = 0;
136
      int i = 0;
137
      while (cnt!=-1) 
138
      {
139
        cnt = fs.read(buf); //read the file
140
        System.out.println("i = "+ i +" Bytes read = " + cnt);
141
        if (cnt!=-1) 
142
        {
143
          dsout.write(buf, 0, cnt); //write the byte to the server
144
        }
145
        i++;
146
      }
147
      fs.close();
148
      dsout.flush();
149
	  }
150
	  catch (Exception w) 
151
    {
152
      System.out.println("error in DataStreamTest.sendFile: " + w.getMessage());
153
    }
154
   
155
    try
156
    { //get the server's response
157
      while(!isr.ready()) 
158
      {
159
        //System.out.println("not ready");
160
      }
161
      int msg = isr.read();
162
      retmsg += (char)msg;
163
      System.out.print("Message from server: ");
164
      while(msg != -1)
165
      {
166
        System.out.print((char)msg);
167
        System.out.flush();
168
        msg = isr.read(); //get the message a character at a time
169
        retmsg += (char)msg;
170
      }
171
      System.out.println();
172
      dsout.flush();
173
      dsout.close();
174
    }
175
    catch(Exception e)
176
    {
177
      System.out.println("error in DataStreamTest.sendFile: " + e.getMessage());
178
    }
179
	  return retmsg;
180
	}
181
  
182
  public static void main(String[] args)
183
  {
184
    System.out.println("Starting DataStreamTest");
185
    try
186
    {
187
      String temp = null;
188
      String servlet = "/berkley/servlet/metacat";
189
      String protocol = "http://";
190
      String host = "dev.nceas.ucsb.edu";
191
      String server = protocol + host + servlet;
192
      String filename = null;
193
      if(args.length == 0)
194
      {
195
        filename = "/home/berkley/xmltodb/test.dat";
196
      }
197
      else
198
      {
199
        filename = args[0];
200
      }
201
      //login url
202
      String u1str = server + "?action=login&username=higgins&password" +
203
                      "=neetar&qformat=xml";
204
      System.out.println("url 1: " + u1str);
205
      URL u1 = new URL(u1str);
206
      HttpMessage msg = new HttpMessage(u1);
207
      msg.sendPostMessage();
208
      String cookie = msg.getCookie();
209
      //get the port to send the data to
210
      System.out.println("url 2: " + server + "?action=getdataport");
211
      URL u2 = new URL(server + "?action=getdataport");
212
      HttpMessage msg2 = new HttpMessage(u2);
213
      InputStream in = msg2.sendPostMessage();
214
      InputStreamReader isr = new InputStreamReader(in);
215
      char c;
216
      int i = isr.read();
217
      String temp2 = null;
218
      while(i != -1)
219
      { //get the server response to the getdataport request
220
        c = (char)i;
221
        temp2 += c;
222
        i = isr.read();
223
      }
224
      int temp3 = temp2.indexOf("<", 32);
225
      temp2 = temp2.substring(32, temp3); //parse out the port
226
      //the port number taken from the xml encoding
227
      temp2 = temp2.trim();
228
      int port = (new Integer(temp2)).intValue();
229
      //while(portIsAvailable(port)) {int x = 1;}
230
      int index = cookie.indexOf("JSESSIONID=");
231
      index = cookie.indexOf("=", index);
232
      int index2 = cookie.indexOf(";", index);
233
      //get just the session id information from the cookie
234
      cookie = cookie.substring(index+1, index2);
235
      
236
      String servermsg = SendFile(filename, host, port, cookie);
237
      System.out.println("server says (end): " + servermsg);
238
    }
239
    catch(Exception e)
240
    {
241
      System.out.println("error in main: " + e.getMessage());
242
      e.printStackTrace(System.out);
243
    }
244
  }
245
}
246 0

  
src/edu/ucsb/nceas/metacat/DataFileServer.java
1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements a socket server for data files that 
4
 *             writes the file to the servlet's local file system
5
 *  Copyright: 2000 Regents of the University of California and the
6
 *             National Center for Ecological Analysis and Synthesis
7
 *    Authors: Chad Berkley
8
 *    Release: @release@
9
 *
10
 *   '$Author$'
11
 *     '$Date$'
12
 * '$Revision$'
13
 *
14
 * This program is free software; you can redistribute it and/or modify
15
 * it under the terms of the GNU General Public License as published by
16
 * the Free Software Foundation; either version 2 of the License, or
17
 * (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU General Public License
25
 * along with this program; if not, write to the Free Software
26
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27
 */
28

  
29
package edu.ucsb.nceas.metacat;
30

  
31
import java.net.*;
32
import java.io.*;
33
import java.util.Properties;
34
import java.util.Date;
35
import java.text.SimpleDateFormat;
36
import java.sql.*;
37

  
38
public class DataFileServer extends DataFileUploadInterface
39
{
40
  MetaCatUtil util = new MetaCatUtil();
41
  static String filedir = "";
42

  
43
  protected Socket s;
44
  
45
  public DataFileServer(int port, String user, String sess_id)
46
  {
47
    super(port, user, sess_id);
48
    System.out.println("port: " + port + " user: " + user + " sess: " +
49
                       sess_id);
50
  }
51
  
52
  public void getFile(int port, String user, String sess_id)
53
  {
54
    filedir = util.getOption("datafilepath"); 
55
    ServerSocket server = null;
56
    Socket client = null;
57
    OutputStreamWriter osw = null;
58
    try
59
    {
60
      System.out.println("Starting on port " + port);
61
      System.out.println("Waiting for sess_id: " + sess_id);
62
      server = new ServerSocket((new Integer(port)).intValue());
63
      server.setSoTimeout(30000); //set a 30 second timeout
64
      client = server.accept();
65
      System.out.println("Accepted from " + client.getInetAddress());
66
    
67
      InputStream in = client.getInputStream();      //in from the client
68
      OutputStream sout = client.getOutputStream();  //out to the client
69
      osw = new OutputStreamWriter(sout);
70
      System.out.println("output stream received");
71
      // first read to get the file name
72
      byte[] str = new byte[1024];
73
      int val = -1;
74
      int i = 0;
75
      //get the filename
76
      while (val != 0) 
77
      {
78
        //System.out.println("i: " + i);
79
        val = in.read();
80
        str[i] = (byte)val;
81
        i++;
82
      }
83
      String filename = (new String(str,0, i-1)).trim();
84
      System.out.println("filename: " + filename);
85
      
86
      val = -1;
87
      i = 0;
88
      str = new byte[1024];
89
      //get the session id
90
      while (val != 0) 
91
      {
92
        val = in.read();
93
        str[i] = (byte)val;
94
        i++;
95
      }
96
      String session_id = (new String(str,0, i-1)).trim();
97
      
98
      //get the length of the file in bytes
99
      val = -1;
100
      i = 0;
101
      str = new byte[1024];
102
      while(val != 0)
103
      {
104
        val = in.read();
105
        str[i] = (byte)val;
106
        i++;
107
      }
108
      String stemp = (new String(str, 0, i-1)).trim();
109
      Long fsizetemp = new Long(stemp);
110
      long fsize = fsizetemp.longValue();
111
      //System.out.println("file size: " + fsize);
112
      
113
      if(!sess_id.equals(session_id))
114
      {//this is an unauthorized connection to this port
115
        System.out.println("unauthorized request");
116
        osw.write("<?xml version=\"1.0\"?><error>unauthorized request</error>");
117
        osw.flush();
118
        osw.close();
119
        return;
120
      }
121
      else
122
      {
123
        System.out.println("User authenticated on port " + port);
124
      }
125
      
126
      String restext=null;
127
      File outfile = new File(filedir + filename);
128
      System.out.println("outfile: " + filedir + filename);
129
      boolean nameInUse = outfile.exists();
130
      int filenametemp = 1;
131
      String fn = filename;
132
      while(nameInUse)
133
      {
134
        filename = fn + filenametemp;
135
        outfile = new File (filedir + filename);
136
        nameInUse = outfile.exists();
137
        filenametemp++;
138
      }
139
       
140
      try
141
      {
142
        AccessionNumber anum = new AccessionNumber();
143
        String accnum = anum.generate(null, "INSERT");
144
        
145
        FileOutputStream out = new FileOutputStream(outfile);
146
        byte[] buf = new byte[1024];
147
        int cnt = 0;
148
        int j = 0;
149
        while (j < fsize) 
150
        {
151
          cnt = in.read(buf, 0, 1024);
152
          if (cnt!=-1) 
153
          {
154
            out.write(buf, 0, cnt);
155
          }
156
          j += cnt;
157
        }
158

  
159
        out.flush();
160
        out.close();
161
        //put the new document info into the DB
162
        updateDB(accnum, filename, user);
163
        //System.out.println("sending new docid: " + accnum);
164
        osw.write("<?xml version=\"1.0\"?><docid>" + accnum + "</docid>");
165
        osw.flush();
166
        osw.close();
167
        //System.out.println("docid sent");
168
      }
169
      catch(Exception e)
170
      {
171
        System.out.println("error in DataFileServer.run(): " + e.getMessage());
172
        try
173
        {
174
          osw.write("<?xml version=\"1.0\"?><error>" + e.getMessage() + 
175
                    "</error>");
176
          osw.flush();
177
          osw.close();
178
        }
179
        catch(Exception ee)
180
        {
181
          System.out.println("error DataFileServer.run(): " + ee.getMessage());
182
        }
183
        e.printStackTrace(System.out);
184
      }
185
    } 
186
    catch(InterruptedIOException iioe)
187
    {
188
      //the accept timeout passed
189
      System.out.println("socket on port " + port + " timed out. " +
190
                         " (DataFileServer.run)");
191
    }
192
    catch (IOException ex) 
193
    {
194
      ex.printStackTrace();
195
      try
196
      {
197
        osw.write("<?xml version=\"1.0\"?><error>" + ex.getMessage() + 
198
                  "</error>");
199
        osw.flush();
200
        osw.close();
201
      }
202
      catch(Exception ee)
203
      {
204
        System.out.println("error in DataFileServer.run(): " + ee.getMessage());
205
      }
206
    } 
207
    finally 
208
    {
209
      try
210
      {
211
        server.close();
212
        //System.out.println("server socket closed");
213
        client.close();
214
        //System.out.println("client socket closed");
215
      } 
216
      catch (IOException ex) 
217
      {
218
        ex.printStackTrace();
219
      }
220
    }
221
  }
222
}
223 0

  
src/edu/ucsb/nceas/metacat/MetaCatServlet.java
316 316
      } else if (action.equals("validate")) {
317 317
        PrintWriter out = response.getWriter();
318 318
        handleValidateAction(out, params, response); 
319
      } else if (action.equals("getdataport")) {
320
        PrintWriter out = response.getWriter();
321
        if ( (username != null) &&  !username.equals("public") ) {
322
        handleGetDataPortAction(out, params, response, username, groupname, 
323
                                sess_id);
324
        } else {
325
          out.println("You must be authenticated to perform the getdataport " +
326
                      "action!");
327
        }
328 319
      } else if (action.equals("getaccesscontrol")) {
329 320
        PrintWriter out = response.getWriter();
330 321
        handleGetAccessControlAction(out, params, response, username, groupname);
......
1288 1279
  // END OF VALIDATE SECTION
1289 1280
 
1290 1281
  // OTHER ACTION HANDLERS
1291
  /**
1292
   * sends the port number that the data socket is running on.
1293
   * This is a parameter set in the metacat.properties file.
1294
   */
1295
  private void handleGetDataPortAction(PrintWriter out, Hashtable params, 
1296
                                       HttpServletResponse response, 
1297
                                       String username, String groupname,
1298
                                       String sess_id)
1299
  {
1300
    int port;
1301
    String filedir = null;
1302
    try
1303
    {
1304
      filedir = util.getOption("datafilepath");
1305
      
1306
      Random r = new Random();
1307
      port = r.nextInt(65000);  //pick a random port between 0-65000
1308
      //System.out.println("random port is: " + port);
1309
      while(!DataFileServer.portIsAvailable(port))
1310
      {
1311
        port = r.nextInt(65000);
1312
        //System.out.println("next port used: " + port);
1313
      }
1314
      DataFileServer dfs = new DataFileServer(port, username, sess_id);
1315
      dfs.start();
1316
      
1317
      //System.out.println("filedir: " + filedir);
1318
      //System.out.println("port: " + port);
1319
      response.setContentType("text/xml");
1320
      out.println("<?xml version=\"1.0\"?>");
1321
      out.println("<port>");
1322
      out.print(port);
1323
      out.print("</port>");
1324
      
1325
    }
1326
	  catch (Exception e) 
1327
    {
1328
      System.out.println("error in MetacatServlet.handleGetDataPortAction: " + 
1329
                          e.getMessage());
1330
    }
1331
  }
1332 1282
  
1333 1283
  /** 
1334 1284
   * Handle "getaccesscontrol" action.

Also available in: Unified diff