idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
154,000
protected void acquireAccessToken ( final OAuthCallback cb ) { if ( isAccessTokenCached ( ) ) { if ( VERBOSE ) Log . d ( TAG , "Access token cached" ) ; if ( cb != null ) { new Thread ( new Runnable ( ) { public void run ( ) { cb . onSuccess ( getRequestFactoryFromCachedCredentials ( ) ) ; } } ) . start ( ) ; } } else ...
Asynchronously attempt to acquire an OAuth Access Token
154,001
protected void executeQueuedCallbacks ( ) { if ( VERBOSE ) Log . i ( TAG , String . format ( "Executing %d queued callbacks" , mCallbackQueue . size ( ) ) ) ; for ( OAuthCallback cb : mCallbackQueue ) { cb . onSuccess ( getRequestFactoryFromCachedCredentials ( ) ) ; } }
Execute queued callbacks once valid OAuth credentials are acquired .
154,002
private void captureH264MetaData ( ByteBuffer encodedData , MediaCodec . BufferInfo bufferInfo ) { mH264MetaSize = bufferInfo . size ; mH264Keyframe = ByteBuffer . allocateDirect ( encodedData . capacity ( ) ) ; byte [ ] videoConfig = new byte [ bufferInfo . size ] ; encodedData . get ( videoConfig , bufferInfo . offse...
Should only be called once when the encoder produces an output buffer with the BUFFER_FLAG_CODEC_CONFIG flag . For H264 output this indicates the Sequence Parameter Set and Picture Parameter Set are contained in the buffer . These NAL units are required before every keyframe to ensure playback is possible in a segmente...
154,003
private void packageH264Keyframe ( ByteBuffer encodedData , MediaCodec . BufferInfo bufferInfo ) { mH264Keyframe . position ( mH264MetaSize ) ; mH264Keyframe . put ( encodedData ) ; }
Adds the SPS + PPS data to the ByteBuffer containing a h264 keyframe
154,004
public void handleTouchEvent ( MotionEvent ev ) { if ( ev . getAction ( ) == MotionEvent . ACTION_MOVE ) { if ( mTexHeight != 0 && mTexWidth != 0 ) { mSummedTouchPosition [ 0 ] += ( 2 * ( ev . getX ( ) - mLastTouchPosition [ 0 ] ) ) / mTexWidth ; mSummedTouchPosition [ 1 ] += ( 2 * ( ev . getY ( ) - mLastTouchPosition ...
Configures the effect offset
154,005
public void setKernel ( float [ ] values , float colorAdj ) { if ( values . length != KERNEL_SIZE ) { throw new IllegalArgumentException ( "Kernel size is " + values . length + " vs. " + KERNEL_SIZE ) ; } System . arraycopy ( values , 0 , mKernel , 0 , KERNEL_SIZE ) ; mColorAdjust = colorAdj ; }
Configures the convolution filter values . This only has an effect for programs that use the FRAGMENT_SHADER_EXT_FILT Fragment shader .
154,006
public void setTexSize ( int width , int height ) { mTexHeight = height ; mTexWidth = width ; float rw = 1.0f / width ; float rh = 1.0f / height ; mTexOffset = new float [ ] { - rw , - rh , 0f , - rh , rw , - rh , - rw , 0f , 0f , 0f , rw , 0f , - rw , rh , 0f , rh , rw , rh } ; }
Sets the size of the texture . This is used to find adjacent texels when filtering .
154,007
public void draw ( float [ ] mvpMatrix , FloatBuffer vertexBuffer , int firstVertex , int vertexCount , int coordsPerVertex , int vertexStride , float [ ] texMatrix , FloatBuffer texBuffer , int textureId , int texStride ) { GlUtil . checkGlError ( "draw start" ) ; GLES20 . glUseProgram ( mProgramHandle ) ; GlUtil . ch...
Issues the draw call . Does the full setup on every call .
154,008
public static void getLastKnownLocation ( Context context , boolean waitForGpsFix , final LocationResult cb ) { DeviceLocation deviceLocation = new DeviceLocation ( ) ; LocationManager lm = ( LocationManager ) context . getSystemService ( Context . LOCATION_SERVICE ) ; Location last_loc ; last_loc = lm . getLastKnownLo...
Get the last known location . If one is not available fetch a fresh location
154,009
public static KickflipApiClient getApiClient ( Context context , KickflipCallback callback ) { checkNotNull ( sClientKey ) ; checkNotNull ( sClientSecret ) ; if ( sKickflip == null || ! sKickflip . getConfig ( ) . getClientId ( ) . equals ( sClientKey ) ) { sKickflip = new KickflipApiClient ( context , sClientKey , sCl...
Create a new instance of the KickflipApiClient if one hasn t yet been created or the provided API keys don t match the existing client .
154,010
public void loginUser ( String username , final String password , final KickflipCallback cb ) { GenericData data = new GenericData ( ) ; data . put ( "username" , username ) ; data . put ( "password" , password ) ; post ( GET_USER_PRIVATE , new UrlEncodedContent ( data ) , User . class , new KickflipCallback ( ) { publ...
Login an exiting Kickflip User and make it active .
154,011
public void setUserInfo ( final String newPassword , String email , String displayName , Map extraInfo , final KickflipCallback cb ) { if ( ! assertActiveUserAvailable ( cb ) ) return ; GenericData data = new GenericData ( ) ; final String finalPassword ; if ( newPassword != null ) { data . put ( "new_password" , newPa...
Set the current active user s meta info . Pass a null argument to leave it as - is .
154,012
public void getUserInfo ( String username , final KickflipCallback cb ) { if ( ! assertActiveUserAvailable ( cb ) ) return ; GenericData data = new GenericData ( ) ; data . put ( "username" , username ) ; post ( GET_USER_PUBLIC , new UrlEncodedContent ( data ) , User . class , new KickflipCallback ( ) { public void onS...
Get public user info
154,013
private void stopStream ( User user , Stream stream , final KickflipCallback cb ) { checkNotNull ( stream ) ; GenericData data = new GenericData ( ) ; data . put ( "stream_id" , stream . getStreamId ( ) ) ; data . put ( "uuid" , user . getUUID ( ) ) ; if ( stream . getLatitude ( ) != 0 ) { data . put ( "lat" , stream ....
Stop a Stream owned by the given Kickflip User .
154,014
private void handleKickflipResponse ( HttpResponse response , Class < ? extends Response > responseClass , KickflipCallback cb ) throws IOException { if ( cb == null ) return ; HashMap responseMap = null ; Response kickFlipResponse = response . parseAs ( responseClass ) ; if ( VERBOSE ) Log . i ( TAG , String . format ...
Parse the HttpResponse as the appropriate Response subclass
154,015
public static File getRootStorageDirectory ( Context c , String directory_name ) { File result ; if ( Environment . getExternalStorageState ( ) . equals ( Environment . MEDIA_MOUNTED ) ) { Log . d ( TAG , "Using sdcard" ) ; result = new File ( Environment . getExternalStorageDirectory ( ) , directory_name ) ; } else { ...
Returns a Java File initialized to a directory of given name at the root storage location with preference to external storage . If the directory did not exist it will be created at the conclusion of this call . If a file with conflicting name exists this method returns null ;
154,016
public static File getStorageDirectory ( File parent_directory , String new_child_directory_name ) { File result = new File ( parent_directory , new_child_directory_name ) ; if ( ! result . exists ( ) ) if ( result . mkdir ( ) ) return result ; else { Log . e ( "getStorageDirectory" , "Error creating " + result . getAb...
Returns a Java File initialized to a directory of given name within the given location .
154,017
public static File createTempFile ( Context c , File root , String filename , String extension ) { File output = null ; try { if ( filename != null ) { if ( ! extension . contains ( "." ) ) extension = "." + extension ; output = new File ( root , filename + extension ) ; output . createNewFile ( ) ; Log . i ( TAG , "Cr...
Returns a TempFile with given root filename and extension . The resulting TempFile is safe for use with Android s MediaRecorder
154,018
public static String tail2 ( File file , int lines ) { lines ++ ; java . io . RandomAccessFile fileHandler = null ; try { fileHandler = new java . io . RandomAccessFile ( file , "r" ) ; long fileLength = fileHandler . length ( ) - 1 ; StringBuilder sb = new StringBuilder ( ) ; int line = 0 ; for ( long filePointer = fi...
Read the last few lines of a file
154,019
public static void deleteDirectory ( File fileOrDirectory ) { if ( fileOrDirectory . isDirectory ( ) ) for ( File child : fileOrDirectory . listFiles ( ) ) deleteDirectory ( child ) ; fileOrDirectory . delete ( ) ; }
Delete a directory and all its contents
154,020
protected long getNextRelativePts ( long absPts , int trackIndex ) { if ( mFirstPts == 0 ) { mFirstPts = absPts ; return 0 ; } return getSafePts ( absPts - mFirstPts , trackIndex ) ; }
Return a relative pts given an absolute pts and trackIndex .
154,021
private long getSafePts ( long pts , int trackIndex ) { if ( mLastPts [ trackIndex ] >= pts ) { mLastPts [ trackIndex ] += 9643 ; return mLastPts [ trackIndex ] ; } mLastPts [ trackIndex ] = pts ; return pts ; }
Sometimes packets with non - increasing pts are dequeued from the MediaCodec output buffer . This method ensures that a crash won t occur due to non monotonically increasing packet timestamp .
154,022
public static void updateFilter ( FullFrameRect rect , int newFilter ) { Texture2dProgram . ProgramType programType ; float [ ] kernel = null ; float colorAdj = 0.0f ; if ( VERBOSE ) Log . d ( TAG , "Updating filter to " + newFilter ) ; switch ( newFilter ) { case FILTER_NONE : programType = Texture2dProgram . ProgramT...
Updates the filter on the provided FullFrameRect
154,023
public void drawFrame ( int textureId , float [ ] texMatrix ) { mProgram . draw ( IDENTITY_MATRIX , mRectDrawable . getVertexArray ( ) , 0 , mRectDrawable . getVertexCount ( ) , mRectDrawable . getCoordsPerVertex ( ) , mRectDrawable . getVertexStride ( ) , texMatrix , TEX_COORDS_BUF , textureId , TEX_COORDS_STRIDE ) ; ...
Draws a rectangle in an area defined by TEX_COORDS
154,024
protected boolean isOneShotQuery ( CachedQuery cachedQuery ) { if ( cachedQuery == null ) { return true ; } cachedQuery . increaseExecuteCount ( ) ; if ( ( mPrepareThreshold == 0 || cachedQuery . getExecuteCount ( ) < mPrepareThreshold ) && ! getForceBinaryTransfer ( ) ) { return true ; } return false ; }
Returns true if query is unlikely to be reused .
154,025
public void setQueryTimeoutMs ( long millis ) throws SQLException { checkClosed ( ) ; if ( millis < 0 ) { throw new PSQLException ( GT . tr ( "Query timeout must be a value greater than or equals to 0." ) , PSQLState . INVALID_PARAMETER_VALUE ) ; } timeout = millis ; }
Sets the queryTimeout limit .
154,026
public void close ( ) throws SQLException { if ( last != null ) { last . close ( ) ; if ( ! con . isClosed ( ) ) { if ( ! con . getAutoCommit ( ) ) { try { con . rollback ( ) ; } catch ( SQLException ignored ) { } } } } try { con . close ( ) ; } finally { con = null ; } }
Closes the physical database connection represented by this PooledConnection . If any client has a connection based on this PooledConnection it is forcibly closed as well .
154,027
public Connection getConnection ( ) throws SQLException { if ( con == null ) { PSQLException sqlException = new PSQLException ( GT . tr ( "This PooledConnection has already been closed." ) , PSQLState . CONNECTION_DOES_NOT_EXIST ) ; fireConnectionFatalError ( sqlException ) ; throw sqlException ; } try { if ( last != n...
Gets a handle for a client to use . This is a wrapper around the physical connection so the client can call close and it will just return the connection to the pool without really closing the pgysical connection .
154,028
void fireConnectionClosed ( ) { ConnectionEvent evt = null ; ConnectionEventListener [ ] local = listeners . toArray ( new ConnectionEventListener [ 0 ] ) ; for ( ConnectionEventListener listener : local ) { if ( evt == null ) { evt = createConnectionEvent ( null ) ; } listener . connectionClosed ( evt ) ; } }
Used to fire a connection closed event to all listeners .
154,029
public int read ( ) throws java . io . IOException { checkClosed ( ) ; try { if ( limit > 0 && apos >= limit ) { return - 1 ; } if ( buffer == null || bpos >= buffer . length ) { buffer = lo . read ( bsize ) ; bpos = 0 ; } if ( bpos >= buffer . length ) { return - 1 ; } int ret = ( buffer [ bpos ] & 0x7F ) ; if ( ( buf...
The minimum required to implement input stream .
154,030
public synchronized Value borrow ( Key key ) throws SQLException { Value value = cache . remove ( key ) ; if ( value == null ) { return createAction . create ( key ) ; } currentSize -= value . getSize ( ) ; return value ; }
Borrows an entry from the cache .
154,031
public synchronized void put ( Key key , Value value ) { long valueSize = value . getSize ( ) ; if ( maxSizeBytes == 0 || maxSizeEntries == 0 || valueSize * 2 > maxSizeBytes ) { evictValue ( value ) ; return ; } currentSize += valueSize ; Value prev = cache . put ( key , value ) ; if ( prev == null ) { return ; } curre...
Returns given value to the cache .
154,032
public synchronized void putAll ( Map < Key , Value > m ) { for ( Map . Entry < Key , Value > entry : m . entrySet ( ) ) { this . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } }
Puts all the values from the given map into the cache .
154,033
private void lock ( Object obtainer ) throws PSQLException { if ( lockedFor == obtainer ) { throw new PSQLException ( GT . tr ( "Tried to obtain lock while already holding it" ) , PSQLState . OBJECT_NOT_IN_STATE ) ; } waitOnLock ( ) ; lockedFor = obtainer ; }
Obtain lock over this connection for given object blocking to wait if necessary .
154,034
private void unlock ( Object holder ) throws PSQLException { if ( lockedFor != holder ) { throw new PSQLException ( GT . tr ( "Tried to break lock on database connection" ) , PSQLState . OBJECT_NOT_IN_STATE ) ; } lockedFor = null ; this . notify ( ) ; }
Release lock on this connection presumably held by given object .
154,035
private void waitOnLock ( ) throws PSQLException { while ( lockedFor != null ) { try { this . wait ( ) ; } catch ( InterruptedException ie ) { Thread . currentThread ( ) . interrupt ( ) ; throw new PSQLException ( GT . tr ( "Interrupted while waiting to obtain lock on database connection" ) , PSQLState . OBJECT_NOT_IN_...
Wait until our lock is released . Execution of a single synchronized method can then continue without further ado . Must be called at beginning of each synchronized public method .
154,036
public synchronized CopyOperation startCopy ( String sql , boolean suppressBegin ) throws SQLException { waitOnLock ( ) ; if ( ! suppressBegin ) { doSubprotocolBegin ( ) ; } byte [ ] buf = Utils . encodeUTF8 ( sql ) ; try { LOGGER . log ( Level . FINEST , " FE=> Query(CopyStart)" ) ; pgStream . sendChar ( 'Q' ) ; pgStr...
Sends given query to BE to start initialize and lock connection for a CopyOperation .
154,037
private synchronized void initCopy ( CopyOperationImpl op ) throws SQLException , IOException { pgStream . receiveInteger4 ( ) ; int rowFormat = pgStream . receiveChar ( ) ; int numFields = pgStream . receiveInteger2 ( ) ; int [ ] fieldFormats = new int [ numFields ] ; for ( int i = 0 ; i < numFields ; i ++ ) { fieldFo...
Locks connection and calls initializer for a new CopyOperation Called via startCopy - > processCopyResults .
154,038
public void cancelCopy ( CopyOperationImpl op ) throws SQLException { if ( ! hasLock ( op ) ) { throw new PSQLException ( GT . tr ( "Tried to cancel an inactive copy operation" ) , PSQLState . OBJECT_NOT_IN_STATE ) ; } SQLException error = null ; int errors = 0 ; try { if ( op instanceof CopyIn ) { synchronized ( this ...
Finishes a copy operation and unlocks connection discarding any exchanged data .
154,039
public synchronized long endCopy ( CopyOperationImpl op ) throws SQLException { if ( ! hasLock ( op ) ) { throw new PSQLException ( GT . tr ( "Tried to end inactive copy" ) , PSQLState . OBJECT_NOT_IN_STATE ) ; } try { LOGGER . log ( Level . FINEST , " FE=> CopyDone" ) ; pgStream . sendChar ( 'c' ) ; pgStream . sendInt...
Finishes writing to copy and unlocks connection .
154,040
public synchronized void writeToCopy ( CopyOperationImpl op , byte [ ] data , int off , int siz ) throws SQLException { if ( ! hasLock ( op ) ) { throw new PSQLException ( GT . tr ( "Tried to write to an inactive copy operation" ) , PSQLState . OBJECT_NOT_IN_STATE ) ; } LOGGER . log ( Level . FINEST , " FE=> CopyData({...
Sends data during a live COPY IN operation . Only unlocks the connection if server suddenly returns CommandComplete which should not happen
154,041
public static String toHexString ( byte [ ] data ) { StringBuilder sb = new StringBuilder ( data . length * 2 ) ; for ( byte element : data ) { sb . append ( Integer . toHexString ( ( element >> 4 ) & 15 ) ) ; sb . append ( Integer . toHexString ( element & 15 ) ) ; } return sb . toString ( ) ; }
Turn a bytearray into a printable form representing each byte in hex .
154,042
private static void doAppendEscapedIdentifier ( Appendable sbuf , String value ) throws SQLException { try { sbuf . append ( '"' ) ; for ( int i = 0 ; i < value . length ( ) ; ++ i ) { char ch = value . charAt ( i ) ; if ( ch == '\0' ) { throw new PSQLException ( GT . tr ( "Zero bytes may not occur in identifiers." ) ,...
Common part for appendEscapedIdentifier .
154,043
public int getInteger ( String name , FastpathArg [ ] args ) throws SQLException { byte [ ] returnValue = fastpath ( name , args ) ; if ( returnValue == null ) { throw new PSQLException ( GT . tr ( "Fastpath call {0} - No result was returned and we expected an integer." , name ) , PSQLState . NO_DATA ) ; } if ( returnV...
This convenience method assumes that the return value is an integer .
154,044
public long getOID ( String name , FastpathArg [ ] args ) throws SQLException { long oid = getInteger ( name , args ) ; if ( oid < 0 ) { oid += NUM_OIDS ; } return oid ; }
This convenience method assumes that the return value is an oid .
154,045
public static FastpathArg createOIDArg ( long oid ) { if ( oid > Integer . MAX_VALUE ) { oid -= NUM_OIDS ; } return new FastpathArg ( ( int ) oid ) ; }
Creates a FastpathArg with an oid parameter . This is here instead of a constructor of FastpathArg because the constructor can t tell the difference between an long that s really int8 and a long thats an oid .
154,046
public Object getObjectInstance ( Object obj , Name name , Context nameCtx , Hashtable < ? , ? > environment ) throws Exception { Reference ref = ( Reference ) obj ; String className = ref . getClassName ( ) ; if ( className . equals ( "org.postgresql.ds.PGSimpleDataSource" ) || className . equals ( "org.postgresql.jdb...
Dereferences a PostgreSQL DataSource . Other types of references are ignored .
154,047
public void setDataSourceName ( String dataSourceName ) { if ( initialized ) { throw new IllegalStateException ( "Cannot set Data Source properties after DataSource has been used" ) ; } if ( this . dataSourceName != null && dataSourceName != null && dataSourceName . equals ( this . dataSourceName ) ) { return ; } PGPoo...
Sets the name of this DataSource . This is required and uniquely identifies the DataSource . You cannot create or use more than one DataSource in the same VM with the same name .
154,048
public void initialize ( ) throws SQLException { synchronized ( lock ) { source = createConnectionPool ( ) ; try { source . initializeFrom ( this ) ; } catch ( Exception e ) { throw new PSQLException ( GT . tr ( "Failed to setup DataSource." ) , PSQLState . UNEXPECTED_ERROR , e ) ; } while ( available . size ( ) < init...
Initializes this DataSource . If the initialConnections is greater than zero that number of connections will be created . After this method is called the DataSource properties cannot be changed . If you do not call this explicitly it will be called the first time you get a connection from the DataSource .
154,049
public void close ( ) { synchronized ( lock ) { while ( ! available . isEmpty ( ) ) { PooledConnection pci = available . pop ( ) ; try { pci . close ( ) ; } catch ( SQLException e ) { } } available = null ; while ( ! used . isEmpty ( ) ) { PooledConnection pci = used . pop ( ) ; pci . removeConnectionEventListener ( co...
Closes this DataSource and all the pooled connections whether in use or not .
154,050
private Connection getPooledConnection ( ) throws SQLException { PooledConnection pc = null ; synchronized ( lock ) { if ( available == null ) { throw new PSQLException ( GT . tr ( "DataSource has been closed." ) , PSQLState . CONNECTION_DOES_NOT_EXIST ) ; } while ( true ) { if ( ! available . isEmpty ( ) ) { pc = avai...
Gets a connection from the pool . Will get an available one if present or create a new one if under the max limit . Will block if all used and a new one would exceed the max .
154,051
public Reference getReference ( ) throws NamingException { Reference ref = super . getReference ( ) ; ref . add ( new StringRefAddr ( "dataSourceName" , dataSourceName ) ) ; if ( initialConnections > 0 ) { ref . add ( new StringRefAddr ( "initialConnections" , Integer . toString ( initialConnections ) ) ) ; } if ( maxC...
Adds custom properties for this DataSource to the properties defined in the superclass .
154,052
void setFields ( Field [ ] fields ) { this . fields = fields ; this . resultSetColumnNameIndexMap = null ; this . cachedMaxResultRowSize = null ; this . needUpdateFieldFormats = fields != null ; this . hasBinaryFields = false ; }
Sets the fields that this query will return .
154,053
public synchronized Timestamp toTimestamp ( Calendar cal , String s ) throws SQLException { if ( s == null ) { return null ; } int slen = s . length ( ) ; if ( slen == 8 && s . equals ( "infinity" ) ) { return new Timestamp ( PGStatement . DATE_POSITIVE_INFINITY ) ; } if ( slen == 9 && s . equals ( "-infinity" ) ) { re...
Parse a string and return a timestamp representing its value .
154,054
public LocalTime toLocalTime ( String s ) throws SQLException { if ( s == null ) { return null ; } if ( s . equals ( "24:00:00" ) ) { return LocalTime . MAX ; } try { return LocalTime . parse ( s ) ; } catch ( DateTimeParseException nfe ) { throw new PSQLException ( GT . tr ( "Bad value for type timestamp/date/time: {1...
Parse a string and return a LocalTime representing its value .
154,055
public LocalDateTime toLocalDateTime ( String s ) throws SQLException { if ( s == null ) { return null ; } int slen = s . length ( ) ; if ( slen == 8 && s . equals ( "infinity" ) ) { return LocalDateTime . MAX ; } if ( slen == 9 && s . equals ( "-infinity" ) ) { return LocalDateTime . MIN ; } ParsedTimestamp ts = parse...
Parse a string and return a LocalDateTime representing its value .
154,056
public Calendar getSharedCalendar ( TimeZone timeZone ) { if ( timeZone == null ) { timeZone = getDefaultTz ( ) ; } Calendar tmp = calendarWithUserTz ; tmp . setTimeZone ( timeZone ) ; return tmp ; }
Get a shared calendar applying the supplied time zone or the default time zone if null .
154,057
public Date convertToDate ( long millis , TimeZone tz ) { if ( millis <= PGStatement . DATE_NEGATIVE_INFINITY || millis >= PGStatement . DATE_POSITIVE_INFINITY ) { return new Date ( millis ) ; } if ( tz == null ) { tz = getDefaultTz ( ) ; } if ( isSimpleTimeZone ( tz . getID ( ) ) ) { int offset = tz . getRawOffset ( )...
Extracts the date part from a timestamp .
154,058
public Time convertToTime ( long millis , TimeZone tz ) { if ( tz == null ) { tz = getDefaultTz ( ) ; } if ( isSimpleTimeZone ( tz . getID ( ) ) ) { int offset = tz . getRawOffset ( ) ; millis += offset ; millis = millis % ONEDAY ; millis -= offset ; return new Time ( millis ) ; } Calendar cal = calendarWithUserTz ; ca...
Extracts the time part from a timestamp . This method ensures the date part of output timestamp looks like 1970 - 01 - 01 in given timezone .
154,059
public String timeToString ( java . util . Date time , boolean withTimeZone ) { Calendar cal = null ; if ( withTimeZone ) { cal = calendarWithUserTz ; cal . setTimeZone ( timeZoneProvider . get ( ) ) ; } if ( time instanceof Timestamp ) { return toString ( cal , ( Timestamp ) time , withTimeZone ) ; } if ( time instanc...
Returns the given time value as String matching what the current postgresql server would send in text mode .
154,060
public XAConnection getXAConnection ( String user , String password ) throws SQLException { Connection con = super . getConnection ( user , password ) ; return new PGXAConnection ( ( BaseConnection ) con ) ; }
Gets a XA - enabled connection to the PostgreSQL database . The database is identified by the DataSource properties serverName databaseName and portNumber . The user to connect as is identified by the arguments user and password which override the DataSource properties by the same name .
154,061
public long copyOut ( final String sql , Writer to ) throws SQLException , IOException { byte [ ] buf ; CopyOut cp = copyOut ( sql ) ; try { while ( ( buf = cp . readFromCopy ( ) ) != null ) { to . write ( encoding . decode ( buf ) ) ; } return cp . getHandledRowCount ( ) ; } catch ( IOException ioEX ) { if ( cp . isAc...
Pass results of a COPY TO STDOUT query from database into a Writer .
154,062
public String getColumnClassName ( int column ) throws SQLException { Field field = getField ( column ) ; String result = connection . getTypeInfo ( ) . getJavaClass ( field . getOID ( ) ) ; if ( result != null ) { return result ; } int sqlType = getSQLType ( column ) ; switch ( sqlType ) { case Types . ARRAY : return ...
This can hook into our PG_Object mechanism
154,063
private static Connection makeConnection ( String url , Properties props ) throws SQLException { return new PgConnection ( hostSpecs ( props ) , user ( props ) , database ( props ) , props , url ) ; }
Create a connection from URL and properties . Always does the connection work in the current thread without enforcing a timeout regardless of any timeout specified in the properties .
154,064
public static SQLFeatureNotSupportedException notImplemented ( Class < ? > callClass , String functionName ) { return new SQLFeatureNotSupportedException ( GT . tr ( "Method {0} is not yet implemented." , callClass . getName ( ) + "." + functionName ) , PSQLState . NOT_IMPLEMENTED . getState ( ) ) ; }
This method was added in v6 . 5 and simply throws an SQLException for an unimplemented method . I decided to do it this way while implementing the JDBC2 extensions to JDBC as it should help keep the overall driver size down . It now requires the call Class and the function name to help when the driver is used with clos...
154,065
public void setValue ( int years , int months , int days , int hours , int minutes , double seconds ) { setYears ( years ) ; setMonths ( months ) ; setDays ( days ) ; setHours ( hours ) ; setMinutes ( minutes ) ; setSeconds ( seconds ) ; }
Set all values of this interval to the specified values .
154,066
public String getValue ( ) { return years + " years " + months + " mons " + days + " days " + hours + " hours " + minutes + " mins " + secondsFormat . format ( seconds ) + " secs" ; }
Returns the stored interval information as a string .
154,067
public void add ( Calendar cal ) { final int microseconds = ( int ) ( getSeconds ( ) * 1000000.0 ) ; final int milliseconds = ( microseconds + ( ( microseconds < 0 ) ? - 500 : 500 ) ) / 1000 ; cal . add ( Calendar . MILLISECOND , milliseconds ) ; cal . add ( Calendar . MINUTE , getMinutes ( ) ) ; cal . add ( Calendar ....
Rolls this interval on a given calendar .
154,068
public void add ( Date date ) { final Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( date ) ; add ( cal ) ; date . setTime ( cal . getTime ( ) . getTime ( ) ) ; }
Rolls this interval on a given date .
154,069
public void add ( PGInterval interval ) { interval . setYears ( interval . getYears ( ) + getYears ( ) ) ; interval . setMonths ( interval . getMonths ( ) + getMonths ( ) ) ; interval . setDays ( interval . getDays ( ) + getDays ( ) ) ; interval . setHours ( interval . getHours ( ) + getHours ( ) ) ; interval . setMinu...
Add this interval s value to the passed interval . This is backwards to what I would expect but this makes it match the other existing add methods .
154,070
public void addWarning ( SQLWarning warn ) { if ( firstWarning != null ) { firstWarning . setNextWarning ( warn ) ; } else { firstWarning = warn ; } }
This adds a warning to the warning chain .
154,071
private void initObjectTypes ( Properties info ) throws SQLException { addDataType ( "box" , org . postgresql . geometric . PGbox . class ) ; addDataType ( "circle" , org . postgresql . geometric . PGcircle . class ) ; addDataType ( "line" , org . postgresql . geometric . PGline . class ) ; addDataType ( "lseg" , org ....
This initialises the objectTypes hash map
154,072
public int getServerMajorVersion ( ) { try { StringTokenizer versionTokens = new StringTokenizer ( queryExecutor . getServerVersion ( ) , "." ) ; return integerPart ( versionTokens . nextToken ( ) ) ; } catch ( NoSuchElementException e ) { return 0 ; } }
Get server major version .
154,073
private static int integerPart ( String dirtyString ) { int start = 0 ; while ( start < dirtyString . length ( ) && ! Character . isDigit ( dirtyString . charAt ( start ) ) ) { ++ start ; } int end = start ; while ( end < dirtyString . length ( ) && Character . isDigit ( dirtyString . charAt ( end ) ) ) { ++ end ; } if...
Parse a dirty integer surrounded by non - numeric characters
154,074
public static LogSequenceNumber valueOf ( String strValue ) { int slashIndex = strValue . lastIndexOf ( '/' ) ; if ( slashIndex <= 0 ) { return INVALID_LSN ; } String logicalXLogStr = strValue . substring ( 0 , slashIndex ) ; int logicalXlog = ( int ) Long . parseLong ( logicalXLogStr , 16 ) ; String segmentStr = strVa...
Create LSN instance by string represent LSN .
154,075
public synchronized long position ( String pattern , long start ) throws SQLException { checkFreed ( ) ; throw org . postgresql . Driver . notImplemented ( this . getClass ( ) , "position(String,long)" ) ; }
For now this is not implemented .
154,076
static boolean castToBoolean ( final Object in ) throws PSQLException { if ( LOGGER . isLoggable ( Level . FINE ) ) { LOGGER . log ( Level . FINE , "Cast to boolean: \"{0}\"" , String . valueOf ( in ) ) ; } if ( in instanceof Boolean ) { return ( Boolean ) in ; } if ( in instanceof String ) { return fromString ( ( Stri...
Cast an Object value to the corresponding boolean value .
154,077
private static void checkByte ( int ch , int pos , int len ) throws IOException { if ( ( ch & 0xc0 ) != 0x80 ) { throw new IOException ( GT . tr ( "Illegal UTF-8 sequence: byte {0} of {1} byte sequence is not 10xxxxxx: {2}" , pos , len , ch ) ) ; } }
helper for decode
154,078
protected int getMaxIndexKeys ( ) throws SQLException { if ( indexMaxKeys == 0 ) { String sql ; sql = "SELECT setting FROM pg_catalog.pg_settings WHERE name='max_index_keys'" ; Statement stmt = connection . createStatement ( ) ; ResultSet rs = null ; try { rs = stmt . executeQuery ( sql ) ; if ( ! rs . next ( ) ) { stm...
maximum number of keys in an index .
154,079
protected String escapeQuotes ( String s ) throws SQLException { StringBuilder sb = new StringBuilder ( ) ; if ( ! connection . getStandardConformingStrings ( ) ) { sb . append ( "E" ) ; } sb . append ( "'" ) ; sb . append ( connection . escapeString ( s ) ) ; sb . append ( "'" ) ; return sb . toString ( ) ; }
Turn the provided value into a valid string literal for direct inclusion into a query . This includes the single quotes needed around it .
154,080
private static List < String > parseACLArray ( String aclString ) { List < String > acls = new ArrayList < String > ( ) ; if ( aclString == null || aclString . isEmpty ( ) ) { return acls ; } boolean inQuotes = false ; int beginIndex = 1 ; char prevChar = ' ' ; for ( int i = beginIndex ; i < aclString . length ( ) ; i ...
Parse an String of ACLs into a List of ACLs .
154,081
public static Object instantiate ( String classname , Properties info , boolean tryString , String stringarg ) throws ClassNotFoundException , SecurityException , NoSuchMethodException , IllegalArgumentException , InstantiationException , IllegalAccessException , InvocationTargetException { Object [ ] args = { info } ;...
Instantiates a class using the appropriate constructor . If a constructor with a single Propertiesparameter exists it is used . Otherwise if tryString is true a constructor with a single String argument is searched if it fails or tryString is true a no argument constructor is tried .
154,082
boolean isUpdateable ( ) throws SQLException { checkClosed ( ) ; if ( resultsetconcurrency == ResultSet . CONCUR_READ_ONLY ) { throw new PSQLException ( GT . tr ( "ResultSets with concurrency CONCUR_READ_ONLY cannot be updated." ) , PSQLState . INVALID_CURSOR_STATE ) ; } if ( updateable ) { return true ; } connection ....
Is this ResultSet updateable?
154,083
private double readDoubleValue ( byte [ ] bytes , int oid , String targetType ) throws PSQLException { switch ( oid ) { case Oid . INT2 : return ByteConverter . int2 ( bytes , 0 ) ; case Oid . INT4 : return ByteConverter . int4 ( bytes , 0 ) ; case Oid . INT8 : return ByteConverter . int8 ( bytes , 0 ) ; case Oid . FLO...
Converts any numeric binary field to double value . This method does no overflow checking .
154,084
private static String createPostgresTimeZone ( ) { String tz = TimeZone . getDefault ( ) . getID ( ) ; if ( tz . length ( ) <= 3 || ! tz . startsWith ( "GMT" ) ) { return tz ; } char sign = tz . charAt ( 3 ) ; String start ; switch ( sign ) { case '+' : start = "GMT-" ; break ; case '-' : start = "GMT+" ; break ; defau...
Convert Java time zone to postgres time zone . All others stay the same except that GMT + nn changes to GMT - nn and vise versa .
154,085
public void close ( ) throws SQLException { if ( ! closed ) { if ( os != null ) { try { os . flush ( ) ; } catch ( IOException ioe ) { throw new PSQLException ( "Exception flushing output stream" , PSQLState . DATA_ERROR , ioe ) ; } finally { os = null ; } } FastpathArg [ ] args = new FastpathArg [ 1 ] ; args [ 0 ] = n...
This method closes the object . You must not call methods in this object after this is called .
154,086
public int read ( byte [ ] buf , int off , int len ) throws SQLException { byte [ ] b = read ( len ) ; if ( b . length < len ) { len = b . length ; } System . arraycopy ( b , 0 , buf , off , len ) ; return len ; }
Reads some data from the object into an existing array .
154,087
public void write ( byte [ ] buf , int off , int len ) throws SQLException { FastpathArg [ ] args = new FastpathArg [ 2 ] ; args [ 0 ] = new FastpathArg ( fd ) ; args [ 1 ] = new FastpathArg ( buf , off , len ) ; fp . fastpath ( "lowrite" , args ) ; }
Writes some data from an array to the object .
154,088
public String getNativeSql ( ) { if ( sql != null ) { return sql ; } sql = buildNativeSql ( null ) ; return sql ; }
Method to return the sql based on number of batches . Skipping the initial batch .
154,089
protected void checkIndex ( int parameterIndex , int type1 , int type2 , String getName ) throws SQLException { checkIndex ( parameterIndex ) ; if ( type1 != this . testReturn [ parameterIndex - 1 ] && type2 != this . testReturn [ parameterIndex - 1 ] ) { throw new PSQLException ( GT . tr ( "Parameter of type {0} was r...
helperfunction for the getXXX calls to check isFunction and index == 1 Compare BOTH type fields against the return type .
154,090
public LargeObject open ( int oid , int mode , boolean commitOnClose ) throws SQLException { return open ( ( long ) oid , mode , commitOnClose ) ; }
This opens an existing large object same as previous method but commits the transaction on close if asked .
154,091
public long createLO ( int mode ) throws SQLException { if ( conn . getAutoCommit ( ) ) { throw new PSQLException ( GT . tr ( "Large Objects may not be used in auto-commit mode." ) , PSQLState . NO_ACTIVE_SQL_TRANSACTION ) ; } FastpathArg [ ] args = new FastpathArg [ 1 ] ; args [ 0 ] = new FastpathArg ( mode ) ; return...
This creates a large object returning its OID .
154,092
public void delete ( long oid ) throws SQLException { FastpathArg [ ] args = new FastpathArg [ 1 ] ; args [ 0 ] = Fastpath . createOIDArg ( oid ) ; fp . fastpath ( "lo_unlink" , args ) ; }
This deletes a large object .
154,093
public boolean ensureBytes ( int n ) throws IOException { int required = n - endIndex + index ; while ( required > 0 ) { if ( ! readMore ( required ) ) { return false ; } required = n - endIndex + index ; } return true ; }
Ensures that the buffer contains at least n bytes . This method invalidates the buffer and index fields .
154,094
private boolean readMore ( int wanted ) throws IOException { if ( endIndex == index ) { index = 0 ; endIndex = 0 ; } int canFit = buffer . length - endIndex ; if ( canFit < wanted ) { if ( index + canFit > wanted + MINIMUM_READ ) { compact ( ) ; } else { doubleBuffer ( ) ; } canFit = buffer . length - endIndex ; } int ...
Reads more bytes into the buffer .
154,095
private void moveBufferTo ( byte [ ] dest ) { int size = endIndex - index ; System . arraycopy ( buffer , index , dest , 0 , size ) ; index = 0 ; endIndex = size ; }
Moves bytes from the buffer to the beginning of the destination buffer . Also sets the index and endIndex variables .
154,096
public String getRawPropertyValue ( String key ) { String value = super . getProperty ( key ) ; if ( value != null ) { return value ; } for ( Properties properties : defaults ) { value = properties . getProperty ( key ) ; if ( value != null ) { return value ; } } return null ; }
Returns raw value of a property without any replacements .
154,097
public synchronized void truncate ( long len ) throws SQLException { checkFreed ( ) ; if ( ! conn . haveMinimumServerVersion ( ServerVersion . v8_3 ) ) { throw new PSQLException ( GT . tr ( "Truncation of large objects is only implemented in 8.3 and later servers." ) , PSQLState . NOT_IMPLEMENTED ) ; } if ( len < 0 ) {...
For Blobs this should be in bytes while for Clobs it should be in characters . Since we really haven t figured out how to handle character sets for Clobs the current implementation uses bytes for both Blobs and Clobs .
154,098
public synchronized long position ( byte [ ] pattern , long start ) throws SQLException { assertPosition ( start , pattern . length ) ; int position = 1 ; int patternIdx = 0 ; long result = - 1 ; int tmpPosition = 1 ; for ( LOIterator i = new LOIterator ( start - 1 ) ; i . hasNext ( ) ; position ++ ) { byte b = i . nex...
Iterate over the buffer looking for the specified pattern .
154,099
protected void assertPosition ( long pos , long len ) throws SQLException { checkFreed ( ) ; if ( pos < 1 ) { throw new PSQLException ( GT . tr ( "LOB positioning offsets start at 1." ) , PSQLState . INVALID_PARAMETER_VALUE ) ; } if ( pos + len - 1 > Integer . MAX_VALUE ) { throw new PSQLException ( GT . tr ( "PostgreS...
Throws an exception if the pos value exceeds the max value by which the large object API can index .