Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements a socket server for data files
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: berkley $'
10
 *     '$Date: 2001-01-10 13:05:31 -0800 (Wed, 10 Jan 2001) $'
11
 * '$Revision: 653 $'
12
 */
13

    
14
package edu.ucsb.nceas.metacat;
15

    
16
import java.net.*;
17
import java.io.*;
18
import java.util.Properties;
19
import java.util.Date;
20
import java.text.SimpleDateFormat;
21
import java.sql.*;
22

    
23
public class DataFileServer extends Thread 
24
{
25
  MetaCatUtil util = new MetaCatUtil();
26
  static String filedir = "";
27
  String user = null;
28
  String sess_id = null;
29
  int port;
30
  static String httpstring = "http://dev.nceas.ucsb.edu:8090/metacat/upload/";
31
  protected Socket s;
32
  
33
  DataFileServer (int port, String user, String sess_id) 
34
  {
35
    this.sess_id = sess_id;
36
    this.user = user;
37
    this.port = port;
38
    filedir = util.getOption("datafilepath");
39
  }
40
  
41
  /**
42
   * attempts to connect a socket, returns null if it is not successful
43
   * returns the connected socket if it is successful.
44
   */
45
  public static Socket getSocket(String host, int port)
46
  {
47
    Socket s = null;
48
    try
49
    {
50
      s = new Socket(host, port);
51
      //we could create a socket on this port so the port is not available
52
      //System.out.println("socket connnected");
53
      return s;
54
    }
55
    catch(UnknownHostException u)
56
    {
57
    }
58
    catch(IOException i)
59
    {
60
      //an ioexception is thrown if the port is not in use
61
      //System.out.println("socket not connected");
62
      return s;
63
    }
64
    return s;
65
  }
66
  
67
  /**
68
   * returns true if the port specified is not in use.  false otherwise
69
   */
70
  public static boolean portIsAvailable(int port)
71
  {
72
    Socket s;
73
    String host = "localhost";
74
    try
75
    {
76
      s = new Socket(host, port);
77
      //s.close();
78
      //we could create a socket on this port so the port is not available
79
      //System.out.println("socket not available");
80
      return false;
81
    }
82
    catch(UnknownHostException u)
83
    {
84
      //it better know localhost!
85
    }
86
    catch(IOException i)
87
    {
88
      //an ioexception is thrown if the port is not in use
89
      //System.out.println("socket available");
90
      return true;
91
    }
92
    return true;
93
  }
94
  
95
  /**
96
   * Updates xml_documents with the new data document information
97
   * @param accnum the accession number of the new data file
98
   * @param filename the filename of the new data file
99
   * @param userOwner the document's owner's username
100
   */
101
  private void updateDB(String accnum, String filename, String userOwner)
102
  {
103
    SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
104
    java.util.Date localtime = new java.util.Date();
105
    String dateString = formatter.format(localtime);
106
    
107
    String sqlDateString = "to_date('" + dateString + "', 'YY-MM-DD HH24:MI:SS')";
108
    
109
    StringBuffer sql = new StringBuffer();
110
    sql.append("insert into xml_documents (docid, docname, doctype, ");
111
    sql.append("user_owner, user_updated, server_location, rev, date_created");
112
    sql.append(", date_updated, public_access) values ('");
113
    sql.append(accnum).append("','").append(filename).append("','BIN','");
114
    sql.append(userOwner).append("','").append(userOwner).append("','1','");
115
    sql.append("1',").append(sqlDateString).append(",");
116
    sql.append(sqlDateString).append(",'0')");
117
    //System.out.println("sql: " + sql.toString());
118
    try
119
    {
120
      Connection conn = util.openDBConnection();
121
      PreparedStatement pstmt = conn.prepareStatement(sql.toString());
122
      pstmt.execute();
123
      conn.close();
124
    }
125
    catch(Exception e)
126
    {
127
      System.out.println("error with db connection in DataFileServer.updateDB" +
128
                         ": " + e.getMessage());
129
    }
130
    
131
  }
132
  
133
  /**
134
   * This method is invoked when this class is broken off into a new thread
135
   */
136
  public void run () 
137
  {
138
    ServerSocket server = null;
139
    Socket client = null;
140
    OutputStreamWriter osw = null;
141
    try
142
    {
143
      //System.out.println("Starting on port " + port);
144
      //System.out.println("Waiting for sess_id: " + sess_id);
145
      server = new ServerSocket((new Integer(port)).intValue());
146
      //System.out.println("Waiting");
147
      server.setSoTimeout(30000); //set a 30 second timeout
148
      client = server.accept();
149
      //System.out.println("Accepted from " + client.getInetAddress());
150
    
151
      InputStream in = client.getInputStream();      //in from the client
152
      OutputStream sout = client.getOutputStream();  //out to the client
153
      osw = new OutputStreamWriter(sout);
154
      //System.out.println("output stream received");
155
      // first read to get the file name
156
      byte[] str = new byte[1024];
157
      int val = -1;
158
      int i = 0;
159
      //get the filename
160
      while (val != 0) 
161
      {
162
        //System.out.println("i: " + i);
163
        val = in.read();
164
        str[i] = (byte)val;
165
        i++;
166
      }
167
      String filename = (new String(str,0, i-1)).trim();
168
      //System.out.println("filename: " + filename);
169
      
170
      val = -1;
171
      i = 0;
172
      str = new byte[1024];
173
      //get the session id
174
      while (val != 0) 
175
      {
176
        val = in.read();
177
        str[i] = (byte)val;
178
        i++;
179
      }
180
      String session_id = (new String(str,0, i-1)).trim();
181
      
182
      //get the length of the file in bytes
183
      int val2 = -1;
184
      long fsize = 0;
185
      while(val2 != 0)
186
      {
187
        val2 = in.read();
188
        if(val2 != 0)
189
        {
190
          fsize = val2;
191
        }
192
      }
193
      //System.out.println("file size: " + fsize);
194
      
195
      if(!sess_id.equals(session_id))
196
      {//this is an unauthorized connection to this port
197
        System.out.println("unauthorized request");
198
        return;
199
      }
200
      else
201
      {
202
        //System.out.println("User authenticated on port " + port);
203
      }
204
      
205
      String restext=null;
206
      File outfile = new File(filedir + filename);
207
      //System.out.println("outfile: " + filedir + filename);
208
      boolean nameInUse = outfile.exists();
209
      int filenametemp = 1;
210
      String fn = filename;
211
      while(nameInUse)
212
      {
213
        filename = fn + filenametemp;
214
        outfile = new File (filedir + filename);
215
        nameInUse = outfile.exists();
216
        filenametemp++;
217
      }
218
       
219
      try
220
      {
221
        AccessionNumber anum = new AccessionNumber();
222
        String accnum = anum.generate(null, "INSERT");
223
        //osw.write(restext,0,restext.length());
224
        //osw.flush();
225
        
226
        FileOutputStream out = new FileOutputStream(outfile);
227
        byte[] buf = new byte[1024];
228
        int cnt = 0;
229
        int j = 0;
230
        while (j < fsize) 
231
        {
232
          //System.out.println("1 j:" + j);
233
          cnt = in.read(buf, 0, 1024);
234
          if (cnt!=-1) 
235
          {
236
            out.write(buf, 0, cnt);
237
          }
238
          j += cnt;
239
        }
240

    
241
        out.flush();
242
        out.close();
243
        //put the new document info into the DB
244
        updateDB(accnum, filename, user);
245
        //System.out.println("sending new docid: " + accnum);
246
        osw.write("<?xml version=\"1.0\"?><docid>" + accnum + "</docid>");
247
        osw.flush();
248
        osw.close();
249
        //System.out.println("docid sent");
250
      }
251
      catch(Exception e)
252
      {
253
        System.out.println("error in DataFileServer.run(): " + e.getMessage());
254
        try
255
        {
256
          osw.write("<?xml version=\"1.0\"?><error>" + e.getMessage() + 
257
                    "</error>");
258
          osw.flush();
259
          osw.close();
260
        }
261
        catch(Exception ee)
262
        {
263
          System.out.println("error: " + ee.getMessage());
264
        }
265
        e.printStackTrace(System.out);
266
      }
267
    } 
268
    catch(InterruptedIOException iioe)
269
    {
270
      //the accept timeout passed
271
      //System.out.println("socket on port " + port + " timed out.");
272
    }
273
    catch (IOException ex) 
274
    {
275
      ex.printStackTrace();
276
      try
277
      {
278
        osw.write("<?xml version=\"1.0\"?><error>" + ex.getMessage() + 
279
                  "</error>");
280
        osw.flush();
281
        osw.close();
282
      }
283
      catch(Exception ee)
284
      {
285
        System.out.println("error: " + ee.getMessage());
286
      }
287
    } 
288
    finally 
289
    {
290
      try
291
      {
292
        server.close();
293
        //System.out.println("server socket closed");
294
        client.close();
295
        //System.out.println("client socket closed");
296
      } 
297
      catch (IOException ex) 
298
      {
299
        ex.printStackTrace();
300
      }
301
      //System.out.println("done");
302
    }
303
  }
304
  
305
}
(21-21/42)