idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
3,000 | private String createChecksum ( String input ) { StringBuilder sb = new StringBuilder ( ) ; try { MessageDigest md = MessageDigest . getInstance ( "MD5" ) ; md . update ( input . getBytes ( ) ) ; byte [ ] digest = md . digest ( ) ; for ( byte b : digest ) { sb . append ( Integer . toString ( ( b & 0xff ) + 0x100 , 16 ) . substring ( 1 ) ) ; } } catch ( Exception ignored ) { } return sb . toString ( ) ; } | Create a checksum string as a unique identifier . |
3,001 | public Report run ( Map < String , Object > options , Closure profiled ) { try { List refs = new ArrayList ( ) ; try { for ( Field field : profiled . getClass ( ) . getDeclaredFields ( ) ) { if ( field . getType ( ) . equals ( Reference . class ) ) { field . setAccessible ( true ) ; Reference ref = ( Reference ) field . get ( profiled ) ; refs . add ( ref ) ; } } } catch ( Exception e ) { } refs . add ( new Reference ( profiled ) ) ; refs . add ( new Reference ( profiled . getDelegate ( ) ) ) ; Map < String , Object > _options = new HashMap ( options ) ; _options . put ( "references" , refs ) ; options = null ; start ( _options ) ; try { profiled . call ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } stop ( ) ; return getReport ( ) ; } finally { reset ( ) ; } } | Runs the specified closure and profiles it . |
3,002 | public void start ( Map < String , Object > options ) { MethodCallFilter methodFilter = new MethodCallFilter ( ) ; ThreadRunFilter threadFilter = new ThreadRunFilter ( ) ; Map < String , Object > opts = new HashMap ( defaultOptions ) ; opts . putAll ( options ) ; methodFilter . addIncludes ( ( List ) opts . get ( "includeMethods" ) ) ; methodFilter . addExcludes ( ( List ) opts . get ( "excludeMethods" ) ) ; threadFilter . addIncludes ( ( List ) opts . get ( "includeThreads" ) ) ; threadFilter . addExcludes ( ( List ) opts . get ( "excludeThreads" ) ) ; if ( interceptor == null ) { this . interceptor = new CallInterceptor ( methodFilter , threadFilter ) ; } proxyMetaClasses ( ) ; List < Reference > refs = ( List ) opts . get ( "references" ) ; if ( refs != null ) { proxyPerInstanceMetaClasses ( refs ) ; } } | Starts profiling with the specified options . |
3,003 | public void stop ( ) { MetaClassRegistry registry = GroovySystem . getMetaClassRegistry ( ) ; Set < ProfileMetaClass > proxyMetaClasses = new HashSet ( ) ; for ( ClassInfo classInfo : ClassInfo . getAllClassInfo ( ) ) { Class theClass = classInfo . get ( ) ; MetaClass metaClass = registry . getMetaClass ( theClass ) ; MetaClass metaClass = classInfo . getMetaClass ( ) ; if ( metaClass instanceof ProfileMetaClass ) { proxyMetaClasses . add ( ( ProfileMetaClass ) metaClass ) ; } } registry . setMetaClassCreationHandle ( originalMetaClassCreationHandle ) ; for ( ProfileMetaClass proxyMetaClass : proxyMetaClasses ) { registry . setMetaClass ( proxyMetaClass . getTheClass ( ) , proxyMetaClass . getAdaptee ( ) ) ; } } | Stops profiling . |
3,004 | public static boolean setDockIcon ( final Image icon ) { try { final Class < ? > clazz = Class . forName ( "com.apple.eawt.Application" ) ; final Method am = clazz . getMethod ( "getApplication" ) ; final Object app = am . invoke ( null , new Object [ 0 ] ) ; final Method si = clazz . getMethod ( "setDockIconImage" , new Class [ ] { Image . class } ) ; si . invoke ( app , new Object [ ] { icon } ) ; return true ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return false ; } | Sets |icon| for Mac OS X dock . |
3,005 | public List < E > find ( E entity , SearchParameters sp ) { if ( sp . hasNamedQuery ( ) ) { return byNamedQueryUtil . findByNamedQuery ( sp ) ; } CriteriaBuilder builder = entityManager . getCriteriaBuilder ( ) ; CriteriaQuery < E > criteriaQuery = builder . createQuery ( type ) ; if ( sp . getDistinct ( ) ) { criteriaQuery . distinct ( true ) ; } Root < E > root = criteriaQuery . from ( type ) ; Predicate predicate = getPredicate ( criteriaQuery , root , builder , entity , sp ) ; if ( predicate != null ) { criteriaQuery = criteriaQuery . where ( predicate ) ; } fetches ( sp , root ) ; criteriaQuery . orderBy ( orderByUtil . buildJpaOrders ( sp . getOrders ( ) , root , builder , sp ) ) ; TypedQuery < E > typedQuery = entityManager . createQuery ( criteriaQuery ) ; applyCacheHints ( typedQuery , sp ) ; jpaUtil . applyPagination ( typedQuery , sp ) ; List < E > entities = typedQuery . getResultList ( ) ; log . fine ( "Returned " + entities . size ( ) + " elements" ) ; return entities ; } | Find and load a list of E instance . |
3,006 | public void save ( E entity ) { checkNotNull ( entity , "The entity to save cannot be null" ) ; if ( ! entity . isIdSet ( ) ) { entityManager . persist ( entity ) ; return ; } if ( jpaUtil . isEntityIdManuallyAssigned ( type ) && ! entityManager . contains ( entity ) ) { entityManager . persist ( entity ) ; return ; } } | Save or update the given entity E to the repository . Assume that the entity is already present in the persistence context . No merge is done . |
3,007 | public void delete ( E entity ) { if ( entityManager . contains ( entity ) ) { entityManager . remove ( entity ) ; } else { E entityRef = entityManager . getReference ( type , entity . getId ( ) ) ; if ( entityRef != null ) { entityManager . remove ( entityRef ) ; } else { log . warning ( "Attempt to delete an instance that is not present in the database: " + entity ) ; } } } | Delete the given entity E from the repository . |
3,008 | public static Connection connection ( ConnectionHandler h , Property ... ps ) { return Driver . connection ( h , ps ) ; } | Creates a connection managed with given handler . |
3,009 | public static < A > A withQueryResult ( QueryResult res , Function < java . sql . Connection , A > f ) { return f . apply ( connection ( handleQuery ( ( x , y ) -> res ) ) ) ; } | Executes |f| using a connection accepting only queries and answering with |result| to any query . |
3,010 | public void perform ( final Appender ap ) throws SQLException , UnsupportedEncodingException { Connection con = null ; Statement stmt = null ; ResultSet rs = null ; try { con = JDBC . connect ( this . jdbcDriver , this . jdbcUrl , this . user , this . pass ) ; stmt = con . createStatement ( ) ; rs = stmt . executeQuery ( this . sql ) ; appendRows ( new ResultIterator ( rs ) , ap , this . charset , this . formatting , this . cols ) ; } finally { if ( rs != null ) { try { rs . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } if ( stmt != null ) { try { stmt . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } if ( con != null ) { try { con . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } } | Performs export . |
3,011 | static void appendNull ( final Appender ap , final Formatting fmt , final ColumnType col ) { switch ( col ) { case BigDecimal : ap . append ( fmt . noneBigDecimal ) ; break ; case Boolean : ap . append ( fmt . noneBoolean ) ; break ; case Byte : ap . append ( fmt . noneByte ) ; break ; case Short : ap . append ( fmt . noneShort ) ; break ; case Date : ap . append ( fmt . noneDate ) ; break ; case Double : ap . append ( fmt . noneDouble ) ; break ; case Float : ap . append ( fmt . noneFloat ) ; break ; case Int : ap . append ( fmt . noneInt ) ; break ; case Long : ap . append ( fmt . noneLong ) ; break ; case Time : ap . append ( fmt . noneTime ) ; break ; case Timestamp : ap . append ( fmt . noneTimestamp ) ; break ; default : ap . append ( fmt . noneString ) ; break ; } } | Appends a null value . |
3,012 | static void appendValues ( final ResultRow rs , final Appender ap , final Charset charset , final Formatting fmt , final Iterator < ColumnType > cols , final int colIndex ) { if ( ! cols . hasNext ( ) ) { return ; } if ( colIndex > 0 ) { ap . append ( fmt . valueSeparator ) ; } final ColumnType col = cols . next ( ) ; if ( rs . isNull ( colIndex ) ) { appendNull ( ap , fmt , col ) ; appendValues ( rs , ap , charset , fmt , cols , colIndex + 1 ) ; return ; } switch ( col ) { case BigDecimal : ap . append ( String . format ( fmt . someBigDecimal , rs . getBigDecimal ( colIndex ) ) ) ; break ; case Boolean : ap . append ( String . format ( fmt . someBoolean , rs . getBoolean ( colIndex ) ) ) ; break ; case Byte : ap . append ( String . format ( fmt . someByte , rs . getByte ( colIndex ) ) ) ; break ; case Short : ap . append ( String . format ( fmt . someShort , rs . getShort ( colIndex ) ) ) ; break ; case Date : ap . append ( String . format ( fmt . someDate , rs . getDate ( colIndex ) . getTime ( ) ) ) ; break ; case Double : ap . append ( String . format ( fmt . someDouble , rs . getDouble ( colIndex ) ) ) ; break ; case Float : ap . append ( String . format ( fmt . someFloat , rs . getFloat ( colIndex ) ) ) ; break ; case Int : ap . append ( String . format ( fmt . someInt , rs . getInt ( colIndex ) ) ) ; break ; case Long : ap . append ( String . format ( fmt . someLong , rs . getLong ( colIndex ) ) ) ; break ; case Time : ap . append ( String . format ( fmt . someTime , rs . getTime ( colIndex ) . getTime ( ) ) ) ; break ; case Timestamp : ap . append ( String . format ( fmt . someTimestamp , rs . getTimestamp ( colIndex ) . getTime ( ) ) ) ; break ; default : ap . append ( String . format ( fmt . someString , new String ( rs . getString ( colIndex ) . getBytes ( charset ) ) . replaceAll ( "\"" , "\\\"" ) ) ) ; break ; } appendValues ( rs , ap , charset , fmt , cols , colIndex + 1 ) ; } | Result set values . |
3,013 | public static void main ( final String [ ] args ) throws Exception { if ( args . length < 4 ) { throw new IllegalArgumentException ( ) ; } if ( new File ( args [ 1 ] ) . exists ( ) ) { final Properties conf = new Properties ( ) ; conf . put ( "jdbc.url" , args [ 0 ] ) ; conf . put ( "jdbc.driverPath" , args [ 1 ] ) ; conf . put ( "db.user" , args [ 2 ] ) ; conf . put ( "db.charset" , args [ 3 ] ) ; execWith ( sysAppender , conf , args , 4 ) ; return ; } final File config = Studio . preferencesFile ( ) ; if ( ! config . exists ( ) ) { throw new IllegalArgumentException ( "Cannot find configuration" ) ; } FileInputStream in = null ; try { in = new FileInputStream ( config ) ; final Properties conf = new Properties ( ) ; conf . load ( in ) ; execWith ( sysAppender , conf , args , 0 ) ; } catch ( Exception e ) { throw new RuntimeException ( "Fails to load configuration: " + config . getAbsolutePath ( ) , e ) ; } finally { if ( in != null ) { try { in . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } } | CLI runner . |
3,014 | public T withQueryDetection ( final String ... pattern ) { if ( pattern == null ) { throw new IllegalArgumentException ( ) ; } final Pattern [ ] ps = new Pattern [ pattern . length ] ; int i = 0 ; for ( final String p : pattern ) { ps [ i ++ ] = Pattern . compile ( p ) ; } return withQueryDetection ( ps ) ; } | Returns an new handler based on this one but including given query detection |pattern| . If there is already existing pattern the new one will be used after . |
3,015 | protected Pattern [ ] queryDetectionPattern ( final Pattern ... pattern ) { if ( pattern == null ) { throw new IllegalArgumentException ( ) ; } if ( this . queryDetection == null ) { return pattern ; } final Pattern [ ] patterns = new Pattern [ this . queryDetection . length + pattern . length ] ; System . arraycopy ( this . queryDetection , 0 , patterns , 0 , this . queryDetection . length ) ; int i = this . queryDetection . length ; for ( final Pattern p : pattern ) { patterns [ i ++ ] = p ; } return patterns ; } | Appends given |pattern| to current query detection . |
3,016 | public static ParameterDef Default ( final int sqlType ) { return new ParameterDef ( jdbcTypeMappings . get ( sqlType ) , parameterModeIn , sqlType , jdbcTypeNames . get ( sqlType ) , jdbcTypePrecisions . get ( sqlType ) , jdbcTypeScales . get ( sqlType ) , parameterNullableUnknown , jdbcTypeSigns . get ( sqlType ) ) ; } | Default parameter . |
3,017 | public static ParameterDef Scaled ( final int sqlType , final int scale ) { return new ParameterDef ( jdbcTypeMappings . get ( sqlType ) , parameterModeIn , sqlType , jdbcTypeNames . get ( sqlType ) , jdbcTypePrecisions . get ( sqlType ) , scale , parameterNullableUnknown , jdbcTypeSigns . get ( sqlType ) ) ; } | Decimal parameter . |
3,018 | public static ParameterDef Float ( final float f ) { final BigDecimal bd = new BigDecimal ( Float . toString ( f ) ) ; return Scaled ( Types . FLOAT , bd . scale ( ) ) ; } | Float constructor . |
3,019 | public static ParameterDef Double ( final double d ) { final BigDecimal bd = new BigDecimal ( String . format ( Locale . US , "%f" , d ) ) . stripTrailingZeros ( ) ; return Scaled ( Types . DOUBLE , bd . scale ( ) ) ; } | Double constructor . |
3,020 | public RowResultSet < R > resultSet ( int maxRows ) { if ( maxRows <= 0 ) { return new RowResultSet < R > ( getRows ( ) ) ; } return new RowResultSet < R > ( getRows ( ) . subList ( 0 , maxRows ) ) ; } | Returns result set from these rows . |
3,021 | public static < T > Column < T > Column ( final Class < T > columnClass , final String name ) { return new Column < T > ( columnClass , name ) ; } | Creates column definition . |
3,022 | public java . sql . Blob getBlob ( final Object value ) throws SQLException { if ( value instanceof java . sql . Blob ) return ( java . sql . Blob ) value ; if ( value instanceof byte [ ] ) { return new SerialBlob ( ( byte [ ] ) value ) ; } } | Tries to get BLOB from raw |value| . |
3,023 | public Blob createBlob ( final byte [ ] data ) throws SQLException { return new javax . sql . rowset . serial . SerialBlob ( data ) ; } | Returns a BLOB with given |data| . |
3,024 | private String escapeForFuzzy ( String word ) { int length = word . length ( ) ; char [ ] tmp = new char [ length * 4 ] ; length = ASCIIFoldingFilter . foldToASCII ( word . toCharArray ( ) , 0 , tmp , 0 , length ) ; return new String ( tmp , 0 , length ) ; } | Apply same filtering as custom analyzer . Lowercase is done by QueryParser for fuzzy search . |
3,025 | public String get ( String key ) throws EtcdClientException { Preconditions . checkNotNull ( key , "key can't be null" ) ; URI uri = buildUriWithKeyAndParams ( key , null ) ; HttpGet httpGet = new HttpGet ( uri ) ; EtcdResult result = syncExecute ( httpGet , new int [ ] { 200 , 404 } , 100 ) ; if ( result . isError ( ) ) { if ( result . errorCode == 100 ) { return null ; } } return result . node != null ? result . node . value : null ; } | Get the value of a key . |
3,026 | public void set ( String key , String value , int ttl ) throws EtcdClientException { set ( key , value , ttl , null ) ; } | Setting the value of a key with optional key TTL |
3,027 | public void delete ( String key ) throws EtcdClientException { Preconditions . checkNotNull ( key ) ; URI uri = buildUriWithKeyAndParams ( key , null ) ; HttpDelete delete = new HttpDelete ( uri ) ; syncExecute ( delete , new int [ ] { 200 , 404 } ) ; } | Delete a key |
3,028 | public List < EtcdNode > listDir ( String key , boolean recursive ) throws EtcdClientException { Preconditions . checkNotNull ( key ) ; Map < String , String > params = new HashMap < String , String > ( ) ; if ( recursive ) { params . put ( "recursive" , String . valueOf ( true ) ) ; } URI uri = buildUriWithKeyAndParams ( key , params ) ; HttpGet httpGet = new HttpGet ( uri ) ; EtcdResult result = syncExecute ( httpGet , new int [ ] { 200 , 404 } , 100 ) ; if ( null == result || null == result . node ) { return null ; } return result . node . nodes ; } | Listing a directory with recursive |
3,029 | public void deleteDir ( String key , boolean recursive ) throws EtcdClientException { Preconditions . checkNotNull ( key ) ; Map < String , String > params = new HashMap < String , String > ( ) ; if ( recursive ) { params . put ( "recursive" , String . valueOf ( true ) ) ; } else { params . put ( "dir" , String . valueOf ( true ) ) ; } URI uri = buildUriWithKeyAndParams ( key , params ) ; HttpDelete httpDelete = new HttpDelete ( uri ) ; syncExecute ( httpDelete , new int [ ] { 200 , 403 } ) ; } | Deleting a directory |
3,030 | public EtcdResult cas ( String key , String value , Map < String , String > params ) throws EtcdClientException { List < BasicNameValuePair > data = Lists . newArrayList ( ) ; data . add ( new BasicNameValuePair ( "value" , value ) ) ; return put ( key , data , params , new int [ ] { 200 , 412 } , 101 , 105 ) ; } | Atomic Compare - and - Swap |
3,031 | public EtcdResult cad ( String key , Map < String , String > params ) throws EtcdClientException { URI uri = buildUriWithKeyAndParams ( key , params ) ; HttpDelete httpDelete = new HttpDelete ( uri ) ; return syncExecute ( httpDelete , new int [ ] { 200 , 412 } , 101 ) ; } | Atomic Compare - and - Delete |
3,032 | public ListenableFuture < EtcdResult > watch ( String key , long index , boolean recursive ) { Map < String , String > params = new HashMap < String , String > ( ) ; params . put ( "wait" , String . valueOf ( true ) ) ; if ( index > 0 ) { params . put ( "waitIndex" , String . valueOf ( index ) ) ; } if ( recursive ) { params . put ( "recursive" , String . valueOf ( recursive ) ) ; } URI uri = buildUriWithKeyAndParams ( key , params ) ; HttpGet httpGet = new HttpGet ( uri ) ; return asyncExecute ( httpGet , new int [ ] { 200 } ) ; } | Watch for a change on a key |
3,033 | private EtcdResult put ( String key , List < BasicNameValuePair > data , Map < String , String > params , int [ ] expectedHttpStatusCodes , int ... expectedErrorCodes ) throws EtcdClientException { URI uri = buildUriWithKeyAndParams ( key , params ) ; HttpPut httpPut = new HttpPut ( uri ) ; UrlEncodedFormEntity entity = new UrlEncodedFormEntity ( data , Charsets . UTF_8 ) ; httpPut . setEntity ( entity ) ; return syncExecute ( httpPut , expectedHttpStatusCodes , expectedErrorCodes ) ; } | The basic put operation |
3,034 | private URI buildUriWithKeyAndParams ( String key , Map < String , String > params ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( URI_PREFIX ) ; if ( key . startsWith ( "/" ) ) { key = key . substring ( 1 ) ; } for ( String token : Splitter . on ( "/" ) . split ( key ) ) { sb . append ( "/" ) . append ( urlEscape ( token ) ) ; } if ( params != null ) { sb . append ( "?" ) ; for ( String str : params . keySet ( ) ) { sb . append ( urlEscape ( str ) ) . append ( "=" ) . append ( urlEscape ( params . get ( str ) ) ) ; sb . append ( "&" ) ; } } String url = sb . toString ( ) ; if ( url . endsWith ( "&" ) ) { url = url . substring ( 0 , url . length ( ) - 1 ) ; } return baseUri . resolve ( url ) ; } | Build url with key and url params |
3,035 | public void setCharset ( final Charset charset ) { final Charset old = this . charset ; this . charset = charset ; this . connectionConfig = System . currentTimeMillis ( ) ; this . connectionValidated = false ; this . pcs . firePropertyChange ( "charset" , old , this . charset ) ; } | Sets DB |charset| . |
3,036 | public void setUser ( final String user ) { final String old = this . user ; this . user = user ; this . connectionConfig = System . currentTimeMillis ( ) ; this . connectionValidated = false ; this . pcs . firePropertyChange ( "user" , old , this . user ) ; } | Sets name of DB |user| . |
3,037 | public void setUrl ( final String url ) { final String old = this . url ; this . url = url ; this . connectionConfig = System . currentTimeMillis ( ) ; this . connectionValidated = false ; this . pcs . firePropertyChange ( "url" , old , this . url ) ; } | Sets JDBC |url| . |
3,038 | public void setDriver ( final Driver driver ) { final Driver old = this . driver ; this . driver = driver ; this . connectionConfig = System . currentTimeMillis ( ) ; this . connectionValidated = false ; this . pcs . firePropertyChange ( "driver" , old , this . driver ) ; } | Sets JDBC |driver| . |
3,039 | public void setConnectionValidated ( final boolean validated ) { final boolean old = this . connectionValidated ; this . connectionValidated = validated ; this . pcs . firePropertyChange ( "connectionValidated" , old , this . connectionValidated ) ; } | Sets whether connection is |validated| . |
3,040 | public void setProcessing ( final boolean processing ) { final boolean old = this . processing ; this . processing = processing ; this . pcs . firePropertyChange ( "processing" , old , this . processing ) ; } | Sets whether is |processing| . |
3,041 | public acolyte . jdbc . Connection connect ( final String url , final Property ... info ) throws SQLException { return connect ( url , props ( info ) ) ; } | Creates a connection to specified |url| with given configuration |info| . |
3,042 | public static ConnectionHandler unregister ( final String id ) { if ( id == null || id . length ( ) == 0 ) { return null ; } return handlers . remove ( id ) ; } | Unregisters specified handler . |
3,043 | private static Properties props ( final Property [ ] info ) { final Properties ps = new Properties ( ) ; for ( final Property p : info ) { ps . put ( p . name , p . value ) ; } return ps ; } | Returns prepared properties . |
3,044 | public CrawlerPack addCookie ( String name , String value ) { if ( null == name ) { log . warn ( "addCookie: Cookie name null." ) ; return this ; } cookies . add ( new Cookie ( "" , name , value ) ) ; return this ; } | Creates a cookie with the given name and value . |
3,045 | public CrawlerPack addCookie ( String domain , String name , String value , String path , Date expires , boolean secure ) { if ( null == name ) { log . warn ( "addCookie: Cookie name null." ) ; return this ; } cookies . add ( new Cookie ( domain , name , value , path , expires , secure ) ) ; return this ; } | Creates a cookie with the given name value domain attribute path attribute expiration attribute and secure attribute |
3,046 | Cookie [ ] getCookies ( String uri ) { if ( null == cookies || 0 == cookies . size ( ) ) return null ; for ( Cookie cookie : cookies ) { if ( "" . equals ( cookie . getDomain ( ) ) ) { String domain = uri . replaceAll ( "^.*:\\/\\/([^\\/]+)[\\/]?.*$" , "$1" ) ; cookie . setDomain ( domain ) ; cookie . setPath ( "/" ) ; cookie . setExpiryDate ( null ) ; cookie . setSecure ( false ) ; } } return cookies . toArray ( new Cookie [ cookies . size ( ) ] ) ; } | Return a Cookie array and auto importing domain and path when domain was empty . |
3,047 | private String detectCharset ( byte [ ] content , Integer offset ) { log . debug ( "detectCharset: offset=" + offset ) ; if ( offset > content . length ) return null ; UniversalDetector detector = new UniversalDetector ( null ) ; detector . handleData ( content , offset , content . length - offset > detectBuffer ? detectBuffer : content . length - offset ) ; detector . dataEnd ( ) ; String detectEncoding = detector . getDetectedCharset ( ) ; return null == detectEncoding ? detectCharset ( content , offset + detectBuffer ) : detectEncoding ; } | Detecting real content encoding |
3,048 | public Java8CompositeHandler withUpdateHandler1 ( CountUpdateHandler h ) { final UpdateHandler uh = new UpdateHandler ( ) { public UpdateResult apply ( String sql , List < Parameter > ps ) { return new UpdateResult ( h . apply ( sql , ps ) ) ; } } ; return withUpdateHandler ( uh ) ; } | Returns handler that delegates update execution to |h| function . Given function will be used only if executed statement is not detected as a query by withQueryDetection . |
3,049 | public CompositeHandler withQueryHandler ( final QueryHandler handler ) { if ( handler == null ) { throw new IllegalArgumentException ( ) ; } return new CompositeHandler ( this . queryDetection , handler , this . updateHandler ) ; } | Returns a new handler based on this one but with given query |handler| appended . |
3,050 | public CompositeHandler withUpdateHandler ( final UpdateHandler handler ) { if ( handler == null ) { throw new IllegalArgumentException ( ) ; } return new CompositeHandler ( this . queryDetection , this . queryHandler , handler ) ; } | Returns a new handler based on this one but with given update |handler| appended . |
3,051 | private ResultSet generateKeysResultSet ( final UpdateResult res ) { if ( this . generatedKeysColumnIndexes == null && this . generatedKeysColumnNames == null ) { return res . generatedKeys . resultSet ( ) . withStatement ( this ) ; } else if ( this . generatedKeysColumnIndexes != null ) { return res . generatedKeys . resultSet ( ) . withStatement ( this ) . withProjection ( this . generatedKeysColumnIndexes ) ; } else { return res . generatedKeys . resultSet ( ) . withStatement ( this ) . withProjection ( this . generatedKeysColumnNames ) ; } } | Returns the resultset corresponding to the keys generated on update . |
3,052 | void setDecimal ( final int parameterIndex , final BigDecimal x ) throws SQLException { final ParameterDef def = ( x == null ) ? Decimal : Decimal ( x ) ; setParam ( parameterIndex , def , x ) ; } | Sets parameter as DECIMAL . |
3,053 | private String normalizeClassName ( final Class < ? > c ) { if ( Blob . class . isAssignableFrom ( c ) ) return "java.sql.Blob" ; else if ( Array . class . isAssignableFrom ( c ) ) return "java.sql.Array" ; return c . getName ( ) ; } | Normalizes parameter class name . |
3,054 | private byte [ ] createBytes ( InputStream stream , long length ) throws SQLException { ByteArrayOutputStream buff = null ; try { buff = new ByteArrayOutputStream ( ) ; if ( length > 0 ) IOUtils . copyLarge ( stream , buff , 0 , length ) ; else IOUtils . copy ( stream , buff ) ; return buff . toByteArray ( ) ; } catch ( IOException e ) { throw new SQLException ( "Fails to create BLOB" , e ) ; } finally { IOUtils . closeQuietly ( buff ) ; } } | Creates bytes array from input stream . |
3,055 | private acolyte . jdbc . Blob createBlob ( InputStream stream , long length ) throws SQLException { final acolyte . jdbc . Blob blob = acolyte . jdbc . Blob . Nil ( ) ; blob . setBytes ( 0L , createBytes ( stream , length ) ) ; return blob ; } | Creates BLOB from input stream . |
3,056 | @ SuppressWarnings ( "unchecked" ) public < A extends Annotation > A getAnnotation ( final Class < ? > clazz , final Class < A > annClass ) throws AnnotationReadException { if ( xmlInfo != null && xmlInfo . containsClassInfo ( clazz . getName ( ) ) ) { final ClassInfo classInfo = xmlInfo . getClassInfo ( clazz . getName ( ) ) ; if ( classInfo . containsAnnotationInfo ( annClass . getName ( ) ) ) { AnnotationInfo annInfo = classInfo . getAnnotationInfo ( annClass . getName ( ) ) ; try { return ( A ) annotationBuilder . buildAnnotation ( Class . forName ( annInfo . getClassName ( ) ) , annInfo ) ; } catch ( ClassNotFoundException e ) { throw new AnnotationReadException ( String . format ( "not found class '%s'" , annInfo . getClassName ( ) ) , e ) ; } } } return clazz . getAnnotation ( annClass ) ; } | Returns a class annotation for the specified type if such an annotation is present else null . |
3,057 | private < T > SwingWorker < T , T > studioProcess ( final int timeout , final Callable < T > c , final UnaryFunction < Callable < T > , T > f ) { final Callable < T > cw = new Callable < T > ( ) { public T call ( ) { final FutureTask < T > t = new FutureTask < T > ( c ) ; try { executor . submit ( t ) ; return t . get ( timeout , TimeUnit . SECONDS ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } return null ; } } ; return new SwingWorker < T , T > ( ) { public T doInBackground ( ) throws Exception { try { f . apply ( cw ) ; } finally { model . setProcessing ( false ) ; } return null ; } } ; } | Studio process . |
3,058 | private static final KeyAdapter closeKeyStrokes ( final java . awt . Window window ) { return new KeyAdapter ( ) { public void keyReleased ( KeyEvent e ) { final int kc = e . getKeyCode ( ) ; if ( kc == KeyEvent . VK_ESCAPE || kc == KeyEvent . VK_ENTER ) { window . dispose ( ) ; } } } ; } | Listens to key to close a |window| . |
3,059 | private void updateConfig ( ) { final String u = this . model . getUrl ( ) ; final String url = ( u != null ) ? u . trim ( ) : null ; if ( url == null || url . length ( ) == 0 ) { this . conf . remove ( "jdbc.url" ) ; } else { this . conf . put ( "jdbc.url" , url ) ; } final String n = this . model . getUser ( ) ; final String user = ( n != null ) ? n . trim ( ) : null ; if ( user == null || user . length ( ) == 0 ) { this . conf . remove ( "db.user" ) ; } else { this . conf . put ( "db.user" , user ) ; } final Charset charset = this . model . getCharset ( ) ; if ( charset == null ) { this . conf . remove ( "db.charset" ) ; } else { this . conf . put ( "db.charset" , charset . name ( ) ) ; } try { this . saveConf . call ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } | Updates application configuration . |
3,060 | private Connection getConnection ( ) throws SQLException { return JDBC . connect ( model . getDriver ( ) , model . getUrl ( ) , model . getUser ( ) , model . getPassword ( ) ) ; } | Returns JDBC connection for configuration in model . |
3,061 | private < A > TableData < A > tableData ( final ResultSet rs , final RowFunction < A > f ) throws SQLException { final ResultSetMetaData meta = rs . getMetaData ( ) ; final int c = meta . getColumnCount ( ) ; final TableData < A > td = new TableData < A > ( ) ; for ( int p = 1 ; p <= c ; p ++ ) { final String n = meta . getColumnLabel ( p ) ; td . columns . add ( ( n == null || "" . equals ( n ) ) ? "col" + p : n ) ; } td . rows . add ( f . apply ( rs ) ) ; while ( rs . next ( ) ) { td . rows . add ( f . apply ( rs ) ) ; } return td ; } | Returns table data from |result| set . |
3,062 | private static ImageIcon setWaitIcon ( final JLabel label ) { final ImageIcon ico = new ImageIcon ( Studio . class . getResource ( "loader.gif" ) ) ; label . setIcon ( ico ) ; ico . setImageObserver ( label ) ; return ico ; } | Sets wait icon on |label| . |
3,063 | private JTable withColRenderers ( final JTable table ) { final DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer ( ) ; table . setDefaultRenderer ( BigDecimal . class , new TableCellRenderer ( ) { public Component getTableCellRendererComponent ( final JTable table , final Object value , final boolean isSelected , final boolean hasFocus , final int row , final int column ) { final BigDecimal bd = ( BigDecimal ) value ; return dtcr . getTableCellRendererComponent ( table , bd . toString ( ) , isSelected , hasFocus , row , column ) ; } } ) ; table . setDefaultRenderer ( Boolean . class , new TableCellRenderer ( ) { public Component getTableCellRendererComponent ( final JTable table , final Object value , final boolean isSelected , final boolean hasFocus , final int row , final int column ) { final Boolean b = ( Boolean ) value ; return dtcr . getTableCellRendererComponent ( table , Boolean . toString ( b ) , isSelected , hasFocus , row , column ) ; } } ) ; table . setDefaultRenderer ( java . sql . Date . class , new TableCellRenderer ( ) { public Component getTableCellRendererComponent ( final JTable table , final Object value , final boolean isSelected , final boolean hasFocus , final int row , final int column ) { final java . sql . Date d = ( java . sql . Date ) value ; return dtcr . getTableCellRendererComponent ( table , String . format ( "%tF" , d ) , isSelected , hasFocus , row , column ) ; } } ) ; table . setDefaultRenderer ( Time . class , new TableCellRenderer ( ) { public Component getTableCellRendererComponent ( final JTable table , final Object value , final boolean isSelected , final boolean hasFocus , final int row , final int column ) { final Time t = ( Time ) value ; return dtcr . getTableCellRendererComponent ( table , String . format ( "%tr" , t ) , isSelected , hasFocus , row , column ) ; } } ) ; table . setDefaultRenderer ( Timestamp . class , new TableCellRenderer ( ) { public Component getTableCellRendererComponent ( final JTable table , final Object value , final boolean isSelected , final boolean hasFocus , final int row , final int column ) { final Time t = ( Time ) value ; return dtcr . getTableCellRendererComponent ( table , String . format ( "%tr" , t ) , isSelected , hasFocus , row , column ) ; } } ) ; return table ; } | Returns table with column renderers . |
3,064 | public void chooseDriver ( final JFrame frm , final JTextField field ) { final JFileChooser chooser = new JFileChooser ( new File ( "." ) ) ; for ( final FileFilter ff : chooser . getChoosableFileFilters ( ) ) { chooser . removeChoosableFileFilter ( ff ) ; } chooser . setFileHidingEnabled ( false ) ; chooser . setDialogTitle ( "Chooser JDBC driver" ) ; chooser . setMultiSelectionEnabled ( false ) ; chooser . setFileFilter ( new JDBCDriverFileFilter ( ) ) ; final int choice = chooser . showOpenDialog ( frm ) ; if ( choice != JFileChooser . APPROVE_OPTION ) { return ; } final File driverFile = chooser . getSelectedFile ( ) ; final String driverPath = driverFile . getAbsolutePath ( ) ; field . setForeground ( Color . BLACK ) ; field . setText ( driverPath ) ; try { model . setDriver ( JDBC . loadDriver ( driverFile ) ) ; conf . put ( "jdbc.driverPath" , driverPath ) ; updateConfig ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } | Chooses a JDBC driver . |
3,065 | private static void displayRows ( final JFrame frm , final Vector < Map . Entry < String , ColumnType > > cols , final Vector < Vector < Object > > data , final Charset charset , final Formatting fmt , final Callable < Void > end ) { final UnaryFunction < Document , Callable < Void > > f = new UnaryFunction < Document , Callable < Void > > ( ) { public Callable < Void > apply ( final Document doc ) { final DocumentAppender ap = new DocumentAppender ( doc ) ; final ArrayList < String > cnames = new ArrayList < String > ( ) ; final ArrayList < ColumnType > ctypes = new ArrayList < ColumnType > ( ) ; final int c = cols . size ( ) ; ap . append ( fmt . imports ) ; ap . append ( "\r\n\r\nRowLists.rowList" + c + "(" ) ; int i = 0 ; for ( final Map . Entry < String , ColumnType > e : cols ) { final String name = e . getKey ( ) ; final ColumnType type = e . getValue ( ) ; cnames . add ( name ) ; ctypes . add ( type ) ; if ( i ++ > 0 ) { ap . append ( ", " ) ; } final String tname = ( fmt . typeMap . containsKey ( type ) ) ? fmt . typeMap . get ( type ) : "String" ; ap . append ( String . format ( fmt . colDef , tname , name ) ) ; } ap . append ( ")\r\n" ) ; return new Callable < Void > ( ) { public Void call ( ) { RowFormatter . appendRows ( new VectorIterator ( data ) , ap , charset , fmt , ctypes ) ; return null ; } } ; } } ; createConvertDialog ( frm , fmt , f , end ) ; } | Displays formatted rows . |
3,066 | protected static void loadConfig ( final Properties config , final File f ) { InputStreamReader r = null ; try { final FileInputStream in = new FileInputStream ( f ) ; r = new InputStreamReader ( in , "UTF-8" ) ; config . load ( r ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { if ( r != null ) { try { r . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } } | Loads configuration from |file| . |
3,067 | public Collection < CascadeType > getCascades ( PluralAttribute < ? , ? , ? > attribute ) { if ( attribute . getJavaMember ( ) instanceof AccessibleObject ) { AccessibleObject accessibleObject = ( AccessibleObject ) attribute . getJavaMember ( ) ; OneToMany oneToMany = accessibleObject . getAnnotation ( OneToMany . class ) ; if ( oneToMany != null ) { return newArrayList ( oneToMany . cascade ( ) ) ; } ManyToMany manyToMany = accessibleObject . getAnnotation ( ManyToMany . class ) ; if ( manyToMany != null ) { return newArrayList ( manyToMany . cascade ( ) ) ; } } return newArrayList ( ) ; } | Retrieves cascade from metamodel attribute |
3,068 | public Collection < CascadeType > getCascades ( SingularAttribute < ? , ? > attribute ) { if ( attribute . getJavaMember ( ) instanceof AccessibleObject ) { AccessibleObject accessibleObject = ( AccessibleObject ) attribute . getJavaMember ( ) ; OneToOne oneToOne = accessibleObject . getAnnotation ( OneToOne . class ) ; if ( oneToOne != null ) { return newArrayList ( oneToOne . cascade ( ) ) ; } ManyToOne manyToOne = accessibleObject . getAnnotation ( ManyToOne . class ) ; if ( manyToOne != null ) { return newArrayList ( manyToOne . cascade ( ) ) ; } } return newArrayList ( ) ; } | Retrieves cascade from metamodel attribute on a xToMany relation . |
3,069 | public static Connection connect ( final Driver driver , final String url , final String user , final String pass ) throws SQLException { final Properties props = new Properties ( ) ; props . put ( "user" , user ) ; props . put ( "password" , pass ) ; return driver . connect ( url , props ) ; } | Returns connection using given |driver| . |
3,070 | public static Object getObject ( final ResultSet rs , final String name , final ColumnType type ) throws SQLException { switch ( type ) { case BigDecimal : return rs . getBigDecimal ( name ) ; case Boolean : return rs . getBoolean ( name ) ; case Byte : return rs . getByte ( name ) ; case Short : return rs . getShort ( name ) ; case Date : return rs . getDate ( name ) ; case Double : return rs . getDouble ( name ) ; case Float : return rs . getFloat ( name ) ; case Int : return rs . getInt ( name ) ; case Long : return rs . getLong ( name ) ; case Time : return rs . getTime ( name ) ; case Timestamp : return rs . getTimestamp ( name ) ; default : return rs . getString ( name ) ; } } | Returns value of specified |column| according its type . |
3,071 | @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public Class classForName ( String className , Map loaderMap ) throws ClassNotFoundException { Collection < ClassLoader > loaders = null ; loaders = new HashSet < ClassLoader > ( ) ; loaders . add ( Thread . currentThread ( ) . getContextClassLoader ( ) ) ; if ( loaderMap != null && ! loaderMap . isEmpty ( ) ) { loaders . addAll ( loaderMap . values ( ) ) ; } Class clazz = null ; ClassNotFoundException lastCause = null ; for ( Iterator < ClassLoader > it = loaders . iterator ( ) ; it . hasNext ( ) ; ) { ClassLoader loader = it . next ( ) ; try { clazz = loader . loadClass ( className ) ; return clazz ; } catch ( ClassNotFoundException fqcnException ) { lastCause = fqcnException ; try { if ( className . indexOf ( '.' ) == - 1 ) { clazz = loader . loadClass ( "java.lang." + className ) ; return clazz ; } } catch ( ClassNotFoundException defaultClassException ) { lastCause = defaultClassException ; } } } throw lastCause ; } | Loads class from multiple ClassLoader . |
3,072 | private void initializeStatically ( ) { bindingData . initializeBindings ( ) ; stopwatch . resetAndLog ( "Binding initialization" ) ; for ( InjectorShell shell : shells ) { shell . getInjector ( ) . index ( ) ; } stopwatch . resetAndLog ( "Binding indexing" ) ; injectionRequestProcessor . process ( shells ) ; stopwatch . resetAndLog ( "Collecting injection requests" ) ; bindingData . runCreationListeners ( errors ) ; stopwatch . resetAndLog ( "Binding validation" ) ; injectionRequestProcessor . validate ( ) ; stopwatch . resetAndLog ( "Static validation" ) ; initializer . validateOustandingInjections ( errors ) ; stopwatch . resetAndLog ( "Instance member validation" ) ; new LookupProcessor ( errors ) . process ( shells ) ; for ( InjectorShell shell : shells ) { ( ( DeferredLookups ) shell . getInjector ( ) . lookups ) . initialize ( errors ) ; } stopwatch . resetAndLog ( "Provider verification" ) ; bindingData . initializeDelayedBindings ( ) ; stopwatch . resetAndLog ( "Delayed Binding initialization" ) ; for ( InjectorShell shell : shells ) { if ( ! shell . getElements ( ) . isEmpty ( ) ) { throw new AssertionError ( "Failed to execute " + shell . getElements ( ) ) ; } } errors . throwCreationExceptionIfErrorsExist ( ) ; } | Initialize and validate everything . |
3,073 | void loadEagerSingletons ( InjectorImpl injector , Stage stage , final Errors errors ) { List < BindingImpl < ? > > candidateBindings = new ArrayList < > ( ) ; @ SuppressWarnings ( "unchecked" ) Collection < BindingImpl < ? > > bindingsAtThisLevel = ( Collection ) injector . state . getExplicitBindingsThisLevel ( ) . values ( ) ; candidateBindings . addAll ( bindingsAtThisLevel ) ; synchronized ( injector . state . lock ( ) ) { candidateBindings . addAll ( injector . jitBindings . values ( ) ) ; } InternalContext context = injector . enterContext ( ) ; try { for ( BindingImpl < ? > binding : candidateBindings ) { if ( isEagerSingleton ( injector , binding , stage ) ) { Dependency < ? > dependency = Dependency . get ( binding . getKey ( ) ) ; Dependency previous = context . pushDependency ( dependency , binding . getSource ( ) ) ; try { binding . getInternalFactory ( ) . get ( context , dependency , false ) ; } catch ( InternalProvisionException e ) { errors . withSource ( dependency ) . merge ( e ) ; } finally { context . popStateAndSetDependency ( previous ) ; } } } } finally { context . close ( ) ; } } | Loads eager singletons or all singletons if we re in Stage . PRODUCTION . Bindings discovered while we re binding these singletons are not be eager . |
3,074 | static void validateExceptions ( Binder binder , Iterable < TypeLiteral < ? > > actualExceptionTypes , Iterable < Class < ? extends Throwable > > expectedExceptionTypes , Class < ? extends CheckedProvider > checkedProvider ) { for ( TypeLiteral < ? > exType : actualExceptionTypes ) { Class < ? > exActual = exType . getRawType ( ) ; if ( RuntimeException . class . isAssignableFrom ( exActual ) || Error . class . isAssignableFrom ( exActual ) ) { continue ; } boolean notAssignable = true ; for ( Class < ? extends Throwable > exExpected : expectedExceptionTypes ) { if ( exExpected . isAssignableFrom ( exActual ) ) { notAssignable = false ; break ; } } if ( notAssignable ) { binder . addError ( "%s is not compatible with the exceptions (%s) declared in " + "the CheckedProvider interface (%s)" , exActual , expectedExceptionTypes , checkedProvider ) ; } } } | Adds errors to the binder if the exceptions aren t valid . |
3,075 | private static Object invokeJavaOptionalOf ( Object o ) { try { return JAVA_OPTIONAL_OF_METHOD . invoke ( null , o ) ; } catch ( IllegalAccessException e ) { throw new SecurityException ( e ) ; } catch ( IllegalArgumentException e ) { throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { throw Throwables . propagate ( e . getCause ( ) ) ; } } | Invokes java . util . Optional . of . |
3,076 | boolean service ( ServletRequest servletRequest , ServletResponse servletResponse ) throws IOException , ServletException { final HttpServletRequest request = ( HttpServletRequest ) servletRequest ; final String path = ServletUtils . getContextRelativePath ( request ) ; final boolean serve = shouldServe ( path ) ; if ( serve ) { doService ( servletRequest , servletResponse ) ; } return serve ; } | Wrapper around the service chain to ensure a servlet is servicing what it must and provides it with a wrapped request . |
3,077 | public static < T > Matcher < T > not ( final Matcher < ? super T > p ) { return new Not < T > ( p ) ; } | Inverts the given matcher . |
3,078 | private static final HadoopPath toHadoopPath ( Path path ) { if ( path == null ) { throw new NullPointerException ( ) ; } if ( ! ( path instanceof HadoopPath ) ) { throw new ProviderMismatchException ( ) ; } return ( HadoopPath ) path ; } | Checks that the given file is a HadoopPath |
3,079 | private static void bindLogger ( InjectorImpl injector ) { Key < Logger > key = Key . get ( Logger . class ) ; LoggerFactory loggerFactory = new LoggerFactory ( ) ; injector . state . putBinding ( key , new ProviderInstanceBindingImpl < Logger > ( injector , key , SourceProvider . UNKNOWN_SOURCE , loggerFactory , Scoping . UNSCOPED , loggerFactory , ImmutableSet . < InjectionPoint > of ( ) ) ) ; try { Key < org . slf4j . Logger > slf4jKey = Key . get ( org . slf4j . Logger . class ) ; SLF4JLoggerFactory slf4jLoggerFactory = new SLF4JLoggerFactory ( injector ) ; injector . state . putBinding ( slf4jKey , new ProviderInstanceBindingImpl < org . slf4j . Logger > ( injector , slf4jKey , SourceProvider . UNKNOWN_SOURCE , slf4jLoggerFactory , Scoping . UNSCOPED , slf4jLoggerFactory , ImmutableSet . < InjectionPoint > of ( ) ) ) ; } catch ( Throwable e ) { } } | The Logger is a special case because it knows the injection point of the injected member . It s the only binding that does this . |
3,080 | public ConfigurationException withPartialValue ( Object partialValue ) { checkState ( this . partialValue == null , "Can't clobber existing partial value %s with %s" , this . partialValue , partialValue ) ; ConfigurationException result = new ConfigurationException ( messages ) ; result . partialValue = partialValue ; return result ; } | Returns a copy of this configuration exception with the specified partial value . |
3,081 | public static < T > Dependency < T > get ( Key < T > key ) { return new Dependency < T > ( null , MoreTypes . canonicalizeKey ( key ) , true , - 1 ) ; } | Returns a new dependency that is not attached to an injection point . The returned dependency is nullable . |
3,082 | public static Set < Dependency < ? > > forInjectionPoints ( Set < InjectionPoint > injectionPoints ) { List < Dependency < ? > > dependencies = Lists . newArrayList ( ) ; for ( InjectionPoint injectionPoint : injectionPoints ) { dependencies . addAll ( injectionPoint . getDependencies ( ) ) ; } return ImmutableSet . copyOf ( dependencies ) ; } | Returns the dependencies from the given injection points . |
3,083 | private byte [ ] normalize ( byte [ ] path ) { if ( path . length == 0 ) return path ; byte prevC = 0 ; for ( int i = 0 ; i < path . length ; i ++ ) { byte c = path [ i ] ; if ( c == '\\' ) return normalize ( path , i ) ; if ( c == ( byte ) '/' && prevC == '/' ) return normalize ( path , i - 1 ) ; if ( c == '\u0000' ) throw new InvalidPathException ( this . hdfs . getString ( path ) , "Path: nul character not allowed" ) ; prevC = c ; } return path ; } | and check for invalid characters |
3,084 | public org . apache . hadoop . fs . Path getRawResolvedPath ( ) { return new org . apache . hadoop . fs . Path ( "hdfs://" + hdfs . getHost ( ) + ":" + hdfs . getPort ( ) + new String ( getResolvedPath ( ) ) ) ; } | Helper to get the raw interface of HDFS path . |
3,085 | private void initOffsets ( ) { if ( offsets == null ) { int count ; int index ; count = 0 ; index = 0 ; while ( index < path . length ) { byte c = path [ index ++ ] ; if ( c != '/' ) { count ++ ; while ( index < path . length && path [ index ] != '/' ) index ++ ; } } int [ ] result = new int [ count ] ; count = 0 ; index = 0 ; while ( index < path . length ) { byte c = path [ index ] ; if ( c == '/' ) { index ++ ; } else { result [ count ++ ] = index ++ ; while ( index < path . length && path [ index ] != '/' ) index ++ ; } } synchronized ( this ) { if ( offsets == null ) offsets = result ; } } } | create offset list if not already created |
3,086 | public Storage < S > storageDelegate ( StorableIndex < S > index ) { if ( mAllIndexInfoMap . get ( index ) instanceof ManagedIndex ) { return null ; } return mMasterStorage ; } | Required by StorageAccess . |
3,087 | public static String makePlainDescriptor ( Class < ? extends Annotation > annotationType ) { return "" + TAG_ANNOTATION + TypeDesc . forClass ( annotationType ) . getDescriptor ( ) ; } | Returns an annotation descriptor that has no parameters . |
3,088 | private void writeObject ( ObjectOutputStream out ) throws IOException { Storable s = mStorable ; if ( s == null ) { out . write ( 0 ) ; } else { out . write ( 1 ) ; out . writeObject ( s . storableType ( ) ) ; try { s . writeTo ( out ) ; } catch ( SupportException e ) { throw new IOException ( e ) ; } } } | server is identical . Linking into the actual repository is a bit trickier . |
3,089 | public static byte [ ] compress ( byte [ ] value , int prefix ) throws SupportException { Deflater compressor = cLocalDeflater . get ( ) ; if ( compressor == null ) { cLocalDeflater . set ( compressor = new Deflater ( ) ) ; } ByteArrayOutputStream bos = new ByteArrayOutputStream ( value . length ) ; try { bos . write ( value , 0 , prefix ) ; DeflaterOutputStream dout = new DeflaterOutputStream ( bos , compressor ) ; dout . write ( value , prefix , value . length - prefix ) ; dout . close ( ) ; return bos . toByteArray ( ) ; } catch ( IOException e ) { throw new SupportException ( e ) ; } finally { compressor . reset ( ) ; } } | Encodes into compressed form . |
3,090 | public static byte [ ] decompress ( byte [ ] value , int prefix ) throws CorruptEncodingException { Inflater inflater = cLocalInflater . get ( ) ; if ( inflater == null ) { cLocalInflater . set ( inflater = new Inflater ( ) ) ; } ByteArrayOutputStream bos = new ByteArrayOutputStream ( value . length * 2 ) ; try { bos . write ( value , 0 , prefix ) ; InflaterOutputStream ios = new InflaterOutputStream ( bos , inflater ) ; ios . write ( value , prefix , value . length - prefix ) ; ios . close ( ) ; return bos . toByteArray ( ) ; } catch ( ZipException e ) { return value ; } catch ( IOException e ) { throw new CorruptEncodingException ( e ) ; } finally { inflater . reset ( ) ; } } | Decodes from compressed form . |
3,091 | private static < S extends Storable > String [ ] selectNaturalOrder ( Repository repo , Class < S > type , Filter < S > filter ) throws RepositoryException { if ( ! filter . isOpen ( ) && repo instanceof RepositoryAccess ) { UnionQueryAnalyzer . Result result = new UnionQueryAnalyzer ( type , ( RepositoryAccess ) repo ) . analyze ( filter , null , QueryHints . emptyHints ( ) . with ( QueryHint . CONSUME_SLICE ) ) ; OrderingList < S > ordering = result . getTotalOrdering ( ) ; if ( ordering == null ) { List < IndexedQueryAnalyzer . Result > list = result . getSubResults ( ) ; if ( ! list . isEmpty ( ) ) { StorableIndex < S > index = list . get ( 0 ) . getLocalIndex ( ) ; if ( index != null ) { ordering = OrderingList . get ( index . getOrderedProperties ( ) ) ; } } } if ( ordering != null ) { String [ ] props = new String [ ordering . size ( ) ] ; for ( int i = 0 ; i < props . length ; i ++ ) { props [ i ] = ordering . get ( i ) . toString ( ) ; } return props ; } } IndexInfoCapability capability = repo . getCapability ( IndexInfoCapability . class ) ; if ( capability == null ) { return null ; } IndexInfo info = null ; for ( IndexInfo candidate : capability . getIndexInfo ( type ) ) { if ( candidate . isClustered ( ) ) { info = candidate ; break ; } } if ( info == null ) { return null ; } Set < String > pkSet = StorableIntrospector . examine ( type ) . getPrimaryKeyProperties ( ) . keySet ( ) ; String [ ] propNames = info . getPropertyNames ( ) ; for ( String prop : propNames ) { if ( ! pkSet . contains ( prop ) ) { return null ; } } String [ ] orderBy = new String [ pkSet . size ( ) ] ; Direction [ ] directions = info . getPropertyDirections ( ) ; pkSet = new LinkedHashSet < String > ( pkSet ) ; int i ; for ( i = 0 ; i < propNames . length ; i ++ ) { orderBy [ i ] = ( ( directions [ i ] == Direction . DESCENDING ) ? "-" : "+" ) + propNames [ i ] ; pkSet . remove ( propNames [ i ] ) ; } if ( pkSet . size ( ) > 0 ) { for ( String prop : pkSet ) { orderBy [ i ++ ] = prop ; } } return orderBy ; } | Utility method to select the natural ordering of a storage by looking for a clustered index on the primary key . Returns null if no clustered index was found . If a filter is provided the ordering which utilizes the best index is used . |
3,092 | public Transaction enter ( IsolationLevel level ) { mLock . lock ( ) ; try { TransactionImpl < Txn > parent = mActive ; IsolationLevel actualLevel = mTxnMgr . selectIsolationLevel ( parent , level ) ; if ( actualLevel == null ) { if ( parent == null ) { throw new UnsupportedOperationException ( "Desired isolation level not supported: " + level ) ; } else { throw new UnsupportedOperationException ( "Desired isolation level not supported: " + level + "; parent isolation level: " + parent . getIsolationLevel ( ) ) ; } } TransactionImpl < Txn > txn = new TransactionImpl < Txn > ( this , parent , false , actualLevel ) ; mActive = txn ; mTxnMgr . entered ( txn , parent ) ; return txn ; } finally { mLock . unlock ( ) ; } } | Enters a new transaction scope which becomes the active transaction . |
3,093 | public Transaction enterTop ( IsolationLevel level ) { mLock . lock ( ) ; try { IsolationLevel actualLevel = mTxnMgr . selectIsolationLevel ( null , level ) ; if ( actualLevel == null ) { throw new UnsupportedOperationException ( "Desired isolation level not supported: " + level ) ; } TransactionImpl < Txn > txn = new TransactionImpl < Txn > ( this , mActive , true , actualLevel ) ; mActive = txn ; mTxnMgr . entered ( txn , null ) ; return txn ; } finally { mLock . unlock ( ) ; } } | Enters a new top - level transaction scope which becomes the active transaction . |
3,094 | void exited ( TransactionImpl < Txn > txn , TransactionImpl < Txn > active ) { mActive = active ; mTxnMgr . exited ( txn , active ) ; } | Called by TransactionImpl with lock held . |
3,095 | public < S extends Storable > void register ( Class < S > type , Cursor < S > cursor ) { mLock . lock ( ) ; try { checkClosed ( ) ; if ( mCursors == null ) { mCursors = new IdentityHashMap < Class < ? > , CursorList < TransactionImpl < Txn > > > ( ) ; } CursorList < TransactionImpl < Txn > > cursorList = mCursors . get ( type ) ; if ( cursorList == null ) { cursorList = new CursorList < TransactionImpl < Txn > > ( ) ; mCursors . put ( type , cursorList ) ; } cursorList . register ( cursor , mActive ) ; if ( mActive != null ) { mActive . register ( cursor ) ; } } finally { mLock . unlock ( ) ; } } | Registers the given cursor against the active transaction allowing it to be closed on transaction exit or transaction manager close . If there is no active transaction in scope the cursor is registered as not part of a transaction . Cursors should register when created . |
3,096 | public < S extends Storable > void unregister ( Class < S > type , Cursor < S > cursor ) { mLock . lock ( ) ; try { if ( mCursors != null ) { CursorList < TransactionImpl < Txn > > cursorList = mCursors . get ( type ) ; if ( cursorList != null ) { TransactionImpl < Txn > txnImpl = cursorList . unregister ( cursor ) ; if ( txnImpl != null ) { txnImpl . unregister ( cursor ) ; } } } } finally { mLock . unlock ( ) ; } } | Unregisters a previously registered cursor . Cursors should unregister when closed . |
3,097 | public Txn getTxn ( ) throws Exception { mLock . lock ( ) ; try { checkClosed ( ) ; return mActive == null ? null : mActive . getTxn ( ) ; } finally { mLock . unlock ( ) ; } } | Returns the implementation for the active transaction or null if there is no active transaction . |
3,098 | public boolean isForUpdate ( ) { mLock . lock ( ) ; try { return ( mClosed || mActive == null ) ? false : mActive . isForUpdate ( ) ; } finally { mLock . unlock ( ) ; } } | Returns true if an active transaction exists and it is for update . |
3,099 | public IsolationLevel getIsolationLevel ( ) { mLock . lock ( ) ; try { return ( mClosed || mActive == null ) ? null : mActive . getIsolationLevel ( ) ; } finally { mLock . unlock ( ) ; } } | Returns the isolation level of the active transaction or null if there is no active transaction . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.