code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
protected void acquireAccessToken(final OAuthCallback cb) {
if (isAccessTokenCached()) {
// Execute the callback immediately with cached OAuth credentials
if (VERBOSE) Log.d(TAG, "Access token cached");
if (cb != null) {
// Ensure networking occurs off the main thread
// TODO: Use an ExecutorService and expose an application shutdown method to shutdown?
new Thread(new Runnable() {
@Override
public void run() {
cb.onSuccess(getRequestFactoryFromCachedCredentials());
}
}).start();
}
} else if (mOauthInProgress && cb != null) {
// Add the callback to the queue for execution when outstanding OAuth negotiation complete
mCallbackQueue.add(cb);
if (VERBOSE) Log.i(TAG, "Adding cb to queue");
} else {
mOauthInProgress = true;
// Perform an OAuth Client Credentials Request
// TODO: Replace with new Thread()
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
TokenResponse response = null;
try {
if (VERBOSE)
Log.i(TAG, "Fetching OAuth " + mConfig.getAccessTokenRequestUrl());
response = new ClientCredentialsTokenRequest(new NetHttpTransport(), new JacksonFactory(), new GenericUrl(mConfig.getAccessTokenRequestUrl()))
.setGrantType("client_credentials")
.setClientAuthentication(new BasicAuthentication(mConfig.getClientId(), mConfig.getClientSecret()))
.execute();
} catch (IOException e) {
// TODO: Alert user Kickflip down
// or client credentials invalid
if (cb != null) {
postExceptionToCallback(cb, e);
}
e.printStackTrace();
}
if (response != null) {
if (VERBOSE)
Log.i(TAG, "Got Access Token " + response.getAccessToken().substring(0, 5) + "...");
storeAccessToken(response);
mOauthInProgress = false;
if (cb != null)
cb.onSuccess(getRequestFactoryFromAccessToken(mStorage.getString(ACCESS_TOKEN_KEY, null)));
executeQueuedCallbacks();
} else {
mOauthInProgress = false;
Log.w(TAG, "Failed to get Access Token");
}
return null;
}
}.execute();
}
} | java |
protected void executeQueuedCallbacks() {
if (VERBOSE)
Log.i(TAG, String.format("Executing %d queued callbacks", mCallbackQueue.size()));
for (OAuthCallback cb : mCallbackQueue) {
cb.onSuccess(getRequestFactoryFromCachedCredentials());
}
} | java |
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.offset, bufferInfo.size);
encodedData.position(bufferInfo.offset);
encodedData.put(videoConfig, 0, bufferInfo.size);
encodedData.position(bufferInfo.offset);
mH264Keyframe.put(videoConfig, 0, bufferInfo.size);
} | java |
private void packageH264Keyframe(ByteBuffer encodedData, MediaCodec.BufferInfo bufferInfo) {
mH264Keyframe.position(mH264MetaSize);
mH264Keyframe.put(encodedData); // BufferOverflow
} | java |
public void handleTouchEvent(MotionEvent ev){
if(ev.getAction() == MotionEvent.ACTION_MOVE){
// A finger is dragging about
if(mTexHeight != 0 && mTexWidth != 0){
mSummedTouchPosition[0] += (2 * (ev.getX() - mLastTouchPosition[0])) / mTexWidth;
mSummedTouchPosition[1] += (2 * (ev.getY() - mLastTouchPosition[1])) / -mTexHeight;
mLastTouchPosition[0] = ev.getX();
mLastTouchPosition[1] = ev.getY();
}
}else if(ev.getAction() == MotionEvent.ACTION_DOWN){
// The primary finger has landed
mLastTouchPosition[0] = ev.getX();
mLastTouchPosition[1] = ev.getY();
}
} | java |
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;
//Log.d(TAG, "filt kernel: " + Arrays.toString(mKernel) + ", adj=" + colorAdj);
} | java |
public void setTexSize(int width, int height) {
mTexHeight = height;
mTexWidth = width;
float rw = 1.0f / width;
float rh = 1.0f / height;
// Don't need to create a new array here, but it's syntactically convenient.
mTexOffset = new float[] {
-rw, -rh, 0f, -rh, rw, -rh,
-rw, 0f, 0f, 0f, rw, 0f,
-rw, rh, 0f, rh, rw, rh
};
//Log.d(TAG, "filt size: " + width + "x" + height + ": " + Arrays.toString(mTexOffset));
} | java |
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");
// Select the program.
GLES20.glUseProgram(mProgramHandle);
GlUtil.checkGlError("glUseProgram");
// Set the texture.
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(mTextureTarget, textureId);
// Copy the model / view / projection matrix over.
GLES20.glUniformMatrix4fv(muMVPMatrixLoc, 1, false, mvpMatrix, 0);
GlUtil.checkGlError("glUniformMatrix4fv");
// Copy the texture transformation matrix over.
GLES20.glUniformMatrix4fv(muTexMatrixLoc, 1, false, texMatrix, 0);
GlUtil.checkGlError("glUniformMatrix4fv");
// Enable the "aPosition" vertex attribute.
GLES20.glEnableVertexAttribArray(maPositionLoc);
GlUtil.checkGlError("glEnableVertexAttribArray");
// Connect vertexBuffer to "aPosition".
GLES20.glVertexAttribPointer(maPositionLoc, coordsPerVertex,
GLES20.GL_FLOAT, false, vertexStride, vertexBuffer);
GlUtil.checkGlError("glVertexAttribPointer");
// Enable the "aTextureCoord" vertex attribute.
GLES20.glEnableVertexAttribArray(maTextureCoordLoc);
GlUtil.checkGlError("glEnableVertexAttribArray");
// Connect texBuffer to "aTextureCoord".
GLES20.glVertexAttribPointer(maTextureCoordLoc, 2,
GLES20.GL_FLOAT, false, texStride, texBuffer);
GlUtil.checkGlError("glVertexAttribPointer");
// Populate the convolution kernel, if present.
if (muKernelLoc >= 0) {
GLES20.glUniform1fv(muKernelLoc, KERNEL_SIZE, mKernel, 0);
GLES20.glUniform2fv(muTexOffsetLoc, KERNEL_SIZE, mTexOffset, 0);
GLES20.glUniform1f(muColorAdjustLoc, mColorAdjust);
}
// Populate touch position data, if present
if (muTouchPositionLoc >= 0){
GLES20.glUniform2fv(muTouchPositionLoc, 1, mSummedTouchPosition, 0);
}
// Draw the rect.
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, firstVertex, vertexCount);
GlUtil.checkGlError("glDrawArrays");
// Done -- disable vertex array, texture, and program.
GLES20.glDisableVertexAttribArray(maPositionLoc);
GLES20.glDisableVertexAttribArray(maTextureCoordLoc);
GLES20.glBindTexture(mTextureTarget, 0);
GLES20.glUseProgram(0);
} | java |
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.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (last_loc == null)
last_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (last_loc != null && cb != null) {
cb.gotLocation(last_loc);
} else {
deviceLocation.getLocation(context, cb, waitForGpsFix);
}
} | java |
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, sClientSecret, callback);
} else if (callback != null) {
callback.onSuccess(sKickflip.getActiveUser());
}
return sKickflip;
} | java |
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() {
@Override
public void onSuccess(final Response response) {
if (VERBOSE)
Log.i(TAG, "loginUser response: " + response);
storeNewUserResponse((User) response, password);
postResponseToCallback(cb, response);
}
@Override
public void onError(final KickflipException error) {
Log.w(TAG, "loginUser Error: " + error);
postExceptionToCallback(cb, error);
}
});
} | java |
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", newPassword);
finalPassword = newPassword;
} else {
finalPassword = getPasswordForActiveUser();
}
if (email != null) data.put("email", email);
if (displayName != null) data.put("display_name", displayName);
if (extraInfo != null) data.put("extra_info", new Gson().toJson(extraInfo));
post(EDIT_USER, new UrlEncodedContent(data), User.class, new KickflipCallback() {
@Override
public void onSuccess(final Response response) {
if (VERBOSE)
Log.i(TAG, "setUserInfo response: " + response);
storeNewUserResponse((User) response, finalPassword);
postResponseToCallback(cb, response);
}
@Override
public void onError(final KickflipException error) {
Log.w(TAG, "setUserInfo Error: " + error);
postExceptionToCallback(cb, error);
}
});
} | java |
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() {
@Override
public void onSuccess(final Response response) {
if (VERBOSE)
Log.i(TAG, "getUserInfo response: " + response);
postResponseToCallback(cb, response);
}
@Override
public void onError(final KickflipException error) {
Log.w(TAG, "getUserInfo Error: " + error);
postExceptionToCallback(cb, error);
}
});
} | java |
private void stopStream(User user, Stream stream, final KickflipCallback cb) {
checkNotNull(stream);
// TODO: Add start / stop lat lon to Stream?
GenericData data = new GenericData();
data.put("stream_id", stream.getStreamId());
data.put("uuid", user.getUUID());
if (stream.getLatitude() != 0) {
data.put("lat", stream.getLatitude());
}
if (stream.getLongitude() != 0) {
data.put("lon", stream.getLongitude());
}
post(STOP_STREAM, new UrlEncodedContent(data), HlsStream.class, cb);
} | java |
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("RESPONSE: %s body: %s", shortenUrlString(response.getRequest().getUrl().toString()), new GsonBuilder().setPrettyPrinting().create().toJson(kickFlipResponse)));
// if (Stream.class.isAssignableFrom(responseClass)) {
// if( ((String) responseMap.get("stream_type")).compareTo("HLS") == 0){
// kickFlipResponse = response.parseAs(HlsStream.class);
// } else if( ((String) responseMap.get("stream_type")).compareTo("RTMP") == 0){
// // TODO:
// }
// } else if(User.class.isAssignableFrom(responseClass)){
// kickFlipResponse = response.parseAs(User.class);
// }
if (kickFlipResponse == null) {
postExceptionToCallback(cb, UNKNOWN_ERROR_CODE);
} else if (!kickFlipResponse.isSuccessful()) {
postExceptionToCallback(cb, UNKNOWN_ERROR_CODE);
} else {
postResponseToCallback(cb, kickFlipResponse);
}
} | java |
public static File getRootStorageDirectory(Context c, String directory_name){
File result;
// First, try getting access to the sdcard partition
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d(TAG,"Using sdcard");
result = new File(Environment.getExternalStorageDirectory(), directory_name);
} else {
// Else, use the internal storage directory for this application
Log.d(TAG,"Using internal storage");
result = new File(c.getApplicationContext().getFilesDir(), directory_name);
}
if(!result.exists())
result.mkdir();
else if(result.isFile()){
return null;
}
Log.d("getRootStorageDirectory", result.getAbsolutePath());
return result;
} | java |
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.getAbsolutePath());
return null;
}
else if(result.isFile()){
return null;
}
Log.d("getStorageDirectory", "directory ready: " + result.getAbsolutePath());
return result;
} | java |
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();
//output = File.createTempFile(filename, extension, root);
Log.i(TAG, "Created temp file: " + output.getAbsolutePath());
}
return output;
} catch (IOException e) {
e.printStackTrace();
return null;
}
} | java |
public static String tail2( File file, int lines) {
lines++; // Read # lines inclusive
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 = fileLength; filePointer != -1; filePointer--){
fileHandler.seek( filePointer );
int readByte = fileHandler.readByte();
if( readByte == 0xA ) {
line = line + 1;
if (line == lines) {
if (filePointer == fileLength - 1) {
continue;
} else {
break;
}
}
}
sb.append( ( char ) readByte );
}
String lastLine = sb.reverse().toString();
return lastLine;
} catch( java.io.FileNotFoundException e ) {
e.printStackTrace();
return null;
} catch( java.io.IOException e ) {
e.printStackTrace();
return null;
}
finally {
if (fileHandler != null )
try {
fileHandler.close();
} catch (IOException e) {
/* ignore */
}
}
} | java |
public static void deleteDirectory(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
deleteDirectory(child);
fileOrDirectory.delete();
} | java |
protected long getNextRelativePts(long absPts, int trackIndex) {
if (mFirstPts == 0) {
mFirstPts = absPts;
return 0;
}
return getSafePts(absPts - mFirstPts, trackIndex);
} | java |
private long getSafePts(long pts, int trackIndex) {
if (mLastPts[trackIndex] >= pts) {
// Enforce a non-zero minimum spacing
// between pts
mLastPts[trackIndex] += 9643;
return mLastPts[trackIndex];
}
mLastPts[trackIndex] = pts;
return pts;
} | java |
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.ProgramType.TEXTURE_EXT;
break;
case FILTER_BLACK_WHITE:
// (In a previous version the TEXTURE_EXT_BW variant was enabled by a flag called
// ROSE_COLORED_GLASSES, because the shader set the red channel to the B&W color
// and green/blue to zero.)
programType = Texture2dProgram.ProgramType.TEXTURE_EXT_BW;
break;
case FILTER_NIGHT:
programType = Texture2dProgram.ProgramType.TEXTURE_EXT_NIGHT;
break;
case FILTER_CHROMA_KEY:
programType = Texture2dProgram.ProgramType.TEXTURE_EXT_CHROMA_KEY;
break;
case FILTER_SQUEEZE:
programType = Texture2dProgram.ProgramType.TEXTURE_EXT_SQUEEZE;
break;
case FILTER_TWIRL:
programType = Texture2dProgram.ProgramType.TEXTURE_EXT_TWIRL;
break;
case FILTER_TUNNEL:
programType = Texture2dProgram.ProgramType.TEXTURE_EXT_TUNNEL;
break;
case FILTER_BULGE:
programType = Texture2dProgram.ProgramType.TEXTURE_EXT_BULGE;
break;
case FILTER_DENT:
programType = Texture2dProgram.ProgramType.TEXTURE_EXT_DENT;
break;
case FILTER_FISHEYE:
programType = Texture2dProgram.ProgramType.TEXTURE_EXT_FISHEYE;
break;
case FILTER_STRETCH:
programType = Texture2dProgram.ProgramType.TEXTURE_EXT_STRETCH;
break;
case FILTER_MIRROR:
programType = Texture2dProgram.ProgramType.TEXTURE_EXT_MIRROR;
break;
case FILTER_BLUR:
programType = Texture2dProgram.ProgramType.TEXTURE_EXT_FILT;
kernel = new float[] {
1f/16f, 2f/16f, 1f/16f,
2f/16f, 4f/16f, 2f/16f,
1f/16f, 2f/16f, 1f/16f };
break;
case FILTER_SHARPEN:
programType = Texture2dProgram.ProgramType.TEXTURE_EXT_FILT;
kernel = new float[] {
0f, -1f, 0f,
-1f, 5f, -1f,
0f, -1f, 0f };
break;
case FILTER_EDGE_DETECT:
programType = Texture2dProgram.ProgramType.TEXTURE_EXT_FILT;
kernel = new float[] {
-1f, -1f, -1f,
-1f, 8f, -1f,
-1f, -1f, -1f };
break;
case FILTER_EMBOSS:
programType = Texture2dProgram.ProgramType.TEXTURE_EXT_FILT;
kernel = new float[] {
2f, 0f, 0f,
0f, -1f, 0f,
0f, 0f, -1f };
colorAdj = 0.5f;
break;
default:
throw new RuntimeException("Unknown filter mode " + newFilter);
}
// Do we need a whole new program? (We want to avoid doing this if we don't have
// too -- compiling a program could be expensive.)
if (programType != rect.getProgram().getProgramType()) {
rect.changeProgram(new Texture2dProgram(programType));
}
// Update the filter kernel (if any).
if (kernel != null) {
rect.getProgram().setKernel(kernel, colorAdj);
}
} | java |
public void drawFrame(int textureId, float[] texMatrix) {
// Use the identity matrix for MVP so our 2x2 FULL_RECTANGLE covers the viewport.
mProgram.draw(IDENTITY_MATRIX, mRectDrawable.getVertexArray(), 0,
mRectDrawable.getVertexCount(), mRectDrawable.getCoordsPerVertex(),
mRectDrawable.getVertexStride(),
texMatrix, TEX_COORDS_BUF, textureId, TEX_COORDS_STRIDE);
} | java |
protected boolean isOneShotQuery(CachedQuery cachedQuery) {
if (cachedQuery == null) {
return true;
}
cachedQuery.increaseExecuteCount();
if ((mPrepareThreshold == 0 || cachedQuery.getExecuteCount() < mPrepareThreshold)
&& !getForceBinaryTransfer()) {
return true;
}
return false;
} | java |
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;
} | java |
@Override
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;
}
} | java |
@Override
public Connection getConnection() throws SQLException {
if (con == null) {
// Before throwing the exception, let's notify the registered listeners about the error
PSQLException sqlException =
new PSQLException(GT.tr("This PooledConnection has already been closed."),
PSQLState.CONNECTION_DOES_NOT_EXIST);
fireConnectionFatalError(sqlException);
throw sqlException;
}
// If any error occurs while opening a new connection, the listeners
// have to be notified. This gives a chance to connection pools to
// eliminate bad pooled connections.
try {
// Only one connection can be open at a time from this PooledConnection. See JDBC 2.0 Optional
// Package spec section 6.2.3
if (last != null) {
last.close();
if (!con.getAutoCommit()) {
try {
con.rollback();
} catch (SQLException ignored) {
}
}
con.clearWarnings();
}
/*
* In XA-mode, autocommit is handled in PGXAConnection, because it depends on whether an
* XA-transaction is open or not
*/
if (!isXA) {
con.setAutoCommit(autoCommit);
}
} catch (SQLException sqlException) {
fireConnectionFatalError(sqlException);
throw (SQLException) sqlException.fillInStackTrace();
}
ConnectionHandler handler = new ConnectionHandler(con);
last = handler;
Connection proxyCon = (Connection) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class[]{Connection.class, PGConnection.class}, handler);
last.setProxy(proxyCon);
return proxyCon;
} | java |
void fireConnectionClosed() {
ConnectionEvent evt = null;
// Copy the listener list so the listener can remove itself during this method call
ConnectionEventListener[] local =
listeners.toArray(new ConnectionEventListener[0]);
for (ConnectionEventListener listener : local) {
if (evt == null) {
evt = createConnectionEvent(null);
}
listener.connectionClosed(evt);
}
} | java |
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;
}
// Handle EOF
if (bpos >= buffer.length) {
return -1;
}
int ret = (buffer[bpos] & 0x7F);
if ((buffer[bpos] & 0x80) == 0x80) {
ret |= 0x80;
}
bpos++;
apos++;
return ret;
} catch (SQLException se) {
throw new IOException(se.toString());
}
} | java |
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;
} | java |
public synchronized void put(Key key, Value value) {
long valueSize = value.getSize();
if (maxSizeBytes == 0 || maxSizeEntries == 0 || valueSize * 2 > maxSizeBytes) {
// Just destroy the value if cache is disabled or if entry would consume more than a half of
// the cache
evictValue(value);
return;
}
currentSize += valueSize;
Value prev = cache.put(key, value);
if (prev == null) {
return;
}
// This should be a rare case
currentSize -= prev.getSize();
if (prev != value) {
evictValue(prev);
}
} | java |
public synchronized void putAll(Map<Key, Value> m) {
for (Map.Entry<Key, Value> entry : m.entrySet()) {
this.put(entry.getKey(), entry.getValue());
}
} | java |
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;
} | java |
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();
} | java |
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_STATE, ie);
}
}
} | java |
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');
pgStream.sendInteger4(buf.length + 4 + 1);
pgStream.send(buf);
pgStream.sendChar(0);
pgStream.flush();
return processCopyResults(null, true);
// expect a CopyInResponse or CopyOutResponse to our query above
} catch (IOException ioe) {
throw new PSQLException(GT.tr("Database connection failed when starting copy"),
PSQLState.CONNECTION_FAILURE, ioe);
}
} | java |
private synchronized void initCopy(CopyOperationImpl op) throws SQLException, IOException {
pgStream.receiveInteger4(); // length not used
int rowFormat = pgStream.receiveChar();
int numFields = pgStream.receiveInteger2();
int[] fieldFormats = new int[numFields];
for (int i = 0; i < numFields; i++) {
fieldFormats[i] = pgStream.receiveInteger2();
}
lock(op);
op.init(this, rowFormat, fieldFormats);
} | java |
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) {
LOGGER.log(Level.FINEST, "FE => CopyFail");
final byte[] msg = Utils.encodeUTF8("Copy cancel requested");
pgStream.sendChar('f'); // CopyFail
pgStream.sendInteger4(5 + msg.length);
pgStream.send(msg);
pgStream.sendChar(0);
pgStream.flush();
do {
try {
processCopyResults(op, true); // discard rest of input
} catch (SQLException se) { // expected error response to failing copy
errors++;
if (error != null) {
SQLException e = se;
SQLException next;
while ((next = e.getNextException()) != null) {
e = next;
}
e.setNextException(error);
}
error = se;
}
} while (hasLock(op));
}
} else if (op instanceof CopyOut) {
sendQueryCancel();
}
} catch (IOException ioe) {
throw new PSQLException(GT.tr("Database connection failed when canceling copy operation"),
PSQLState.CONNECTION_FAILURE, ioe);
} finally {
// Need to ensure the lock isn't held anymore, or else
// future operations, rather than failing due to the
// broken connection, will simply hang waiting for this
// lock.
synchronized (this) {
if (hasLock(op)) {
unlock(op);
}
}
}
if (op instanceof CopyIn) {
if (errors < 1) {
throw new PSQLException(GT.tr("Missing expected error response to copy cancel request"),
PSQLState.COMMUNICATION_ERROR);
} else if (errors > 1) {
throw new PSQLException(
GT.tr("Got {0} error responses to single copy cancel request", String.valueOf(errors)),
PSQLState.COMMUNICATION_ERROR, error);
}
}
} | java |
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'); // CopyDone
pgStream.sendInteger4(4);
pgStream.flush();
do {
processCopyResults(op, true);
} while (hasLock(op));
return op.getHandledRowCount();
} catch (IOException ioe) {
throw new PSQLException(GT.tr("Database connection failed when ending copy"),
PSQLState.CONNECTION_FAILURE, ioe);
}
} | java |
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({0})", siz);
try {
pgStream.sendChar('d');
pgStream.sendInteger4(siz + 4);
pgStream.send(data, off, siz);
processCopyResults(op, false); // collect any pending notifications without blocking
} catch (IOException ioe) {
throw new PSQLException(GT.tr("Database connection failed when writing to copy"),
PSQLState.CONNECTION_FAILURE, ioe);
}
} | java |
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();
} | java |
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."),
PSQLState.INVALID_PARAMETER_VALUE);
}
if (ch == '"') {
sbuf.append(ch);
}
sbuf.append(ch);
}
sbuf.append('"');
} catch (IOException e) {
throw new PSQLException(GT.tr("No IOException expected from StringBuffer or StringBuilder"),
PSQLState.UNEXPECTED_ERROR, e);
}
} | java |
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 (returnValue.length == 4) {
return ByteConverter.int4(returnValue, 0);
} else {
throw new PSQLException(GT.tr(
"Fastpath call {0} - No result was returned or wrong size while expecting an integer.",
name), PSQLState.NO_DATA);
}
} | java |
public long getOID(String name, FastpathArg[] args) throws SQLException {
long oid = getInteger(name, args);
if (oid < 0) {
oid += NUM_OIDS;
}
return oid;
} | java |
public static FastpathArg createOIDArg(long oid) {
if (oid > Integer.MAX_VALUE) {
oid -= NUM_OIDS;
}
return new FastpathArg((int) oid);
} | java |
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable<?, ?> environment) throws Exception {
Reference ref = (Reference) obj;
String className = ref.getClassName();
// Old names are here for those who still use them
if (className.equals("org.postgresql.ds.PGSimpleDataSource")
|| className.equals("org.postgresql.jdbc2.optional.SimpleDataSource")
|| className.equals("org.postgresql.jdbc3.Jdbc3SimpleDataSource")) {
return loadSimpleDataSource(ref);
} else if (className.equals("org.postgresql.ds.PGConnectionPoolDataSource")
|| className.equals("org.postgresql.jdbc2.optional.ConnectionPool")
|| className.equals("org.postgresql.jdbc3.Jdbc3ConnectionPool")) {
return loadConnectionPool(ref);
} else if (className.equals("org.postgresql.ds.PGPoolingDataSource")
|| className.equals("org.postgresql.jdbc2.optional.PoolingDataSource")
|| className.equals("org.postgresql.jdbc3.Jdbc3PoolingDataSource")) {
return loadPoolingDataSource(ref);
} else {
return null;
}
} | java |
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;
}
PGPoolingDataSource previous = dataSources.putIfAbsent(dataSourceName, this);
if (previous != null) {
throw new IllegalArgumentException(
"DataSource with name '" + dataSourceName + "' already exists!");
}
if (this.dataSourceName != null) {
dataSources.remove(this.dataSourceName);
}
this.dataSourceName = dataSourceName;
} | java |
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() < initialConnections) {
available.push(source.getPooledConnection());
}
initialized = true;
}
} | java |
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(connectionEventListener);
try {
pci.close();
} catch (SQLException e) {
}
}
used = null;
}
removeStoredDataSource();
} | java |
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 = available.pop();
used.push(pc);
break;
}
if (maxConnections == 0 || used.size() < maxConnections) {
pc = source.getPooledConnection();
used.push(pc);
break;
} else {
try {
// Wake up every second at a minimum
lock.wait(1000L);
} catch (InterruptedException e) {
}
}
}
}
pc.addConnectionEventListener(connectionEventListener);
return pc.getConnection();
} | java |
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 (maxConnections > 0) {
ref.add(new StringRefAddr("maxConnections", Integer.toString(maxConnections)));
}
return ref;
} | java |
void setFields(Field[] fields) {
this.fields = fields;
this.resultSetColumnNameIndexMap = null;
this.cachedMaxResultRowSize = null;
this.needUpdateFieldFormats = fields != null;
this.hasBinaryFields = false; // just in case
} | java |
public synchronized Timestamp toTimestamp(Calendar cal, String s) throws SQLException {
if (s == null) {
return null;
}
int slen = s.length();
// convert postgres's infinity values to internal infinity magic value
if (slen == 8 && s.equals("infinity")) {
return new Timestamp(PGStatement.DATE_POSITIVE_INFINITY);
}
if (slen == 9 && s.equals("-infinity")) {
return new Timestamp(PGStatement.DATE_NEGATIVE_INFINITY);
}
ParsedTimestamp ts = parseBackendTimestamp(s);
Calendar useCal = ts.tz != null ? ts.tz : setupCalendar(cal);
useCal.set(Calendar.ERA, ts.era);
useCal.set(Calendar.YEAR, ts.year);
useCal.set(Calendar.MONTH, ts.month - 1);
useCal.set(Calendar.DAY_OF_MONTH, ts.day);
useCal.set(Calendar.HOUR_OF_DAY, ts.hour);
useCal.set(Calendar.MINUTE, ts.minute);
useCal.set(Calendar.SECOND, ts.second);
useCal.set(Calendar.MILLISECOND, 0);
Timestamp result = new Timestamp(useCal.getTimeInMillis());
result.setNanos(ts.nanos);
return result;
} | java |
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}", s),
PSQLState.BAD_DATETIME_FORMAT, nfe);
}
} | java |
public LocalDateTime toLocalDateTime(String s) throws SQLException {
if (s == null) {
return null;
}
int slen = s.length();
// convert postgres's infinity values to internal infinity magic value
if (slen == 8 && s.equals("infinity")) {
return LocalDateTime.MAX;
}
if (slen == 9 && s.equals("-infinity")) {
return LocalDateTime.MIN;
}
ParsedTimestamp ts = parseBackendTimestamp(s);
// intentionally ignore time zone
// 2004-10-19 10:23:54+03:00 is 2004-10-19 10:23:54 locally
LocalDateTime result = LocalDateTime.of(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second, ts.nanos);
if (ts.era == GregorianCalendar.BC) {
return result.with(ChronoField.ERA, IsoEra.BCE.getValue());
} else {
return result;
}
} | java |
public Calendar getSharedCalendar(TimeZone timeZone) {
if (timeZone == null) {
timeZone = getDefaultTz();
}
Calendar tmp = calendarWithUserTz;
tmp.setTimeZone(timeZone);
return tmp;
} | java |
public Date convertToDate(long millis, TimeZone tz) {
// no adjustments for the inifity hack values
if (millis <= PGStatement.DATE_NEGATIVE_INFINITY
|| millis >= PGStatement.DATE_POSITIVE_INFINITY) {
return new Date(millis);
}
if (tz == null) {
tz = getDefaultTz();
}
if (isSimpleTimeZone(tz.getID())) {
// Truncate to 00:00 of the day.
// Suppose the input date is 7 Jan 15:40 GMT+02:00 (that is 13:40 UTC)
// We want it to become 7 Jan 00:00 GMT+02:00
// 1) Make sure millis becomes 15:40 in UTC, so add offset
int offset = tz.getRawOffset();
millis += offset;
// 2) Truncate hours, minutes, etc. Day is always 86400 seconds, no matter what leap seconds
// are
millis = millis / ONEDAY * ONEDAY;
// 2) Now millis is 7 Jan 00:00 UTC, however we need that in GMT+02:00, so subtract some
// offset
millis -= offset;
// Now we have brand-new 7 Jan 00:00 GMT+02:00
return new Date(millis);
}
Calendar cal = calendarWithUserTz;
cal.setTimeZone(tz);
cal.setTimeInMillis(millis);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return new Date(cal.getTimeInMillis());
} | java |
public Time convertToTime(long millis, TimeZone tz) {
if (tz == null) {
tz = getDefaultTz();
}
if (isSimpleTimeZone(tz.getID())) {
// Leave just time part of the day.
// Suppose the input date is 2015 7 Jan 15:40 GMT+02:00 (that is 13:40 UTC)
// We want it to become 1970 1 Jan 15:40 GMT+02:00
// 1) Make sure millis becomes 15:40 in UTC, so add offset
int offset = tz.getRawOffset();
millis += offset;
// 2) Truncate year, month, day. Day is always 86400 seconds, no matter what leap seconds are
millis = millis % ONEDAY;
// 2) Now millis is 1970 1 Jan 15:40 UTC, however we need that in GMT+02:00, so subtract some
// offset
millis -= offset;
// Now we have brand-new 1970 1 Jan 15:40 GMT+02:00
return new Time(millis);
}
Calendar cal = calendarWithUserTz;
cal.setTimeZone(tz);
cal.setTimeInMillis(millis);
cal.set(Calendar.ERA, GregorianCalendar.AD);
cal.set(Calendar.YEAR, 1970);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
return new Time(cal.getTimeInMillis());
} | java |
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 instanceof Time) {
return toString(cal, (Time) time, withTimeZone);
}
return toString(cal, (Date) time, withTimeZone);
} | java |
public XAConnection getXAConnection(String user, String password) throws SQLException {
Connection con = super.getConnection(user, password);
return new PGXAConnection((BaseConnection) con);
} | java |
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 not handled this way the close call will hang, at least in 8.2
if (cp.isActive()) {
cp.cancelCopy();
}
try { // read until exhausted or operation cancelled SQLException
while ((buf = cp.readFromCopy()) != null) {
}
} catch (SQLException sqlEx) {
} // typically after several kB
throw ioEX;
} finally { // see to it that we do not leave the connection locked
if (cp.isActive()) {
cp.cancelCopy();
}
}
} | java |
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 ("java.sql.Array");
default:
String type = getPGType(column);
if ("unknown".equals(type)) {
return ("java.lang.String");
}
return ("java.lang.Object");
}
} | java |
private static Connection makeConnection(String url, Properties props) throws SQLException {
return new PgConnection(hostSpecs(props), user(props), database(props), props, url);
} | java |
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());
} | java |
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);
} | java |
public String getValue() {
return years + " years "
+ months + " mons "
+ days + " days "
+ hours + " hours "
+ minutes + " mins "
+ secondsFormat.format(seconds) + " secs";
} | java |
public void add(Calendar cal) {
// Avoid precision loss
// Be aware postgres doesn't return more than 60 seconds - no overflow can happen
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.HOUR, getHours());
cal.add(Calendar.DAY_OF_MONTH, getDays());
cal.add(Calendar.MONTH, getMonths());
cal.add(Calendar.YEAR, getYears());
} | java |
public void add(Date date) {
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
add(cal);
date.setTime(cal.getTime().getTime());
} | java |
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.setMinutes(interval.getMinutes() + getMinutes());
interval.setSeconds(interval.getSeconds() + getSeconds());
} | java |
public void addWarning(SQLWarning warn) {
// Add the warning to the chain
if (firstWarning != null) {
firstWarning.setNextWarning(warn);
} else {
firstWarning = warn;
}
} | java |
private void initObjectTypes(Properties info) throws SQLException {
// Add in the types that come packaged with the driver.
// These can be overridden later if desired.
addDataType("box", org.postgresql.geometric.PGbox.class);
addDataType("circle", org.postgresql.geometric.PGcircle.class);
addDataType("line", org.postgresql.geometric.PGline.class);
addDataType("lseg", org.postgresql.geometric.PGlseg.class);
addDataType("path", org.postgresql.geometric.PGpath.class);
addDataType("point", org.postgresql.geometric.PGpoint.class);
addDataType("polygon", org.postgresql.geometric.PGpolygon.class);
addDataType("money", org.postgresql.util.PGmoney.class);
addDataType("interval", org.postgresql.util.PGInterval.class);
Enumeration<?> e = info.propertyNames();
while (e.hasMoreElements()) {
String propertyName = (String) e.nextElement();
if (propertyName.startsWith("datatype.")) {
String typeName = propertyName.substring(9);
String className = info.getProperty(propertyName);
Class<?> klass;
try {
klass = Class.forName(className);
} catch (ClassNotFoundException cnfe) {
throw new PSQLException(
GT.tr("Unable to load the class {0} responsible for the datatype {1}",
className, typeName),
PSQLState.SYSTEM_ERROR, cnfe);
}
addDataType(typeName, klass.asSubclass(PGobject.class));
}
}
} | java |
public int getServerMajorVersion() {
try {
StringTokenizer versionTokens = new StringTokenizer(queryExecutor.getServerVersion(), "."); // aaXbb.ccYdd
return integerPart(versionTokens.nextToken()); // return X
} catch (NoSuchElementException e) {
return 0;
}
} | java |
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 (start == end) {
return 0;
}
return Integer.parseInt(dirtyString.substring(start, end));
} | java |
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 = strValue.substring(slashIndex + 1, strValue.length());
int segment = (int) Long.parseLong(segmentStr, 16);
ByteBuffer buf = ByteBuffer.allocate(8);
buf.putInt(logicalXlog);
buf.putInt(segment);
buf.position(0);
long value = buf.getLong();
return LogSequenceNumber.valueOf(value);
} | java |
public synchronized long position(String pattern, long start) throws SQLException {
checkFreed();
throw org.postgresql.Driver.notImplemented(this.getClass(), "position(String,long)");
} | java |
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((String) in);
}
if (in instanceof Character) {
return fromCharacter((Character) in);
}
if (in instanceof Number) {
return fromNumber((Number) in);
}
throw new PSQLException("Cannot cast to boolean", PSQLState.CANNOT_COERCE);
} | java |
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));
}
} | java |
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()) {
stmt.close();
throw new PSQLException(
GT.tr(
"Unable to determine a value for MaxIndexKeys due to missing system catalog data."),
PSQLState.UNEXPECTED_ERROR);
}
indexMaxKeys = rs.getInt(1);
} finally {
JdbcBlackHole.close(rs);
JdbcBlackHole.close(stmt);
}
}
return indexMaxKeys;
} | java |
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();
} | java |
private static List<String> parseACLArray(String aclString) {
List<String> acls = new ArrayList<String>();
if (aclString == null || aclString.isEmpty()) {
return acls;
}
boolean inQuotes = false;
// start at 1 because of leading "{"
int beginIndex = 1;
char prevChar = ' ';
for (int i = beginIndex; i < aclString.length(); i++) {
char c = aclString.charAt(i);
if (c == '"' && prevChar != '\\') {
inQuotes = !inQuotes;
} else if (c == ',' && !inQuotes) {
acls.add(aclString.substring(beginIndex, i));
beginIndex = i + 1;
}
prevChar = c;
}
// add last element removing the trailing "}"
acls.add(aclString.substring(beginIndex, aclString.length() - 1));
// Strip out enclosing quotes, if any.
for (int i = 0; i < acls.size(); i++) {
String acl = acls.get(i);
if (acl.startsWith("\"") && acl.endsWith("\"")) {
acl = acl.substring(1, acl.length() - 1);
acls.set(i, acl);
}
}
return acls;
} | java |
public static Object instantiate(String classname, Properties info, boolean tryString,
String stringarg) throws ClassNotFoundException, SecurityException, NoSuchMethodException,
IllegalArgumentException, InstantiationException, IllegalAccessException,
InvocationTargetException {
Object[] args = {info};
Constructor<?> ctor = null;
Class<?> cls = Class.forName(classname);
try {
ctor = cls.getConstructor(Properties.class);
} catch (NoSuchMethodException nsme) {
if (tryString) {
try {
ctor = cls.getConstructor(String.class);
args = new String[]{stringarg};
} catch (NoSuchMethodException nsme2) {
tryString = false;
}
}
if (!tryString) {
ctor = cls.getConstructor((Class[]) null);
args = null;
}
}
return ctor.newInstance(args);
} | java |
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.getLogger().log(Level.FINE, "checking if rs is updateable");
parseQuery();
if (!singleTable) {
connection.getLogger().log(Level.FINE, "not a single table");
return false;
}
connection.getLogger().log(Level.FINE, "getting primary keys");
//
// Contains the primary key?
//
primaryKeys = new ArrayList<PrimaryKey>();
// this is not strictly jdbc spec, but it will make things much faster if used
// the user has to select oid, * from table and then we will just use oid
usingOID = false;
int oidIndex = findColumnIndex("oid"); // 0 if not present
int i = 0;
int numPKcolumns = 0;
// if we find the oid then just use it
// oidIndex will be >0 if the oid was in the select list
if (oidIndex > 0) {
i++;
numPKcolumns++;
primaryKeys.add(new PrimaryKey(oidIndex, "oid"));
usingOID = true;
} else {
// otherwise go and get the primary keys and create a list of keys
String[] s = quotelessTableName(tableName);
String quotelessTableName = s[0];
String quotelessSchemaName = s[1];
java.sql.ResultSet rs = connection.getMetaData().getPrimaryKeys("",
quotelessSchemaName, quotelessTableName);
while (rs.next()) {
numPKcolumns++;
String columnName = rs.getString(4); // get the columnName
int index = findColumnIndex(columnName);
if (index > 0) {
i++;
primaryKeys.add(new PrimaryKey(index, columnName)); // get the primary key information
}
}
rs.close();
}
connection.getLogger().log(Level.FINE, "no of keys={0}", i);
if (i < 1) {
throw new PSQLException(GT.tr("No primary key found for table {0}.", tableName),
PSQLState.DATA_ERROR);
}
updateable = (i == numPKcolumns);
connection.getLogger().log(Level.FINE, "checking primary key {0}", updateable);
return updateable;
} | java |
private double readDoubleValue(byte[] bytes, int oid, String targetType) throws PSQLException {
// currently implemented binary encoded fields
switch (oid) {
case Oid.INT2:
return ByteConverter.int2(bytes, 0);
case Oid.INT4:
return ByteConverter.int4(bytes, 0);
case Oid.INT8:
// might not fit but there still should be no overflow checking
return ByteConverter.int8(bytes, 0);
case Oid.FLOAT4:
return ByteConverter.float4(bytes, 0);
case Oid.FLOAT8:
return ByteConverter.float8(bytes, 0);
}
throw new PSQLException(GT.tr("Cannot convert the column of type {0} to requested type {1}.",
Oid.toString(oid), targetType), PSQLState.DATA_TYPE_MISMATCH);
} | java |
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;
default:
// unknown type
return tz;
}
return start + tz.substring(4);
} | java |
public void close() throws SQLException {
if (!closed) {
// flush any open output streams
if (os != null) {
try {
// we can't call os.close() otherwise we go into an infinite loop!
os.flush();
} catch (IOException ioe) {
throw new PSQLException("Exception flushing output stream", PSQLState.DATA_ERROR, ioe);
} finally {
os = null;
}
}
// finally close
FastpathArg[] args = new FastpathArg[1];
args[0] = new FastpathArg(fd);
fp.fastpath("lo_close", args); // true here as we dont care!!
closed = true;
if (this.commitOnClose) {
this.conn.commit();
}
}
} | java |
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;
} | java |
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);
} | java |
@Override
public String getNativeSql() {
if (sql != null) {
return sql;
}
sql = buildNativeSql(null);
return sql;
} | java |
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 registered, but call to get{1} (sqltype={2}) was made.",
"java.sql.Types=" + testReturn[parameterIndex - 1], getName,
"java.sql.Types=" + type1),
PSQLState.MOST_SPECIFIC_TYPE_DOES_NOT_MATCH);
}
} | java |
public LargeObject open(int oid, int mode, boolean commitOnClose) throws SQLException {
return open((long) oid, mode, commitOnClose);
} | java |
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 fp.getOID("lo_creat", args);
} | java |
public void delete(long oid) throws SQLException {
FastpathArg[] args = new FastpathArg[1];
args[0] = Fastpath.createOIDArg(oid);
fp.fastpath("lo_unlink", args);
} | java |
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;
} | java |
private boolean readMore(int wanted) throws IOException {
if (endIndex == index) {
index = 0;
endIndex = 0;
}
int canFit = buffer.length - endIndex;
if (canFit < wanted) {
// would the wanted bytes fit if we compacted the buffer
// and still leave some slack
if (index + canFit > wanted + MINIMUM_READ) {
compact();
} else {
doubleBuffer();
}
canFit = buffer.length - endIndex;
}
int read = wrapped.read(buffer, endIndex, canFit);
if (read < 0) {
return false;
}
endIndex += read;
return true;
} | java |
private void moveBufferTo(byte[] dest) {
int size = endIndex - index;
System.arraycopy(buffer, index, dest, 0, size);
index = 0;
endIndex = size;
} | java |
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;
} | java |
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) {
throw new PSQLException(GT.tr("Cannot truncate LOB to a negative length."),
PSQLState.INVALID_PARAMETER_VALUE);
}
if (len > Integer.MAX_VALUE) {
if (support64bit) {
getLo(true).truncate64(len);
} else {
throw new PSQLException(GT.tr("PostgreSQL LOBs can only index to: {0}", Integer.MAX_VALUE),
PSQLState.INVALID_PARAMETER_VALUE);
}
} else {
getLo(true).truncate((int) len);
}
} | java |
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.next();
if (b == pattern[patternIdx]) {
if (patternIdx == 0) {
tmpPosition = position;
}
patternIdx++;
if (patternIdx == pattern.length) {
result = tmpPosition;
break;
}
} else {
patternIdx = 0;
}
}
return result;
} | java |
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("PostgreSQL LOBs can only index to: {0}", Integer.MAX_VALUE),
PSQLState.INVALID_PARAMETER_VALUE);
}
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.