View Javadoc
1   /*
2    * The baseCode project
3    *
4    * Copyright (c) 2006 University of British Columbia
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *       http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   *
18   */
19  package ubic.basecode.util;
20  
21  import ubic.basecode.io.ByteArrayConverter;
22  
23  import java.math.BigInteger;
24  import java.nio.charset.Charset;
25  import java.sql.Blob;
26  import java.sql.SQLException;
27  
28  /**
29   * @author pavlidis
30   */
31  public class SQLUtils {
32  
33      private static ByteArrayConverter#ByteArrayConverter">ByteArrayConverter bac = new ByteArrayConverter();
34  
35      /**
36       * Convert a blob to a string.
37       */
38      public static String blobToString( Blob blob, Charset charset ) throws SQLException {
39          if ( blob == null ) {
40              return null;
41          }
42          return new String( blob.getBytes( 1L, ( int ) blob.length() ), charset );
43      }
44  
45      /**
46       * Convert an arbitrary object to a {@link Long} ID.
47       */
48      public static Long asId( Object o ) {
49          if ( o == null ) return null;
50          if ( o instanceof BigInteger ) {
51              return ( ( BigInteger ) o ).longValue();
52          } else if ( o instanceof Long ) {
53              return ( Long ) o;
54          } else if ( o instanceof Integer ) {
55              return ( ( Integer ) o ).longValue();
56          } else {
57              throw new IllegalArgumentException( "Cannot figure out how to turn object to an id: " + o.getClass().getName() );
58          }
59      }
60  }