Project

General

Profile

« Previous | Next » 

Revision 647

Added by berkley over 23 years ago

added support for data file upload via a random, authenticated socket.

View differences:

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

  
src/edu/ucsb/nceas/metacat/HttpMessage.java
1
/**
2
 *        Name: HttpMessage.java
3
 *     Purpose: Used for Java applet/application communication
4
 *              with servlet. Based on code given in the book
5
 *              "Java Servlet Programming" by Hunter & crawford
6
 *   Copyright: 2000 Regents of the University of California and the
7
 *              National Center for Ecological Analysis and Synthesis
8
 *     Authors: Dan Higgins modified for metacat by Chad Berkley
9
 *
10
 *     Version: '$Id$'
11
 *
12
 *     '$Author$'
13
 *     '$Date$'
14
 *     '$Revision$'
15
 */
16

  
17
package edu.ucsb.nceas.metacat;
18

  
19
import java.io.*;
20
import java.net.*;
21
import java.util.*;
22

  
23
public class HttpMessage {
24
    public String contype;
25
    URL servlet = null;
26
    String argString = null;
27
    static String cookie = null;
28
    public HttpMessage(URL servlet) {
29
        this.servlet = servlet;
30
    }
31
    
32
    /**
33
     * return the cookie that this message object contains
34
     */
35
    public String getCookie()
36
    {
37
      return cookie;
38
    }
39
    
40
    /**
41
     * Performs a GET request to the previously given servlet
42
     * with no query string
43
    */
44
    public InputStream sendGetMessage() throws IOException {
45
        return sendGetMessage(null);
46
    }
47
    
48
    /**
49
     * Performs a GET request to the previously given servlet
50
     *Builds a query string from the supplied Properties list.
51
     */
52
    public InputStream sendGetMessage(Properties args) throws IOException {
53
        argString = ""; //default
54
        
55
        if (args != null) {
56
            argString = "?" + toEncodedString(args);
57
        }
58
        URL url = new URL(servlet.toExternalForm() + argString);
59
        
60
        // turn off caching
61
        URLConnection con = url.openConnection();
62
        con.setUseCaches(false);
63
        contype = con.getContentType();
64
        
65
        return con.getInputStream();
66
    }
67
    
68
    /**
69
     * Performs a POST request to the previously given servlet
70
     * with no query string
71
     */
72
    public InputStream sendPostMessage() throws IOException {
73
        return sendPostMessage(null);
74
    }
75
    
76
    /**
77
     * Builds post data from the supplied properties list
78
     */
79
    public InputStream sendPostMessage(Properties args) throws IOException {
80
        argString = ""; //default
81
        if (args != null) {
82
            argString = toEncodedString(args); 
83
        }
84
        URLConnection con = servlet.openConnection();
85
        if (cookie!=null) {
86
            int k = cookie.indexOf(";");
87
            if (k>0) {
88
                cookie = cookie.substring(0, k);
89
            }
90
            //System.out.println("Cookie = " + cookie);
91
            con.setRequestProperty("Cookie", cookie); 
92
            con.setRequestProperty("User-Agent", "MORPHO");  // add 10/26/00 by DFH so Metacat can determine where request come from
93
        }
94
        //prepare for both input and output
95
        con.setDoInput(true);
96
        con.setDoOutput(true);
97
        //turn off caching
98
        con.setUseCaches(false);
99
        
100
        //work around a Netscape bug
101
        //con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
102
        //Write the arguments as post data
103
        DataOutputStream out = new DataOutputStream(con.getOutputStream());
104
        out.writeBytes(argString);
105
        out.flush();
106
        contype = con.getContentType();
107
        String temp = con.getHeaderField("Set-Cookie");
108
        if (temp!=null) {
109
            cookie = temp;
110
        }
111
        //System.out.println(cookie);
112
        out.close();
113
        
114
        return con.getInputStream();
115
    }
116

  
117
    /**
118
     * Returns the urls argument strings
119
     */
120
    public String getArgString() {
121
        String argString1 = argString;
122
        if (!argString1.startsWith("?")) {
123
            argString1 = "?"+argString1;}
124
        return argString1;
125
    }
126
    
127
    /**
128
     * Converts a Properties list to a URL-encoded query string
129
     */
130
    private String toEncodedString(Properties args) {
131
        StringBuffer buf = new StringBuffer();
132
        Enumeration names = args.propertyNames();
133
        while (names.hasMoreElements()) {
134
            String name = (String)names.nextElement();
135
            String value = args.getProperty(name);
136
            buf.append(URLEncoder.encode(name) + "=" + URLEncoder.encode(value));
137
            if (names.hasMoreElements()) buf.append("&");
138
        }
139
        return buf.toString();
140
    }
141
}
142

  
0 143

  
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

  
14
package edu.ucsb.nceas.metacat;
15

  
16
import java.io.*;
17
import java.lang.*;
18
import java.util.*;
19
import java.sql.*;
20
import java.net.*;
21
import edu.ucsb.nceas.metacat.*;
22
import javax.servlet.http.*;
23

  
24

  
25
public class DataStreamTest
26
{
27
  DataStreamTest()
28
  {
29
  
30
  }
31
  
32
  /**
33
   * sends a file to the data file server socket
34
   */
35
  public static String SendFile(String filename, String host, int port, 
36
                                String cookie) 
37
  {
38
    Socket echoSocket = null;
39
    OutputStream out = null;
40
    InputStream in = null;
41
    
42
		String res = "return";
43
    
44
    System.out.println("host: " + host + " port: " + port + " filename: " +
45
                       filename + " cookie: " + cookie);
46
    try 
47
    {
48
      //while(DataFileServer.portIsAvailable(port)) 
49
      //{//loop until the port is there
50
      //}
51
      echoSocket = new Socket(host, port);
52
      out = echoSocket.getOutputStream();
53
      in = echoSocket.getInputStream();
54
    } 
55
    catch (UnknownHostException e) 
56
    {
57
      System.err.println("Don't know about host: " + host);
58
      System.out.println("error: " + e.getMessage());
59
      e.printStackTrace(System.out);
60
      System.exit(1);
61
    } 
62
    catch (IOException e) 
63
    {
64
      System.err.println("Couldn't get I/O for "
65
                         + "the connection to: "+host);
66
      System.out.println("error: " + e.getMessage());
67
      e.printStackTrace(System.out);
68
      System.exit(1);
69
    }
70
	  
71
    try
72
    {  
73
      File file = new File(filename);
74
      DataOutputStream dsout = new DataOutputStream(out);
75
      FileInputStream fs = new FileInputStream(file);
76
      // first convert the filename to a byte array
77
      String fn = file.getName();
78
      byte[] fname = fn.getBytes();
79
      // now write the string bytes followed by a '0'
80
      for (int i=0;i<fname.length;i++) 
81
      {
82
        dsout.write(fname[i]);    
83
      }
84
      dsout.write(0);  // marks end of name info
85
      
86
      //write the session id to the stream
87
      byte[] cook = cookie.getBytes();
88
      for(int i=0; i<cook.length; i++)
89
      {
90
        dsout.write(cook[i]);
91
      }
92
      dsout.write(0);
93
      
94
      // now read response from server
95
      InputStreamReader isr = new InputStreamReader(in);
96
      BufferedReader rin = new BufferedReader(isr);
97

  
98
      // now send the file data
99
      byte[] buf = new byte[1024];
100
      int cnt = 0;
101
      int i = 0;
102
      while (cnt!=-1) 
103
      {
104
        cnt = fs.read(buf);
105
        System.out.println("i = "+ i +" Bytes read = " + cnt);
106
        if (cnt!=-1) 
107
        {
108
          dsout.write(buf, 0, cnt);
109
        }
110
        i++;
111
      }
112
      fs.close();
113
      dsout.flush();
114
      dsout.close();
115
	  }
116
	  catch (Exception w) 
117
    {
118
      System.out.println("error in DataStreamTest: " + w.getMessage());
119
    }
120

  
121
	  return res;
122
	}
123
  
124
  public static void main(String[] args)
125
  {
126
    System.out.println("Starting DataStreamTest");
127
    try
128
    {
129
      String temp = null;
130
      String servlet = ":8080/berkley/servlet/metacat";
131
      String protocol = "http://";
132
      String host = "alpha.nceas.ucsb.edu";
133
      String server = protocol + host + servlet;
134
      String filename = "/home/berkley/xmltodb/test.dat";
135
      //login url
136
      String u1str = server + "?action=login&username=higgins&password" +
137
                      "=neetar&qformat=xml";
138
      System.out.println("u1: " + u1str);
139
      URL u1 = new URL(u1str);
140
      HttpMessage msg = new HttpMessage(u1);
141
      msg.sendPostMessage();
142
      String cookie = msg.getCookie();
143
      //get the port to send the data to
144
      System.out.println("u2: " + server + "?action=getdataport");
145
      URL u2 = new URL(server + "?action=getdataport");
146
      HttpMessage msg2 = new HttpMessage(u2);
147
      InputStream in = msg2.sendPostMessage();
148
      InputStreamReader isr = new InputStreamReader(in);
149
      char c;
150
      int i = isr.read();
151
      String temp2 = null;
152
      while(i != -1)
153
      { //get the server response to the getdataport request
154
        c = (char)i;
155
        temp2 += c;
156
        i = isr.read();
157
      }
158
      int temp3 = temp2.indexOf("<", 32);
159
      temp2 = temp2.substring(32, temp3); //parse out the port
160
      //the port number taken from the xml encoding
161
      temp2 = temp2.trim();
162
      int port = (new Integer(temp2)).intValue();
163
      int index = cookie.indexOf("JSESSIONID=");
164
      index = cookie.indexOf("=", index);
165
      int index2 = cookie.indexOf(";", index);
166
      //get just the session id information from the cookie
167
      cookie = cookie.substring(index+1, index2);
168
      
169
      //this for loop is a hack to give the servlet enough time to start
170
      //the socket thread.  Sometimes it doesn't work
171
      //for(int j=0; j<100000000; j++) { int x = 1; }
172
      
173
      SendFile(filename, host, port, cookie);
174
    }
175
    catch(Exception e)
176
    {
177
      System.out.println("error in main: " + e.getMessage());
178
      e.printStackTrace(System.out);
179
    }
180
    
181
    
182
  }
183
}
0 184

  

Also available in: Unified diff