Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: org/media/datastore/sepengine/driver/beepDriver/BeepConnection.java


1   /*
2    * $COPYRIGHT$y
3    * $Id: BeepConnection.java,v 1.19 2002/10/14 16:41:00 atech Exp $
4    *
5    *  Date           Author            Changes
6    *  Jun 29 2001    Szabo Csaba       Created
7    *  Oct 01 2001    Antal Attila      implemented beep things
8    */
9          
10  package org.media.datastore.sepengine.driver.beepDriver;
11  
12  import java.util.Properties;
13  import java.io.IOException;
14  import java.io.InputStream;
15  import java.io.ByteArrayInputStream;
16  import java.io.BufferedReader;
17  import java.io.InputStreamReader;
18  import java.security.Security;
19  
20  import org.beepcore.beep.util.*;
21  import org.beepcore.beep.core.*;
22  import org.beepcore.beep.lib.Reply;
23  import org.beepcore.beep.transport.tcp.*;
24  import org.beepcore.beep.profile.ProfileConfiguration;
25  import org.beepcore.beep.profile.tls.TLSProfile;
26  import org.beepcore.beep.profile.sasl.otp.SASLOTPProfile;
27  import org.beepcore.beep.profile.sasl.otp.algorithm.md5.*;
28  import org.beepcore.beep.profile.sasl.otp.algorithm.sha1.*;
29  import org.beepcore.beep.profile.sasl.otp.database.UserDatabasePool;
30  
31  import org.media.datastore.sepengine.driver.SepStoreDriver;
32  import org.media.datastore.sepengine.SepInterpreter;
33  import org.media.datastore.beepserver.SEPprofile; 
34  import org.media.datastore.sepengine.util.StringInputStream;
35  import org.media.datastore.sepengine.util.ProgressBar;
36  
37  /**
38   * @author <a href="mailto:crow@nolimits.ro">Szabo Csaba </a>
39   * @version $Revision: 1.19 $ $Date: 2001/08/21 15:00:00
40   * @see java.lang.String
41   * @see java.io.InputStream
42   * @see org.media.datastore.sepengine.driver.SepStoreConnection
43   * @see org.beepcore.beep.core.Message
44   */
45       
46  public class BeepConnection 
47      implements org.media.datastore.sepengine.driver.SepStoreConnection {
48  
49      private Session _session = null;
50      private String         SEP_HOST;
51      private int            SEP_PORT;
52      private String         SEP_DATABASE;
53      private String         SEP_USER;
54      private String         SEP_PASSWD;
55      private boolean        SEP_STATUS;
56      private String         SEP_SECURE = "";
57      public  boolean        CONNECTION_BAD;
58      public  boolean        CONNECTION_OK;
59      public  SepStoreDriver this_driver;
60      private String         this_url;
61      private boolean         replayed = false;
62      private InputStream     response = null;
63      private StringInputStream    sis = new StringInputStream();
64      
65      private final int    BUFFER_SIZE = SEPprofile.BUFFER_SIZE;
66      private final String  hashMethod = "otp-md5";
67      private final String        seed = "xyz";
68      private final int            seq = 1;
69              
70      public BeepConnection () {
71          CONNECTION_OK  = true;
72          CONNECTION_BAD = false;
73      }
74  
75  
76      public InputStream executeSEP( InputStream sepStream ) throws Exception {
77          Reply     reply = new Reply();        
78          Channel channel = initChannel( _session );
79          StringBuffer sb = new StringBuffer();
80  
81          OutputDataStream data = new OutputDataStream(
82                    new MimeHeaders(MimeHeaders.BEEP_XML_CONTENT_TYPE));
83          BufferSegment buff;
84          byte[] tbuff;
85          if ( sepStream != null ) {
86              while ( true ) {
87      tbuff = new byte[BUFFER_SIZE];
88                  int b = sepStream.read(tbuff);
89                  if (b<0) break;
90                  buff = new BufferSegment(tbuff);
91                  data.add(buff);
92              }
93              data.setComplete();
94              channel.sendMSG(data, reply);
95          }
96  
97          while( reply.hasNext() ) 
98              sb.append(streamToString(reply.getNextReply().getDataStream().getInputStream()));
99          channel.close();
100         
101         return new ByteArrayInputStream( sb.toString().getBytes());
102     }
103 
104 
105     public InputStream executeSEP( String sepString ) throws Exception {
106         Reply     reply = new Reply();
107         Channel channel = initChannel( _session );
108         StringBuffer sb = new StringBuffer();
109 
110         channel.sendMSG( new StringOutputDataStream(sepString), reply);
111         Message msg;
112         while( reply.hasNext() ) {
113             sb.append(streamToString(reply.getNextReply().getDataStream().getInputStream()));
114         }
115         channel.close();
116         return new ByteArrayInputStream( sb.toString().getBytes());
117     }
118     
119     
120     public String getURL() throws Exception {
121         return this_url;
122     }
123 
124     
125     public String getUserName() throws Exception {
126         return SEP_USER;
127     }
128 
129     protected void openConnection (String host, int port, Properties prop, 
130                                    String dbName, String url, SepStoreDriver driver )
131         throws Exception {
132 
133         if ( prop.getProperty("user") == null )
134             throw new Exception("The user property is missing. It is mandatory.");
135         if ( prop.getProperty("password") == null )
136             throw new Exception("The password property is missing. It is mandatory.");
137         if ( prop.getProperty("security") != null )
138             SEP_SECURE = new String( prop.getProperty("security") );
139             
140         this_driver  = driver;
141         this_url     = new String( url );
142         SEP_DATABASE = new String( dbName );
143         SEP_PASSWD   = new String( prop.getProperty("password") );
144         SEP_USER     = new String( prop.getProperty("user") );
145         SEP_PORT     = port;
146         SEP_HOST     = new String(host);
147         SEP_STATUS   = CONNECTION_BAD;
148 
149         _session = initSession(SEP_HOST, SEP_PORT);
150         Channel channel = initChannel( _session );
151 
152         try {
153             Reply reply= new Reply();
154             Message result  = null;
155             channel.sendMSG( new StringOutputDataStream("SEP:" + SEP_DATABASE), reply ); 
156             result = reply.getNextReply();
157             channel.close();
158             if ( result != null && result.getMessageType() == Message.MESSAGE_TYPE_ERR )
159                 throw new RuntimeException( streamToString(
160                   result.getDataStream().getInputStream()));
161         }
162         catch ( Exception e ) {
163             throw new Exception("Connection failed to " + SEP_DATABASE);
164         }
165     }
166 
167 
168     public void close() throws BEEPException {
169         //channel.close();
170         _session.close();
171     }
172 
173 
174     private String streamToString( InputDataStreamAdapter is ) throws Exception {
175         char[]   buffer = new char [ BUFFER_SIZE ];
176         StringBuffer sb = new StringBuffer();
177         try {
178             BufferedReader in = new BufferedReader( new InputStreamReader( is ) );
179             while ( true ) {
180                 int size = in.read(buffer);
181                 if (size <= 0) break;
182                 sb.append(new String(buffer, 0, size)); 
183             } 
184         }
185         catch ( Exception _ex ) {
186             throw new Exception ("Server response stream is failed!");
187         }
188         return sb.toString();
189     }
190 
191     
192     private String preDigest( String pwd ) throws Exception {
193         return SASLOTPProfile.convertBytesToHex(
194             ( new MD5() ).generateHash( pwd.getBytes() )
195             );
196     }
197 
198                  
199     private String getPasswdHash( String pwd ) throws Exception {
200         byte[] pw = ( seed + pwd ).getBytes();
201                                      
202         try {
203             for ( int cx = 0; cx <= seq; cx++ ) {
204                 if ( hashMethod.equals( "otp-md5" ) )
205                     pw = ( new MD5() ).generateHash( pw );
206                 else
207                     if ( hashMethod.equals( "otp-sha1" ) )
208                         pw = ( new SHA1() ).generateHash( pw );
209                     else
210                         throw new Exception( "\nInvalid algorithm method:" +
211                                              hashMethod + "\n");
212             }
213         }
214         catch ( Exception e ) {
215             throw e;
216         }
217         return SASLOTPProfile.convertBytesToHex( pw );
218     }
219 
220     
221     private Session authenticate ( Session sess, String user, String  pwd )
222         throws Exception {
223         try {
224             String newHash = getPasswdHash( pwd = preDigest( pwd ) );
225             (new UserDatabasePool()).addUser( user, hashMethod, newHash, seed, seq + "" );
226             SASLOTPProfile otp = new SASLOTPProfile();
227             otp.init(SASLOTPProfile.URI, new ProfileConfiguration()) ;
228             sess = otp.AuthenticateSASLOTPWithInit( sess,
229                                                     SEP_DATABASE + "_",
230                                                     user, pwd,
231                                                     hashMethod,
232                                                     newHash, seed, seq + "" );
233         }
234         catch ( Exception e ) {
235             sess = null;
236             throw e;
237         }
238         
239         return sess;
240     }
241 
242 
243     private Session tls( Session tlsSes, String privacy) throws Exception {
244 
245         if ( privacy.trim().length() > 0 ) {
246             //    Security.addProvider( new com.sun.net.ssl.internal.ssl.Provider() );  
247             if ( "jsse".equals( privacy.toLowerCase() ) ) {
248                 try {
249                    tlsSes = TLSProfile.getInstance("org.beepcore.beep." +
250                        "profile.tls.jsse.TLSProfileJSSE").startTLS( (TCPSession) tlsSes );
251                 } 
252                 catch ( Exception e ) {
253                     //                    e.printStackTrace();
254                     if ( e.getMessage() == null  ) {
255                         throw new Exception( "JSSE TLS Provider is not specified!" );
256                     }
257                     else {
258                         throw new Exception("JSSE TLS connection not supported by server!");
259                     }
260                 }
261             }
262             else { 
263                 if ( "ptls".equals(privacy.toLowerCase()) ) {
264                     try {
265                         tlsSes = 
266                             TLSProfile.getDefaultInstance().startTLS( (TCPSession)tlsSes );
267                     } 
268                     catch ( Exception e1 ) {
269                         throw new Exception( "Pure TLS connection not supported by server!" );
270                     }
271                 }
272                 else {
273                     throw new Exception( "Invalid security parameter!" );
274                 }
275             }
276         }
277         
278         return tlsSes;
279     }
280    
281 
282     private void beepLogger() {
283         ConsoleLog log = new ConsoleLog();
284         log.setSeverity( Log.SEV_DEBUG_VERBOSE );
285         Log.setLogService( log );
286     }
287 
288    
289     private Session initSession( String host, int port ) throws Exception {
290         Session ses = null;
291         //beepLogger();
292         try {
293             ses = TCPSessionCreator.initiate(host, port);
294             ses = tls( ses, SEP_SECURE );
295             ses = authenticate( ses, SEP_USER, SEP_PASSWD );
296         }
297         catch ( Exception e ) {
298             throw e;
299         }
300         
301         return ses;
302     } 
303 
304     
305     private Channel initChannel( Session ses ) throws Exception {
306         Channel chan = null;
307         if ( ses == null ) return null;
308         try {
309             chan = ses.startChannel( SEPprofile.URI );
310             if (chan == null) throw new Exception("Cannot open Channel.");
311         }
312         catch (Exception e) {
313             throw e;
314         }
315         return chan;
316     }
317 }