id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
25,500
getsentry/sentry-java
sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java
AndroidEventBuilderHelper.isCharging
protected static Boolean isCharging(Context ctx) { try { Intent intent = ctx.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); if (intent == null) { return null; } int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB; } catch (Exception e) { Log.e(TAG, "Error getting device charging state.", e); return null; } }
java
protected static Boolean isCharging(Context ctx) { try { Intent intent = ctx.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); if (intent == null) { return null; } int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB; } catch (Exception e) { Log.e(TAG, "Error getting device charging state.", e); return null; } }
[ "protected", "static", "Boolean", "isCharging", "(", "Context", "ctx", ")", "{", "try", "{", "Intent", "intent", "=", "ctx", ".", "registerReceiver", "(", "null", ",", "new", "IntentFilter", "(", "Intent", ".", "ACTION_BATTERY_CHANGED", ")", ")", ";", "if", "(", "intent", "==", "null", ")", "{", "return", "null", ";", "}", "int", "plugged", "=", "intent", ".", "getIntExtra", "(", "BatteryManager", ".", "EXTRA_PLUGGED", ",", "-", "1", ")", ";", "return", "plugged", "==", "BatteryManager", ".", "BATTERY_PLUGGED_AC", "||", "plugged", "==", "BatteryManager", ".", "BATTERY_PLUGGED_USB", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Error getting device charging state.\"", ",", "e", ")", ";", "return", "null", ";", "}", "}" ]
Checks whether or not the device is currently plugged in and charging, or null if unknown. @param ctx Android application context @return whether or not the device is currently plugged in and charging, or null if unknown
[ "Checks", "whether", "or", "not", "the", "device", "is", "currently", "plugged", "in", "and", "charging", "or", "null", "if", "unknown", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java#L313-L326
25,501
getsentry/sentry-java
sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java
AndroidEventBuilderHelper.getUnusedInternalStorage
protected static Long getUnusedInternalStorage() { try { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } catch (Exception e) { Log.e(TAG, "Error getting unused internal storage amount.", e); return null; } }
java
protected static Long getUnusedInternalStorage() { try { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } catch (Exception e) { Log.e(TAG, "Error getting unused internal storage amount.", e); return null; } }
[ "protected", "static", "Long", "getUnusedInternalStorage", "(", ")", "{", "try", "{", "File", "path", "=", "Environment", ".", "getDataDirectory", "(", ")", ";", "StatFs", "stat", "=", "new", "StatFs", "(", "path", ".", "getPath", "(", ")", ")", ";", "long", "blockSize", "=", "stat", ".", "getBlockSize", "(", ")", ";", "long", "availableBlocks", "=", "stat", ".", "getAvailableBlocks", "(", ")", ";", "return", "availableBlocks", "*", "blockSize", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Error getting unused internal storage amount.\"", ",", "e", ")", ";", "return", "null", ";", "}", "}" ]
Get the unused amount of internal storage, in bytes. @return the unused amount of internal storage, in bytes
[ "Get", "the", "unused", "amount", "of", "internal", "storage", "in", "bytes", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java#L414-L425
25,502
getsentry/sentry-java
sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java
AndroidEventBuilderHelper.getTotalInternalStorage
protected static Long getTotalInternalStorage() { try { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return totalBlocks * blockSize; } catch (Exception e) { Log.e(TAG, "Error getting total internal storage amount.", e); return null; } }
java
protected static Long getTotalInternalStorage() { try { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return totalBlocks * blockSize; } catch (Exception e) { Log.e(TAG, "Error getting total internal storage amount.", e); return null; } }
[ "protected", "static", "Long", "getTotalInternalStorage", "(", ")", "{", "try", "{", "File", "path", "=", "Environment", ".", "getDataDirectory", "(", ")", ";", "StatFs", "stat", "=", "new", "StatFs", "(", "path", ".", "getPath", "(", ")", ")", ";", "long", "blockSize", "=", "stat", ".", "getBlockSize", "(", ")", ";", "long", "totalBlocks", "=", "stat", ".", "getBlockCount", "(", ")", ";", "return", "totalBlocks", "*", "blockSize", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Error getting total internal storage amount.\"", ",", "e", ")", ";", "return", "null", ";", "}", "}" ]
Get the total amount of internal storage, in bytes. @return the total amount of internal storage, in bytes
[ "Get", "the", "total", "amount", "of", "internal", "storage", "in", "bytes", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java#L432-L443
25,503
getsentry/sentry-java
sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java
AndroidEventBuilderHelper.getUnusedExternalStorage
protected static Long getUnusedExternalStorage() { try { if (isExternalStorageMounted()) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } } catch (Exception e) { Log.e(TAG, "Error getting unused external storage amount.", e); } return null; }
java
protected static Long getUnusedExternalStorage() { try { if (isExternalStorageMounted()) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } } catch (Exception e) { Log.e(TAG, "Error getting unused external storage amount.", e); } return null; }
[ "protected", "static", "Long", "getUnusedExternalStorage", "(", ")", "{", "try", "{", "if", "(", "isExternalStorageMounted", "(", ")", ")", "{", "File", "path", "=", "Environment", ".", "getExternalStorageDirectory", "(", ")", ";", "StatFs", "stat", "=", "new", "StatFs", "(", "path", ".", "getPath", "(", ")", ")", ";", "long", "blockSize", "=", "stat", ".", "getBlockSize", "(", ")", ";", "long", "availableBlocks", "=", "stat", ".", "getAvailableBlocks", "(", ")", ";", "return", "availableBlocks", "*", "blockSize", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Error getting unused external storage amount.\"", ",", "e", ")", ";", "}", "return", "null", ";", "}" ]
Get the unused amount of external storage, in bytes, or null if no external storage is mounted. @return the unused amount of external storage, in bytes, or null if no external storage is mounted
[ "Get", "the", "unused", "amount", "of", "external", "storage", "in", "bytes", "or", "null", "if", "no", "external", "storage", "is", "mounted", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java#L452-L466
25,504
getsentry/sentry-java
sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java
AndroidEventBuilderHelper.getTotalExternalStorage
protected static Long getTotalExternalStorage() { try { if (isExternalStorageMounted()) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return totalBlocks * blockSize; } } catch (Exception e) { Log.e(TAG, "Error getting total external storage amount.", e); } return null; }
java
protected static Long getTotalExternalStorage() { try { if (isExternalStorageMounted()) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return totalBlocks * blockSize; } } catch (Exception e) { Log.e(TAG, "Error getting total external storage amount.", e); } return null; }
[ "protected", "static", "Long", "getTotalExternalStorage", "(", ")", "{", "try", "{", "if", "(", "isExternalStorageMounted", "(", ")", ")", "{", "File", "path", "=", "Environment", ".", "getExternalStorageDirectory", "(", ")", ";", "StatFs", "stat", "=", "new", "StatFs", "(", "path", ".", "getPath", "(", ")", ")", ";", "long", "blockSize", "=", "stat", ".", "getBlockSize", "(", ")", ";", "long", "totalBlocks", "=", "stat", ".", "getBlockCount", "(", ")", ";", "return", "totalBlocks", "*", "blockSize", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Error getting total external storage amount.\"", ",", "e", ")", ";", "}", "return", "null", ";", "}" ]
Get the total amount of external storage, in bytes, or null if no external storage is mounted. @return the total amount of external storage, in bytes, or null if no external storage is mounted
[ "Get", "the", "total", "amount", "of", "external", "storage", "in", "bytes", "or", "null", "if", "no", "external", "storage", "is", "mounted", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java#L475-L489
25,505
getsentry/sentry-java
sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java
AndroidEventBuilderHelper.getDisplayMetrics
protected static DisplayMetrics getDisplayMetrics(Context ctx) { try { return ctx.getResources().getDisplayMetrics(); } catch (Exception e) { Log.e(TAG, "Error getting DisplayMetrics.", e); return null; } }
java
protected static DisplayMetrics getDisplayMetrics(Context ctx) { try { return ctx.getResources().getDisplayMetrics(); } catch (Exception e) { Log.e(TAG, "Error getting DisplayMetrics.", e); return null; } }
[ "protected", "static", "DisplayMetrics", "getDisplayMetrics", "(", "Context", "ctx", ")", "{", "try", "{", "return", "ctx", ".", "getResources", "(", ")", ".", "getDisplayMetrics", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Error getting DisplayMetrics.\"", ",", "e", ")", ";", "return", "null", ";", "}", "}" ]
Get the DisplayMetrics object for the current application. @param ctx Android application context @return the DisplayMetrics object for the current application
[ "Get", "the", "DisplayMetrics", "object", "for", "the", "current", "application", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java#L497-L504
25,506
getsentry/sentry-java
sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java
AndroidEventBuilderHelper.getApplicationName
protected static String getApplicationName(Context ctx) { try { ApplicationInfo applicationInfo = ctx.getApplicationInfo(); int stringId = applicationInfo.labelRes; if (stringId == 0) { if (applicationInfo.nonLocalizedLabel != null) { return applicationInfo.nonLocalizedLabel.toString(); } } else { return ctx.getString(stringId); } } catch (Exception e) { Log.e(TAG, "Error getting application name.", e); } return null; }
java
protected static String getApplicationName(Context ctx) { try { ApplicationInfo applicationInfo = ctx.getApplicationInfo(); int stringId = applicationInfo.labelRes; if (stringId == 0) { if (applicationInfo.nonLocalizedLabel != null) { return applicationInfo.nonLocalizedLabel.toString(); } } else { return ctx.getString(stringId); } } catch (Exception e) { Log.e(TAG, "Error getting application name.", e); } return null; }
[ "protected", "static", "String", "getApplicationName", "(", "Context", "ctx", ")", "{", "try", "{", "ApplicationInfo", "applicationInfo", "=", "ctx", ".", "getApplicationInfo", "(", ")", ";", "int", "stringId", "=", "applicationInfo", ".", "labelRes", ";", "if", "(", "stringId", "==", "0", ")", "{", "if", "(", "applicationInfo", ".", "nonLocalizedLabel", "!=", "null", ")", "{", "return", "applicationInfo", ".", "nonLocalizedLabel", ".", "toString", "(", ")", ";", "}", "}", "else", "{", "return", "ctx", ".", "getString", "(", "stringId", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Error getting application name.\"", ",", "e", ")", ";", "}", "return", "null", ";", "}" ]
Get the human-facing Application name. @param ctx Android application context @return Application name
[ "Get", "the", "human", "-", "facing", "Application", "name", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java#L523-L539
25,507
getsentry/sentry-java
sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java
AndroidEventBuilderHelper.isConnected
protected static boolean isConnected(Context ctx) { ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); }
java
protected static boolean isConnected(Context ctx) { ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); }
[ "protected", "static", "boolean", "isConnected", "(", "Context", "ctx", ")", "{", "ConnectivityManager", "connectivityManager", "=", "(", "ConnectivityManager", ")", "ctx", ".", "getSystemService", "(", "Context", ".", "CONNECTIVITY_SERVICE", ")", ";", "NetworkInfo", "activeNetworkInfo", "=", "connectivityManager", ".", "getActiveNetworkInfo", "(", ")", ";", "return", "activeNetworkInfo", "!=", "null", "&&", "activeNetworkInfo", ".", "isConnected", "(", ")", ";", "}" ]
Check whether the application has internet access at a point in time. @param ctx Android application context @return true if the application has internet access
[ "Check", "whether", "the", "application", "has", "internet", "access", "at", "a", "point", "in", "time", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry-android/src/main/java/io/sentry/android/event/helper/AndroidEventBuilderHelper.java#L547-L552
25,508
getsentry/sentry-java
sentry-android/src/main/java/io/sentry/android/AndroidSentryClientFactory.java
AndroidSentryClientFactory.checkPermission
private boolean checkPermission(String permission) { int res = ctx.checkCallingOrSelfPermission(permission); return (res == PackageManager.PERMISSION_GRANTED); }
java
private boolean checkPermission(String permission) { int res = ctx.checkCallingOrSelfPermission(permission); return (res == PackageManager.PERMISSION_GRANTED); }
[ "private", "boolean", "checkPermission", "(", "String", "permission", ")", "{", "int", "res", "=", "ctx", ".", "checkCallingOrSelfPermission", "(", "permission", ")", ";", "return", "(", "res", "==", "PackageManager", ".", "PERMISSION_GRANTED", ")", ";", "}" ]
Check whether the application has been granted a certain permission. @param permission Permission as a string @return true if permissions is granted
[ "Check", "whether", "the", "application", "has", "been", "granted", "a", "certain", "permission", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry-android/src/main/java/io/sentry/android/AndroidSentryClientFactory.java#L128-L131
25,509
getsentry/sentry-java
sentry/src/main/java/io/sentry/jvmti/FrameCache.java
FrameCache.add
public static void add(Throwable throwable, Frame[] frames) { Map<Throwable, Frame[]> weakMap = cache.get(); weakMap.put(throwable, frames); }
java
public static void add(Throwable throwable, Frame[] frames) { Map<Throwable, Frame[]> weakMap = cache.get(); weakMap.put(throwable, frames); }
[ "public", "static", "void", "add", "(", "Throwable", "throwable", ",", "Frame", "[", "]", "frames", ")", "{", "Map", "<", "Throwable", ",", "Frame", "[", "]", ">", "weakMap", "=", "cache", ".", "get", "(", ")", ";", "weakMap", ".", "put", "(", "throwable", ",", "frames", ")", ";", "}" ]
Store the per-frame local variable information for the last exception thrown on this thread. @param throwable Throwable that the provided {@link Frame}s represent. @param frames Array of {@link Frame}s to store
[ "Store", "the", "per", "-", "frame", "local", "variable", "information", "for", "the", "last", "exception", "thrown", "on", "this", "thread", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/jvmti/FrameCache.java#L33-L36
25,510
getsentry/sentry-java
sentry/src/main/java/io/sentry/jvmti/FrameCache.java
FrameCache.get
public static Frame[] get(Throwable throwable) { Map<Throwable, Frame[]> weakMap = cache.get(); return weakMap.get(throwable); }
java
public static Frame[] get(Throwable throwable) { Map<Throwable, Frame[]> weakMap = cache.get(); return weakMap.get(throwable); }
[ "public", "static", "Frame", "[", "]", "get", "(", "Throwable", "throwable", ")", "{", "Map", "<", "Throwable", ",", "Frame", "[", "]", ">", "weakMap", "=", "cache", ".", "get", "(", ")", ";", "return", "weakMap", ".", "get", "(", "throwable", ")", ";", "}" ]
Retrieve the per-frame local variable information for the last exception thrown on this thread. @param throwable Throwable to look up cached {@link Frame}s for. @return Array of {@link Frame}s
[ "Retrieve", "the", "per", "-", "frame", "local", "variable", "information", "for", "the", "last", "exception", "thrown", "on", "this", "thread", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/jvmti/FrameCache.java#L44-L47
25,511
getsentry/sentry-java
sentry/src/main/java/io/sentry/marshaller/json/ExceptionInterfaceBinding.java
ExceptionInterfaceBinding.writeException
private void writeException(JsonGenerator generator, SentryException sentryException) throws IOException { generator.writeStartObject(); generator.writeStringField(TYPE_PARAMETER, sentryException.getExceptionClassName()); generator.writeStringField(VALUE_PARAMETER, sentryException.getExceptionMessage()); generator.writeStringField(MODULE_PARAMETER, sentryException.getExceptionPackageName()); generator.writeFieldName(STACKTRACE_PARAMETER); stackTraceInterfaceBinding.writeInterface(generator, sentryException.getStackTraceInterface()); generator.writeEndObject(); }
java
private void writeException(JsonGenerator generator, SentryException sentryException) throws IOException { generator.writeStartObject(); generator.writeStringField(TYPE_PARAMETER, sentryException.getExceptionClassName()); generator.writeStringField(VALUE_PARAMETER, sentryException.getExceptionMessage()); generator.writeStringField(MODULE_PARAMETER, sentryException.getExceptionPackageName()); generator.writeFieldName(STACKTRACE_PARAMETER); stackTraceInterfaceBinding.writeInterface(generator, sentryException.getStackTraceInterface()); generator.writeEndObject(); }
[ "private", "void", "writeException", "(", "JsonGenerator", "generator", ",", "SentryException", "sentryException", ")", "throws", "IOException", "{", "generator", ".", "writeStartObject", "(", ")", ";", "generator", ".", "writeStringField", "(", "TYPE_PARAMETER", ",", "sentryException", ".", "getExceptionClassName", "(", ")", ")", ";", "generator", ".", "writeStringField", "(", "VALUE_PARAMETER", ",", "sentryException", ".", "getExceptionMessage", "(", ")", ")", ";", "generator", ".", "writeStringField", "(", "MODULE_PARAMETER", ",", "sentryException", ".", "getExceptionPackageName", "(", ")", ")", ";", "generator", ".", "writeFieldName", "(", "STACKTRACE_PARAMETER", ")", ";", "stackTraceInterfaceBinding", ".", "writeInterface", "(", "generator", ",", "sentryException", ".", "getStackTraceInterface", "(", ")", ")", ";", "generator", ".", "writeEndObject", "(", ")", ";", "}" ]
Outputs an exception with its StackTrace on a JSon stream. @param generator JSonGenerator. @param sentryException Sentry exception with its associated {@link StackTraceInterface}. @throws IOException
[ "Outputs", "an", "exception", "with", "its", "StackTrace", "on", "a", "JSon", "stream", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/marshaller/json/ExceptionInterfaceBinding.java#L53-L61
25,512
getsentry/sentry-java
sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java
DefaultSentryClientFactory.createConnection
protected Connection createConnection(Dsn dsn) { String protocol = dsn.getProtocol(); Connection connection; if (protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("https")) { logger.debug("Using an {} connection to Sentry.", protocol.toUpperCase()); connection = createHttpConnection(dsn); } else if (protocol.equalsIgnoreCase("out")) { logger.debug("Using StdOut to send events."); connection = createStdOutConnection(dsn); } else if (protocol.equalsIgnoreCase("noop")) { logger.debug("Using noop to send events."); connection = new NoopConnection(); } else { throw new IllegalStateException("Couldn't create a connection for the protocol '" + protocol + "'"); } BufferedConnection bufferedConnection = null; if (getBufferEnabled(dsn)) { Buffer eventBuffer = getBuffer(dsn); if (eventBuffer != null) { long flushtime = getBufferFlushtime(dsn); boolean gracefulShutdown = getBufferedConnectionGracefulShutdownEnabled(dsn); Long shutdownTimeout = getBufferedConnectionShutdownTimeout(dsn); bufferedConnection = new BufferedConnection(connection, eventBuffer, flushtime, gracefulShutdown, shutdownTimeout); connection = bufferedConnection; } } // Enable async unless its value is 'false'. if (getAsyncEnabled(dsn)) { connection = createAsyncConnection(dsn, connection); } // If buffering is enabled, wrap connection with synchronous disk buffering "connection" if (bufferedConnection != null) { connection = bufferedConnection.wrapConnectionWithBufferWriter(connection); } return connection; }
java
protected Connection createConnection(Dsn dsn) { String protocol = dsn.getProtocol(); Connection connection; if (protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("https")) { logger.debug("Using an {} connection to Sentry.", protocol.toUpperCase()); connection = createHttpConnection(dsn); } else if (protocol.equalsIgnoreCase("out")) { logger.debug("Using StdOut to send events."); connection = createStdOutConnection(dsn); } else if (protocol.equalsIgnoreCase("noop")) { logger.debug("Using noop to send events."); connection = new NoopConnection(); } else { throw new IllegalStateException("Couldn't create a connection for the protocol '" + protocol + "'"); } BufferedConnection bufferedConnection = null; if (getBufferEnabled(dsn)) { Buffer eventBuffer = getBuffer(dsn); if (eventBuffer != null) { long flushtime = getBufferFlushtime(dsn); boolean gracefulShutdown = getBufferedConnectionGracefulShutdownEnabled(dsn); Long shutdownTimeout = getBufferedConnectionShutdownTimeout(dsn); bufferedConnection = new BufferedConnection(connection, eventBuffer, flushtime, gracefulShutdown, shutdownTimeout); connection = bufferedConnection; } } // Enable async unless its value is 'false'. if (getAsyncEnabled(dsn)) { connection = createAsyncConnection(dsn, connection); } // If buffering is enabled, wrap connection with synchronous disk buffering "connection" if (bufferedConnection != null) { connection = bufferedConnection.wrapConnectionWithBufferWriter(connection); } return connection; }
[ "protected", "Connection", "createConnection", "(", "Dsn", "dsn", ")", "{", "String", "protocol", "=", "dsn", ".", "getProtocol", "(", ")", ";", "Connection", "connection", ";", "if", "(", "protocol", ".", "equalsIgnoreCase", "(", "\"http\"", ")", "||", "protocol", ".", "equalsIgnoreCase", "(", "\"https\"", ")", ")", "{", "logger", ".", "debug", "(", "\"Using an {} connection to Sentry.\"", ",", "protocol", ".", "toUpperCase", "(", ")", ")", ";", "connection", "=", "createHttpConnection", "(", "dsn", ")", ";", "}", "else", "if", "(", "protocol", ".", "equalsIgnoreCase", "(", "\"out\"", ")", ")", "{", "logger", ".", "debug", "(", "\"Using StdOut to send events.\"", ")", ";", "connection", "=", "createStdOutConnection", "(", "dsn", ")", ";", "}", "else", "if", "(", "protocol", ".", "equalsIgnoreCase", "(", "\"noop\"", ")", ")", "{", "logger", ".", "debug", "(", "\"Using noop to send events.\"", ")", ";", "connection", "=", "new", "NoopConnection", "(", ")", ";", "}", "else", "{", "throw", "new", "IllegalStateException", "(", "\"Couldn't create a connection for the protocol '\"", "+", "protocol", "+", "\"'\"", ")", ";", "}", "BufferedConnection", "bufferedConnection", "=", "null", ";", "if", "(", "getBufferEnabled", "(", "dsn", ")", ")", "{", "Buffer", "eventBuffer", "=", "getBuffer", "(", "dsn", ")", ";", "if", "(", "eventBuffer", "!=", "null", ")", "{", "long", "flushtime", "=", "getBufferFlushtime", "(", "dsn", ")", ";", "boolean", "gracefulShutdown", "=", "getBufferedConnectionGracefulShutdownEnabled", "(", "dsn", ")", ";", "Long", "shutdownTimeout", "=", "getBufferedConnectionShutdownTimeout", "(", "dsn", ")", ";", "bufferedConnection", "=", "new", "BufferedConnection", "(", "connection", ",", "eventBuffer", ",", "flushtime", ",", "gracefulShutdown", ",", "shutdownTimeout", ")", ";", "connection", "=", "bufferedConnection", ";", "}", "}", "// Enable async unless its value is 'false'.", "if", "(", "getAsyncEnabled", "(", "dsn", ")", ")", "{", "connection", "=", "createAsyncConnection", "(", "dsn", ",", "connection", ")", ";", "}", "// If buffering is enabled, wrap connection with synchronous disk buffering \"connection\"", "if", "(", "bufferedConnection", "!=", "null", ")", "{", "connection", "=", "bufferedConnection", ".", "wrapConnectionWithBufferWriter", "(", "connection", ")", ";", "}", "return", "connection", ";", "}" ]
Creates a connection to the given DSN by determining the protocol. @param dsn Data Source Name of the Sentry server to use. @return a connection to the server.
[ "Creates", "a", "connection", "to", "the", "given", "DSN", "by", "determining", "the", "protocol", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java#L321-L362
25,513
getsentry/sentry-java
sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java
DefaultSentryClientFactory.createHttpConnection
protected Connection createHttpConnection(Dsn dsn) { URL sentryApiUrl = HttpConnection.getSentryApiUrl(dsn.getUri(), dsn.getProjectId()); String proxyHost = getProxyHost(dsn); String proxyUser = getProxyUser(dsn); String proxyPass = getProxyPass(dsn); int proxyPort = getProxyPort(dsn); Proxy proxy = null; if (proxyHost != null) { InetSocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort); proxy = new Proxy(Proxy.Type.HTTP, proxyAddr); if (proxyUser != null && proxyPass != null) { Authenticator.setDefault(new ProxyAuthenticator(proxyUser, proxyPass)); } } Double sampleRate = getSampleRate(dsn); EventSampler eventSampler = null; if (sampleRate != null) { eventSampler = new RandomEventSampler(sampleRate); } HttpConnection httpConnection = new HttpConnection(sentryApiUrl, dsn.getPublicKey(), dsn.getSecretKey(), proxy, eventSampler); Marshaller marshaller = createMarshaller(dsn); httpConnection.setMarshaller(marshaller); int timeout = getTimeout(dsn); httpConnection.setConnectionTimeout(timeout); boolean bypassSecurityEnabled = getBypassSecurityEnabled(dsn); httpConnection.setBypassSecurity(bypassSecurityEnabled); return httpConnection; }
java
protected Connection createHttpConnection(Dsn dsn) { URL sentryApiUrl = HttpConnection.getSentryApiUrl(dsn.getUri(), dsn.getProjectId()); String proxyHost = getProxyHost(dsn); String proxyUser = getProxyUser(dsn); String proxyPass = getProxyPass(dsn); int proxyPort = getProxyPort(dsn); Proxy proxy = null; if (proxyHost != null) { InetSocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort); proxy = new Proxy(Proxy.Type.HTTP, proxyAddr); if (proxyUser != null && proxyPass != null) { Authenticator.setDefault(new ProxyAuthenticator(proxyUser, proxyPass)); } } Double sampleRate = getSampleRate(dsn); EventSampler eventSampler = null; if (sampleRate != null) { eventSampler = new RandomEventSampler(sampleRate); } HttpConnection httpConnection = new HttpConnection(sentryApiUrl, dsn.getPublicKey(), dsn.getSecretKey(), proxy, eventSampler); Marshaller marshaller = createMarshaller(dsn); httpConnection.setMarshaller(marshaller); int timeout = getTimeout(dsn); httpConnection.setConnectionTimeout(timeout); boolean bypassSecurityEnabled = getBypassSecurityEnabled(dsn); httpConnection.setBypassSecurity(bypassSecurityEnabled); return httpConnection; }
[ "protected", "Connection", "createHttpConnection", "(", "Dsn", "dsn", ")", "{", "URL", "sentryApiUrl", "=", "HttpConnection", ".", "getSentryApiUrl", "(", "dsn", ".", "getUri", "(", ")", ",", "dsn", ".", "getProjectId", "(", ")", ")", ";", "String", "proxyHost", "=", "getProxyHost", "(", "dsn", ")", ";", "String", "proxyUser", "=", "getProxyUser", "(", "dsn", ")", ";", "String", "proxyPass", "=", "getProxyPass", "(", "dsn", ")", ";", "int", "proxyPort", "=", "getProxyPort", "(", "dsn", ")", ";", "Proxy", "proxy", "=", "null", ";", "if", "(", "proxyHost", "!=", "null", ")", "{", "InetSocketAddress", "proxyAddr", "=", "new", "InetSocketAddress", "(", "proxyHost", ",", "proxyPort", ")", ";", "proxy", "=", "new", "Proxy", "(", "Proxy", ".", "Type", ".", "HTTP", ",", "proxyAddr", ")", ";", "if", "(", "proxyUser", "!=", "null", "&&", "proxyPass", "!=", "null", ")", "{", "Authenticator", ".", "setDefault", "(", "new", "ProxyAuthenticator", "(", "proxyUser", ",", "proxyPass", ")", ")", ";", "}", "}", "Double", "sampleRate", "=", "getSampleRate", "(", "dsn", ")", ";", "EventSampler", "eventSampler", "=", "null", ";", "if", "(", "sampleRate", "!=", "null", ")", "{", "eventSampler", "=", "new", "RandomEventSampler", "(", "sampleRate", ")", ";", "}", "HttpConnection", "httpConnection", "=", "new", "HttpConnection", "(", "sentryApiUrl", ",", "dsn", ".", "getPublicKey", "(", ")", ",", "dsn", ".", "getSecretKey", "(", ")", ",", "proxy", ",", "eventSampler", ")", ";", "Marshaller", "marshaller", "=", "createMarshaller", "(", "dsn", ")", ";", "httpConnection", ".", "setMarshaller", "(", "marshaller", ")", ";", "int", "timeout", "=", "getTimeout", "(", "dsn", ")", ";", "httpConnection", ".", "setConnectionTimeout", "(", "timeout", ")", ";", "boolean", "bypassSecurityEnabled", "=", "getBypassSecurityEnabled", "(", "dsn", ")", ";", "httpConnection", ".", "setBypassSecurity", "(", "bypassSecurityEnabled", ")", ";", "return", "httpConnection", ";", "}" ]
Creates an HTTP connection to the Sentry server. @param dsn Data Source Name of the Sentry server. @return an {@link HttpConnection} to the server.
[ "Creates", "an", "HTTP", "connection", "to", "the", "Sentry", "server", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java#L401-L437
25,514
getsentry/sentry-java
sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java
DefaultSentryClientFactory.createStdOutConnection
protected Connection createStdOutConnection(Dsn dsn) { //CHECKSTYLE.OFF: RegexpSinglelineJava OutputStreamConnection stdOutConnection = new OutputStreamConnection(System.out); //CHECKSTYLE.ON: RegexpSinglelineJava stdOutConnection.setMarshaller(createMarshaller(dsn)); return stdOutConnection; }
java
protected Connection createStdOutConnection(Dsn dsn) { //CHECKSTYLE.OFF: RegexpSinglelineJava OutputStreamConnection stdOutConnection = new OutputStreamConnection(System.out); //CHECKSTYLE.ON: RegexpSinglelineJava stdOutConnection.setMarshaller(createMarshaller(dsn)); return stdOutConnection; }
[ "protected", "Connection", "createStdOutConnection", "(", "Dsn", "dsn", ")", "{", "//CHECKSTYLE.OFF: RegexpSinglelineJava", "OutputStreamConnection", "stdOutConnection", "=", "new", "OutputStreamConnection", "(", "System", ".", "out", ")", ";", "//CHECKSTYLE.ON: RegexpSinglelineJava", "stdOutConnection", ".", "setMarshaller", "(", "createMarshaller", "(", "dsn", ")", ")", ";", "return", "stdOutConnection", ";", "}" ]
Uses stdout to send the logs. @param dsn Data Source Name of the Sentry server. @return an {@link OutputStreamConnection} using {@code System.out}.
[ "Uses", "stdout", "to", "send", "the", "logs", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java#L445-L451
25,515
getsentry/sentry-java
sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java
DefaultSentryClientFactory.getBufferFlushtime
protected long getBufferFlushtime(Dsn dsn) { return Util.parseLong(Lookup.lookup(BUFFER_FLUSHTIME_OPTION, dsn), BUFFER_FLUSHTIME_DEFAULT); }
java
protected long getBufferFlushtime(Dsn dsn) { return Util.parseLong(Lookup.lookup(BUFFER_FLUSHTIME_OPTION, dsn), BUFFER_FLUSHTIME_DEFAULT); }
[ "protected", "long", "getBufferFlushtime", "(", "Dsn", "dsn", ")", "{", "return", "Util", ".", "parseLong", "(", "Lookup", ".", "lookup", "(", "BUFFER_FLUSHTIME_OPTION", ",", "dsn", ")", ",", "BUFFER_FLUSHTIME_DEFAULT", ")", ";", "}" ]
How long to wait between attempts to flush the disk buffer, in milliseconds. @param dsn Sentry server DSN which may contain options. @return ow long to wait between attempts to flush the disk buffer, in milliseconds.
[ "How", "long", "to", "wait", "between", "attempts", "to", "flush", "the", "disk", "buffer", "in", "milliseconds", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java#L600-L602
25,516
getsentry/sentry-java
sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java
DefaultSentryClientFactory.getAsyncShutdownTimeout
protected long getAsyncShutdownTimeout(Dsn dsn) { return Util.parseLong(Lookup.lookup(ASYNC_SHUTDOWN_TIMEOUT_OPTION, dsn), ASYNC_SHUTDOWN_TIMEOUT_DEFAULT); }
java
protected long getAsyncShutdownTimeout(Dsn dsn) { return Util.parseLong(Lookup.lookup(ASYNC_SHUTDOWN_TIMEOUT_OPTION, dsn), ASYNC_SHUTDOWN_TIMEOUT_DEFAULT); }
[ "protected", "long", "getAsyncShutdownTimeout", "(", "Dsn", "dsn", ")", "{", "return", "Util", ".", "parseLong", "(", "Lookup", ".", "lookup", "(", "ASYNC_SHUTDOWN_TIMEOUT_OPTION", ",", "dsn", ")", ",", "ASYNC_SHUTDOWN_TIMEOUT_DEFAULT", ")", ";", "}" ]
The graceful shutdown timeout of the async executor, in milliseconds. @param dsn Sentry server DSN which may contain options. @return The graceful shutdown timeout of the async executor, in milliseconds.
[ "The", "graceful", "shutdown", "timeout", "of", "the", "async", "executor", "in", "milliseconds", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java#L610-L612
25,517
getsentry/sentry-java
sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java
DefaultSentryClientFactory.getAsyncQueueSize
protected int getAsyncQueueSize(Dsn dsn) { return Util.parseInteger(Lookup.lookup(ASYNC_QUEUE_SIZE_OPTION, dsn), QUEUE_SIZE_DEFAULT); }
java
protected int getAsyncQueueSize(Dsn dsn) { return Util.parseInteger(Lookup.lookup(ASYNC_QUEUE_SIZE_OPTION, dsn), QUEUE_SIZE_DEFAULT); }
[ "protected", "int", "getAsyncQueueSize", "(", "Dsn", "dsn", ")", "{", "return", "Util", ".", "parseInteger", "(", "Lookup", ".", "lookup", "(", "ASYNC_QUEUE_SIZE_OPTION", ",", "dsn", ")", ",", "QUEUE_SIZE_DEFAULT", ")", ";", "}" ]
Maximum size of the async send queue. @param dsn Sentry server DSN which may contain options. @return Maximum size of the async send queue.
[ "Maximum", "size", "of", "the", "async", "send", "queue", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java#L630-L632
25,518
getsentry/sentry-java
sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java
DefaultSentryClientFactory.getAsyncPriority
protected int getAsyncPriority(Dsn dsn) { return Util.parseInteger(Lookup.lookup(ASYNC_PRIORITY_OPTION, dsn), Thread.MIN_PRIORITY); }
java
protected int getAsyncPriority(Dsn dsn) { return Util.parseInteger(Lookup.lookup(ASYNC_PRIORITY_OPTION, dsn), Thread.MIN_PRIORITY); }
[ "protected", "int", "getAsyncPriority", "(", "Dsn", "dsn", ")", "{", "return", "Util", ".", "parseInteger", "(", "Lookup", ".", "lookup", "(", "ASYNC_PRIORITY_OPTION", ",", "dsn", ")", ",", "Thread", ".", "MIN_PRIORITY", ")", ";", "}" ]
Priority of threads used for the async connection. @param dsn Sentry server DSN which may contain options. @return Priority of threads used for the async connection.
[ "Priority", "of", "threads", "used", "for", "the", "async", "connection", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java#L640-L642
25,519
getsentry/sentry-java
sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java
DefaultSentryClientFactory.getAsyncThreads
protected int getAsyncThreads(Dsn dsn) { return Util.parseInteger(Lookup.lookup(ASYNC_THREADS_OPTION, dsn), Runtime.getRuntime().availableProcessors()); }
java
protected int getAsyncThreads(Dsn dsn) { return Util.parseInteger(Lookup.lookup(ASYNC_THREADS_OPTION, dsn), Runtime.getRuntime().availableProcessors()); }
[ "protected", "int", "getAsyncThreads", "(", "Dsn", "dsn", ")", "{", "return", "Util", ".", "parseInteger", "(", "Lookup", ".", "lookup", "(", "ASYNC_THREADS_OPTION", ",", "dsn", ")", ",", "Runtime", ".", "getRuntime", "(", ")", ".", "availableProcessors", "(", ")", ")", ";", "}" ]
The number of threads used for the async connection. @param dsn Sentry server DSN which may contain options. @return The number of threads used for the async connection.
[ "The", "number", "of", "threads", "used", "for", "the", "async", "connection", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java#L650-L653
25,520
getsentry/sentry-java
sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java
DefaultSentryClientFactory.getProxyPort
protected int getProxyPort(Dsn dsn) { return Util.parseInteger(Lookup.lookup(HTTP_PROXY_PORT_OPTION, dsn), HTTP_PROXY_PORT_DEFAULT); }
java
protected int getProxyPort(Dsn dsn) { return Util.parseInteger(Lookup.lookup(HTTP_PROXY_PORT_OPTION, dsn), HTTP_PROXY_PORT_DEFAULT); }
[ "protected", "int", "getProxyPort", "(", "Dsn", "dsn", ")", "{", "return", "Util", ".", "parseInteger", "(", "Lookup", ".", "lookup", "(", "HTTP_PROXY_PORT_OPTION", ",", "dsn", ")", ",", "HTTP_PROXY_PORT_DEFAULT", ")", ";", "}" ]
HTTP proxy port for Sentry connections. @param dsn Sentry server DSN which may contain options. @return HTTP proxy port for Sentry connections.
[ "HTTP", "proxy", "port", "for", "Sentry", "connections", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java#L681-L683
25,521
getsentry/sentry-java
sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java
DefaultSentryClientFactory.getMaxMessageLength
protected int getMaxMessageLength(Dsn dsn) { return Util.parseInteger( Lookup.lookup(MAX_MESSAGE_LENGTH_OPTION, dsn), JsonMarshaller.DEFAULT_MAX_MESSAGE_LENGTH); }
java
protected int getMaxMessageLength(Dsn dsn) { return Util.parseInteger( Lookup.lookup(MAX_MESSAGE_LENGTH_OPTION, dsn), JsonMarshaller.DEFAULT_MAX_MESSAGE_LENGTH); }
[ "protected", "int", "getMaxMessageLength", "(", "Dsn", "dsn", ")", "{", "return", "Util", ".", "parseInteger", "(", "Lookup", ".", "lookup", "(", "MAX_MESSAGE_LENGTH_OPTION", ",", "dsn", ")", ",", "JsonMarshaller", ".", "DEFAULT_MAX_MESSAGE_LENGTH", ")", ";", "}" ]
The maximum length of the message body in the requests to the Sentry Server. @param dsn Sentry server DSN which may contain options. @return The maximum length of the message body in the requests to the Sentry Server.
[ "The", "maximum", "length", "of", "the", "message", "body", "in", "the", "requests", "to", "the", "Sentry", "Server", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java#L836-L839
25,522
getsentry/sentry-java
sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java
DefaultSentryClientFactory.getTimeout
protected int getTimeout(Dsn dsn) { return Util.parseInteger(Lookup.lookup(TIMEOUT_OPTION, dsn), TIMEOUT_DEFAULT); }
java
protected int getTimeout(Dsn dsn) { return Util.parseInteger(Lookup.lookup(TIMEOUT_OPTION, dsn), TIMEOUT_DEFAULT); }
[ "protected", "int", "getTimeout", "(", "Dsn", "dsn", ")", "{", "return", "Util", ".", "parseInteger", "(", "Lookup", ".", "lookup", "(", "TIMEOUT_OPTION", ",", "dsn", ")", ",", "TIMEOUT_DEFAULT", ")", ";", "}" ]
Timeout for requests to the Sentry server, in milliseconds. @param dsn Sentry server DSN which may contain options. @return Timeout for requests to the Sentry server, in milliseconds.
[ "Timeout", "for", "requests", "to", "the", "Sentry", "server", "in", "milliseconds", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java#L847-L849
25,523
getsentry/sentry-java
sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java
DefaultSentryClientFactory.getBufferEnabled
protected boolean getBufferEnabled(Dsn dsn) { String bufferEnabled = Lookup.lookup(BUFFER_ENABLED_OPTION, dsn); if (bufferEnabled != null) { return Boolean.parseBoolean(bufferEnabled); } return BUFFER_ENABLED_DEFAULT; }
java
protected boolean getBufferEnabled(Dsn dsn) { String bufferEnabled = Lookup.lookup(BUFFER_ENABLED_OPTION, dsn); if (bufferEnabled != null) { return Boolean.parseBoolean(bufferEnabled); } return BUFFER_ENABLED_DEFAULT; }
[ "protected", "boolean", "getBufferEnabled", "(", "Dsn", "dsn", ")", "{", "String", "bufferEnabled", "=", "Lookup", ".", "lookup", "(", "BUFFER_ENABLED_OPTION", ",", "dsn", ")", ";", "if", "(", "bufferEnabled", "!=", "null", ")", "{", "return", "Boolean", ".", "parseBoolean", "(", "bufferEnabled", ")", ";", "}", "return", "BUFFER_ENABLED_DEFAULT", ";", "}" ]
Whether or not buffering is enabled. @param dsn Sentry server DSN which may contain options. @return Whether or not buffering is enabled.
[ "Whether", "or", "not", "buffering", "is", "enabled", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java#L857-L863
25,524
getsentry/sentry-java
sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java
DefaultSentryClientFactory.getBufferSize
protected int getBufferSize(Dsn dsn) { return Util.parseInteger(Lookup.lookup(BUFFER_SIZE_OPTION, dsn), BUFFER_SIZE_DEFAULT); }
java
protected int getBufferSize(Dsn dsn) { return Util.parseInteger(Lookup.lookup(BUFFER_SIZE_OPTION, dsn), BUFFER_SIZE_DEFAULT); }
[ "protected", "int", "getBufferSize", "(", "Dsn", "dsn", ")", "{", "return", "Util", ".", "parseInteger", "(", "Lookup", ".", "lookup", "(", "BUFFER_SIZE_OPTION", ",", "dsn", ")", ",", "BUFFER_SIZE_DEFAULT", ")", ";", "}" ]
Get the maximum number of events to cache offline when network is down. @param dsn Dsn passed in by the user. @return the maximum number of events to cache offline when network is down.
[ "Get", "the", "maximum", "number", "of", "events", "to", "cache", "offline", "when", "network", "is", "down", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/DefaultSentryClientFactory.java#L885-L887
25,525
getsentry/sentry-java
sentry/src/main/java/io/sentry/util/CircularFifoQueue.java
CircularFifoQueue.writeObject
private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(size()); for (final E e : this) { out.writeObject(e); } }
java
private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(size()); for (final E e : this) { out.writeObject(e); } }
[ "private", "void", "writeObject", "(", "final", "ObjectOutputStream", "out", ")", "throws", "IOException", "{", "out", ".", "defaultWriteObject", "(", ")", ";", "out", ".", "writeInt", "(", "size", "(", ")", ")", ";", "for", "(", "final", "E", "e", ":", "this", ")", "{", "out", ".", "writeObject", "(", "e", ")", ";", "}", "}" ]
Write the queue out using a custom routine. @param out the output stream @throws IOException if an I/O error occurs while writing to the output stream
[ "Write", "the", "queue", "out", "using", "a", "custom", "routine", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/util/CircularFifoQueue.java#L115-L121
25,526
getsentry/sentry-java
sentry/src/main/java/io/sentry/util/CircularFifoQueue.java
CircularFifoQueue.readObject
@SuppressWarnings("unchecked") private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); elements = (E[]) new Object[maxElements]; final int size = in.readInt(); for (int i = 0; i < size; i++) { elements[i] = (E) in.readObject(); } start = 0; full = size == maxElements; if (full) { end = 0; } else { end = size; } }
java
@SuppressWarnings("unchecked") private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); elements = (E[]) new Object[maxElements]; final int size = in.readInt(); for (int i = 0; i < size; i++) { elements[i] = (E) in.readObject(); } start = 0; full = size == maxElements; if (full) { end = 0; } else { end = size; } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "void", "readObject", "(", "final", "ObjectInputStream", "in", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "in", ".", "defaultReadObject", "(", ")", ";", "elements", "=", "(", "E", "[", "]", ")", "new", "Object", "[", "maxElements", "]", ";", "final", "int", "size", "=", "in", ".", "readInt", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "elements", "[", "i", "]", "=", "(", "E", ")", "in", ".", "readObject", "(", ")", ";", "}", "start", "=", "0", ";", "full", "=", "size", "==", "maxElements", ";", "if", "(", "full", ")", "{", "end", "=", "0", ";", "}", "else", "{", "end", "=", "size", ";", "}", "}" ]
Read the queue in using a custom routine. @param in the input stream @throws IOException if an I/O error occurs while writing to the output stream @throws ClassNotFoundException if the class of a serialized object can not be found
[ "Read", "the", "queue", "in", "using", "a", "custom", "routine", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/util/CircularFifoQueue.java#L130-L145
25,527
getsentry/sentry-java
sentry/src/main/java/io/sentry/util/CircularFifoQueue.java
CircularFifoQueue.clear
@Override public void clear() { full = false; start = 0; end = 0; Arrays.fill(elements, null); }
java
@Override public void clear() { full = false; start = 0; end = 0; Arrays.fill(elements, null); }
[ "@", "Override", "public", "void", "clear", "(", ")", "{", "full", "=", "false", ";", "start", "=", "0", ";", "end", "=", "0", ";", "Arrays", ".", "fill", "(", "elements", ",", "null", ")", ";", "}" ]
Clears this queue.
[ "Clears", "this", "queue", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/util/CircularFifoQueue.java#L213-L219
25,528
getsentry/sentry-java
sentry/src/main/java/io/sentry/util/CircularFifoQueue.java
CircularFifoQueue.add
@Override public boolean add(final E element) { if (null == element) { throw new NullPointerException("Attempted to add null object to queue"); } if (isAtFullCapacity()) { remove(); } elements[end++] = element; if (end >= maxElements) { end = 0; } if (end == start) { full = true; } return true; }
java
@Override public boolean add(final E element) { if (null == element) { throw new NullPointerException("Attempted to add null object to queue"); } if (isAtFullCapacity()) { remove(); } elements[end++] = element; if (end >= maxElements) { end = 0; } if (end == start) { full = true; } return true; }
[ "@", "Override", "public", "boolean", "add", "(", "final", "E", "element", ")", "{", "if", "(", "null", "==", "element", ")", "{", "throw", "new", "NullPointerException", "(", "\"Attempted to add null object to queue\"", ")", ";", "}", "if", "(", "isAtFullCapacity", "(", ")", ")", "{", "remove", "(", ")", ";", "}", "elements", "[", "end", "++", "]", "=", "element", ";", "if", "(", "end", ">=", "maxElements", ")", "{", "end", "=", "0", ";", "}", "if", "(", "end", "==", "start", ")", "{", "full", "=", "true", ";", "}", "return", "true", ";", "}" ]
Adds the given element to this queue. If the queue is full, the least recently added element is discarded so that a new element can be inserted. @param element the element to add @return true, always @throws NullPointerException if the given element is null
[ "Adds", "the", "given", "element", "to", "this", "queue", ".", "If", "the", "queue", "is", "full", "the", "least", "recently", "added", "element", "is", "discarded", "so", "that", "a", "new", "element", "can", "be", "inserted", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/util/CircularFifoQueue.java#L229-L250
25,529
getsentry/sentry-java
sentry/src/main/java/io/sentry/util/CircularFifoQueue.java
CircularFifoQueue.get
public E get(final int index) { final int sz = size(); if (index < 0 || index >= sz) { throw new NoSuchElementException( String.format("The specified index (%1$d) is outside the available range [0, %2$d)", Integer.valueOf(index), Integer.valueOf(sz))); } final int idx = (start + index) % maxElements; return elements[idx]; }
java
public E get(final int index) { final int sz = size(); if (index < 0 || index >= sz) { throw new NoSuchElementException( String.format("The specified index (%1$d) is outside the available range [0, %2$d)", Integer.valueOf(index), Integer.valueOf(sz))); } final int idx = (start + index) % maxElements; return elements[idx]; }
[ "public", "E", "get", "(", "final", "int", "index", ")", "{", "final", "int", "sz", "=", "size", "(", ")", ";", "if", "(", "index", "<", "0", "||", "index", ">=", "sz", ")", "{", "throw", "new", "NoSuchElementException", "(", "String", ".", "format", "(", "\"The specified index (%1$d) is outside the available range [0, %2$d)\"", ",", "Integer", ".", "valueOf", "(", "index", ")", ",", "Integer", ".", "valueOf", "(", "sz", ")", ")", ")", ";", "}", "final", "int", "idx", "=", "(", "start", "+", "index", ")", "%", "maxElements", ";", "return", "elements", "[", "idx", "]", ";", "}" ]
Returns the element at the specified position in this queue. @param index the position of the element in the queue @return the element at position {@code index} @throws NoSuchElementException if the requested position is outside the range [0, size)
[ "Returns", "the", "element", "at", "the", "specified", "position", "in", "this", "queue", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/util/CircularFifoQueue.java#L259-L269
25,530
getsentry/sentry-java
sentry/src/main/java/io/sentry/util/CircularFifoQueue.java
CircularFifoQueue.iterator
@Override public Iterator<E> iterator() { return new Iterator<E>() { private int index = start; private int lastReturnedIndex = -1; private boolean isFirst = full; @Override public boolean hasNext() { return isFirst || index != end; } @Override public E next() { if (!hasNext()) { throw new NoSuchElementException(); } isFirst = false; lastReturnedIndex = index; index = increment(index); return elements[lastReturnedIndex]; } @Override public void remove() { if (lastReturnedIndex == -1) { throw new IllegalStateException(); } // First element can be removed quickly if (lastReturnedIndex == start) { CircularFifoQueue.this.remove(); lastReturnedIndex = -1; return; } int pos = lastReturnedIndex + 1; if (start < lastReturnedIndex && pos < end) { // shift in one part System.arraycopy(elements, pos, elements, lastReturnedIndex, end - pos); } else { // Other elements require us to shift the subsequent elements while (pos != end) { if (pos >= maxElements) { elements[pos - 1] = elements[0]; pos = 0; } else { elements[decrement(pos)] = elements[pos]; pos = increment(pos); } } } lastReturnedIndex = -1; end = decrement(end); elements[end] = null; full = false; index = decrement(index); } }; }
java
@Override public Iterator<E> iterator() { return new Iterator<E>() { private int index = start; private int lastReturnedIndex = -1; private boolean isFirst = full; @Override public boolean hasNext() { return isFirst || index != end; } @Override public E next() { if (!hasNext()) { throw new NoSuchElementException(); } isFirst = false; lastReturnedIndex = index; index = increment(index); return elements[lastReturnedIndex]; } @Override public void remove() { if (lastReturnedIndex == -1) { throw new IllegalStateException(); } // First element can be removed quickly if (lastReturnedIndex == start) { CircularFifoQueue.this.remove(); lastReturnedIndex = -1; return; } int pos = lastReturnedIndex + 1; if (start < lastReturnedIndex && pos < end) { // shift in one part System.arraycopy(elements, pos, elements, lastReturnedIndex, end - pos); } else { // Other elements require us to shift the subsequent elements while (pos != end) { if (pos >= maxElements) { elements[pos - 1] = elements[0]; pos = 0; } else { elements[decrement(pos)] = elements[pos]; pos = increment(pos); } } } lastReturnedIndex = -1; end = decrement(end); elements[end] = null; full = false; index = decrement(index); } }; }
[ "@", "Override", "public", "Iterator", "<", "E", ">", "iterator", "(", ")", "{", "return", "new", "Iterator", "<", "E", ">", "(", ")", "{", "private", "int", "index", "=", "start", ";", "private", "int", "lastReturnedIndex", "=", "-", "1", ";", "private", "boolean", "isFirst", "=", "full", ";", "@", "Override", "public", "boolean", "hasNext", "(", ")", "{", "return", "isFirst", "||", "index", "!=", "end", ";", "}", "@", "Override", "public", "E", "next", "(", ")", "{", "if", "(", "!", "hasNext", "(", ")", ")", "{", "throw", "new", "NoSuchElementException", "(", ")", ";", "}", "isFirst", "=", "false", ";", "lastReturnedIndex", "=", "index", ";", "index", "=", "increment", "(", "index", ")", ";", "return", "elements", "[", "lastReturnedIndex", "]", ";", "}", "@", "Override", "public", "void", "remove", "(", ")", "{", "if", "(", "lastReturnedIndex", "==", "-", "1", ")", "{", "throw", "new", "IllegalStateException", "(", ")", ";", "}", "// First element can be removed quickly", "if", "(", "lastReturnedIndex", "==", "start", ")", "{", "CircularFifoQueue", ".", "this", ".", "remove", "(", ")", ";", "lastReturnedIndex", "=", "-", "1", ";", "return", ";", "}", "int", "pos", "=", "lastReturnedIndex", "+", "1", ";", "if", "(", "start", "<", "lastReturnedIndex", "&&", "pos", "<", "end", ")", "{", "// shift in one part", "System", ".", "arraycopy", "(", "elements", ",", "pos", ",", "elements", ",", "lastReturnedIndex", ",", "end", "-", "pos", ")", ";", "}", "else", "{", "// Other elements require us to shift the subsequent elements", "while", "(", "pos", "!=", "end", ")", "{", "if", "(", "pos", ">=", "maxElements", ")", "{", "elements", "[", "pos", "-", "1", "]", "=", "elements", "[", "0", "]", ";", "pos", "=", "0", ";", "}", "else", "{", "elements", "[", "decrement", "(", "pos", ")", "]", "=", "elements", "[", "pos", "]", ";", "pos", "=", "increment", "(", "pos", ")", ";", "}", "}", "}", "lastReturnedIndex", "=", "-", "1", ";", "end", "=", "decrement", "(", "end", ")", ";", "elements", "[", "end", "]", "=", "null", ";", "full", "=", "false", ";", "index", "=", "decrement", "(", "index", ")", ";", "}", "}", ";", "}" ]
Returns an iterator over this queue's elements. @return an iterator over this queue's elements
[ "Returns", "an", "iterator", "over", "this", "queue", "s", "elements", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/util/CircularFifoQueue.java#L362-L424
25,531
getsentry/sentry-java
sentry/src/main/java/io/sentry/connection/AsyncConnection.java
AsyncConnection.doClose
@SuppressWarnings("checkstyle:magicnumber") private void doClose() throws IOException { logger.debug("Gracefully shutting down Sentry async threads."); closed = true; executorService.shutdown(); try { if (shutdownTimeout == -1L) { // Block until the executor terminates, but log periodically. long waitBetweenLoggingMs = 5000L; while (true) { if (executorService.awaitTermination(waitBetweenLoggingMs, TimeUnit.MILLISECONDS)) { break; } logger.debug("Still waiting on async executor to terminate."); } } else if (!executorService.awaitTermination(shutdownTimeout, TimeUnit.MILLISECONDS)) { logger.warn("Graceful shutdown took too much time, forcing the shutdown."); List<Runnable> tasks = executorService.shutdownNow(); logger.warn("{} tasks failed to execute before shutdown.", tasks.size()); } logger.debug("Shutdown finished."); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn("Graceful shutdown interrupted, forcing the shutdown."); List<Runnable> tasks = executorService.shutdownNow(); logger.warn("{} tasks failed to execute before shutdown.", tasks.size()); } finally { actualConnection.close(); } }
java
@SuppressWarnings("checkstyle:magicnumber") private void doClose() throws IOException { logger.debug("Gracefully shutting down Sentry async threads."); closed = true; executorService.shutdown(); try { if (shutdownTimeout == -1L) { // Block until the executor terminates, but log periodically. long waitBetweenLoggingMs = 5000L; while (true) { if (executorService.awaitTermination(waitBetweenLoggingMs, TimeUnit.MILLISECONDS)) { break; } logger.debug("Still waiting on async executor to terminate."); } } else if (!executorService.awaitTermination(shutdownTimeout, TimeUnit.MILLISECONDS)) { logger.warn("Graceful shutdown took too much time, forcing the shutdown."); List<Runnable> tasks = executorService.shutdownNow(); logger.warn("{} tasks failed to execute before shutdown.", tasks.size()); } logger.debug("Shutdown finished."); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn("Graceful shutdown interrupted, forcing the shutdown."); List<Runnable> tasks = executorService.shutdownNow(); logger.warn("{} tasks failed to execute before shutdown.", tasks.size()); } finally { actualConnection.close(); } }
[ "@", "SuppressWarnings", "(", "\"checkstyle:magicnumber\"", ")", "private", "void", "doClose", "(", ")", "throws", "IOException", "{", "logger", ".", "debug", "(", "\"Gracefully shutting down Sentry async threads.\"", ")", ";", "closed", "=", "true", ";", "executorService", ".", "shutdown", "(", ")", ";", "try", "{", "if", "(", "shutdownTimeout", "==", "-", "1L", ")", "{", "// Block until the executor terminates, but log periodically.", "long", "waitBetweenLoggingMs", "=", "5000L", ";", "while", "(", "true", ")", "{", "if", "(", "executorService", ".", "awaitTermination", "(", "waitBetweenLoggingMs", ",", "TimeUnit", ".", "MILLISECONDS", ")", ")", "{", "break", ";", "}", "logger", ".", "debug", "(", "\"Still waiting on async executor to terminate.\"", ")", ";", "}", "}", "else", "if", "(", "!", "executorService", ".", "awaitTermination", "(", "shutdownTimeout", ",", "TimeUnit", ".", "MILLISECONDS", ")", ")", "{", "logger", ".", "warn", "(", "\"Graceful shutdown took too much time, forcing the shutdown.\"", ")", ";", "List", "<", "Runnable", ">", "tasks", "=", "executorService", ".", "shutdownNow", "(", ")", ";", "logger", ".", "warn", "(", "\"{} tasks failed to execute before shutdown.\"", ",", "tasks", ".", "size", "(", ")", ")", ";", "}", "logger", ".", "debug", "(", "\"Shutdown finished.\"", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "logger", ".", "warn", "(", "\"Graceful shutdown interrupted, forcing the shutdown.\"", ")", ";", "List", "<", "Runnable", ">", "tasks", "=", "executorService", ".", "shutdownNow", "(", ")", ";", "logger", ".", "warn", "(", "\"{} tasks failed to execute before shutdown.\"", ",", "tasks", ".", "size", "(", ")", ")", ";", "}", "finally", "{", "actualConnection", ".", "close", "(", ")", ";", "}", "}" ]
Close the connection whether it's from the shutdown hook or not. @see #close()
[ "Close", "the", "connection", "whether", "it", "s", "from", "the", "shutdown", "hook", "or", "not", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/connection/AsyncConnection.java#L128-L157
25,532
getsentry/sentry-java
sentry/src/main/java/io/sentry/event/EventBuilder.java
EventBuilder.calculateChecksum
private static String calculateChecksum(String string) { byte[] bytes = string.getBytes(UTF_8); Checksum checksum = new CRC32(); checksum.update(bytes, 0, bytes.length); return Long.toHexString(checksum.getValue()).toUpperCase(); }
java
private static String calculateChecksum(String string) { byte[] bytes = string.getBytes(UTF_8); Checksum checksum = new CRC32(); checksum.update(bytes, 0, bytes.length); return Long.toHexString(checksum.getValue()).toUpperCase(); }
[ "private", "static", "String", "calculateChecksum", "(", "String", "string", ")", "{", "byte", "[", "]", "bytes", "=", "string", ".", "getBytes", "(", "UTF_8", ")", ";", "Checksum", "checksum", "=", "new", "CRC32", "(", ")", ";", "checksum", ".", "update", "(", "bytes", ",", "0", ",", "bytes", ".", "length", ")", ";", "return", "Long", ".", "toHexString", "(", "checksum", ".", "getValue", "(", ")", ")", ".", "toUpperCase", "(", ")", ";", "}" ]
Calculates a checksum for a given string. @param string string from which a checksum should be obtained @return a checksum allowing two events with the same properties to be grouped later.
[ "Calculates", "a", "checksum", "for", "a", "given", "string", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/event/EventBuilder.java#L67-L72
25,533
getsentry/sentry-java
sentry/src/main/java/io/sentry/event/EventBuilder.java
EventBuilder.autoSetMissingValues
private void autoSetMissingValues() { // Ensure that a timestamp is set (to now at least!) if (event.getTimestamp() == null) { event.setTimestamp(new Date()); } // Ensure that a platform is set if (event.getPlatform() == null) { event.setPlatform(DEFAULT_PLATFORM); } // Ensure that an SDK is set if (event.getSdk() == null) { event.setSdk(new Sdk(SentryEnvironment.SDK_NAME, SentryEnvironment.SDK_VERSION, sdkIntegrations)); } // Ensure that a hostname is set if (event.getServerName() == null) { event.setServerName(HOSTNAME_CACHE.getHostname()); } }
java
private void autoSetMissingValues() { // Ensure that a timestamp is set (to now at least!) if (event.getTimestamp() == null) { event.setTimestamp(new Date()); } // Ensure that a platform is set if (event.getPlatform() == null) { event.setPlatform(DEFAULT_PLATFORM); } // Ensure that an SDK is set if (event.getSdk() == null) { event.setSdk(new Sdk(SentryEnvironment.SDK_NAME, SentryEnvironment.SDK_VERSION, sdkIntegrations)); } // Ensure that a hostname is set if (event.getServerName() == null) { event.setServerName(HOSTNAME_CACHE.getHostname()); } }
[ "private", "void", "autoSetMissingValues", "(", ")", "{", "// Ensure that a timestamp is set (to now at least!)", "if", "(", "event", ".", "getTimestamp", "(", ")", "==", "null", ")", "{", "event", ".", "setTimestamp", "(", "new", "Date", "(", ")", ")", ";", "}", "// Ensure that a platform is set", "if", "(", "event", ".", "getPlatform", "(", ")", "==", "null", ")", "{", "event", ".", "setPlatform", "(", "DEFAULT_PLATFORM", ")", ";", "}", "// Ensure that an SDK is set", "if", "(", "event", ".", "getSdk", "(", ")", "==", "null", ")", "{", "event", ".", "setSdk", "(", "new", "Sdk", "(", "SentryEnvironment", ".", "SDK_NAME", ",", "SentryEnvironment", ".", "SDK_VERSION", ",", "sdkIntegrations", ")", ")", ";", "}", "// Ensure that a hostname is set", "if", "(", "event", ".", "getServerName", "(", ")", "==", "null", ")", "{", "event", ".", "setServerName", "(", "HOSTNAME_CACHE", ".", "getHostname", "(", ")", ")", ";", "}", "}" ]
Sets default values for each field that hasn't been provided manually.
[ "Sets", "default", "values", "for", "each", "field", "that", "hasn", "t", "been", "provided", "manually", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/event/EventBuilder.java#L77-L98
25,534
getsentry/sentry-java
sentry/src/main/java/io/sentry/event/EventBuilder.java
EventBuilder.withContexts
public EventBuilder withContexts(Map<String, Map<String, Object>> contexts) { event.setContexts(contexts); return this; }
java
public EventBuilder withContexts(Map<String, Map<String, Object>> contexts) { event.setContexts(contexts); return this; }
[ "public", "EventBuilder", "withContexts", "(", "Map", "<", "String", ",", "Map", "<", "String", ",", "Object", ">", ">", "contexts", ")", "{", "event", ".", "setContexts", "(", "contexts", ")", ";", "return", "this", ";", "}" ]
Adds a map of map of context objects to the event. @param contexts map of map of contexts @return the current {@code EventBuilder} for chained calls.
[ "Adds", "a", "map", "of", "map", "of", "context", "objects", "to", "the", "event", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/event/EventBuilder.java#L325-L328
25,535
getsentry/sentry-java
sentry/src/main/java/io/sentry/event/EventBuilder.java
EventBuilder.withExtra
public EventBuilder withExtra(String extraName, Object extraValue) { event.getExtra().put(extraName, extraValue); return this; }
java
public EventBuilder withExtra(String extraName, Object extraValue) { event.getExtra().put(extraName, extraValue); return this; }
[ "public", "EventBuilder", "withExtra", "(", "String", "extraName", ",", "Object", "extraValue", ")", "{", "event", ".", "getExtra", "(", ")", ".", "put", "(", "extraName", ",", "extraValue", ")", ";", "return", "this", ";", "}" ]
Adds an extra property to the event. @param extraName name of the extra property. @param extraValue value of the extra property. @return the current {@code EventBuilder} for chained calls.
[ "Adds", "an", "extra", "property", "to", "the", "event", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/event/EventBuilder.java#L348-L351
25,536
getsentry/sentry-java
sentry/src/main/java/io/sentry/event/EventBuilder.java
EventBuilder.withFingerprint
public EventBuilder withFingerprint(String... fingerprint) { List<String> list = new ArrayList<>(fingerprint.length); Collections.addAll(list, fingerprint); event.setFingerprint(list); return this; }
java
public EventBuilder withFingerprint(String... fingerprint) { List<String> list = new ArrayList<>(fingerprint.length); Collections.addAll(list, fingerprint); event.setFingerprint(list); return this; }
[ "public", "EventBuilder", "withFingerprint", "(", "String", "...", "fingerprint", ")", "{", "List", "<", "String", ">", "list", "=", "new", "ArrayList", "<>", "(", "fingerprint", ".", "length", ")", ";", "Collections", ".", "addAll", "(", "list", ",", "fingerprint", ")", ";", "event", ".", "setFingerprint", "(", "list", ")", ";", "return", "this", ";", "}" ]
Sets event fingerprint, an array of strings used to dictate the deduplicating for this event. @param fingerprint fingerprint @return the current {@code EventBuilder} for chained calls.
[ "Sets", "event", "fingerprint", "an", "array", "of", "strings", "used", "to", "dictate", "the", "deduplicating", "for", "this", "event", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/event/EventBuilder.java#L359-L364
25,537
getsentry/sentry-java
sentry/src/main/java/io/sentry/SentryUncaughtExceptionHandler.java
SentryUncaughtExceptionHandler.uncaughtException
@Override public void uncaughtException(Thread thread, Throwable thrown) { if (enabled) { logger.trace("Uncaught exception received."); EventBuilder eventBuilder = new EventBuilder() .withMessage(thrown.getMessage()) .withLevel(Event.Level.FATAL) .withSentryInterface(new ExceptionInterface(thrown)); try { Sentry.capture(eventBuilder); } catch (Exception e) { logger.error("Error sending uncaught exception to Sentry.", e); } } // taken from ThreadGroup#uncaughtException if (defaultExceptionHandler != null) { // call the original handler defaultExceptionHandler.uncaughtException(thread, thrown); } else if (!(thrown instanceof ThreadDeath)) { // CHECKSTYLE.OFF: RegexpSinglelineJava System.err.print("Exception in thread \"" + thread.getName() + "\" "); thrown.printStackTrace(System.err); // CHECKSTYLE.ON: RegexpSinglelineJava } }
java
@Override public void uncaughtException(Thread thread, Throwable thrown) { if (enabled) { logger.trace("Uncaught exception received."); EventBuilder eventBuilder = new EventBuilder() .withMessage(thrown.getMessage()) .withLevel(Event.Level.FATAL) .withSentryInterface(new ExceptionInterface(thrown)); try { Sentry.capture(eventBuilder); } catch (Exception e) { logger.error("Error sending uncaught exception to Sentry.", e); } } // taken from ThreadGroup#uncaughtException if (defaultExceptionHandler != null) { // call the original handler defaultExceptionHandler.uncaughtException(thread, thrown); } else if (!(thrown instanceof ThreadDeath)) { // CHECKSTYLE.OFF: RegexpSinglelineJava System.err.print("Exception in thread \"" + thread.getName() + "\" "); thrown.printStackTrace(System.err); // CHECKSTYLE.ON: RegexpSinglelineJava } }
[ "@", "Override", "public", "void", "uncaughtException", "(", "Thread", "thread", ",", "Throwable", "thrown", ")", "{", "if", "(", "enabled", ")", "{", "logger", ".", "trace", "(", "\"Uncaught exception received.\"", ")", ";", "EventBuilder", "eventBuilder", "=", "new", "EventBuilder", "(", ")", ".", "withMessage", "(", "thrown", ".", "getMessage", "(", ")", ")", ".", "withLevel", "(", "Event", ".", "Level", ".", "FATAL", ")", ".", "withSentryInterface", "(", "new", "ExceptionInterface", "(", "thrown", ")", ")", ";", "try", "{", "Sentry", ".", "capture", "(", "eventBuilder", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"Error sending uncaught exception to Sentry.\"", ",", "e", ")", ";", "}", "}", "// taken from ThreadGroup#uncaughtException", "if", "(", "defaultExceptionHandler", "!=", "null", ")", "{", "// call the original handler", "defaultExceptionHandler", ".", "uncaughtException", "(", "thread", ",", "thrown", ")", ";", "}", "else", "if", "(", "!", "(", "thrown", "instanceof", "ThreadDeath", ")", ")", "{", "// CHECKSTYLE.OFF: RegexpSinglelineJava", "System", ".", "err", ".", "print", "(", "\"Exception in thread \\\"\"", "+", "thread", ".", "getName", "(", ")", "+", "\"\\\" \"", ")", ";", "thrown", ".", "printStackTrace", "(", "System", ".", "err", ")", ";", "// CHECKSTYLE.ON: RegexpSinglelineJava", "}", "}" ]
Sends any uncaught exception to Sentry, then passes the exception on to the pre-existing uncaught exception handler. @param thread thread that threw the error @param thrown the uncaught throwable
[ "Sends", "any", "uncaught", "exception", "to", "Sentry", "then", "passes", "the", "exception", "on", "to", "the", "pre", "-", "existing", "uncaught", "exception", "handler", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/SentryUncaughtExceptionHandler.java#L44-L71
25,538
getsentry/sentry-java
sentry/src/main/java/io/sentry/SentryUncaughtExceptionHandler.java
SentryUncaughtExceptionHandler.setup
public static SentryUncaughtExceptionHandler setup() { logger.debug("Configuring uncaught exception handler."); Thread.UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler(); if (currentHandler != null) { logger.debug("default UncaughtExceptionHandler class='" + currentHandler.getClass().getName() + "'"); } SentryUncaughtExceptionHandler handler = new SentryUncaughtExceptionHandler(currentHandler); Thread.setDefaultUncaughtExceptionHandler(handler); return handler; }
java
public static SentryUncaughtExceptionHandler setup() { logger.debug("Configuring uncaught exception handler."); Thread.UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler(); if (currentHandler != null) { logger.debug("default UncaughtExceptionHandler class='" + currentHandler.getClass().getName() + "'"); } SentryUncaughtExceptionHandler handler = new SentryUncaughtExceptionHandler(currentHandler); Thread.setDefaultUncaughtExceptionHandler(handler); return handler; }
[ "public", "static", "SentryUncaughtExceptionHandler", "setup", "(", ")", "{", "logger", ".", "debug", "(", "\"Configuring uncaught exception handler.\"", ")", ";", "Thread", ".", "UncaughtExceptionHandler", "currentHandler", "=", "Thread", ".", "getDefaultUncaughtExceptionHandler", "(", ")", ";", "if", "(", "currentHandler", "!=", "null", ")", "{", "logger", ".", "debug", "(", "\"default UncaughtExceptionHandler class='\"", "+", "currentHandler", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\"'\"", ")", ";", "}", "SentryUncaughtExceptionHandler", "handler", "=", "new", "SentryUncaughtExceptionHandler", "(", "currentHandler", ")", ";", "Thread", ".", "setDefaultUncaughtExceptionHandler", "(", "handler", ")", ";", "return", "handler", ";", "}" ]
Configures an uncaught exception handler which sends events to Sentry, then calls the preexisting uncaught exception handler. @return {@link SentryUncaughtExceptionHandler} that was setup.
[ "Configures", "an", "uncaught", "exception", "handler", "which", "sends", "events", "to", "Sentry", "then", "calls", "the", "preexisting", "uncaught", "exception", "handler", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/SentryUncaughtExceptionHandler.java#L79-L90
25,539
getsentry/sentry-java
sentry/src/main/java/io/sentry/marshaller/json/JsonMarshaller.java
JsonMarshaller.formatLevel
private String formatLevel(Event.Level level) { if (level == null) { return null; } switch (level) { case DEBUG: return "debug"; case FATAL: return "fatal"; case WARNING: return "warning"; case INFO: return "info"; case ERROR: return "error"; default: logger.error("The level '{}' isn't supported, this should NEVER happen, contact Sentry developers", level.name()); return null; } }
java
private String formatLevel(Event.Level level) { if (level == null) { return null; } switch (level) { case DEBUG: return "debug"; case FATAL: return "fatal"; case WARNING: return "warning"; case INFO: return "info"; case ERROR: return "error"; default: logger.error("The level '{}' isn't supported, this should NEVER happen, contact Sentry developers", level.name()); return null; } }
[ "private", "String", "formatLevel", "(", "Event", ".", "Level", "level", ")", "{", "if", "(", "level", "==", "null", ")", "{", "return", "null", ";", "}", "switch", "(", "level", ")", "{", "case", "DEBUG", ":", "return", "\"debug\"", ";", "case", "FATAL", ":", "return", "\"fatal\"", ";", "case", "WARNING", ":", "return", "\"warning\"", ";", "case", "INFO", ":", "return", "\"info\"", ";", "case", "ERROR", ":", "return", "\"error\"", ";", "default", ":", "logger", ".", "error", "(", "\"The level '{}' isn't supported, this should NEVER happen, contact Sentry developers\"", ",", "level", ".", "name", "(", ")", ")", ";", "return", "null", ";", "}", "}" ]
Formats a log level into one of the accepted string representation of a log level. @param level log level to format. @return log level as a String.
[ "Formats", "a", "log", "level", "into", "one", "of", "the", "accepted", "string", "representation", "of", "a", "log", "level", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/marshaller/json/JsonMarshaller.java#L358-L379
25,540
getsentry/sentry-java
sentry-log4j2/src/main/java/io/sentry/log4j2/SentryAppender.java
SentryAppender.createAppender
@PluginFactory @SuppressWarnings("checkstyle:parameternumber") public static SentryAppender createAppender(@PluginAttribute("name") final String name, @PluginElement("filter") final Filter filter) { if (name == null) { LOGGER.error("No name provided for SentryAppender"); return null; } return new SentryAppender(name, filter); }
java
@PluginFactory @SuppressWarnings("checkstyle:parameternumber") public static SentryAppender createAppender(@PluginAttribute("name") final String name, @PluginElement("filter") final Filter filter) { if (name == null) { LOGGER.error("No name provided for SentryAppender"); return null; } return new SentryAppender(name, filter); }
[ "@", "PluginFactory", "@", "SuppressWarnings", "(", "\"checkstyle:parameternumber\"", ")", "public", "static", "SentryAppender", "createAppender", "(", "@", "PluginAttribute", "(", "\"name\"", ")", "final", "String", "name", ",", "@", "PluginElement", "(", "\"filter\"", ")", "final", "Filter", "filter", ")", "{", "if", "(", "name", "==", "null", ")", "{", "LOGGER", ".", "error", "(", "\"No name provided for SentryAppender\"", ")", ";", "return", "null", ";", "}", "return", "new", "SentryAppender", "(", "name", ",", "filter", ")", ";", "}" ]
Create a Sentry Appender. @param name The name of the Appender. @param filter The filter, if any, to use. @return The SentryAppender.
[ "Create", "a", "Sentry", "Appender", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry-log4j2/src/main/java/io/sentry/log4j2/SentryAppender.java#L75-L85
25,541
getsentry/sentry-java
sentry/src/main/java/io/sentry/connection/HttpConnection.java
HttpConnection.getSentryApiUrl
public static URL getSentryApiUrl(URI sentryUri, String projectId) { try { String url = sentryUri.toString() + "api/" + projectId + "/store/"; return new URL(url); } catch (MalformedURLException e) { throw new IllegalArgumentException("Couldn't build a valid URL from the Sentry API.", e); } }
java
public static URL getSentryApiUrl(URI sentryUri, String projectId) { try { String url = sentryUri.toString() + "api/" + projectId + "/store/"; return new URL(url); } catch (MalformedURLException e) { throw new IllegalArgumentException("Couldn't build a valid URL from the Sentry API.", e); } }
[ "public", "static", "URL", "getSentryApiUrl", "(", "URI", "sentryUri", ",", "String", "projectId", ")", "{", "try", "{", "String", "url", "=", "sentryUri", ".", "toString", "(", ")", "+", "\"api/\"", "+", "projectId", "+", "\"/store/\"", ";", "return", "new", "URL", "(", "url", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Couldn't build a valid URL from the Sentry API.\"", ",", "e", ")", ";", "}", "}" ]
Automatically determines the URL to the HTTP API of Sentry. @param sentryUri URI of the Sentry server. @param projectId unique identifier of the current project. @return an URL to the HTTP API of Sentry.
[ "Automatically", "determines", "the", "URL", "to", "the", "HTTP", "API", "of", "Sentry", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/connection/HttpConnection.java#L113-L120
25,542
getsentry/sentry-java
sentry/src/main/java/io/sentry/connection/HttpConnection.java
HttpConnection.getConnection
protected HttpURLConnection getConnection() { try { HttpURLConnection connection; if (proxy != null) { connection = (HttpURLConnection) sentryUrl.openConnection(proxy); } else { connection = (HttpURLConnection) sentryUrl.openConnection(); } if (bypassSecurity && connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setHostnameVerifier(NAIVE_VERIFIER); } connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setConnectTimeout(connectionTimeout); connection.setReadTimeout(readTimeout); connection.setRequestProperty(USER_AGENT, SentryEnvironment.getSentryName()); connection.setRequestProperty(SENTRY_AUTH, getAuthHeader()); if (marshaller.getContentType() != null) { connection.setRequestProperty("Content-Type", marshaller.getContentType()); } if (marshaller.getContentEncoding() != null) { connection.setRequestProperty("Content-Encoding", marshaller.getContentEncoding()); } return connection; } catch (IOException e) { throw new IllegalStateException("Couldn't set up a connection to the Sentry server.", e); } }
java
protected HttpURLConnection getConnection() { try { HttpURLConnection connection; if (proxy != null) { connection = (HttpURLConnection) sentryUrl.openConnection(proxy); } else { connection = (HttpURLConnection) sentryUrl.openConnection(); } if (bypassSecurity && connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setHostnameVerifier(NAIVE_VERIFIER); } connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setConnectTimeout(connectionTimeout); connection.setReadTimeout(readTimeout); connection.setRequestProperty(USER_AGENT, SentryEnvironment.getSentryName()); connection.setRequestProperty(SENTRY_AUTH, getAuthHeader()); if (marshaller.getContentType() != null) { connection.setRequestProperty("Content-Type", marshaller.getContentType()); } if (marshaller.getContentEncoding() != null) { connection.setRequestProperty("Content-Encoding", marshaller.getContentEncoding()); } return connection; } catch (IOException e) { throw new IllegalStateException("Couldn't set up a connection to the Sentry server.", e); } }
[ "protected", "HttpURLConnection", "getConnection", "(", ")", "{", "try", "{", "HttpURLConnection", "connection", ";", "if", "(", "proxy", "!=", "null", ")", "{", "connection", "=", "(", "HttpURLConnection", ")", "sentryUrl", ".", "openConnection", "(", "proxy", ")", ";", "}", "else", "{", "connection", "=", "(", "HttpURLConnection", ")", "sentryUrl", ".", "openConnection", "(", ")", ";", "}", "if", "(", "bypassSecurity", "&&", "connection", "instanceof", "HttpsURLConnection", ")", "{", "(", "(", "HttpsURLConnection", ")", "connection", ")", ".", "setHostnameVerifier", "(", "NAIVE_VERIFIER", ")", ";", "}", "connection", ".", "setRequestMethod", "(", "\"POST\"", ")", ";", "connection", ".", "setDoOutput", "(", "true", ")", ";", "connection", ".", "setConnectTimeout", "(", "connectionTimeout", ")", ";", "connection", ".", "setReadTimeout", "(", "readTimeout", ")", ";", "connection", ".", "setRequestProperty", "(", "USER_AGENT", ",", "SentryEnvironment", ".", "getSentryName", "(", ")", ")", ";", "connection", ".", "setRequestProperty", "(", "SENTRY_AUTH", ",", "getAuthHeader", "(", ")", ")", ";", "if", "(", "marshaller", ".", "getContentType", "(", ")", "!=", "null", ")", "{", "connection", ".", "setRequestProperty", "(", "\"Content-Type\"", ",", "marshaller", ".", "getContentType", "(", ")", ")", ";", "}", "if", "(", "marshaller", ".", "getContentEncoding", "(", ")", "!=", "null", ")", "{", "connection", ".", "setRequestProperty", "(", "\"Content-Encoding\"", ",", "marshaller", ".", "getContentEncoding", "(", ")", ")", ";", "}", "return", "connection", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Couldn't set up a connection to the Sentry server.\"", ",", "e", ")", ";", "}", "}" ]
Opens a connection to the Sentry API allowing to send new events. @return an HTTP connection to Sentry.
[ "Opens", "a", "connection", "to", "the", "Sentry", "API", "allowing", "to", "send", "new", "events", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/connection/HttpConnection.java#L127-L158
25,543
getsentry/sentry-java
sentry/src/main/java/io/sentry/context/Context.java
Context.getTags
public synchronized Map<String, String> getTags() { if (tags == null || tags.isEmpty()) { return Collections.emptyMap(); } return Collections.unmodifiableMap(tags); }
java
public synchronized Map<String, String> getTags() { if (tags == null || tags.isEmpty()) { return Collections.emptyMap(); } return Collections.unmodifiableMap(tags); }
[ "public", "synchronized", "Map", "<", "String", ",", "String", ">", "getTags", "(", ")", "{", "if", "(", "tags", "==", "null", "||", "tags", ".", "isEmpty", "(", ")", ")", "{", "return", "Collections", ".", "emptyMap", "(", ")", ";", "}", "return", "Collections", ".", "unmodifiableMap", "(", "tags", ")", ";", "}" ]
Return tags attached to this context. @return tags attached to this context.
[ "Return", "tags", "attached", "to", "this", "context", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/context/Context.java#L100-L106
25,544
getsentry/sentry-java
sentry/src/main/java/io/sentry/context/Context.java
Context.getExtra
public synchronized Map<String, Object> getExtra() { if (extra == null || extra.isEmpty()) { return Collections.emptyMap(); } return Collections.unmodifiableMap(extra); }
java
public synchronized Map<String, Object> getExtra() { if (extra == null || extra.isEmpty()) { return Collections.emptyMap(); } return Collections.unmodifiableMap(extra); }
[ "public", "synchronized", "Map", "<", "String", ",", "Object", ">", "getExtra", "(", ")", "{", "if", "(", "extra", "==", "null", "||", "extra", ".", "isEmpty", "(", ")", ")", "{", "return", "Collections", ".", "emptyMap", "(", ")", ";", "}", "return", "Collections", ".", "unmodifiableMap", "(", "extra", ")", ";", "}" ]
Return extra data attached to this context. @return extra data attached to this context.
[ "Return", "extra", "data", "attached", "to", "this", "context", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/context/Context.java#L113-L119
25,545
getsentry/sentry-java
sentry/src/main/java/io/sentry/context/Context.java
Context.addExtra
public synchronized void addExtra(String name, Object value) { if (extra == null) { extra = new HashMap<>(); } extra.put(name, value); }
java
public synchronized void addExtra(String name, Object value) { if (extra == null) { extra = new HashMap<>(); } extra.put(name, value); }
[ "public", "synchronized", "void", "addExtra", "(", "String", "name", ",", "Object", "value", ")", "{", "if", "(", "extra", "==", "null", ")", "{", "extra", "=", "new", "HashMap", "<>", "(", ")", ";", "}", "extra", ".", "put", "(", "name", ",", "value", ")", ";", "}" ]
Add extra data to the current context. @param name extra name @param value extra value
[ "Add", "extra", "data", "to", "the", "current", "context", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/context/Context.java#L161-L167
25,546
getsentry/sentry-java
sentry/src/main/java/io/sentry/buffer/DiskBuffer.java
DiskBuffer.add
@Override public void add(Event event) { if (getNumStoredEvents() >= maxEvents) { logger.warn("Not adding Event because at least " + Integer.toString(maxEvents) + " events are already stored: " + event.getId()); return; } File eventFile = new File(bufferDir.getAbsolutePath(), event.getId().toString() + FILE_SUFFIX); if (eventFile.exists()) { logger.trace("Not adding Event to offline storage because it already exists: " + eventFile.getAbsolutePath()); return; } else { logger.debug("Adding Event to offline storage: " + eventFile.getAbsolutePath()); } try (FileOutputStream fileOutputStream = new FileOutputStream(eventFile); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) { objectOutputStream.writeObject(event); } catch (Exception e) { logger.error("Error writing Event to offline storage: " + event.getId(), e); } logger.debug(Integer.toString(getNumStoredEvents()) + " stored events are now in dir: " + bufferDir.getAbsolutePath()); }
java
@Override public void add(Event event) { if (getNumStoredEvents() >= maxEvents) { logger.warn("Not adding Event because at least " + Integer.toString(maxEvents) + " events are already stored: " + event.getId()); return; } File eventFile = new File(bufferDir.getAbsolutePath(), event.getId().toString() + FILE_SUFFIX); if (eventFile.exists()) { logger.trace("Not adding Event to offline storage because it already exists: " + eventFile.getAbsolutePath()); return; } else { logger.debug("Adding Event to offline storage: " + eventFile.getAbsolutePath()); } try (FileOutputStream fileOutputStream = new FileOutputStream(eventFile); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) { objectOutputStream.writeObject(event); } catch (Exception e) { logger.error("Error writing Event to offline storage: " + event.getId(), e); } logger.debug(Integer.toString(getNumStoredEvents()) + " stored events are now in dir: " + bufferDir.getAbsolutePath()); }
[ "@", "Override", "public", "void", "add", "(", "Event", "event", ")", "{", "if", "(", "getNumStoredEvents", "(", ")", ">=", "maxEvents", ")", "{", "logger", ".", "warn", "(", "\"Not adding Event because at least \"", "+", "Integer", ".", "toString", "(", "maxEvents", ")", "+", "\" events are already stored: \"", "+", "event", ".", "getId", "(", ")", ")", ";", "return", ";", "}", "File", "eventFile", "=", "new", "File", "(", "bufferDir", ".", "getAbsolutePath", "(", ")", ",", "event", ".", "getId", "(", ")", ".", "toString", "(", ")", "+", "FILE_SUFFIX", ")", ";", "if", "(", "eventFile", ".", "exists", "(", ")", ")", "{", "logger", ".", "trace", "(", "\"Not adding Event to offline storage because it already exists: \"", "+", "eventFile", ".", "getAbsolutePath", "(", ")", ")", ";", "return", ";", "}", "else", "{", "logger", ".", "debug", "(", "\"Adding Event to offline storage: \"", "+", "eventFile", ".", "getAbsolutePath", "(", ")", ")", ";", "}", "try", "(", "FileOutputStream", "fileOutputStream", "=", "new", "FileOutputStream", "(", "eventFile", ")", ";", "ObjectOutputStream", "objectOutputStream", "=", "new", "ObjectOutputStream", "(", "fileOutputStream", ")", ")", "{", "objectOutputStream", ".", "writeObject", "(", "event", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"Error writing Event to offline storage: \"", "+", "event", ".", "getId", "(", ")", ",", "e", ")", ";", "}", "logger", ".", "debug", "(", "Integer", ".", "toString", "(", "getNumStoredEvents", "(", ")", ")", "+", "\" stored events are now in dir: \"", "+", "bufferDir", ".", "getAbsolutePath", "(", ")", ")", ";", "}" ]
Store a single event to the add directory. Java serialization is used and each event is stored in a file named by its UUID. @param event Event to store in add directory
[ "Store", "a", "single", "event", "to", "the", "add", "directory", ".", "Java", "serialization", "is", "used", "and", "each", "event", "is", "stored", "in", "a", "file", "named", "by", "its", "UUID", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/buffer/DiskBuffer.java#L60-L87
25,547
getsentry/sentry-java
sentry/src/main/java/io/sentry/dsn/Dsn.java
Dsn.dsnLookup
public static String dsnLookup() { String dsn = Lookup.lookup("dsn"); if (Util.isNullOrEmpty(dsn)) { // check if the user accidentally set "dns" instead of "dsn" dsn = Lookup.lookup("dns"); } if (Util.isNullOrEmpty(dsn)) { logger.warn("*** Couldn't find a suitable DSN, Sentry operations will do nothing!" + " See documentation: https://docs.sentry.io/clients/java/ ***"); dsn = DEFAULT_DSN; } return dsn; }
java
public static String dsnLookup() { String dsn = Lookup.lookup("dsn"); if (Util.isNullOrEmpty(dsn)) { // check if the user accidentally set "dns" instead of "dsn" dsn = Lookup.lookup("dns"); } if (Util.isNullOrEmpty(dsn)) { logger.warn("*** Couldn't find a suitable DSN, Sentry operations will do nothing!" + " See documentation: https://docs.sentry.io/clients/java/ ***"); dsn = DEFAULT_DSN; } return dsn; }
[ "public", "static", "String", "dsnLookup", "(", ")", "{", "String", "dsn", "=", "Lookup", ".", "lookup", "(", "\"dsn\"", ")", ";", "if", "(", "Util", ".", "isNullOrEmpty", "(", "dsn", ")", ")", "{", "// check if the user accidentally set \"dns\" instead of \"dsn\"", "dsn", "=", "Lookup", ".", "lookup", "(", "\"dns\"", ")", ";", "}", "if", "(", "Util", ".", "isNullOrEmpty", "(", "dsn", ")", ")", "{", "logger", ".", "warn", "(", "\"*** Couldn't find a suitable DSN, Sentry operations will do nothing!\"", "+", "\" See documentation: https://docs.sentry.io/clients/java/ ***\"", ")", ";", "dsn", "=", "DEFAULT_DSN", ";", "}", "return", "dsn", ";", "}" ]
Looks for a DSN configuration within JNDI, the System environment or Java properties. @return a DSN configuration or null if nothing could be found.
[ "Looks", "for", "a", "DSN", "configuration", "within", "JNDI", "the", "System", "environment", "or", "Java", "properties", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/dsn/Dsn.java#L80-L95
25,548
getsentry/sentry-java
sentry/src/main/java/io/sentry/SentryClientFactory.java
SentryClientFactory.sentryClient
public static SentryClient sentryClient(String dsn, SentryClientFactory sentryClientFactory) { Dsn realDsn = resolveDsn(dsn); // If the caller didn't pass a factory, try to look one up if (sentryClientFactory == null) { String sentryClientFactoryName = Lookup.lookup("factory", realDsn); if (Util.isNullOrEmpty(sentryClientFactoryName)) { // no name specified, use the default factory sentryClientFactory = new DefaultSentryClientFactory(); } else { // attempt to construct the user specified factory class Class<? extends SentryClientFactory> factoryClass = null; try { factoryClass = (Class<? extends SentryClientFactory>) Class.forName(sentryClientFactoryName); sentryClientFactory = factoryClass.newInstance(); } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) { logger.error("Error creating SentryClient using factory class: '" + sentryClientFactoryName + "'.", e); return null; } } } return sentryClientFactory.createSentryClient(realDsn); }
java
public static SentryClient sentryClient(String dsn, SentryClientFactory sentryClientFactory) { Dsn realDsn = resolveDsn(dsn); // If the caller didn't pass a factory, try to look one up if (sentryClientFactory == null) { String sentryClientFactoryName = Lookup.lookup("factory", realDsn); if (Util.isNullOrEmpty(sentryClientFactoryName)) { // no name specified, use the default factory sentryClientFactory = new DefaultSentryClientFactory(); } else { // attempt to construct the user specified factory class Class<? extends SentryClientFactory> factoryClass = null; try { factoryClass = (Class<? extends SentryClientFactory>) Class.forName(sentryClientFactoryName); sentryClientFactory = factoryClass.newInstance(); } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) { logger.error("Error creating SentryClient using factory class: '" + sentryClientFactoryName + "'.", e); return null; } } } return sentryClientFactory.createSentryClient(realDsn); }
[ "public", "static", "SentryClient", "sentryClient", "(", "String", "dsn", ",", "SentryClientFactory", "sentryClientFactory", ")", "{", "Dsn", "realDsn", "=", "resolveDsn", "(", "dsn", ")", ";", "// If the caller didn't pass a factory, try to look one up", "if", "(", "sentryClientFactory", "==", "null", ")", "{", "String", "sentryClientFactoryName", "=", "Lookup", ".", "lookup", "(", "\"factory\"", ",", "realDsn", ")", ";", "if", "(", "Util", ".", "isNullOrEmpty", "(", "sentryClientFactoryName", ")", ")", "{", "// no name specified, use the default factory", "sentryClientFactory", "=", "new", "DefaultSentryClientFactory", "(", ")", ";", "}", "else", "{", "// attempt to construct the user specified factory class", "Class", "<", "?", "extends", "SentryClientFactory", ">", "factoryClass", "=", "null", ";", "try", "{", "factoryClass", "=", "(", "Class", "<", "?", "extends", "SentryClientFactory", ">", ")", "Class", ".", "forName", "(", "sentryClientFactoryName", ")", ";", "sentryClientFactory", "=", "factoryClass", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "ClassNotFoundException", "|", "IllegalAccessException", "|", "InstantiationException", "e", ")", "{", "logger", ".", "error", "(", "\"Error creating SentryClient using factory class: '\"", "+", "sentryClientFactoryName", "+", "\"'.\"", ",", "e", ")", ";", "return", "null", ";", "}", "}", "}", "return", "sentryClientFactory", ".", "createSentryClient", "(", "realDsn", ")", ";", "}" ]
Creates an instance of Sentry using the provided DSN and the specified factory. @param dsn Data Source Name of the Sentry server. @param sentryClientFactory SentryClientFactory instance to use, or null to do a config lookup. @return SentryClient instance, or null if one couldn't be constructed.
[ "Creates", "an", "instance", "of", "Sentry", "using", "the", "provided", "DSN", "and", "the", "specified", "factory", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/SentryClientFactory.java#L41-L65
25,549
getsentry/sentry-java
sentry-logback/src/main/java/io/sentry/logback/SentryAppender.java
SentryAppender.setMinLevel
@Deprecated public void setMinLevel(String minLevel) { this.minLevel = minLevel != null ? Level.toLevel(minLevel) : null; }
java
@Deprecated public void setMinLevel(String minLevel) { this.minLevel = minLevel != null ? Level.toLevel(minLevel) : null; }
[ "@", "Deprecated", "public", "void", "setMinLevel", "(", "String", "minLevel", ")", "{", "this", ".", "minLevel", "=", "minLevel", "!=", "null", "?", "Level", ".", "toLevel", "(", "minLevel", ")", ":", "null", ";", "}" ]
Set minimum level to log. @param minLevel minimum level to log. @deprecated use logback filters.
[ "Set", "minimum", "level", "to", "log", "." ]
2e01461775cbd5951ff82b566069c349146d8aca
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry-logback/src/main/java/io/sentry/logback/SentryAppender.java#L268-L271
25,550
markzhai/AndroidPerformanceMonitor
blockcanary-android/src/main/java/com/github/moduth/blockcanary/ui/BlockCanaryUtils.java
BlockCanaryUtils.concernStackString
public static String concernStackString(BlockInfo blockInfo) { String result = ""; for (String stackEntry : blockInfo.threadStackEntries) { if (Character.isLetter(stackEntry.charAt(0))) { String[] lines = stackEntry.split(BlockInfo.SEPARATOR); for (String line : lines) { String keyStackString = concernStackString(line); if (keyStackString != null) { return keyStackString; } } return classSimpleName(lines[0]); } } return result; }
java
public static String concernStackString(BlockInfo blockInfo) { String result = ""; for (String stackEntry : blockInfo.threadStackEntries) { if (Character.isLetter(stackEntry.charAt(0))) { String[] lines = stackEntry.split(BlockInfo.SEPARATOR); for (String line : lines) { String keyStackString = concernStackString(line); if (keyStackString != null) { return keyStackString; } } return classSimpleName(lines[0]); } } return result; }
[ "public", "static", "String", "concernStackString", "(", "BlockInfo", "blockInfo", ")", "{", "String", "result", "=", "\"\"", ";", "for", "(", "String", "stackEntry", ":", "blockInfo", ".", "threadStackEntries", ")", "{", "if", "(", "Character", ".", "isLetter", "(", "stackEntry", ".", "charAt", "(", "0", ")", ")", ")", "{", "String", "[", "]", "lines", "=", "stackEntry", ".", "split", "(", "BlockInfo", ".", "SEPARATOR", ")", ";", "for", "(", "String", "line", ":", "lines", ")", "{", "String", "keyStackString", "=", "concernStackString", "(", "line", ")", ";", "if", "(", "keyStackString", "!=", "null", ")", "{", "return", "keyStackString", ";", "}", "}", "return", "classSimpleName", "(", "lines", "[", "0", "]", ")", ";", "}", "}", "return", "result", ";", "}" ]
Get key stack string to show as title in ui list.
[ "Get", "key", "stack", "string", "to", "show", "as", "title", "in", "ui", "list", "." ]
ed688391cdf95742892ce61494736667cf5baf08
https://github.com/markzhai/AndroidPerformanceMonitor/blob/ed688391cdf95742892ce61494736667cf5baf08/blockcanary-android/src/main/java/com/github/moduth/blockcanary/ui/BlockCanaryUtils.java#L31-L46
25,551
markzhai/AndroidPerformanceMonitor
blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/internal/PerformanceUtils.java
PerformanceUtils.getNumCores
public static int getNumCores() { class CpuFilter implements FileFilter { @Override public boolean accept(File pathname) { return Pattern.matches("cpu[0-9]", pathname.getName()); } } if (sCoreNum == 0) { try { // Get directory containing CPU info File dir = new File("/sys/devices/system/cpu/"); // Filter to only list the devices we care about File[] files = dir.listFiles(new CpuFilter()); // Return the number of cores (virtual CPU devices) sCoreNum = files.length; } catch (Exception e) { Log.e(TAG, "getNumCores exception", e); sCoreNum = 1; } } return sCoreNum; }
java
public static int getNumCores() { class CpuFilter implements FileFilter { @Override public boolean accept(File pathname) { return Pattern.matches("cpu[0-9]", pathname.getName()); } } if (sCoreNum == 0) { try { // Get directory containing CPU info File dir = new File("/sys/devices/system/cpu/"); // Filter to only list the devices we care about File[] files = dir.listFiles(new CpuFilter()); // Return the number of cores (virtual CPU devices) sCoreNum = files.length; } catch (Exception e) { Log.e(TAG, "getNumCores exception", e); sCoreNum = 1; } } return sCoreNum; }
[ "public", "static", "int", "getNumCores", "(", ")", "{", "class", "CpuFilter", "implements", "FileFilter", "{", "@", "Override", "public", "boolean", "accept", "(", "File", "pathname", ")", "{", "return", "Pattern", ".", "matches", "(", "\"cpu[0-9]\"", ",", "pathname", ".", "getName", "(", ")", ")", ";", "}", "}", "if", "(", "sCoreNum", "==", "0", ")", "{", "try", "{", "// Get directory containing CPU info", "File", "dir", "=", "new", "File", "(", "\"/sys/devices/system/cpu/\"", ")", ";", "// Filter to only list the devices we care about", "File", "[", "]", "files", "=", "dir", ".", "listFiles", "(", "new", "CpuFilter", "(", ")", ")", ";", "// Return the number of cores (virtual CPU devices)", "sCoreNum", "=", "files", ".", "length", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"getNumCores exception\"", ",", "e", ")", ";", "sCoreNum", "=", "1", ";", "}", "}", "return", "sCoreNum", ";", "}" ]
Get cpu core number @return int cpu core number
[ "Get", "cpu", "core", "number" ]
ed688391cdf95742892ce61494736667cf5baf08
https://github.com/markzhai/AndroidPerformanceMonitor/blob/ed688391cdf95742892ce61494736667cf5baf08/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/internal/PerformanceUtils.java#L46-L68
25,552
markzhai/AndroidPerformanceMonitor
blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/BlockCanaryContext.java
BlockCanaryContext.provideWhiteList
public List<String> provideWhiteList() { LinkedList<String> whiteList = new LinkedList<>(); whiteList.add("org.chromium"); return whiteList; }
java
public List<String> provideWhiteList() { LinkedList<String> whiteList = new LinkedList<>(); whiteList.add("org.chromium"); return whiteList; }
[ "public", "List", "<", "String", ">", "provideWhiteList", "(", ")", "{", "LinkedList", "<", "String", ">", "whiteList", "=", "new", "LinkedList", "<>", "(", ")", ";", "whiteList", ".", "add", "(", "\"org.chromium\"", ")", ";", "return", "whiteList", ";", "}" ]
Provide white list, entry in white list will not be shown in ui list. @return return null if you don't need white-list filter.
[ "Provide", "white", "list", "entry", "in", "white", "list", "will", "not", "be", "shown", "in", "ui", "list", "." ]
ed688391cdf95742892ce61494736667cf5baf08
https://github.com/markzhai/AndroidPerformanceMonitor/blob/ed688391cdf95742892ce61494736667cf5baf08/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/BlockCanaryContext.java#L180-L184
25,553
markzhai/AndroidPerformanceMonitor
blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/BlockCanaryInternals.java
BlockCanaryInternals.getInstance
static BlockCanaryInternals getInstance() { if (sInstance == null) { synchronized (BlockCanaryInternals.class) { if (sInstance == null) { sInstance = new BlockCanaryInternals(); } } } return sInstance; }
java
static BlockCanaryInternals getInstance() { if (sInstance == null) { synchronized (BlockCanaryInternals.class) { if (sInstance == null) { sInstance = new BlockCanaryInternals(); } } } return sInstance; }
[ "static", "BlockCanaryInternals", "getInstance", "(", ")", "{", "if", "(", "sInstance", "==", "null", ")", "{", "synchronized", "(", "BlockCanaryInternals", ".", "class", ")", "{", "if", "(", "sInstance", "==", "null", ")", "{", "sInstance", "=", "new", "BlockCanaryInternals", "(", ")", ";", "}", "}", "}", "return", "sInstance", ";", "}" ]
Get BlockCanaryInternals singleton @return BlockCanaryInternals instance
[ "Get", "BlockCanaryInternals", "singleton" ]
ed688391cdf95742892ce61494736667cf5baf08
https://github.com/markzhai/AndroidPerformanceMonitor/blob/ed688391cdf95742892ce61494736667cf5baf08/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/BlockCanaryInternals.java#L82-L91
25,554
markzhai/AndroidPerformanceMonitor
blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/LogWriter.java
LogWriter.save
public static String save(String str) { String path; synchronized (SAVE_DELETE_LOCK) { path = save("looper", str); } return path; }
java
public static String save(String str) { String path; synchronized (SAVE_DELETE_LOCK) { path = save("looper", str); } return path; }
[ "public", "static", "String", "save", "(", "String", "str", ")", "{", "String", "path", ";", "synchronized", "(", "SAVE_DELETE_LOCK", ")", "{", "path", "=", "save", "(", "\"looper\"", ",", "str", ")", ";", "}", "return", "path", ";", "}" ]
Save log to file @param str block info string @return log file path
[ "Save", "log", "to", "file" ]
ed688391cdf95742892ce61494736667cf5baf08
https://github.com/markzhai/AndroidPerformanceMonitor/blob/ed688391cdf95742892ce61494736667cf5baf08/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/LogWriter.java#L53-L59
25,555
markzhai/AndroidPerformanceMonitor
blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/LogWriter.java
LogWriter.cleanObsolete
public static void cleanObsolete() { HandlerThreadFactory.getWriteLogThreadHandler().post(new Runnable() { @Override public void run() { long now = System.currentTimeMillis(); File[] f = BlockCanaryInternals.getLogFiles(); if (f != null && f.length > 0) { synchronized (SAVE_DELETE_LOCK) { for (File aF : f) { if (now - aF.lastModified() > OBSOLETE_DURATION) { aF.delete(); } } } } } }); }
java
public static void cleanObsolete() { HandlerThreadFactory.getWriteLogThreadHandler().post(new Runnable() { @Override public void run() { long now = System.currentTimeMillis(); File[] f = BlockCanaryInternals.getLogFiles(); if (f != null && f.length > 0) { synchronized (SAVE_DELETE_LOCK) { for (File aF : f) { if (now - aF.lastModified() > OBSOLETE_DURATION) { aF.delete(); } } } } } }); }
[ "public", "static", "void", "cleanObsolete", "(", ")", "{", "HandlerThreadFactory", ".", "getWriteLogThreadHandler", "(", ")", ".", "post", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "File", "[", "]", "f", "=", "BlockCanaryInternals", ".", "getLogFiles", "(", ")", ";", "if", "(", "f", "!=", "null", "&&", "f", ".", "length", ">", "0", ")", "{", "synchronized", "(", "SAVE_DELETE_LOCK", ")", "{", "for", "(", "File", "aF", ":", "f", ")", "{", "if", "(", "now", "-", "aF", ".", "lastModified", "(", ")", ">", "OBSOLETE_DURATION", ")", "{", "aF", ".", "delete", "(", ")", ";", "}", "}", "}", "}", "}", "}", ")", ";", "}" ]
Delete obsolete log files, which is by default 2 days.
[ "Delete", "obsolete", "log", "files", "which", "is", "by", "default", "2", "days", "." ]
ed688391cdf95742892ce61494736667cf5baf08
https://github.com/markzhai/AndroidPerformanceMonitor/blob/ed688391cdf95742892ce61494736667cf5baf08/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/LogWriter.java#L64-L81
25,556
markzhai/AndroidPerformanceMonitor
blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/CpuSampler.java
CpuSampler.getCpuRateInfo
public String getCpuRateInfo() { StringBuilder sb = new StringBuilder(); synchronized (mCpuInfoEntries) { for (Map.Entry<Long, String> entry : mCpuInfoEntries.entrySet()) { long time = entry.getKey(); sb.append(BlockInfo.TIME_FORMATTER.format(time)) .append(' ') .append(entry.getValue()) .append(BlockInfo.SEPARATOR); } } return sb.toString(); }
java
public String getCpuRateInfo() { StringBuilder sb = new StringBuilder(); synchronized (mCpuInfoEntries) { for (Map.Entry<Long, String> entry : mCpuInfoEntries.entrySet()) { long time = entry.getKey(); sb.append(BlockInfo.TIME_FORMATTER.format(time)) .append(' ') .append(entry.getValue()) .append(BlockInfo.SEPARATOR); } } return sb.toString(); }
[ "public", "String", "getCpuRateInfo", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "synchronized", "(", "mCpuInfoEntries", ")", "{", "for", "(", "Map", ".", "Entry", "<", "Long", ",", "String", ">", "entry", ":", "mCpuInfoEntries", ".", "entrySet", "(", ")", ")", "{", "long", "time", "=", "entry", ".", "getKey", "(", ")", ";", "sb", ".", "append", "(", "BlockInfo", ".", "TIME_FORMATTER", ".", "format", "(", "time", ")", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "entry", ".", "getValue", "(", ")", ")", ".", "append", "(", "BlockInfo", ".", "SEPARATOR", ")", ";", "}", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Get cpu rate information @return string show cpu rate information
[ "Get", "cpu", "rate", "information" ]
ed688391cdf95742892ce61494736667cf5baf08
https://github.com/markzhai/AndroidPerformanceMonitor/blob/ed688391cdf95742892ce61494736667cf5baf08/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/CpuSampler.java#L68-L80
25,557
markzhai/AndroidPerformanceMonitor
blockcanary-android/src/main/java/com/github/moduth/blockcanary/BlockCanary.java
BlockCanary.stop
public void stop() { if (mMonitorStarted) { mMonitorStarted = false; Looper.getMainLooper().setMessageLogging(null); mBlockCanaryCore.stackSampler.stop(); mBlockCanaryCore.cpuSampler.stop(); } }
java
public void stop() { if (mMonitorStarted) { mMonitorStarted = false; Looper.getMainLooper().setMessageLogging(null); mBlockCanaryCore.stackSampler.stop(); mBlockCanaryCore.cpuSampler.stop(); } }
[ "public", "void", "stop", "(", ")", "{", "if", "(", "mMonitorStarted", ")", "{", "mMonitorStarted", "=", "false", ";", "Looper", ".", "getMainLooper", "(", ")", ".", "setMessageLogging", "(", "null", ")", ";", "mBlockCanaryCore", ".", "stackSampler", ".", "stop", "(", ")", ";", "mBlockCanaryCore", ".", "cpuSampler", ".", "stop", "(", ")", ";", "}", "}" ]
Stop monitoring.
[ "Stop", "monitoring", "." ]
ed688391cdf95742892ce61494736667cf5baf08
https://github.com/markzhai/AndroidPerformanceMonitor/blob/ed688391cdf95742892ce61494736667cf5baf08/blockcanary-android/src/main/java/com/github/moduth/blockcanary/BlockCanary.java#L94-L101
25,558
markzhai/AndroidPerformanceMonitor
blockcanary-android/src/main/java/com/github/moduth/blockcanary/BlockCanary.java
BlockCanary.recordStartTime
public void recordStartTime() { PreferenceManager.getDefaultSharedPreferences(BlockCanaryContext.get().provideContext()) .edit() .putLong("BlockCanary_StartTime", System.currentTimeMillis()) .commit(); }
java
public void recordStartTime() { PreferenceManager.getDefaultSharedPreferences(BlockCanaryContext.get().provideContext()) .edit() .putLong("BlockCanary_StartTime", System.currentTimeMillis()) .commit(); }
[ "public", "void", "recordStartTime", "(", ")", "{", "PreferenceManager", ".", "getDefaultSharedPreferences", "(", "BlockCanaryContext", ".", "get", "(", ")", ".", "provideContext", "(", ")", ")", ".", "edit", "(", ")", ".", "putLong", "(", "\"BlockCanary_StartTime\"", ",", "System", ".", "currentTimeMillis", "(", ")", ")", ".", "commit", "(", ")", ";", "}" ]
Record monitor start time to preference, you may use it when after push which tells start BlockCanary.
[ "Record", "monitor", "start", "time", "to", "preference", "you", "may", "use", "it", "when", "after", "push", "which", "tells", "start", "BlockCanary", "." ]
ed688391cdf95742892ce61494736667cf5baf08
https://github.com/markzhai/AndroidPerformanceMonitor/blob/ed688391cdf95742892ce61494736667cf5baf08/blockcanary-android/src/main/java/com/github/moduth/blockcanary/BlockCanary.java#L114-L119
25,559
markzhai/AndroidPerformanceMonitor
blockcanary-android/src/main/java/com/github/moduth/blockcanary/BlockCanary.java
BlockCanary.isMonitorDurationEnd
public boolean isMonitorDurationEnd() { long startTime = PreferenceManager.getDefaultSharedPreferences(BlockCanaryContext.get().provideContext()) .getLong("BlockCanary_StartTime", 0); return startTime != 0 && System.currentTimeMillis() - startTime > BlockCanaryContext.get().provideMonitorDuration() * 3600 * 1000; }
java
public boolean isMonitorDurationEnd() { long startTime = PreferenceManager.getDefaultSharedPreferences(BlockCanaryContext.get().provideContext()) .getLong("BlockCanary_StartTime", 0); return startTime != 0 && System.currentTimeMillis() - startTime > BlockCanaryContext.get().provideMonitorDuration() * 3600 * 1000; }
[ "public", "boolean", "isMonitorDurationEnd", "(", ")", "{", "long", "startTime", "=", "PreferenceManager", ".", "getDefaultSharedPreferences", "(", "BlockCanaryContext", ".", "get", "(", ")", ".", "provideContext", "(", ")", ")", ".", "getLong", "(", "\"BlockCanary_StartTime\"", ",", "0", ")", ";", "return", "startTime", "!=", "0", "&&", "System", ".", "currentTimeMillis", "(", ")", "-", "startTime", ">", "BlockCanaryContext", ".", "get", "(", ")", ".", "provideMonitorDuration", "(", ")", "*", "3600", "*", "1000", ";", "}" ]
Is monitor duration end, compute from recordStartTime end provideMonitorDuration. @return true if ended
[ "Is", "monitor", "duration", "end", "compute", "from", "recordStartTime", "end", "provideMonitorDuration", "." ]
ed688391cdf95742892ce61494736667cf5baf08
https://github.com/markzhai/AndroidPerformanceMonitor/blob/ed688391cdf95742892ce61494736667cf5baf08/blockcanary-android/src/main/java/com/github/moduth/blockcanary/BlockCanary.java#L126-L132
25,560
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java
MediaHttpUploader.directUpload
private HttpResponse directUpload(GenericUrl initiationRequestUrl) throws IOException { updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS); HttpContent content = mediaContent; if (metadata != null) { content = new MultipartContent().setContentParts(Arrays.asList(metadata, mediaContent)); initiationRequestUrl.put("uploadType", "multipart"); } else { initiationRequestUrl.put("uploadType", "media"); } HttpRequest request = requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content); request.getHeaders().putAll(initiationHeaders); // We do not have to do anything special here if media content length is unspecified because // direct media upload works even when the media content length == -1. HttpResponse response = executeCurrentRequest(request); boolean responseProcessed = false; try { if (isMediaLengthKnown()) { totalBytesServerReceived = getMediaContentLength(); } updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE); responseProcessed = true; } finally { if (!responseProcessed) { response.disconnect(); } } return response; }
java
private HttpResponse directUpload(GenericUrl initiationRequestUrl) throws IOException { updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS); HttpContent content = mediaContent; if (metadata != null) { content = new MultipartContent().setContentParts(Arrays.asList(metadata, mediaContent)); initiationRequestUrl.put("uploadType", "multipart"); } else { initiationRequestUrl.put("uploadType", "media"); } HttpRequest request = requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content); request.getHeaders().putAll(initiationHeaders); // We do not have to do anything special here if media content length is unspecified because // direct media upload works even when the media content length == -1. HttpResponse response = executeCurrentRequest(request); boolean responseProcessed = false; try { if (isMediaLengthKnown()) { totalBytesServerReceived = getMediaContentLength(); } updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE); responseProcessed = true; } finally { if (!responseProcessed) { response.disconnect(); } } return response; }
[ "private", "HttpResponse", "directUpload", "(", "GenericUrl", "initiationRequestUrl", ")", "throws", "IOException", "{", "updateStateAndNotifyListener", "(", "UploadState", ".", "MEDIA_IN_PROGRESS", ")", ";", "HttpContent", "content", "=", "mediaContent", ";", "if", "(", "metadata", "!=", "null", ")", "{", "content", "=", "new", "MultipartContent", "(", ")", ".", "setContentParts", "(", "Arrays", ".", "asList", "(", "metadata", ",", "mediaContent", ")", ")", ";", "initiationRequestUrl", ".", "put", "(", "\"uploadType\"", ",", "\"multipart\"", ")", ";", "}", "else", "{", "initiationRequestUrl", ".", "put", "(", "\"uploadType\"", ",", "\"media\"", ")", ";", "}", "HttpRequest", "request", "=", "requestFactory", ".", "buildRequest", "(", "initiationRequestMethod", ",", "initiationRequestUrl", ",", "content", ")", ";", "request", ".", "getHeaders", "(", ")", ".", "putAll", "(", "initiationHeaders", ")", ";", "// We do not have to do anything special here if media content length is unspecified because", "// direct media upload works even when the media content length == -1.", "HttpResponse", "response", "=", "executeCurrentRequest", "(", "request", ")", ";", "boolean", "responseProcessed", "=", "false", ";", "try", "{", "if", "(", "isMediaLengthKnown", "(", ")", ")", "{", "totalBytesServerReceived", "=", "getMediaContentLength", "(", ")", ";", "}", "updateStateAndNotifyListener", "(", "UploadState", ".", "MEDIA_COMPLETE", ")", ";", "responseProcessed", "=", "true", ";", "}", "finally", "{", "if", "(", "!", "responseProcessed", ")", "{", "response", ".", "disconnect", "(", ")", ";", "}", "}", "return", "response", ";", "}" ]
Direct Uploads the media. @param initiationRequestUrl The request URL where the initiation request will be sent @return HTTP response
[ "Direct", "Uploads", "the", "media", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java#L345-L374
25,561
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java
MediaHttpUploader.resumableUpload
private HttpResponse resumableUpload(GenericUrl initiationRequestUrl) throws IOException { // Make initial request to get the unique upload URL. HttpResponse initialResponse = executeUploadInitiation(initiationRequestUrl); if (!initialResponse.isSuccessStatusCode()) { // If the initiation request is not successful return it immediately. return initialResponse; } GenericUrl uploadUrl; try { uploadUrl = new GenericUrl(initialResponse.getHeaders().getLocation()); } finally { initialResponse.disconnect(); } // Convert media content into a byte stream to upload in chunks. contentInputStream = mediaContent.getInputStream(); if (!contentInputStream.markSupported() && isMediaLengthKnown()) { // If we know the media content length then wrap the stream into a Buffered input stream to // support the {@link InputStream#mark} and {@link InputStream#reset} methods required for // handling server errors. contentInputStream = new BufferedInputStream(contentInputStream); } HttpResponse response; // Upload the media content in chunks. while (true) { ContentChunk contentChunk = buildContentChunk(); currentRequest = requestFactory.buildPutRequest(uploadUrl, null); currentRequest.setContent(contentChunk.getContent()); currentRequest.getHeaders().setContentRange(contentChunk.getContentRange()); // set mediaErrorHandler as I/O exception handler and as unsuccessful response handler for // calling to serverErrorCallback on an I/O exception or an abnormal HTTP response new MediaUploadErrorHandler(this, currentRequest); if (isMediaLengthKnown()) { // TODO(rmistry): Support gzipping content for the case where media content length is // known (https://github.com/googleapis/google-api-java-client/issues/691). response = executeCurrentRequestWithoutGZip(currentRequest); } else { response = executeCurrentRequest(currentRequest); } boolean returningResponse = false; try { if (response.isSuccessStatusCode()) { totalBytesServerReceived = getMediaContentLength(); if (mediaContent.getCloseInputStream()) { contentInputStream.close(); } updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE); returningResponse = true; return response; } if (response.getStatusCode() != 308) { returningResponse = true; return response; } // Check to see if the upload URL has changed on the server. String updatedUploadUrl = response.getHeaders().getLocation(); if (updatedUploadUrl != null) { uploadUrl = new GenericUrl(updatedUploadUrl); } // we check the amount of bytes the server received so far, because the server may process // fewer bytes than the amount of bytes the client had sent long newBytesServerReceived = getNextByteIndex(response.getHeaders().getRange()); // the server can receive any amount of bytes from 0 to current chunk length long currentBytesServerReceived = newBytesServerReceived - totalBytesServerReceived; Preconditions.checkState( currentBytesServerReceived >= 0 && currentBytesServerReceived <= currentChunkLength); long copyBytes = currentChunkLength - currentBytesServerReceived; if (isMediaLengthKnown()) { if (copyBytes > 0) { // If the server didn't receive all the bytes the client sent the current position of // the input stream is incorrect. So we should reset the stream and skip those bytes // that the server had already received. // Otherwise (the server got all bytes the client sent), the stream is in its right // position, and we can continue from there contentInputStream.reset(); long actualSkipValue = contentInputStream.skip(currentBytesServerReceived); Preconditions.checkState(currentBytesServerReceived == actualSkipValue); } } else if (copyBytes == 0) { // server got all the bytes, so we don't need to use this buffer. Otherwise, we have to // keep the buffer and copy part (or all) of its bytes to the stream we are sending to the // server currentRequestContentBuffer = null; } totalBytesServerReceived = newBytesServerReceived; updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS); } finally { if (!returningResponse) { response.disconnect(); } } } }
java
private HttpResponse resumableUpload(GenericUrl initiationRequestUrl) throws IOException { // Make initial request to get the unique upload URL. HttpResponse initialResponse = executeUploadInitiation(initiationRequestUrl); if (!initialResponse.isSuccessStatusCode()) { // If the initiation request is not successful return it immediately. return initialResponse; } GenericUrl uploadUrl; try { uploadUrl = new GenericUrl(initialResponse.getHeaders().getLocation()); } finally { initialResponse.disconnect(); } // Convert media content into a byte stream to upload in chunks. contentInputStream = mediaContent.getInputStream(); if (!contentInputStream.markSupported() && isMediaLengthKnown()) { // If we know the media content length then wrap the stream into a Buffered input stream to // support the {@link InputStream#mark} and {@link InputStream#reset} methods required for // handling server errors. contentInputStream = new BufferedInputStream(contentInputStream); } HttpResponse response; // Upload the media content in chunks. while (true) { ContentChunk contentChunk = buildContentChunk(); currentRequest = requestFactory.buildPutRequest(uploadUrl, null); currentRequest.setContent(contentChunk.getContent()); currentRequest.getHeaders().setContentRange(contentChunk.getContentRange()); // set mediaErrorHandler as I/O exception handler and as unsuccessful response handler for // calling to serverErrorCallback on an I/O exception or an abnormal HTTP response new MediaUploadErrorHandler(this, currentRequest); if (isMediaLengthKnown()) { // TODO(rmistry): Support gzipping content for the case where media content length is // known (https://github.com/googleapis/google-api-java-client/issues/691). response = executeCurrentRequestWithoutGZip(currentRequest); } else { response = executeCurrentRequest(currentRequest); } boolean returningResponse = false; try { if (response.isSuccessStatusCode()) { totalBytesServerReceived = getMediaContentLength(); if (mediaContent.getCloseInputStream()) { contentInputStream.close(); } updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE); returningResponse = true; return response; } if (response.getStatusCode() != 308) { returningResponse = true; return response; } // Check to see if the upload URL has changed on the server. String updatedUploadUrl = response.getHeaders().getLocation(); if (updatedUploadUrl != null) { uploadUrl = new GenericUrl(updatedUploadUrl); } // we check the amount of bytes the server received so far, because the server may process // fewer bytes than the amount of bytes the client had sent long newBytesServerReceived = getNextByteIndex(response.getHeaders().getRange()); // the server can receive any amount of bytes from 0 to current chunk length long currentBytesServerReceived = newBytesServerReceived - totalBytesServerReceived; Preconditions.checkState( currentBytesServerReceived >= 0 && currentBytesServerReceived <= currentChunkLength); long copyBytes = currentChunkLength - currentBytesServerReceived; if (isMediaLengthKnown()) { if (copyBytes > 0) { // If the server didn't receive all the bytes the client sent the current position of // the input stream is incorrect. So we should reset the stream and skip those bytes // that the server had already received. // Otherwise (the server got all bytes the client sent), the stream is in its right // position, and we can continue from there contentInputStream.reset(); long actualSkipValue = contentInputStream.skip(currentBytesServerReceived); Preconditions.checkState(currentBytesServerReceived == actualSkipValue); } } else if (copyBytes == 0) { // server got all the bytes, so we don't need to use this buffer. Otherwise, we have to // keep the buffer and copy part (or all) of its bytes to the stream we are sending to the // server currentRequestContentBuffer = null; } totalBytesServerReceived = newBytesServerReceived; updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS); } finally { if (!returningResponse) { response.disconnect(); } } } }
[ "private", "HttpResponse", "resumableUpload", "(", "GenericUrl", "initiationRequestUrl", ")", "throws", "IOException", "{", "// Make initial request to get the unique upload URL.", "HttpResponse", "initialResponse", "=", "executeUploadInitiation", "(", "initiationRequestUrl", ")", ";", "if", "(", "!", "initialResponse", ".", "isSuccessStatusCode", "(", ")", ")", "{", "// If the initiation request is not successful return it immediately.", "return", "initialResponse", ";", "}", "GenericUrl", "uploadUrl", ";", "try", "{", "uploadUrl", "=", "new", "GenericUrl", "(", "initialResponse", ".", "getHeaders", "(", ")", ".", "getLocation", "(", ")", ")", ";", "}", "finally", "{", "initialResponse", ".", "disconnect", "(", ")", ";", "}", "// Convert media content into a byte stream to upload in chunks.", "contentInputStream", "=", "mediaContent", ".", "getInputStream", "(", ")", ";", "if", "(", "!", "contentInputStream", ".", "markSupported", "(", ")", "&&", "isMediaLengthKnown", "(", ")", ")", "{", "// If we know the media content length then wrap the stream into a Buffered input stream to", "// support the {@link InputStream#mark} and {@link InputStream#reset} methods required for", "// handling server errors.", "contentInputStream", "=", "new", "BufferedInputStream", "(", "contentInputStream", ")", ";", "}", "HttpResponse", "response", ";", "// Upload the media content in chunks.", "while", "(", "true", ")", "{", "ContentChunk", "contentChunk", "=", "buildContentChunk", "(", ")", ";", "currentRequest", "=", "requestFactory", ".", "buildPutRequest", "(", "uploadUrl", ",", "null", ")", ";", "currentRequest", ".", "setContent", "(", "contentChunk", ".", "getContent", "(", ")", ")", ";", "currentRequest", ".", "getHeaders", "(", ")", ".", "setContentRange", "(", "contentChunk", ".", "getContentRange", "(", ")", ")", ";", "// set mediaErrorHandler as I/O exception handler and as unsuccessful response handler for", "// calling to serverErrorCallback on an I/O exception or an abnormal HTTP response", "new", "MediaUploadErrorHandler", "(", "this", ",", "currentRequest", ")", ";", "if", "(", "isMediaLengthKnown", "(", ")", ")", "{", "// TODO(rmistry): Support gzipping content for the case where media content length is", "// known (https://github.com/googleapis/google-api-java-client/issues/691).", "response", "=", "executeCurrentRequestWithoutGZip", "(", "currentRequest", ")", ";", "}", "else", "{", "response", "=", "executeCurrentRequest", "(", "currentRequest", ")", ";", "}", "boolean", "returningResponse", "=", "false", ";", "try", "{", "if", "(", "response", ".", "isSuccessStatusCode", "(", ")", ")", "{", "totalBytesServerReceived", "=", "getMediaContentLength", "(", ")", ";", "if", "(", "mediaContent", ".", "getCloseInputStream", "(", ")", ")", "{", "contentInputStream", ".", "close", "(", ")", ";", "}", "updateStateAndNotifyListener", "(", "UploadState", ".", "MEDIA_COMPLETE", ")", ";", "returningResponse", "=", "true", ";", "return", "response", ";", "}", "if", "(", "response", ".", "getStatusCode", "(", ")", "!=", "308", ")", "{", "returningResponse", "=", "true", ";", "return", "response", ";", "}", "// Check to see if the upload URL has changed on the server.", "String", "updatedUploadUrl", "=", "response", ".", "getHeaders", "(", ")", ".", "getLocation", "(", ")", ";", "if", "(", "updatedUploadUrl", "!=", "null", ")", "{", "uploadUrl", "=", "new", "GenericUrl", "(", "updatedUploadUrl", ")", ";", "}", "// we check the amount of bytes the server received so far, because the server may process", "// fewer bytes than the amount of bytes the client had sent", "long", "newBytesServerReceived", "=", "getNextByteIndex", "(", "response", ".", "getHeaders", "(", ")", ".", "getRange", "(", ")", ")", ";", "// the server can receive any amount of bytes from 0 to current chunk length", "long", "currentBytesServerReceived", "=", "newBytesServerReceived", "-", "totalBytesServerReceived", ";", "Preconditions", ".", "checkState", "(", "currentBytesServerReceived", ">=", "0", "&&", "currentBytesServerReceived", "<=", "currentChunkLength", ")", ";", "long", "copyBytes", "=", "currentChunkLength", "-", "currentBytesServerReceived", ";", "if", "(", "isMediaLengthKnown", "(", ")", ")", "{", "if", "(", "copyBytes", ">", "0", ")", "{", "// If the server didn't receive all the bytes the client sent the current position of", "// the input stream is incorrect. So we should reset the stream and skip those bytes", "// that the server had already received.", "// Otherwise (the server got all bytes the client sent), the stream is in its right", "// position, and we can continue from there", "contentInputStream", ".", "reset", "(", ")", ";", "long", "actualSkipValue", "=", "contentInputStream", ".", "skip", "(", "currentBytesServerReceived", ")", ";", "Preconditions", ".", "checkState", "(", "currentBytesServerReceived", "==", "actualSkipValue", ")", ";", "}", "}", "else", "if", "(", "copyBytes", "==", "0", ")", "{", "// server got all the bytes, so we don't need to use this buffer. Otherwise, we have to", "// keep the buffer and copy part (or all) of its bytes to the stream we are sending to the", "// server", "currentRequestContentBuffer", "=", "null", ";", "}", "totalBytesServerReceived", "=", "newBytesServerReceived", ";", "updateStateAndNotifyListener", "(", "UploadState", ".", "MEDIA_IN_PROGRESS", ")", ";", "}", "finally", "{", "if", "(", "!", "returningResponse", ")", "{", "response", ".", "disconnect", "(", ")", ";", "}", "}", "}", "}" ]
Uploads the media in a resumable manner. @param initiationRequestUrl The request URL where the initiation request will be sent @return HTTP response
[ "Uploads", "the", "media", "in", "a", "resumable", "manner", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java#L382-L481
25,562
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java
MediaHttpUploader.executeUploadInitiation
private HttpResponse executeUploadInitiation(GenericUrl initiationRequestUrl) throws IOException { updateStateAndNotifyListener(UploadState.INITIATION_STARTED); initiationRequestUrl.put("uploadType", "resumable"); HttpContent content = metadata == null ? new EmptyContent() : metadata; HttpRequest request = requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content); initiationHeaders.set(CONTENT_TYPE_HEADER, mediaContent.getType()); if (isMediaLengthKnown()) { initiationHeaders.set(CONTENT_LENGTH_HEADER, getMediaContentLength()); } request.getHeaders().putAll(initiationHeaders); HttpResponse response = executeCurrentRequest(request); boolean notificationCompleted = false; try { updateStateAndNotifyListener(UploadState.INITIATION_COMPLETE); notificationCompleted = true; } finally { if (!notificationCompleted) { response.disconnect(); } } return response; }
java
private HttpResponse executeUploadInitiation(GenericUrl initiationRequestUrl) throws IOException { updateStateAndNotifyListener(UploadState.INITIATION_STARTED); initiationRequestUrl.put("uploadType", "resumable"); HttpContent content = metadata == null ? new EmptyContent() : metadata; HttpRequest request = requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content); initiationHeaders.set(CONTENT_TYPE_HEADER, mediaContent.getType()); if (isMediaLengthKnown()) { initiationHeaders.set(CONTENT_LENGTH_HEADER, getMediaContentLength()); } request.getHeaders().putAll(initiationHeaders); HttpResponse response = executeCurrentRequest(request); boolean notificationCompleted = false; try { updateStateAndNotifyListener(UploadState.INITIATION_COMPLETE); notificationCompleted = true; } finally { if (!notificationCompleted) { response.disconnect(); } } return response; }
[ "private", "HttpResponse", "executeUploadInitiation", "(", "GenericUrl", "initiationRequestUrl", ")", "throws", "IOException", "{", "updateStateAndNotifyListener", "(", "UploadState", ".", "INITIATION_STARTED", ")", ";", "initiationRequestUrl", ".", "put", "(", "\"uploadType\"", ",", "\"resumable\"", ")", ";", "HttpContent", "content", "=", "metadata", "==", "null", "?", "new", "EmptyContent", "(", ")", ":", "metadata", ";", "HttpRequest", "request", "=", "requestFactory", ".", "buildRequest", "(", "initiationRequestMethod", ",", "initiationRequestUrl", ",", "content", ")", ";", "initiationHeaders", ".", "set", "(", "CONTENT_TYPE_HEADER", ",", "mediaContent", ".", "getType", "(", ")", ")", ";", "if", "(", "isMediaLengthKnown", "(", ")", ")", "{", "initiationHeaders", ".", "set", "(", "CONTENT_LENGTH_HEADER", ",", "getMediaContentLength", "(", ")", ")", ";", "}", "request", ".", "getHeaders", "(", ")", ".", "putAll", "(", "initiationHeaders", ")", ";", "HttpResponse", "response", "=", "executeCurrentRequest", "(", "request", ")", ";", "boolean", "notificationCompleted", "=", "false", ";", "try", "{", "updateStateAndNotifyListener", "(", "UploadState", ".", "INITIATION_COMPLETE", ")", ";", "notificationCompleted", "=", "true", ";", "}", "finally", "{", "if", "(", "!", "notificationCompleted", ")", "{", "response", ".", "disconnect", "(", ")", ";", "}", "}", "return", "response", ";", "}" ]
This method sends a POST request with empty content to get the unique upload URL. @param initiationRequestUrl The request URL where the initiation request will be sent
[ "This", "method", "sends", "a", "POST", "request", "with", "empty", "content", "to", "get", "the", "unique", "upload", "URL", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java#L510-L534
25,563
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java
MediaHttpUploader.executeCurrentRequestWithoutGZip
private HttpResponse executeCurrentRequestWithoutGZip(HttpRequest request) throws IOException { // method override for non-POST verbs new MethodOverride().intercept(request); // don't throw an exception so we can let a custom Google exception be thrown request.setThrowExceptionOnExecuteError(false); // execute the request HttpResponse response = request.execute(); return response; }
java
private HttpResponse executeCurrentRequestWithoutGZip(HttpRequest request) throws IOException { // method override for non-POST verbs new MethodOverride().intercept(request); // don't throw an exception so we can let a custom Google exception be thrown request.setThrowExceptionOnExecuteError(false); // execute the request HttpResponse response = request.execute(); return response; }
[ "private", "HttpResponse", "executeCurrentRequestWithoutGZip", "(", "HttpRequest", "request", ")", "throws", "IOException", "{", "// method override for non-POST verbs", "new", "MethodOverride", "(", ")", ".", "intercept", "(", "request", ")", ";", "// don't throw an exception so we can let a custom Google exception be thrown", "request", ".", "setThrowExceptionOnExecuteError", "(", "false", ")", ";", "// execute the request", "HttpResponse", "response", "=", "request", ".", "execute", "(", ")", ";", "return", "response", ";", "}" ]
Executes the current request with some minimal common code. @param request current request @return HTTP response
[ "Executes", "the", "current", "request", "with", "some", "minimal", "common", "code", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java#L542-L550
25,564
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java
MediaHttpUploader.executeCurrentRequest
private HttpResponse executeCurrentRequest(HttpRequest request) throws IOException { // enable GZip encoding if necessary if (!disableGZipContent && !(request.getContent() instanceof EmptyContent)) { request.setEncoding(new GZipEncoding()); } // execute request HttpResponse response = executeCurrentRequestWithoutGZip(request); return response; }
java
private HttpResponse executeCurrentRequest(HttpRequest request) throws IOException { // enable GZip encoding if necessary if (!disableGZipContent && !(request.getContent() instanceof EmptyContent)) { request.setEncoding(new GZipEncoding()); } // execute request HttpResponse response = executeCurrentRequestWithoutGZip(request); return response; }
[ "private", "HttpResponse", "executeCurrentRequest", "(", "HttpRequest", "request", ")", "throws", "IOException", "{", "// enable GZip encoding if necessary", "if", "(", "!", "disableGZipContent", "&&", "!", "(", "request", ".", "getContent", "(", ")", "instanceof", "EmptyContent", ")", ")", "{", "request", ".", "setEncoding", "(", "new", "GZipEncoding", "(", ")", ")", ";", "}", "// execute request", "HttpResponse", "response", "=", "executeCurrentRequestWithoutGZip", "(", "request", ")", ";", "return", "response", ";", "}" ]
Executes the current request with some common code that includes exponential backoff and GZip encoding. @param request current request @return HTTP response
[ "Executes", "the", "current", "request", "with", "some", "common", "code", "that", "includes", "exponential", "backoff", "and", "GZip", "encoding", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java#L559-L567
25,565
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java
MediaHttpUploader.buildContentChunk
private ContentChunk buildContentChunk() throws IOException { int blockSize; if (isMediaLengthKnown()) { // We know exactly what the blockSize will be because we know the media content length. blockSize = (int) Math.min(chunkSize, getMediaContentLength() - totalBytesServerReceived); } else { // Use the chunkSize as the blockSize because we do know what what it is yet. blockSize = chunkSize; } AbstractInputStreamContent contentChunk; int actualBlockSize = blockSize; if (isMediaLengthKnown()) { // Mark the current position in case we need to retry the request. contentInputStream.mark(blockSize); InputStream limitInputStream = ByteStreams.limit(contentInputStream, blockSize); contentChunk = new InputStreamContent( mediaContent.getType(), limitInputStream).setRetrySupported(true) .setLength(blockSize).setCloseInputStream(false); mediaContentLengthStr = String.valueOf(getMediaContentLength()); } else { // If the media content length is not known we implement a custom buffered input stream that // enables us to detect the length of the media content when the last chunk is sent. We // accomplish this by always trying to read an extra byte further than the end of the current // chunk. int actualBytesRead; int bytesAllowedToRead; // amount of bytes which need to be copied from last chunk buffer int copyBytes = 0; if (currentRequestContentBuffer == null) { bytesAllowedToRead = cachedByte == null ? blockSize + 1 : blockSize; currentRequestContentBuffer = new byte[blockSize + 1]; if (cachedByte != null) { currentRequestContentBuffer[0] = cachedByte; } } else { // currentRequestContentBuffer is not null that means one of the following: // 1. This is a request to recover from a server error (e.g. 503) // or // 2. The server received less bytes than the amount of bytes the client had sent. For // example, the client sends bytes 100-199, but the server returns back status code 308, // and its "Range" header is "bytes=0-150". // In that case, the new request will be constructed from the previous request's byte buffer // plus new bytes from the stream. copyBytes = (int) (totalBytesClientSent - totalBytesServerReceived); // shift copyBytes bytes to the beginning - those are the bytes which weren't received by // the server in the last chunk. System.arraycopy(currentRequestContentBuffer, currentChunkLength - copyBytes, currentRequestContentBuffer, 0, copyBytes); if (cachedByte != null) { // add the last cached byte to the buffer currentRequestContentBuffer[copyBytes] = cachedByte; } bytesAllowedToRead = blockSize - copyBytes; } actualBytesRead = ByteStreams.read( contentInputStream, currentRequestContentBuffer, blockSize + 1 - bytesAllowedToRead, bytesAllowedToRead); if (actualBytesRead < bytesAllowedToRead) { actualBlockSize = copyBytes + Math.max(0, actualBytesRead); if (cachedByte != null) { actualBlockSize++; cachedByte = null; } if (mediaContentLengthStr.equals("*")) { // At this point we know we reached the media content length because we either read less // than the specified chunk size or there is no more data left to be read. mediaContentLengthStr = String.valueOf(totalBytesServerReceived + actualBlockSize); } } else { cachedByte = currentRequestContentBuffer[blockSize]; } contentChunk = new ByteArrayContent( mediaContent.getType(), currentRequestContentBuffer, 0, actualBlockSize); totalBytesClientSent = totalBytesServerReceived + actualBlockSize; } currentChunkLength = actualBlockSize; String contentRange; if (actualBlockSize == 0) { // No bytes to upload. Either zero content media being uploaded, or a server failure on the // last write, even though the write actually succeeded. Either way, // mediaContentLengthStr will contain the actual media length. contentRange = "bytes */" + mediaContentLengthStr; } else { contentRange = "bytes " + totalBytesServerReceived + "-" + (totalBytesServerReceived + actualBlockSize - 1) + "/" + mediaContentLengthStr; } return new ContentChunk(contentChunk, contentRange); }
java
private ContentChunk buildContentChunk() throws IOException { int blockSize; if (isMediaLengthKnown()) { // We know exactly what the blockSize will be because we know the media content length. blockSize = (int) Math.min(chunkSize, getMediaContentLength() - totalBytesServerReceived); } else { // Use the chunkSize as the blockSize because we do know what what it is yet. blockSize = chunkSize; } AbstractInputStreamContent contentChunk; int actualBlockSize = blockSize; if (isMediaLengthKnown()) { // Mark the current position in case we need to retry the request. contentInputStream.mark(blockSize); InputStream limitInputStream = ByteStreams.limit(contentInputStream, blockSize); contentChunk = new InputStreamContent( mediaContent.getType(), limitInputStream).setRetrySupported(true) .setLength(blockSize).setCloseInputStream(false); mediaContentLengthStr = String.valueOf(getMediaContentLength()); } else { // If the media content length is not known we implement a custom buffered input stream that // enables us to detect the length of the media content when the last chunk is sent. We // accomplish this by always trying to read an extra byte further than the end of the current // chunk. int actualBytesRead; int bytesAllowedToRead; // amount of bytes which need to be copied from last chunk buffer int copyBytes = 0; if (currentRequestContentBuffer == null) { bytesAllowedToRead = cachedByte == null ? blockSize + 1 : blockSize; currentRequestContentBuffer = new byte[blockSize + 1]; if (cachedByte != null) { currentRequestContentBuffer[0] = cachedByte; } } else { // currentRequestContentBuffer is not null that means one of the following: // 1. This is a request to recover from a server error (e.g. 503) // or // 2. The server received less bytes than the amount of bytes the client had sent. For // example, the client sends bytes 100-199, but the server returns back status code 308, // and its "Range" header is "bytes=0-150". // In that case, the new request will be constructed from the previous request's byte buffer // plus new bytes from the stream. copyBytes = (int) (totalBytesClientSent - totalBytesServerReceived); // shift copyBytes bytes to the beginning - those are the bytes which weren't received by // the server in the last chunk. System.arraycopy(currentRequestContentBuffer, currentChunkLength - copyBytes, currentRequestContentBuffer, 0, copyBytes); if (cachedByte != null) { // add the last cached byte to the buffer currentRequestContentBuffer[copyBytes] = cachedByte; } bytesAllowedToRead = blockSize - copyBytes; } actualBytesRead = ByteStreams.read( contentInputStream, currentRequestContentBuffer, blockSize + 1 - bytesAllowedToRead, bytesAllowedToRead); if (actualBytesRead < bytesAllowedToRead) { actualBlockSize = copyBytes + Math.max(0, actualBytesRead); if (cachedByte != null) { actualBlockSize++; cachedByte = null; } if (mediaContentLengthStr.equals("*")) { // At this point we know we reached the media content length because we either read less // than the specified chunk size or there is no more data left to be read. mediaContentLengthStr = String.valueOf(totalBytesServerReceived + actualBlockSize); } } else { cachedByte = currentRequestContentBuffer[blockSize]; } contentChunk = new ByteArrayContent( mediaContent.getType(), currentRequestContentBuffer, 0, actualBlockSize); totalBytesClientSent = totalBytesServerReceived + actualBlockSize; } currentChunkLength = actualBlockSize; String contentRange; if (actualBlockSize == 0) { // No bytes to upload. Either zero content media being uploaded, or a server failure on the // last write, even though the write actually succeeded. Either way, // mediaContentLengthStr will contain the actual media length. contentRange = "bytes */" + mediaContentLengthStr; } else { contentRange = "bytes " + totalBytesServerReceived + "-" + (totalBytesServerReceived + actualBlockSize - 1) + "/" + mediaContentLengthStr; } return new ContentChunk(contentChunk, contentRange); }
[ "private", "ContentChunk", "buildContentChunk", "(", ")", "throws", "IOException", "{", "int", "blockSize", ";", "if", "(", "isMediaLengthKnown", "(", ")", ")", "{", "// We know exactly what the blockSize will be because we know the media content length.", "blockSize", "=", "(", "int", ")", "Math", ".", "min", "(", "chunkSize", ",", "getMediaContentLength", "(", ")", "-", "totalBytesServerReceived", ")", ";", "}", "else", "{", "// Use the chunkSize as the blockSize because we do know what what it is yet.", "blockSize", "=", "chunkSize", ";", "}", "AbstractInputStreamContent", "contentChunk", ";", "int", "actualBlockSize", "=", "blockSize", ";", "if", "(", "isMediaLengthKnown", "(", ")", ")", "{", "// Mark the current position in case we need to retry the request.", "contentInputStream", ".", "mark", "(", "blockSize", ")", ";", "InputStream", "limitInputStream", "=", "ByteStreams", ".", "limit", "(", "contentInputStream", ",", "blockSize", ")", ";", "contentChunk", "=", "new", "InputStreamContent", "(", "mediaContent", ".", "getType", "(", ")", ",", "limitInputStream", ")", ".", "setRetrySupported", "(", "true", ")", ".", "setLength", "(", "blockSize", ")", ".", "setCloseInputStream", "(", "false", ")", ";", "mediaContentLengthStr", "=", "String", ".", "valueOf", "(", "getMediaContentLength", "(", ")", ")", ";", "}", "else", "{", "// If the media content length is not known we implement a custom buffered input stream that", "// enables us to detect the length of the media content when the last chunk is sent. We", "// accomplish this by always trying to read an extra byte further than the end of the current", "// chunk.", "int", "actualBytesRead", ";", "int", "bytesAllowedToRead", ";", "// amount of bytes which need to be copied from last chunk buffer", "int", "copyBytes", "=", "0", ";", "if", "(", "currentRequestContentBuffer", "==", "null", ")", "{", "bytesAllowedToRead", "=", "cachedByte", "==", "null", "?", "blockSize", "+", "1", ":", "blockSize", ";", "currentRequestContentBuffer", "=", "new", "byte", "[", "blockSize", "+", "1", "]", ";", "if", "(", "cachedByte", "!=", "null", ")", "{", "currentRequestContentBuffer", "[", "0", "]", "=", "cachedByte", ";", "}", "}", "else", "{", "// currentRequestContentBuffer is not null that means one of the following:", "// 1. This is a request to recover from a server error (e.g. 503)", "// or", "// 2. The server received less bytes than the amount of bytes the client had sent. For", "// example, the client sends bytes 100-199, but the server returns back status code 308,", "// and its \"Range\" header is \"bytes=0-150\".", "// In that case, the new request will be constructed from the previous request's byte buffer", "// plus new bytes from the stream.", "copyBytes", "=", "(", "int", ")", "(", "totalBytesClientSent", "-", "totalBytesServerReceived", ")", ";", "// shift copyBytes bytes to the beginning - those are the bytes which weren't received by", "// the server in the last chunk.", "System", ".", "arraycopy", "(", "currentRequestContentBuffer", ",", "currentChunkLength", "-", "copyBytes", ",", "currentRequestContentBuffer", ",", "0", ",", "copyBytes", ")", ";", "if", "(", "cachedByte", "!=", "null", ")", "{", "// add the last cached byte to the buffer", "currentRequestContentBuffer", "[", "copyBytes", "]", "=", "cachedByte", ";", "}", "bytesAllowedToRead", "=", "blockSize", "-", "copyBytes", ";", "}", "actualBytesRead", "=", "ByteStreams", ".", "read", "(", "contentInputStream", ",", "currentRequestContentBuffer", ",", "blockSize", "+", "1", "-", "bytesAllowedToRead", ",", "bytesAllowedToRead", ")", ";", "if", "(", "actualBytesRead", "<", "bytesAllowedToRead", ")", "{", "actualBlockSize", "=", "copyBytes", "+", "Math", ".", "max", "(", "0", ",", "actualBytesRead", ")", ";", "if", "(", "cachedByte", "!=", "null", ")", "{", "actualBlockSize", "++", ";", "cachedByte", "=", "null", ";", "}", "if", "(", "mediaContentLengthStr", ".", "equals", "(", "\"*\"", ")", ")", "{", "// At this point we know we reached the media content length because we either read less", "// than the specified chunk size or there is no more data left to be read.", "mediaContentLengthStr", "=", "String", ".", "valueOf", "(", "totalBytesServerReceived", "+", "actualBlockSize", ")", ";", "}", "}", "else", "{", "cachedByte", "=", "currentRequestContentBuffer", "[", "blockSize", "]", ";", "}", "contentChunk", "=", "new", "ByteArrayContent", "(", "mediaContent", ".", "getType", "(", ")", ",", "currentRequestContentBuffer", ",", "0", ",", "actualBlockSize", ")", ";", "totalBytesClientSent", "=", "totalBytesServerReceived", "+", "actualBlockSize", ";", "}", "currentChunkLength", "=", "actualBlockSize", ";", "String", "contentRange", ";", "if", "(", "actualBlockSize", "==", "0", ")", "{", "// No bytes to upload. Either zero content media being uploaded, or a server failure on the", "// last write, even though the write actually succeeded. Either way,", "// mediaContentLengthStr will contain the actual media length.", "contentRange", "=", "\"bytes */\"", "+", "mediaContentLengthStr", ";", "}", "else", "{", "contentRange", "=", "\"bytes \"", "+", "totalBytesServerReceived", "+", "\"-\"", "+", "(", "totalBytesServerReceived", "+", "actualBlockSize", "-", "1", ")", "+", "\"/\"", "+", "mediaContentLengthStr", ";", "}", "return", "new", "ContentChunk", "(", "contentChunk", ",", "contentRange", ")", ";", "}" ]
Sets the HTTP media content chunk and the required headers that should be used in the upload request.
[ "Sets", "the", "HTTP", "media", "content", "chunk", "and", "the", "required", "headers", "that", "should", "be", "used", "in", "the", "upload", "request", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java#L573-L670
25,566
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java
MediaHttpUploader.setInitiationRequestMethod
public MediaHttpUploader setInitiationRequestMethod(String initiationRequestMethod) { Preconditions.checkArgument(initiationRequestMethod.equals(HttpMethods.POST) || initiationRequestMethod.equals(HttpMethods.PUT) || initiationRequestMethod.equals(HttpMethods.PATCH)); this.initiationRequestMethod = initiationRequestMethod; return this; }
java
public MediaHttpUploader setInitiationRequestMethod(String initiationRequestMethod) { Preconditions.checkArgument(initiationRequestMethod.equals(HttpMethods.POST) || initiationRequestMethod.equals(HttpMethods.PUT) || initiationRequestMethod.equals(HttpMethods.PATCH)); this.initiationRequestMethod = initiationRequestMethod; return this; }
[ "public", "MediaHttpUploader", "setInitiationRequestMethod", "(", "String", "initiationRequestMethod", ")", "{", "Preconditions", ".", "checkArgument", "(", "initiationRequestMethod", ".", "equals", "(", "HttpMethods", ".", "POST", ")", "||", "initiationRequestMethod", ".", "equals", "(", "HttpMethods", ".", "PUT", ")", "||", "initiationRequestMethod", ".", "equals", "(", "HttpMethods", ".", "PATCH", ")", ")", ";", "this", ".", "initiationRequestMethod", "=", "initiationRequestMethod", ";", "return", "this", ";", "}" ]
Sets the HTTP method used for the initiation request. <p> Can only be {@link HttpMethods#POST} (for media upload) or {@link HttpMethods#PUT} (for media update). The default value is {@link HttpMethods#POST}. </p> @since 1.12
[ "Sets", "the", "HTTP", "method", "used", "for", "the", "initiation", "request", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java#L895-L901
25,567
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java
MediaHttpUploader.updateStateAndNotifyListener
private void updateStateAndNotifyListener(UploadState uploadState) throws IOException { this.uploadState = uploadState; if (progressListener != null) { progressListener.progressChanged(this); } }
java
private void updateStateAndNotifyListener(UploadState uploadState) throws IOException { this.uploadState = uploadState; if (progressListener != null) { progressListener.progressChanged(this); } }
[ "private", "void", "updateStateAndNotifyListener", "(", "UploadState", "uploadState", ")", "throws", "IOException", "{", "this", ".", "uploadState", "=", "uploadState", ";", "if", "(", "progressListener", "!=", "null", ")", "{", "progressListener", ".", "progressChanged", "(", "this", ")", ";", "}", "}" ]
Sets the upload state and notifies the progress listener. @param uploadState value to set to
[ "Sets", "the", "upload", "state", "and", "notifies", "the", "progress", "listener", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java#L929-L934
25,568
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/GoogleUtils.java
GoogleUtils.getCertificateTrustStore
public static synchronized KeyStore getCertificateTrustStore() throws IOException, GeneralSecurityException { if (certTrustStore == null) { certTrustStore = SecurityUtils.getJavaKeyStore(); InputStream keyStoreStream = GoogleUtils.class.getResourceAsStream("google.jks"); SecurityUtils.loadKeyStore(certTrustStore, keyStoreStream, "notasecret"); } return certTrustStore; }
java
public static synchronized KeyStore getCertificateTrustStore() throws IOException, GeneralSecurityException { if (certTrustStore == null) { certTrustStore = SecurityUtils.getJavaKeyStore(); InputStream keyStoreStream = GoogleUtils.class.getResourceAsStream("google.jks"); SecurityUtils.loadKeyStore(certTrustStore, keyStoreStream, "notasecret"); } return certTrustStore; }
[ "public", "static", "synchronized", "KeyStore", "getCertificateTrustStore", "(", ")", "throws", "IOException", ",", "GeneralSecurityException", "{", "if", "(", "certTrustStore", "==", "null", ")", "{", "certTrustStore", "=", "SecurityUtils", ".", "getJavaKeyStore", "(", ")", ";", "InputStream", "keyStoreStream", "=", "GoogleUtils", ".", "class", ".", "getResourceAsStream", "(", "\"google.jks\"", ")", ";", "SecurityUtils", ".", "loadKeyStore", "(", "certTrustStore", ",", "keyStoreStream", ",", "\"notasecret\"", ")", ";", "}", "return", "certTrustStore", ";", "}" ]
Returns the key store for trusted root certificates to use for Google APIs. <p> Value is cached, so subsequent access is fast. </p> @since 1.14
[ "Returns", "the", "key", "store", "for", "trusted", "root", "certificates", "to", "use", "for", "Google", "APIs", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/GoogleUtils.java#L71-L79
25,569
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/batch/BatchUnparsedResponse.java
BatchUnparsedResponse.getFakeResponse
private HttpResponse getFakeResponse(final int statusCode, final InputStream partContent, List<String> headerNames, List<String> headerValues) throws IOException { HttpRequest request = new FakeResponseHttpTransport( statusCode, partContent, headerNames, headerValues).createRequestFactory() .buildPostRequest(new GenericUrl("http://google.com/"), null); request.setLoggingEnabled(false); request.setThrowExceptionOnExecuteError(false); return request.execute(); }
java
private HttpResponse getFakeResponse(final int statusCode, final InputStream partContent, List<String> headerNames, List<String> headerValues) throws IOException { HttpRequest request = new FakeResponseHttpTransport( statusCode, partContent, headerNames, headerValues).createRequestFactory() .buildPostRequest(new GenericUrl("http://google.com/"), null); request.setLoggingEnabled(false); request.setThrowExceptionOnExecuteError(false); return request.execute(); }
[ "private", "HttpResponse", "getFakeResponse", "(", "final", "int", "statusCode", ",", "final", "InputStream", "partContent", ",", "List", "<", "String", ">", "headerNames", ",", "List", "<", "String", ">", "headerValues", ")", "throws", "IOException", "{", "HttpRequest", "request", "=", "new", "FakeResponseHttpTransport", "(", "statusCode", ",", "partContent", ",", "headerNames", ",", "headerValues", ")", ".", "createRequestFactory", "(", ")", ".", "buildPostRequest", "(", "new", "GenericUrl", "(", "\"http://google.com/\"", ")", ",", "null", ")", ";", "request", ".", "setLoggingEnabled", "(", "false", ")", ";", "request", ".", "setThrowExceptionOnExecuteError", "(", "false", ")", ";", "return", "request", ".", "execute", "(", ")", ";", "}" ]
Create a fake HTTP response object populated with the partContent and the statusCode.
[ "Create", "a", "fake", "HTTP", "response", "object", "populated", "with", "the", "partContent", "and", "the", "statusCode", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/batch/BatchUnparsedResponse.java#L227-L236
25,570
googleapis/google-api-java-client
google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GoogleAccountCredential.java
GoogleAccountCredential.usingOAuth2
public static GoogleAccountCredential usingOAuth2(Context context, Collection<String> scopes) { Preconditions.checkArgument(scopes != null && scopes.iterator().hasNext()); String scopesStr = "oauth2: " + Joiner.on(' ').join(scopes); return new GoogleAccountCredential(context, scopesStr); }
java
public static GoogleAccountCredential usingOAuth2(Context context, Collection<String> scopes) { Preconditions.checkArgument(scopes != null && scopes.iterator().hasNext()); String scopesStr = "oauth2: " + Joiner.on(' ').join(scopes); return new GoogleAccountCredential(context, scopesStr); }
[ "public", "static", "GoogleAccountCredential", "usingOAuth2", "(", "Context", "context", ",", "Collection", "<", "String", ">", "scopes", ")", "{", "Preconditions", ".", "checkArgument", "(", "scopes", "!=", "null", "&&", "scopes", ".", "iterator", "(", ")", ".", "hasNext", "(", ")", ")", ";", "String", "scopesStr", "=", "\"oauth2: \"", "+", "Joiner", ".", "on", "(", "'", "'", ")", ".", "join", "(", "scopes", ")", ";", "return", "new", "GoogleAccountCredential", "(", "context", ",", "scopesStr", ")", ";", "}" ]
Constructs a new instance using OAuth 2.0 scopes. @param context context @param scopes non empty OAuth 2.0 scope list @return new instance @since 1.15
[ "Constructs", "a", "new", "instance", "using", "OAuth", "2", ".", "0", "scopes", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GoogleAccountCredential.java#L112-L116
25,571
googleapis/google-api-java-client
google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GoogleAccountCredential.java
GoogleAccountCredential.usingAudience
public static GoogleAccountCredential usingAudience(Context context, String audience) { Preconditions.checkArgument(audience.length() != 0); return new GoogleAccountCredential(context, "audience:" + audience); }
java
public static GoogleAccountCredential usingAudience(Context context, String audience) { Preconditions.checkArgument(audience.length() != 0); return new GoogleAccountCredential(context, "audience:" + audience); }
[ "public", "static", "GoogleAccountCredential", "usingAudience", "(", "Context", "context", ",", "String", "audience", ")", "{", "Preconditions", ".", "checkArgument", "(", "audience", ".", "length", "(", ")", "!=", "0", ")", ";", "return", "new", "GoogleAccountCredential", "(", "context", ",", "\"audience:\"", "+", "audience", ")", ";", "}" ]
Sets the audience scope to use with Google Cloud Endpoints. @param context context @param audience audience @return new instance
[ "Sets", "the", "audience", "scope", "to", "use", "with", "Google", "Cloud", "Endpoints", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GoogleAccountCredential.java#L125-L128
25,572
googleapis/google-api-java-client
google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GoogleAccountCredential.java
GoogleAccountCredential.newChooseAccountIntent
public final Intent newChooseAccountIntent() { return AccountPicker.newChooseAccountIntent(selectedAccount, null, new String[] {GoogleAccountManager.ACCOUNT_TYPE}, true, null, null, null, null); }
java
public final Intent newChooseAccountIntent() { return AccountPicker.newChooseAccountIntent(selectedAccount, null, new String[] {GoogleAccountManager.ACCOUNT_TYPE}, true, null, null, null, null); }
[ "public", "final", "Intent", "newChooseAccountIntent", "(", ")", "{", "return", "AccountPicker", ".", "newChooseAccountIntent", "(", "selectedAccount", ",", "null", ",", "new", "String", "[", "]", "{", "GoogleAccountManager", ".", "ACCOUNT_TYPE", "}", ",", "true", ",", "null", ",", "null", ",", "null", ",", "null", ")", ";", "}" ]
Returns an intent to show the user to select a Google account, or create a new one if there are none on the device yet. <p> Must be run from the main UI thread. </p>
[ "Returns", "an", "intent", "to", "show", "the", "user", "to", "select", "a", "Google", "account", "or", "create", "a", "new", "one", "if", "there", "are", "none", "on", "the", "device", "yet", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GoogleAccountCredential.java#L242-L251
25,573
googleapis/google-api-java-client
google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GoogleAccountCredential.java
GoogleAccountCredential.getToken
public String getToken() throws IOException, GoogleAuthException { if (backOff != null) { backOff.reset(); } while (true) { try { return GoogleAuthUtil.getToken(context, accountName, scope); } catch (IOException e) { // network or server error, so retry using back-off policy try { if (backOff == null || !BackOffUtils.next(sleeper, backOff)) { throw e; } } catch (InterruptedException e2) { // ignore } } } }
java
public String getToken() throws IOException, GoogleAuthException { if (backOff != null) { backOff.reset(); } while (true) { try { return GoogleAuthUtil.getToken(context, accountName, scope); } catch (IOException e) { // network or server error, so retry using back-off policy try { if (backOff == null || !BackOffUtils.next(sleeper, backOff)) { throw e; } } catch (InterruptedException e2) { // ignore } } } }
[ "public", "String", "getToken", "(", ")", "throws", "IOException", ",", "GoogleAuthException", "{", "if", "(", "backOff", "!=", "null", ")", "{", "backOff", ".", "reset", "(", ")", ";", "}", "while", "(", "true", ")", "{", "try", "{", "return", "GoogleAuthUtil", ".", "getToken", "(", "context", ",", "accountName", ",", "scope", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// network or server error, so retry using back-off policy", "try", "{", "if", "(", "backOff", "==", "null", "||", "!", "BackOffUtils", ".", "next", "(", "sleeper", ",", "backOff", ")", ")", "{", "throw", "e", ";", "}", "}", "catch", "(", "InterruptedException", "e2", ")", "{", "// ignore", "}", "}", "}", "}" ]
Returns an OAuth 2.0 access token. <p> Must be run from a background thread, not the main UI thread. </p>
[ "Returns", "an", "OAuth", "2", ".", "0", "access", "token", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GoogleAccountCredential.java#L260-L279
25,574
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleClientSecrets.java
GoogleClientSecrets.getDetails
public Details getDetails() { // that web or installed, but not both Preconditions.checkArgument((web == null) != (installed == null)); return web == null ? installed : web; }
java
public Details getDetails() { // that web or installed, but not both Preconditions.checkArgument((web == null) != (installed == null)); return web == null ? installed : web; }
[ "public", "Details", "getDetails", "(", ")", "{", "// that web or installed, but not both", "Preconditions", ".", "checkArgument", "(", "(", "web", "==", "null", ")", "!=", "(", "installed", "==", "null", ")", ")", ";", "return", "web", "==", "null", "?", "installed", ":", "web", ";", "}" ]
Returns the details for either installed or web applications.
[ "Returns", "the", "details", "for", "either", "installed", "or", "web", "applications", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleClientSecrets.java#L80-L84
25,575
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpDownloader.java
MediaHttpDownloader.executeCurrentRequest
private HttpResponse executeCurrentRequest(long currentRequestLastBytePos, GenericUrl requestUrl, HttpHeaders requestHeaders, OutputStream outputStream) throws IOException { // prepare the GET request HttpRequest request = requestFactory.buildGetRequest(requestUrl); // add request headers if (requestHeaders != null) { request.getHeaders().putAll(requestHeaders); } // set Range header (if necessary) if (bytesDownloaded != 0 || currentRequestLastBytePos != -1) { StringBuilder rangeHeader = new StringBuilder(); rangeHeader.append("bytes=").append(bytesDownloaded).append("-"); if (currentRequestLastBytePos != -1) { rangeHeader.append(currentRequestLastBytePos); } request.getHeaders().setRange(rangeHeader.toString()); } // execute the request and copy into the output stream HttpResponse response = request.execute(); try { ByteStreams.copy(response.getContent(), outputStream); } finally { response.disconnect(); } return response; }
java
private HttpResponse executeCurrentRequest(long currentRequestLastBytePos, GenericUrl requestUrl, HttpHeaders requestHeaders, OutputStream outputStream) throws IOException { // prepare the GET request HttpRequest request = requestFactory.buildGetRequest(requestUrl); // add request headers if (requestHeaders != null) { request.getHeaders().putAll(requestHeaders); } // set Range header (if necessary) if (bytesDownloaded != 0 || currentRequestLastBytePos != -1) { StringBuilder rangeHeader = new StringBuilder(); rangeHeader.append("bytes=").append(bytesDownloaded).append("-"); if (currentRequestLastBytePos != -1) { rangeHeader.append(currentRequestLastBytePos); } request.getHeaders().setRange(rangeHeader.toString()); } // execute the request and copy into the output stream HttpResponse response = request.execute(); try { ByteStreams.copy(response.getContent(), outputStream); } finally { response.disconnect(); } return response; }
[ "private", "HttpResponse", "executeCurrentRequest", "(", "long", "currentRequestLastBytePos", ",", "GenericUrl", "requestUrl", ",", "HttpHeaders", "requestHeaders", ",", "OutputStream", "outputStream", ")", "throws", "IOException", "{", "// prepare the GET request", "HttpRequest", "request", "=", "requestFactory", ".", "buildGetRequest", "(", "requestUrl", ")", ";", "// add request headers", "if", "(", "requestHeaders", "!=", "null", ")", "{", "request", ".", "getHeaders", "(", ")", ".", "putAll", "(", "requestHeaders", ")", ";", "}", "// set Range header (if necessary)", "if", "(", "bytesDownloaded", "!=", "0", "||", "currentRequestLastBytePos", "!=", "-", "1", ")", "{", "StringBuilder", "rangeHeader", "=", "new", "StringBuilder", "(", ")", ";", "rangeHeader", ".", "append", "(", "\"bytes=\"", ")", ".", "append", "(", "bytesDownloaded", ")", ".", "append", "(", "\"-\"", ")", ";", "if", "(", "currentRequestLastBytePos", "!=", "-", "1", ")", "{", "rangeHeader", ".", "append", "(", "currentRequestLastBytePos", ")", ";", "}", "request", ".", "getHeaders", "(", ")", ".", "setRange", "(", "rangeHeader", ".", "toString", "(", ")", ")", ";", "}", "// execute the request and copy into the output stream", "HttpResponse", "response", "=", "request", ".", "execute", "(", ")", ";", "try", "{", "ByteStreams", ".", "copy", "(", "response", ".", "getContent", "(", ")", ",", "outputStream", ")", ";", "}", "finally", "{", "response", ".", "disconnect", "(", ")", ";", "}", "return", "response", ";", "}" ]
Executes the current request. @param currentRequestLastBytePos last byte position for current request @param requestUrl request URL where the download requests will be sent @param requestHeaders request headers or {@code null} to ignore @param outputStream destination output stream @return HTTP response
[ "Executes", "the", "current", "request", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpDownloader.java#L237-L262
25,576
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpDownloader.java
MediaHttpDownloader.updateStateAndNotifyListener
private void updateStateAndNotifyListener(DownloadState downloadState) throws IOException { this.downloadState = downloadState; if (progressListener != null) { progressListener.progressChanged(this); } }
java
private void updateStateAndNotifyListener(DownloadState downloadState) throws IOException { this.downloadState = downloadState; if (progressListener != null) { progressListener.progressChanged(this); } }
[ "private", "void", "updateStateAndNotifyListener", "(", "DownloadState", "downloadState", ")", "throws", "IOException", "{", "this", ".", "downloadState", "=", "downloadState", ";", "if", "(", "progressListener", "!=", "null", ")", "{", "progressListener", ".", "progressChanged", "(", "this", ")", ";", "}", "}" ]
Sets the download state and notifies the progress listener. @param downloadState value to set to
[ "Sets", "the", "download", "state", "and", "notifies", "the", "progress", "listener", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpDownloader.java#L433-L438
25,577
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/batch/BatchRequest.java
BatchRequest.execute
public void execute() throws IOException { boolean retryAllowed; Preconditions.checkState(!requestInfos.isEmpty()); HttpRequest batchRequest = requestFactory.buildPostRequest(this.batchUrl, null); // NOTE: batch does not support gzip encoding HttpExecuteInterceptor originalInterceptor = batchRequest.getInterceptor(); batchRequest.setInterceptor(new BatchInterceptor(originalInterceptor)); int retriesRemaining = batchRequest.getNumberOfRetries(); do { retryAllowed = retriesRemaining > 0; MultipartContent batchContent = new MultipartContent(); batchContent.getMediaType().setSubType("mixed"); int contentId = 1; for (RequestInfo<?, ?> requestInfo : requestInfos) { batchContent.addPart(new MultipartContent.Part( new HttpHeaders().setAcceptEncoding(null).set("Content-ID", contentId++), new HttpRequestContent(requestInfo.request))); } batchRequest.setContent(batchContent); HttpResponse response = batchRequest.execute(); BatchUnparsedResponse batchResponse; try { // Find the boundary from the Content-Type header. String boundary = "--" + response.getMediaType().getParameter("boundary"); // Parse the content stream. InputStream contentStream = response.getContent(); batchResponse = new BatchUnparsedResponse(contentStream, boundary, requestInfos, retryAllowed); while (batchResponse.hasNext) { batchResponse.parseNextResponse(); } } finally { response.disconnect(); } List<RequestInfo<?, ?>> unsuccessfulRequestInfos = batchResponse.unsuccessfulRequestInfos; if (!unsuccessfulRequestInfos.isEmpty()) { requestInfos = unsuccessfulRequestInfos; } else { break; } retriesRemaining--; } while (retryAllowed); requestInfos.clear(); }
java
public void execute() throws IOException { boolean retryAllowed; Preconditions.checkState(!requestInfos.isEmpty()); HttpRequest batchRequest = requestFactory.buildPostRequest(this.batchUrl, null); // NOTE: batch does not support gzip encoding HttpExecuteInterceptor originalInterceptor = batchRequest.getInterceptor(); batchRequest.setInterceptor(new BatchInterceptor(originalInterceptor)); int retriesRemaining = batchRequest.getNumberOfRetries(); do { retryAllowed = retriesRemaining > 0; MultipartContent batchContent = new MultipartContent(); batchContent.getMediaType().setSubType("mixed"); int contentId = 1; for (RequestInfo<?, ?> requestInfo : requestInfos) { batchContent.addPart(new MultipartContent.Part( new HttpHeaders().setAcceptEncoding(null).set("Content-ID", contentId++), new HttpRequestContent(requestInfo.request))); } batchRequest.setContent(batchContent); HttpResponse response = batchRequest.execute(); BatchUnparsedResponse batchResponse; try { // Find the boundary from the Content-Type header. String boundary = "--" + response.getMediaType().getParameter("boundary"); // Parse the content stream. InputStream contentStream = response.getContent(); batchResponse = new BatchUnparsedResponse(contentStream, boundary, requestInfos, retryAllowed); while (batchResponse.hasNext) { batchResponse.parseNextResponse(); } } finally { response.disconnect(); } List<RequestInfo<?, ?>> unsuccessfulRequestInfos = batchResponse.unsuccessfulRequestInfos; if (!unsuccessfulRequestInfos.isEmpty()) { requestInfos = unsuccessfulRequestInfos; } else { break; } retriesRemaining--; } while (retryAllowed); requestInfos.clear(); }
[ "public", "void", "execute", "(", ")", "throws", "IOException", "{", "boolean", "retryAllowed", ";", "Preconditions", ".", "checkState", "(", "!", "requestInfos", ".", "isEmpty", "(", ")", ")", ";", "HttpRequest", "batchRequest", "=", "requestFactory", ".", "buildPostRequest", "(", "this", ".", "batchUrl", ",", "null", ")", ";", "// NOTE: batch does not support gzip encoding", "HttpExecuteInterceptor", "originalInterceptor", "=", "batchRequest", ".", "getInterceptor", "(", ")", ";", "batchRequest", ".", "setInterceptor", "(", "new", "BatchInterceptor", "(", "originalInterceptor", ")", ")", ";", "int", "retriesRemaining", "=", "batchRequest", ".", "getNumberOfRetries", "(", ")", ";", "do", "{", "retryAllowed", "=", "retriesRemaining", ">", "0", ";", "MultipartContent", "batchContent", "=", "new", "MultipartContent", "(", ")", ";", "batchContent", ".", "getMediaType", "(", ")", ".", "setSubType", "(", "\"mixed\"", ")", ";", "int", "contentId", "=", "1", ";", "for", "(", "RequestInfo", "<", "?", ",", "?", ">", "requestInfo", ":", "requestInfos", ")", "{", "batchContent", ".", "addPart", "(", "new", "MultipartContent", ".", "Part", "(", "new", "HttpHeaders", "(", ")", ".", "setAcceptEncoding", "(", "null", ")", ".", "set", "(", "\"Content-ID\"", ",", "contentId", "++", ")", ",", "new", "HttpRequestContent", "(", "requestInfo", ".", "request", ")", ")", ")", ";", "}", "batchRequest", ".", "setContent", "(", "batchContent", ")", ";", "HttpResponse", "response", "=", "batchRequest", ".", "execute", "(", ")", ";", "BatchUnparsedResponse", "batchResponse", ";", "try", "{", "// Find the boundary from the Content-Type header.", "String", "boundary", "=", "\"--\"", "+", "response", ".", "getMediaType", "(", ")", ".", "getParameter", "(", "\"boundary\"", ")", ";", "// Parse the content stream.", "InputStream", "contentStream", "=", "response", ".", "getContent", "(", ")", ";", "batchResponse", "=", "new", "BatchUnparsedResponse", "(", "contentStream", ",", "boundary", ",", "requestInfos", ",", "retryAllowed", ")", ";", "while", "(", "batchResponse", ".", "hasNext", ")", "{", "batchResponse", ".", "parseNextResponse", "(", ")", ";", "}", "}", "finally", "{", "response", ".", "disconnect", "(", ")", ";", "}", "List", "<", "RequestInfo", "<", "?", ",", "?", ">", ">", "unsuccessfulRequestInfos", "=", "batchResponse", ".", "unsuccessfulRequestInfos", ";", "if", "(", "!", "unsuccessfulRequestInfos", ".", "isEmpty", "(", ")", ")", "{", "requestInfos", "=", "unsuccessfulRequestInfos", ";", "}", "else", "{", "break", ";", "}", "retriesRemaining", "--", ";", "}", "while", "(", "retryAllowed", ")", ";", "requestInfos", ".", "clear", "(", ")", ";", "}" ]
Executes all queued HTTP requests in a single call, parses the responses and invokes callbacks. <p> Calling {@link #execute()} executes and clears the queued requests. This means that the {@link BatchRequest} object can be reused to {@link #queue} and {@link #execute()} requests again. </p>
[ "Executes", "all", "queued", "HTTP", "requests", "in", "a", "single", "call", "parses", "the", "responses", "and", "invokes", "callbacks", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/batch/BatchRequest.java#L213-L260
25,578
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GooglePublicKeysManager.java
GooglePublicKeysManager.getPublicKeys
public final List<PublicKey> getPublicKeys() throws GeneralSecurityException, IOException { lock.lock(); try { if (publicKeys == null || clock.currentTimeMillis() + REFRESH_SKEW_MILLIS > expirationTimeMilliseconds) { refresh(); } return publicKeys; } finally { lock.unlock(); } }
java
public final List<PublicKey> getPublicKeys() throws GeneralSecurityException, IOException { lock.lock(); try { if (publicKeys == null || clock.currentTimeMillis() + REFRESH_SKEW_MILLIS > expirationTimeMilliseconds) { refresh(); } return publicKeys; } finally { lock.unlock(); } }
[ "public", "final", "List", "<", "PublicKey", ">", "getPublicKeys", "(", ")", "throws", "GeneralSecurityException", ",", "IOException", "{", "lock", ".", "lock", "(", ")", ";", "try", "{", "if", "(", "publicKeys", "==", "null", "||", "clock", ".", "currentTimeMillis", "(", ")", "+", "REFRESH_SKEW_MILLIS", ">", "expirationTimeMilliseconds", ")", "{", "refresh", "(", ")", ";", "}", "return", "publicKeys", ";", "}", "finally", "{", "lock", ".", "unlock", "(", ")", ";", "}", "}" ]
Returns an unmodifiable view of the public keys. <p> For efficiency, an in-memory cache of the public keys is used here. If this method is called for the first time, or the certificates have expired since last time it has been called (or are within 5 minutes of expiring), {@link #refresh()} will be called before returning the value. </p>
[ "Returns", "an", "unmodifiable", "view", "of", "the", "public", "keys", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GooglePublicKeysManager.java#L135-L146
25,579
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GooglePublicKeysManager.java
GooglePublicKeysManager.getCacheTimeInSec
long getCacheTimeInSec(HttpHeaders httpHeaders) { long cacheTimeInSec = 0; if (httpHeaders.getCacheControl() != null) { for (String arg : httpHeaders.getCacheControl().split(",")) { Matcher m = MAX_AGE_PATTERN.matcher(arg); if (m.matches()) { cacheTimeInSec = Long.parseLong(m.group(1)); break; } } } if (httpHeaders.getAge() != null) { cacheTimeInSec -= httpHeaders.getAge(); } return Math.max(0, cacheTimeInSec); }
java
long getCacheTimeInSec(HttpHeaders httpHeaders) { long cacheTimeInSec = 0; if (httpHeaders.getCacheControl() != null) { for (String arg : httpHeaders.getCacheControl().split(",")) { Matcher m = MAX_AGE_PATTERN.matcher(arg); if (m.matches()) { cacheTimeInSec = Long.parseLong(m.group(1)); break; } } } if (httpHeaders.getAge() != null) { cacheTimeInSec -= httpHeaders.getAge(); } return Math.max(0, cacheTimeInSec); }
[ "long", "getCacheTimeInSec", "(", "HttpHeaders", "httpHeaders", ")", "{", "long", "cacheTimeInSec", "=", "0", ";", "if", "(", "httpHeaders", ".", "getCacheControl", "(", ")", "!=", "null", ")", "{", "for", "(", "String", "arg", ":", "httpHeaders", ".", "getCacheControl", "(", ")", ".", "split", "(", "\",\"", ")", ")", "{", "Matcher", "m", "=", "MAX_AGE_PATTERN", ".", "matcher", "(", "arg", ")", ";", "if", "(", "m", ".", "matches", "(", ")", ")", "{", "cacheTimeInSec", "=", "Long", ".", "parseLong", "(", "m", ".", "group", "(", "1", ")", ")", ";", "break", ";", "}", "}", "}", "if", "(", "httpHeaders", ".", "getAge", "(", ")", "!=", "null", ")", "{", "cacheTimeInSec", "-=", "httpHeaders", ".", "getAge", "(", ")", ";", "}", "return", "Math", ".", "max", "(", "0", ",", "cacheTimeInSec", ")", ";", "}" ]
Gets the cache time in seconds. "max-age" in "Cache-Control" header and "Age" header are considered. @param httpHeaders the http header of the response @return the cache time in seconds or zero if the response should not be cached
[ "Gets", "the", "cache", "time", "in", "seconds", ".", "max", "-", "age", "in", "Cache", "-", "Control", "header", "and", "Age", "header", "are", "considered", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GooglePublicKeysManager.java#L208-L223
25,580
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/notifications/StoredChannel.java
StoredChannel.store
public StoredChannel store(DataStore<StoredChannel> dataStore) throws IOException { lock.lock(); try { dataStore.set(getId(), this); return this; } finally { lock.unlock(); } }
java
public StoredChannel store(DataStore<StoredChannel> dataStore) throws IOException { lock.lock(); try { dataStore.set(getId(), this); return this; } finally { lock.unlock(); } }
[ "public", "StoredChannel", "store", "(", "DataStore", "<", "StoredChannel", ">", "dataStore", ")", "throws", "IOException", "{", "lock", ".", "lock", "(", ")", ";", "try", "{", "dataStore", ".", "set", "(", "getId", "(", ")", ",", "this", ")", ";", "return", "this", ";", "}", "finally", "{", "lock", ".", "unlock", "(", ")", ";", "}", "}" ]
Stores this notification channel in the given notification channel data store. <p> It is important that this method be called before the watch HTTP request is made in case the notification is received before the watch HTTP response is received. </p> @param dataStore notification channel data store
[ "Stores", "this", "notification", "channel", "in", "the", "given", "notification", "channel", "data", "store", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/notifications/StoredChannel.java#L122-L130
25,581
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/services/AbstractGoogleClientRequest.java
AbstractGoogleClientRequest.initializeMediaUpload
protected final void initializeMediaUpload(AbstractInputStreamContent mediaContent) { HttpRequestFactory requestFactory = abstractGoogleClient.getRequestFactory(); this.uploader = new MediaHttpUploader( mediaContent, requestFactory.getTransport(), requestFactory.getInitializer()); this.uploader.setInitiationRequestMethod(requestMethod); if (httpContent != null) { this.uploader.setMetadata(httpContent); } }
java
protected final void initializeMediaUpload(AbstractInputStreamContent mediaContent) { HttpRequestFactory requestFactory = abstractGoogleClient.getRequestFactory(); this.uploader = new MediaHttpUploader( mediaContent, requestFactory.getTransport(), requestFactory.getInitializer()); this.uploader.setInitiationRequestMethod(requestMethod); if (httpContent != null) { this.uploader.setMetadata(httpContent); } }
[ "protected", "final", "void", "initializeMediaUpload", "(", "AbstractInputStreamContent", "mediaContent", ")", "{", "HttpRequestFactory", "requestFactory", "=", "abstractGoogleClient", ".", "getRequestFactory", "(", ")", ";", "this", ".", "uploader", "=", "new", "MediaHttpUploader", "(", "mediaContent", ",", "requestFactory", ".", "getTransport", "(", ")", ",", "requestFactory", ".", "getInitializer", "(", ")", ")", ";", "this", ".", "uploader", ".", "setInitiationRequestMethod", "(", "requestMethod", ")", ";", "if", "(", "httpContent", "!=", "null", ")", "{", "this", ".", "uploader", ".", "setMetadata", "(", "httpContent", ")", ";", "}", "}" ]
Initializes the media HTTP uploader based on the media content. @param mediaContent media content
[ "Initializes", "the", "media", "HTTP", "uploader", "based", "on", "the", "media", "content", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/services/AbstractGoogleClientRequest.java#L329-L337
25,582
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/services/AbstractGoogleClientRequest.java
AbstractGoogleClientRequest.initializeMediaDownload
protected final void initializeMediaDownload() { HttpRequestFactory requestFactory = abstractGoogleClient.getRequestFactory(); this.downloader = new MediaHttpDownloader(requestFactory.getTransport(), requestFactory.getInitializer()); }
java
protected final void initializeMediaDownload() { HttpRequestFactory requestFactory = abstractGoogleClient.getRequestFactory(); this.downloader = new MediaHttpDownloader(requestFactory.getTransport(), requestFactory.getInitializer()); }
[ "protected", "final", "void", "initializeMediaDownload", "(", ")", "{", "HttpRequestFactory", "requestFactory", "=", "abstractGoogleClient", ".", "getRequestFactory", "(", ")", ";", "this", ".", "downloader", "=", "new", "MediaHttpDownloader", "(", "requestFactory", ".", "getTransport", "(", ")", ",", "requestFactory", ".", "getInitializer", "(", ")", ")", ";", "}" ]
Initializes the media HTTP downloader.
[ "Initializes", "the", "media", "HTTP", "downloader", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/services/AbstractGoogleClientRequest.java#L345-L349
25,583
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/services/AbstractGoogleClientRequest.java
AbstractGoogleClientRequest.buildHttpRequest
private HttpRequest buildHttpRequest(boolean usingHead) throws IOException { Preconditions.checkArgument(uploader == null); Preconditions.checkArgument(!usingHead || requestMethod.equals(HttpMethods.GET)); String requestMethodToUse = usingHead ? HttpMethods.HEAD : requestMethod; final HttpRequest httpRequest = getAbstractGoogleClient() .getRequestFactory().buildRequest(requestMethodToUse, buildHttpRequestUrl(), httpContent); new MethodOverride().intercept(httpRequest); httpRequest.setParser(getAbstractGoogleClient().getObjectParser()); // custom methods may use POST with no content but require a Content-Length header if (httpContent == null && (requestMethod.equals(HttpMethods.POST) || requestMethod.equals(HttpMethods.PUT) || requestMethod.equals(HttpMethods.PATCH))) { httpRequest.setContent(new EmptyContent()); } httpRequest.getHeaders().putAll(requestHeaders); if (!disableGZipContent) { httpRequest.setEncoding(new GZipEncoding()); } final HttpResponseInterceptor responseInterceptor = httpRequest.getResponseInterceptor(); httpRequest.setResponseInterceptor(new HttpResponseInterceptor() { public void interceptResponse(HttpResponse response) throws IOException { if (responseInterceptor != null) { responseInterceptor.interceptResponse(response); } if (!response.isSuccessStatusCode() && httpRequest.getThrowExceptionOnExecuteError()) { throw newExceptionOnError(response); } } }); return httpRequest; }
java
private HttpRequest buildHttpRequest(boolean usingHead) throws IOException { Preconditions.checkArgument(uploader == null); Preconditions.checkArgument(!usingHead || requestMethod.equals(HttpMethods.GET)); String requestMethodToUse = usingHead ? HttpMethods.HEAD : requestMethod; final HttpRequest httpRequest = getAbstractGoogleClient() .getRequestFactory().buildRequest(requestMethodToUse, buildHttpRequestUrl(), httpContent); new MethodOverride().intercept(httpRequest); httpRequest.setParser(getAbstractGoogleClient().getObjectParser()); // custom methods may use POST with no content but require a Content-Length header if (httpContent == null && (requestMethod.equals(HttpMethods.POST) || requestMethod.equals(HttpMethods.PUT) || requestMethod.equals(HttpMethods.PATCH))) { httpRequest.setContent(new EmptyContent()); } httpRequest.getHeaders().putAll(requestHeaders); if (!disableGZipContent) { httpRequest.setEncoding(new GZipEncoding()); } final HttpResponseInterceptor responseInterceptor = httpRequest.getResponseInterceptor(); httpRequest.setResponseInterceptor(new HttpResponseInterceptor() { public void interceptResponse(HttpResponse response) throws IOException { if (responseInterceptor != null) { responseInterceptor.interceptResponse(response); } if (!response.isSuccessStatusCode() && httpRequest.getThrowExceptionOnExecuteError()) { throw newExceptionOnError(response); } } }); return httpRequest; }
[ "private", "HttpRequest", "buildHttpRequest", "(", "boolean", "usingHead", ")", "throws", "IOException", "{", "Preconditions", ".", "checkArgument", "(", "uploader", "==", "null", ")", ";", "Preconditions", ".", "checkArgument", "(", "!", "usingHead", "||", "requestMethod", ".", "equals", "(", "HttpMethods", ".", "GET", ")", ")", ";", "String", "requestMethodToUse", "=", "usingHead", "?", "HttpMethods", ".", "HEAD", ":", "requestMethod", ";", "final", "HttpRequest", "httpRequest", "=", "getAbstractGoogleClient", "(", ")", ".", "getRequestFactory", "(", ")", ".", "buildRequest", "(", "requestMethodToUse", ",", "buildHttpRequestUrl", "(", ")", ",", "httpContent", ")", ";", "new", "MethodOverride", "(", ")", ".", "intercept", "(", "httpRequest", ")", ";", "httpRequest", ".", "setParser", "(", "getAbstractGoogleClient", "(", ")", ".", "getObjectParser", "(", ")", ")", ";", "// custom methods may use POST with no content but require a Content-Length header", "if", "(", "httpContent", "==", "null", "&&", "(", "requestMethod", ".", "equals", "(", "HttpMethods", ".", "POST", ")", "||", "requestMethod", ".", "equals", "(", "HttpMethods", ".", "PUT", ")", "||", "requestMethod", ".", "equals", "(", "HttpMethods", ".", "PATCH", ")", ")", ")", "{", "httpRequest", ".", "setContent", "(", "new", "EmptyContent", "(", ")", ")", ";", "}", "httpRequest", ".", "getHeaders", "(", ")", ".", "putAll", "(", "requestHeaders", ")", ";", "if", "(", "!", "disableGZipContent", ")", "{", "httpRequest", ".", "setEncoding", "(", "new", "GZipEncoding", "(", ")", ")", ";", "}", "final", "HttpResponseInterceptor", "responseInterceptor", "=", "httpRequest", ".", "getResponseInterceptor", "(", ")", ";", "httpRequest", ".", "setResponseInterceptor", "(", "new", "HttpResponseInterceptor", "(", ")", "{", "public", "void", "interceptResponse", "(", "HttpResponse", "response", ")", "throws", "IOException", "{", "if", "(", "responseInterceptor", "!=", "null", ")", "{", "responseInterceptor", ".", "interceptResponse", "(", "response", ")", ";", "}", "if", "(", "!", "response", ".", "isSuccessStatusCode", "(", ")", "&&", "httpRequest", ".", "getThrowExceptionOnExecuteError", "(", ")", ")", "{", "throw", "newExceptionOnError", "(", "response", ")", ";", "}", "}", "}", ")", ";", "return", "httpRequest", ";", "}" ]
Create a request suitable for use against this service.
[ "Create", "a", "request", "suitable", "for", "use", "against", "this", "service", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/services/AbstractGoogleClientRequest.java#L392-L422
25,584
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/services/AbstractGoogleClientRequest.java
AbstractGoogleClientRequest.queue
public final <E> void queue( BatchRequest batchRequest, Class<E> errorClass, BatchCallback<T, E> callback) throws IOException { Preconditions.checkArgument(uploader == null, "Batching media requests is not supported"); batchRequest.queue(buildHttpRequest(), getResponseClass(), errorClass, callback); }
java
public final <E> void queue( BatchRequest batchRequest, Class<E> errorClass, BatchCallback<T, E> callback) throws IOException { Preconditions.checkArgument(uploader == null, "Batching media requests is not supported"); batchRequest.queue(buildHttpRequest(), getResponseClass(), errorClass, callback); }
[ "public", "final", "<", "E", ">", "void", "queue", "(", "BatchRequest", "batchRequest", ",", "Class", "<", "E", ">", "errorClass", ",", "BatchCallback", "<", "T", ",", "E", ">", "callback", ")", "throws", "IOException", "{", "Preconditions", ".", "checkArgument", "(", "uploader", "==", "null", ",", "\"Batching media requests is not supported\"", ")", ";", "batchRequest", ".", "queue", "(", "buildHttpRequest", "(", ")", ",", "getResponseClass", "(", ")", ",", "errorClass", ",", "callback", ")", ";", "}" ]
Queues the request into the specified batch request container using the specified error class. <p> Batched requests are then executed when {@link BatchRequest#execute()} is called. </p> @param batchRequest batch request container @param errorClass data class the unsuccessful response will be parsed into or {@code Void.class} to ignore the content @param callback batch callback
[ "Queues", "the", "request", "into", "the", "specified", "batch", "request", "container", "using", "the", "specified", "error", "class", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/services/AbstractGoogleClientRequest.java#L674-L679
25,585
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/services/AbstractGoogleClientRequest.java
AbstractGoogleClientRequest.set
@SuppressWarnings("unchecked") @Override public AbstractGoogleClientRequest<T> set(String fieldName, Object value) { return (AbstractGoogleClientRequest<T>) super.set(fieldName, value); }
java
@SuppressWarnings("unchecked") @Override public AbstractGoogleClientRequest<T> set(String fieldName, Object value) { return (AbstractGoogleClientRequest<T>) super.set(fieldName, value); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "Override", "public", "AbstractGoogleClientRequest", "<", "T", ">", "set", "(", "String", "fieldName", ",", "Object", "value", ")", "{", "return", "(", "AbstractGoogleClientRequest", "<", "T", ">", ")", "super", ".", "set", "(", "fieldName", ",", "value", ")", ";", "}" ]
for more details
[ "for", "more", "details" ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/services/AbstractGoogleClientRequest.java#L685-L689
25,586
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/json/GoogleJsonError.java
GoogleJsonError.parse
public static GoogleJsonError parse(JsonFactory jsonFactory, HttpResponse response) throws IOException { JsonObjectParser jsonObjectParser = new JsonObjectParser.Builder(jsonFactory).setWrapperKeys( Collections.singleton("error")).build(); return jsonObjectParser.parseAndClose( response.getContent(), response.getContentCharset(), GoogleJsonError.class); }
java
public static GoogleJsonError parse(JsonFactory jsonFactory, HttpResponse response) throws IOException { JsonObjectParser jsonObjectParser = new JsonObjectParser.Builder(jsonFactory).setWrapperKeys( Collections.singleton("error")).build(); return jsonObjectParser.parseAndClose( response.getContent(), response.getContentCharset(), GoogleJsonError.class); }
[ "public", "static", "GoogleJsonError", "parse", "(", "JsonFactory", "jsonFactory", ",", "HttpResponse", "response", ")", "throws", "IOException", "{", "JsonObjectParser", "jsonObjectParser", "=", "new", "JsonObjectParser", ".", "Builder", "(", "jsonFactory", ")", ".", "setWrapperKeys", "(", "Collections", ".", "singleton", "(", "\"error\"", ")", ")", ".", "build", "(", ")", ";", "return", "jsonObjectParser", ".", "parseAndClose", "(", "response", ".", "getContent", "(", ")", ",", "response", ".", "getContentCharset", "(", ")", ",", "GoogleJsonError", ".", "class", ")", ";", "}" ]
Parses the given error HTTP response using the given JSON factory. @param jsonFactory JSON factory @param response HTTP response @return new instance of the Google JSON error information @throws IllegalArgumentException if content type is not {@link Json#MEDIA_TYPE} or if expected {@code "data"} or {@code "error"} key is not found
[ "Parses", "the", "given", "error", "HTTP", "response", "using", "the", "given", "JSON", "factory", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/json/GoogleJsonError.java#L48-L54
25,587
googleapis/google-api-java-client
google-api-client/src/main/java/com/google/api/client/googleapis/services/CommonGoogleClientRequestInitializer.java
CommonGoogleClientRequestInitializer.initialize
public void initialize(AbstractGoogleClientRequest<?> request) throws IOException { if (key != null) { request.put("key", key); } if (userIp != null) { request.put("userIp", userIp); } }
java
public void initialize(AbstractGoogleClientRequest<?> request) throws IOException { if (key != null) { request.put("key", key); } if (userIp != null) { request.put("userIp", userIp); } }
[ "public", "void", "initialize", "(", "AbstractGoogleClientRequest", "<", "?", ">", "request", ")", "throws", "IOException", "{", "if", "(", "key", "!=", "null", ")", "{", "request", ".", "put", "(", "\"key\"", ",", "key", ")", ";", "}", "if", "(", "userIp", "!=", "null", ")", "{", "request", ".", "put", "(", "\"userIp\"", ",", "userIp", ")", ";", "}", "}" ]
Subclasses should call super implementation in order to set the key and userIp. @throws IOException I/O exception
[ "Subclasses", "should", "call", "super", "implementation", "in", "order", "to", "set", "the", "key", "and", "userIp", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/services/CommonGoogleClientRequestInitializer.java#L115-L122
25,588
googleapis/google-api-java-client
google-api-client-xml/src/main/java/com/google/api/client/googleapis/xml/atom/MultiKindFeedParser.java
MultiKindFeedParser.setEntryClasses
public void setEntryClasses(Class<?>... entryClasses) { int numEntries = entryClasses.length; HashMap<String, Class<?>> kindToEntryClassMap = this.kindToEntryClassMap; for (int i = 0; i < numEntries; i++) { Class<?> entryClass = entryClasses[i]; ClassInfo typeInfo = ClassInfo.of(entryClass); Field field = typeInfo.getField("@gd:kind"); if (field == null) { throw new IllegalArgumentException("missing @gd:kind field for " + entryClass.getName()); } Object entry = Types.newInstance(entryClass); String kind = (String) FieldInfo.getFieldValue(field, entry); if (kind == null) { throw new IllegalArgumentException( "missing value for @gd:kind field in " + entryClass.getName()); } kindToEntryClassMap.put(kind, entryClass); } }
java
public void setEntryClasses(Class<?>... entryClasses) { int numEntries = entryClasses.length; HashMap<String, Class<?>> kindToEntryClassMap = this.kindToEntryClassMap; for (int i = 0; i < numEntries; i++) { Class<?> entryClass = entryClasses[i]; ClassInfo typeInfo = ClassInfo.of(entryClass); Field field = typeInfo.getField("@gd:kind"); if (field == null) { throw new IllegalArgumentException("missing @gd:kind field for " + entryClass.getName()); } Object entry = Types.newInstance(entryClass); String kind = (String) FieldInfo.getFieldValue(field, entry); if (kind == null) { throw new IllegalArgumentException( "missing value for @gd:kind field in " + entryClass.getName()); } kindToEntryClassMap.put(kind, entryClass); } }
[ "public", "void", "setEntryClasses", "(", "Class", "<", "?", ">", "...", "entryClasses", ")", "{", "int", "numEntries", "=", "entryClasses", ".", "length", ";", "HashMap", "<", "String", ",", "Class", "<", "?", ">", ">", "kindToEntryClassMap", "=", "this", ".", "kindToEntryClassMap", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numEntries", ";", "i", "++", ")", "{", "Class", "<", "?", ">", "entryClass", "=", "entryClasses", "[", "i", "]", ";", "ClassInfo", "typeInfo", "=", "ClassInfo", ".", "of", "(", "entryClass", ")", ";", "Field", "field", "=", "typeInfo", ".", "getField", "(", "\"@gd:kind\"", ")", ";", "if", "(", "field", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"missing @gd:kind field for \"", "+", "entryClass", ".", "getName", "(", ")", ")", ";", "}", "Object", "entry", "=", "Types", ".", "newInstance", "(", "entryClass", ")", ";", "String", "kind", "=", "(", "String", ")", "FieldInfo", ".", "getFieldValue", "(", "field", ",", "entry", ")", ";", "if", "(", "kind", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"missing value for @gd:kind field in \"", "+", "entryClass", ".", "getName", "(", ")", ")", ";", "}", "kindToEntryClassMap", ".", "put", "(", "kind", ",", "entryClass", ")", ";", "}", "}" ]
Sets the entry classes to use when parsing.
[ "Sets", "the", "entry", "classes", "to", "use", "when", "parsing", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client-xml/src/main/java/com/google/api/client/googleapis/xml/atom/MultiKindFeedParser.java#L59-L77
25,589
googleapis/google-api-java-client
google-api-client-xml/src/main/java/com/google/api/client/googleapis/xml/atom/MultiKindFeedParser.java
MultiKindFeedParser.create
public static <T, E> MultiKindFeedParser<T> create(HttpResponse response, XmlNamespaceDictionary namespaceDictionary, Class<T> feedClass, Class<E>... entryClasses) throws IOException, XmlPullParserException { InputStream content = response.getContent(); try { Atom.checkContentType(response.getContentType()); XmlPullParser parser = Xml.createParser(); parser.setInput(content, null); MultiKindFeedParser<T> result = new MultiKindFeedParser<T>(namespaceDictionary, parser, content, feedClass); result.setEntryClasses(entryClasses); return result; } finally { content.close(); } }
java
public static <T, E> MultiKindFeedParser<T> create(HttpResponse response, XmlNamespaceDictionary namespaceDictionary, Class<T> feedClass, Class<E>... entryClasses) throws IOException, XmlPullParserException { InputStream content = response.getContent(); try { Atom.checkContentType(response.getContentType()); XmlPullParser parser = Xml.createParser(); parser.setInput(content, null); MultiKindFeedParser<T> result = new MultiKindFeedParser<T>(namespaceDictionary, parser, content, feedClass); result.setEntryClasses(entryClasses); return result; } finally { content.close(); } }
[ "public", "static", "<", "T", ",", "E", ">", "MultiKindFeedParser", "<", "T", ">", "create", "(", "HttpResponse", "response", ",", "XmlNamespaceDictionary", "namespaceDictionary", ",", "Class", "<", "T", ">", "feedClass", ",", "Class", "<", "E", ">", "...", "entryClasses", ")", "throws", "IOException", ",", "XmlPullParserException", "{", "InputStream", "content", "=", "response", ".", "getContent", "(", ")", ";", "try", "{", "Atom", ".", "checkContentType", "(", "response", ".", "getContentType", "(", ")", ")", ";", "XmlPullParser", "parser", "=", "Xml", ".", "createParser", "(", ")", ";", "parser", ".", "setInput", "(", "content", ",", "null", ")", ";", "MultiKindFeedParser", "<", "T", ">", "result", "=", "new", "MultiKindFeedParser", "<", "T", ">", "(", "namespaceDictionary", ",", "parser", ",", "content", ",", "feedClass", ")", ";", "result", ".", "setEntryClasses", "(", "entryClasses", ")", ";", "return", "result", ";", "}", "finally", "{", "content", ".", "close", "(", ")", ";", "}", "}" ]
Parses the given HTTP response using the given feed class and entry classes. @param <T> feed type @param <E> entry type @param response HTTP response @param namespaceDictionary XML namespace dictionary @param feedClass feed class @param entryClasses entry class @return Atom multi-kind feed pull parser @throws IOException I/O exception @throws XmlPullParserException XML pull parser exception
[ "Parses", "the", "given", "HTTP", "response", "using", "the", "given", "feed", "class", "and", "entry", "classes", "." ]
88decfd14fc40cae6eb6729a45c7d56a1132e450
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client-xml/src/main/java/com/google/api/client/googleapis/xml/atom/MultiKindFeedParser.java#L105-L120
25,590
devnied/EMV-NFC-Paycard-Enrollment
library/src/main/java/com/github/devnied/emvnfccard/parser/impl/GeldKarteParser.java
GeldKarteParser.getType
protected TransactionTypeEnum getType(byte logstate) { switch ( (logstate & 0x60) >> 5) { case 0: return TransactionTypeEnum.LOADED; case 1: return TransactionTypeEnum.UNLOADED; case 2: return TransactionTypeEnum.PURCHASE; case 3: return TransactionTypeEnum.REFUND; } return null; }
java
protected TransactionTypeEnum getType(byte logstate) { switch ( (logstate & 0x60) >> 5) { case 0: return TransactionTypeEnum.LOADED; case 1: return TransactionTypeEnum.UNLOADED; case 2: return TransactionTypeEnum.PURCHASE; case 3: return TransactionTypeEnum.REFUND; } return null; }
[ "protected", "TransactionTypeEnum", "getType", "(", "byte", "logstate", ")", "{", "switch", "(", "(", "logstate", "&", "0x60", ")", ">>", "5", ")", "{", "case", "0", ":", "return", "TransactionTypeEnum", ".", "LOADED", ";", "case", "1", ":", "return", "TransactionTypeEnum", ".", "UNLOADED", ";", "case", "2", ":", "return", "TransactionTypeEnum", ".", "PURCHASE", ";", "case", "3", ":", "return", "TransactionTypeEnum", ".", "REFUND", ";", "}", "return", "null", ";", "}" ]
Method used to get the transaction type @param logstate the log state @return the transaction type or null
[ "Method", "used", "to", "get", "the", "transaction", "type" ]
bfbd3960708689154a7a75c8a9a934197d738a5b
https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/impl/GeldKarteParser.java#L162-L170
25,591
devnied/EMV-NFC-Paycard-Enrollment
library/src/main/java/com/github/devnied/emvnfccard/parser/impl/GeldKarteParser.java
GeldKarteParser.extractEF_ID
protected void extractEF_ID(final Application pApplication) throws CommunicationException { // 00B201BC00 byte[] data = template.get().getProvider().transceive(new CommandApdu(CommandEnum.READ_RECORD, 0x01, 0xBC, 0).toBytes()); if (ResponseUtils.isSucceed(data)) { pApplication.setReadingStep(ApplicationStepEnum.READ); // Date SimpleDateFormat format = new SimpleDateFormat("MM/yy",Locale.getDefault()); // Track 2 EmvTrack2 track2 = new EmvTrack2(); track2.setCardNumber(BytesUtils.bytesToStringNoSpace(Arrays.copyOfRange(data, 4, 9))); try { track2.setExpireDate(format.parse(String.format("%02x/%02x", data[11], data[10]))); } catch (ParseException e) { LOGGER.error(e.getMessage(),e); } template.get().getCard().setTrack2(track2); } }
java
protected void extractEF_ID(final Application pApplication) throws CommunicationException { // 00B201BC00 byte[] data = template.get().getProvider().transceive(new CommandApdu(CommandEnum.READ_RECORD, 0x01, 0xBC, 0).toBytes()); if (ResponseUtils.isSucceed(data)) { pApplication.setReadingStep(ApplicationStepEnum.READ); // Date SimpleDateFormat format = new SimpleDateFormat("MM/yy",Locale.getDefault()); // Track 2 EmvTrack2 track2 = new EmvTrack2(); track2.setCardNumber(BytesUtils.bytesToStringNoSpace(Arrays.copyOfRange(data, 4, 9))); try { track2.setExpireDate(format.parse(String.format("%02x/%02x", data[11], data[10]))); } catch (ParseException e) { LOGGER.error(e.getMessage(),e); } template.get().getCard().setTrack2(track2); } }
[ "protected", "void", "extractEF_ID", "(", "final", "Application", "pApplication", ")", "throws", "CommunicationException", "{", "// 00B201BC00", "byte", "[", "]", "data", "=", "template", ".", "get", "(", ")", ".", "getProvider", "(", ")", ".", "transceive", "(", "new", "CommandApdu", "(", "CommandEnum", ".", "READ_RECORD", ",", "0x01", ",", "0xBC", ",", "0", ")", ".", "toBytes", "(", ")", ")", ";", "if", "(", "ResponseUtils", ".", "isSucceed", "(", "data", ")", ")", "{", "pApplication", ".", "setReadingStep", "(", "ApplicationStepEnum", ".", "READ", ")", ";", "// Date", "SimpleDateFormat", "format", "=", "new", "SimpleDateFormat", "(", "\"MM/yy\"", ",", "Locale", ".", "getDefault", "(", ")", ")", ";", "// Track 2", "EmvTrack2", "track2", "=", "new", "EmvTrack2", "(", ")", ";", "track2", ".", "setCardNumber", "(", "BytesUtils", ".", "bytesToStringNoSpace", "(", "Arrays", ".", "copyOfRange", "(", "data", ",", "4", ",", "9", ")", ")", ")", ";", "try", "{", "track2", ".", "setExpireDate", "(", "format", ".", "parse", "(", "String", ".", "format", "(", "\"%02x/%02x\"", ",", "data", "[", "11", "]", ",", "data", "[", "10", "]", ")", ")", ")", ";", "}", "catch", "(", "ParseException", "e", ")", "{", "LOGGER", ".", "error", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "template", ".", "get", "(", ")", ".", "getCard", "(", ")", ".", "setTrack2", "(", "track2", ")", ";", "}", "}" ]
Method used to extract Ef_iD record @param pApplication EMV application @throws CommunicationException communication error
[ "Method", "used", "to", "extract", "Ef_iD", "record" ]
bfbd3960708689154a7a75c8a9a934197d738a5b
https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/impl/GeldKarteParser.java#L195-L213
25,592
devnied/EMV-NFC-Paycard-Enrollment
library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/AbstractByteBean.java
AbstractByteBean.getAnnotationSet
private Collection<AnnotationData> getAnnotationSet(final Collection<TagAndLength> pTags) { Collection<AnnotationData> ret = null; if (pTags != null) { Map<ITag, AnnotationData> data = AnnotationUtils.getInstance().getMap().get(getClass().getName()); ret = new ArrayList<AnnotationData>(data.size()); for (TagAndLength tal : pTags) { AnnotationData ann = data.get(tal.getTag()); if (ann != null) { ann.setSize(tal.getLength() * BitUtils.BYTE_SIZE); } else { ann = new AnnotationData(); ann.setSkip(true); ann.setSize(tal.getLength() * BitUtils.BYTE_SIZE); } ret.add(ann); } } else { ret = AnnotationUtils.getInstance().getMapSet().get(getClass().getName()); } return ret; }
java
private Collection<AnnotationData> getAnnotationSet(final Collection<TagAndLength> pTags) { Collection<AnnotationData> ret = null; if (pTags != null) { Map<ITag, AnnotationData> data = AnnotationUtils.getInstance().getMap().get(getClass().getName()); ret = new ArrayList<AnnotationData>(data.size()); for (TagAndLength tal : pTags) { AnnotationData ann = data.get(tal.getTag()); if (ann != null) { ann.setSize(tal.getLength() * BitUtils.BYTE_SIZE); } else { ann = new AnnotationData(); ann.setSkip(true); ann.setSize(tal.getLength() * BitUtils.BYTE_SIZE); } ret.add(ann); } } else { ret = AnnotationUtils.getInstance().getMapSet().get(getClass().getName()); } return ret; }
[ "private", "Collection", "<", "AnnotationData", ">", "getAnnotationSet", "(", "final", "Collection", "<", "TagAndLength", ">", "pTags", ")", "{", "Collection", "<", "AnnotationData", ">", "ret", "=", "null", ";", "if", "(", "pTags", "!=", "null", ")", "{", "Map", "<", "ITag", ",", "AnnotationData", ">", "data", "=", "AnnotationUtils", ".", "getInstance", "(", ")", ".", "getMap", "(", ")", ".", "get", "(", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "ret", "=", "new", "ArrayList", "<", "AnnotationData", ">", "(", "data", ".", "size", "(", ")", ")", ";", "for", "(", "TagAndLength", "tal", ":", "pTags", ")", "{", "AnnotationData", "ann", "=", "data", ".", "get", "(", "tal", ".", "getTag", "(", ")", ")", ";", "if", "(", "ann", "!=", "null", ")", "{", "ann", ".", "setSize", "(", "tal", ".", "getLength", "(", ")", "*", "BitUtils", ".", "BYTE_SIZE", ")", ";", "}", "else", "{", "ann", "=", "new", "AnnotationData", "(", ")", ";", "ann", ".", "setSkip", "(", "true", ")", ";", "ann", ".", "setSize", "(", "tal", ".", "getLength", "(", ")", "*", "BitUtils", ".", "BYTE_SIZE", ")", ";", "}", "ret", ".", "add", "(", "ann", ")", ";", "}", "}", "else", "{", "ret", "=", "AnnotationUtils", ".", "getInstance", "(", ")", ".", "getMapSet", "(", ")", ".", "get", "(", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "}", "return", "ret", ";", "}" ]
Method to get the annotation set from the current class @return An annotation set which contain all annotation data
[ "Method", "to", "get", "the", "annotation", "set", "from", "the", "current", "class" ]
bfbd3960708689154a7a75c8a9a934197d738a5b
https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/AbstractByteBean.java#L58-L78
25,593
devnied/EMV-NFC-Paycard-Enrollment
library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/AbstractByteBean.java
AbstractByteBean.parse
@Override public void parse(final byte[] pData, final Collection<TagAndLength> pTags) { Collection<AnnotationData> set = getAnnotationSet(pTags); BitUtils bit = new BitUtils(pData); Iterator<AnnotationData> it = set.iterator(); while (it.hasNext()) { AnnotationData data = it.next(); if (data.isSkip()) { bit.addCurrentBitIndex(data.getSize()); } else { Object obj = DataFactory.getObject(data, bit); setField(data.getField(), this, obj); } } }
java
@Override public void parse(final byte[] pData, final Collection<TagAndLength> pTags) { Collection<AnnotationData> set = getAnnotationSet(pTags); BitUtils bit = new BitUtils(pData); Iterator<AnnotationData> it = set.iterator(); while (it.hasNext()) { AnnotationData data = it.next(); if (data.isSkip()) { bit.addCurrentBitIndex(data.getSize()); } else { Object obj = DataFactory.getObject(data, bit); setField(data.getField(), this, obj); } } }
[ "@", "Override", "public", "void", "parse", "(", "final", "byte", "[", "]", "pData", ",", "final", "Collection", "<", "TagAndLength", ">", "pTags", ")", "{", "Collection", "<", "AnnotationData", ">", "set", "=", "getAnnotationSet", "(", "pTags", ")", ";", "BitUtils", "bit", "=", "new", "BitUtils", "(", "pData", ")", ";", "Iterator", "<", "AnnotationData", ">", "it", "=", "set", ".", "iterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "AnnotationData", "data", "=", "it", ".", "next", "(", ")", ";", "if", "(", "data", ".", "isSkip", "(", ")", ")", "{", "bit", ".", "addCurrentBitIndex", "(", "data", ".", "getSize", "(", ")", ")", ";", "}", "else", "{", "Object", "obj", "=", "DataFactory", ".", "getObject", "(", "data", ",", "bit", ")", ";", "setField", "(", "data", ".", "getField", "(", ")", ",", "this", ",", "obj", ")", ";", "}", "}", "}" ]
Method to parse byte data @param pData byte to parse @param pTags
[ "Method", "to", "parse", "byte", "data" ]
bfbd3960708689154a7a75c8a9a934197d738a5b
https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/AbstractByteBean.java#L87-L101
25,594
devnied/EMV-NFC-Paycard-Enrollment
library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/AbstractByteBean.java
AbstractByteBean.setField
protected void setField(final Field field, final IFile pData, final Object pValue) { if (field != null) { try { field.set(pData, pValue); } catch (IllegalArgumentException e) { LOGGER.error("Parameters of fied.set are not valid", e); } catch (IllegalAccessException e) { LOGGER.error("Impossible to set the Field :" + field.getName(), e); } } }
java
protected void setField(final Field field, final IFile pData, final Object pValue) { if (field != null) { try { field.set(pData, pValue); } catch (IllegalArgumentException e) { LOGGER.error("Parameters of fied.set are not valid", e); } catch (IllegalAccessException e) { LOGGER.error("Impossible to set the Field :" + field.getName(), e); } } }
[ "protected", "void", "setField", "(", "final", "Field", "field", ",", "final", "IFile", "pData", ",", "final", "Object", "pValue", ")", "{", "if", "(", "field", "!=", "null", ")", "{", "try", "{", "field", ".", "set", "(", "pData", ",", "pValue", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "LOGGER", ".", "error", "(", "\"Parameters of fied.set are not valid\"", ",", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "LOGGER", ".", "error", "(", "\"Impossible to set the Field :\"", "+", "field", ".", "getName", "(", ")", ",", "e", ")", ";", "}", "}", "}" ]
Method used to set the value of a field @param field the field to set @param pData Object containing the field @param pValue the value of the field
[ "Method", "used", "to", "set", "the", "value", "of", "a", "field" ]
bfbd3960708689154a7a75c8a9a934197d738a5b
https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/AbstractByteBean.java#L113-L123
25,595
devnied/EMV-NFC-Paycard-Enrollment
library/src/main/java/com/github/devnied/emvnfccard/utils/AtrUtils.java
AtrUtils.getDescription
public static final Collection<String> getDescription(final String pAtr) { Collection<String> ret = null; if (StringUtils.isNotBlank(pAtr)) { String val = StringUtils.deleteWhitespace(pAtr).toUpperCase(); for (String key : MAP.keySet()) { if (val.matches("^" + key + "$")) { ret = (Collection<String>) MAP.get(key); break; } } } return ret; }
java
public static final Collection<String> getDescription(final String pAtr) { Collection<String> ret = null; if (StringUtils.isNotBlank(pAtr)) { String val = StringUtils.deleteWhitespace(pAtr).toUpperCase(); for (String key : MAP.keySet()) { if (val.matches("^" + key + "$")) { ret = (Collection<String>) MAP.get(key); break; } } } return ret; }
[ "public", "static", "final", "Collection", "<", "String", ">", "getDescription", "(", "final", "String", "pAtr", ")", "{", "Collection", "<", "String", ">", "ret", "=", "null", ";", "if", "(", "StringUtils", ".", "isNotBlank", "(", "pAtr", ")", ")", "{", "String", "val", "=", "StringUtils", ".", "deleteWhitespace", "(", "pAtr", ")", ".", "toUpperCase", "(", ")", ";", "for", "(", "String", "key", ":", "MAP", ".", "keySet", "(", ")", ")", "{", "if", "(", "val", ".", "matches", "(", "\"^\"", "+", "key", "+", "\"$\"", ")", ")", "{", "ret", "=", "(", "Collection", "<", "String", ">", ")", "MAP", ".", "get", "(", "key", ")", ";", "break", ";", "}", "}", "}", "return", "ret", ";", "}" ]
Method used to find description from ATR @param pAtr Card ATR @return list of description
[ "Method", "used", "to", "find", "description", "from", "ATR" ]
bfbd3960708689154a7a75c8a9a934197d738a5b
https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/utils/AtrUtils.java#L94-L106
25,596
devnied/EMV-NFC-Paycard-Enrollment
library/src/main/java/com/github/devnied/emvnfccard/utils/TrackUtils.java
TrackUtils.extractTrack2EquivalentData
public static EmvTrack2 extractTrack2EquivalentData(final byte[] pRawTrack2) { EmvTrack2 ret = null; if (pRawTrack2 != null) { EmvTrack2 track2 = new EmvTrack2(); track2.setRaw(pRawTrack2); String data = BytesUtils.bytesToStringNoSpace(pRawTrack2); Matcher m = TRACK2_EQUIVALENT_PATTERN.matcher(data); // Check pattern if (m.find()) { // read card number track2.setCardNumber(m.group(1)); // Read expire date SimpleDateFormat sdf = new SimpleDateFormat("yyMM", Locale.getDefault()); try { track2.setExpireDate(DateUtils.truncate(sdf.parse(m.group(2)), Calendar.MONTH)); } catch (ParseException e) { LOGGER.error("Unparsable expire card date : {}", e.getMessage()); return ret; } // Read service track2.setService(new Service(m.group(3))); ret = track2; } } return ret; }
java
public static EmvTrack2 extractTrack2EquivalentData(final byte[] pRawTrack2) { EmvTrack2 ret = null; if (pRawTrack2 != null) { EmvTrack2 track2 = new EmvTrack2(); track2.setRaw(pRawTrack2); String data = BytesUtils.bytesToStringNoSpace(pRawTrack2); Matcher m = TRACK2_EQUIVALENT_PATTERN.matcher(data); // Check pattern if (m.find()) { // read card number track2.setCardNumber(m.group(1)); // Read expire date SimpleDateFormat sdf = new SimpleDateFormat("yyMM", Locale.getDefault()); try { track2.setExpireDate(DateUtils.truncate(sdf.parse(m.group(2)), Calendar.MONTH)); } catch (ParseException e) { LOGGER.error("Unparsable expire card date : {}", e.getMessage()); return ret; } // Read service track2.setService(new Service(m.group(3))); ret = track2; } } return ret; }
[ "public", "static", "EmvTrack2", "extractTrack2EquivalentData", "(", "final", "byte", "[", "]", "pRawTrack2", ")", "{", "EmvTrack2", "ret", "=", "null", ";", "if", "(", "pRawTrack2", "!=", "null", ")", "{", "EmvTrack2", "track2", "=", "new", "EmvTrack2", "(", ")", ";", "track2", ".", "setRaw", "(", "pRawTrack2", ")", ";", "String", "data", "=", "BytesUtils", ".", "bytesToStringNoSpace", "(", "pRawTrack2", ")", ";", "Matcher", "m", "=", "TRACK2_EQUIVALENT_PATTERN", ".", "matcher", "(", "data", ")", ";", "// Check pattern", "if", "(", "m", ".", "find", "(", ")", ")", "{", "// read card number", "track2", ".", "setCardNumber", "(", "m", ".", "group", "(", "1", ")", ")", ";", "// Read expire date", "SimpleDateFormat", "sdf", "=", "new", "SimpleDateFormat", "(", "\"yyMM\"", ",", "Locale", ".", "getDefault", "(", ")", ")", ";", "try", "{", "track2", ".", "setExpireDate", "(", "DateUtils", ".", "truncate", "(", "sdf", ".", "parse", "(", "m", ".", "group", "(", "2", ")", ")", ",", "Calendar", ".", "MONTH", ")", ")", ";", "}", "catch", "(", "ParseException", "e", ")", "{", "LOGGER", ".", "error", "(", "\"Unparsable expire card date : {}\"", ",", "e", ".", "getMessage", "(", ")", ")", ";", "return", "ret", ";", "}", "// Read service", "track2", ".", "setService", "(", "new", "Service", "(", "m", ".", "group", "(", "3", ")", ")", ")", ";", "ret", "=", "track2", ";", "}", "}", "return", "ret", ";", "}" ]
Extract track 2 Equivalent data @param pRawTrack2 Raw track 2 data @return EmvTrack2 object data or null
[ "Extract", "track", "2", "Equivalent", "data" ]
bfbd3960708689154a7a75c8a9a934197d738a5b
https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/utils/TrackUtils.java#L70-L96
25,597
devnied/EMV-NFC-Paycard-Enrollment
library/src/main/java/com/github/devnied/emvnfccard/utils/TrackUtils.java
TrackUtils.extractTrack1Data
public static EmvTrack1 extractTrack1Data(final byte[] pRawTrack1) { EmvTrack1 ret = null; if (pRawTrack1 != null) { EmvTrack1 track1 = new EmvTrack1(); track1.setRaw(pRawTrack1); Matcher m = TRACK1_PATTERN.matcher(new String(pRawTrack1)); // Check pattern if (m.find()) { // Set format code track1.setFormatCode(m.group(1)); // Set card number track1.setCardNumber(m.group(2)); // Extract holder name String[] name = StringUtils.split(m.group(4).trim(), CARD_HOLDER_NAME_SEPARATOR); if (name != null && name.length == 2) { track1.setHolderLastname(StringUtils.trimToNull(name[0])); track1.setHolderFirstname(StringUtils.trimToNull(name[1])); } // Read expire date SimpleDateFormat sdf = new SimpleDateFormat("yyMM", Locale.getDefault()); try { track1.setExpireDate(DateUtils.truncate(sdf.parse(m.group(5)), Calendar.MONTH)); } catch (ParseException e) { LOGGER.error("Unparsable expire card date : {}", e.getMessage()); return ret; } // Read service track1.setService(new Service(m.group(6))); ret = track1; } } return ret; }
java
public static EmvTrack1 extractTrack1Data(final byte[] pRawTrack1) { EmvTrack1 ret = null; if (pRawTrack1 != null) { EmvTrack1 track1 = new EmvTrack1(); track1.setRaw(pRawTrack1); Matcher m = TRACK1_PATTERN.matcher(new String(pRawTrack1)); // Check pattern if (m.find()) { // Set format code track1.setFormatCode(m.group(1)); // Set card number track1.setCardNumber(m.group(2)); // Extract holder name String[] name = StringUtils.split(m.group(4).trim(), CARD_HOLDER_NAME_SEPARATOR); if (name != null && name.length == 2) { track1.setHolderLastname(StringUtils.trimToNull(name[0])); track1.setHolderFirstname(StringUtils.trimToNull(name[1])); } // Read expire date SimpleDateFormat sdf = new SimpleDateFormat("yyMM", Locale.getDefault()); try { track1.setExpireDate(DateUtils.truncate(sdf.parse(m.group(5)), Calendar.MONTH)); } catch (ParseException e) { LOGGER.error("Unparsable expire card date : {}", e.getMessage()); return ret; } // Read service track1.setService(new Service(m.group(6))); ret = track1; } } return ret; }
[ "public", "static", "EmvTrack1", "extractTrack1Data", "(", "final", "byte", "[", "]", "pRawTrack1", ")", "{", "EmvTrack1", "ret", "=", "null", ";", "if", "(", "pRawTrack1", "!=", "null", ")", "{", "EmvTrack1", "track1", "=", "new", "EmvTrack1", "(", ")", ";", "track1", ".", "setRaw", "(", "pRawTrack1", ")", ";", "Matcher", "m", "=", "TRACK1_PATTERN", ".", "matcher", "(", "new", "String", "(", "pRawTrack1", ")", ")", ";", "// Check pattern", "if", "(", "m", ".", "find", "(", ")", ")", "{", "// Set format code", "track1", ".", "setFormatCode", "(", "m", ".", "group", "(", "1", ")", ")", ";", "// Set card number", "track1", ".", "setCardNumber", "(", "m", ".", "group", "(", "2", ")", ")", ";", "// Extract holder name", "String", "[", "]", "name", "=", "StringUtils", ".", "split", "(", "m", ".", "group", "(", "4", ")", ".", "trim", "(", ")", ",", "CARD_HOLDER_NAME_SEPARATOR", ")", ";", "if", "(", "name", "!=", "null", "&&", "name", ".", "length", "==", "2", ")", "{", "track1", ".", "setHolderLastname", "(", "StringUtils", ".", "trimToNull", "(", "name", "[", "0", "]", ")", ")", ";", "track1", ".", "setHolderFirstname", "(", "StringUtils", ".", "trimToNull", "(", "name", "[", "1", "]", ")", ")", ";", "}", "// Read expire date", "SimpleDateFormat", "sdf", "=", "new", "SimpleDateFormat", "(", "\"yyMM\"", ",", "Locale", ".", "getDefault", "(", ")", ")", ";", "try", "{", "track1", ".", "setExpireDate", "(", "DateUtils", ".", "truncate", "(", "sdf", ".", "parse", "(", "m", ".", "group", "(", "5", ")", ")", ",", "Calendar", ".", "MONTH", ")", ")", ";", "}", "catch", "(", "ParseException", "e", ")", "{", "LOGGER", ".", "error", "(", "\"Unparsable expire card date : {}\"", ",", "e", ".", "getMessage", "(", ")", ")", ";", "return", "ret", ";", "}", "// Read service", "track1", ".", "setService", "(", "new", "Service", "(", "m", ".", "group", "(", "6", ")", ")", ")", ";", "ret", "=", "track1", ";", "}", "}", "return", "ret", ";", "}" ]
Extract track 1 data @param pRawTrack1 track1 raw data @return EmvTrack1 object
[ "Extract", "track", "1", "data" ]
bfbd3960708689154a7a75c8a9a934197d738a5b
https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/utils/TrackUtils.java#L105-L138
25,598
devnied/EMV-NFC-Paycard-Enrollment
library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/annotation/AnnotationData.java
AnnotationData.initFromAnnotation
public void initFromAnnotation(final Data pData) { dateStandard = pData.dateStandard(); format = pData.format(); index = pData.index(); readHexa = pData.readHexa(); size = pData.size(); if (pData.tag() != null) { tag = EmvTags.find(BytesUtils.fromString(pData.tag())); } }
java
public void initFromAnnotation(final Data pData) { dateStandard = pData.dateStandard(); format = pData.format(); index = pData.index(); readHexa = pData.readHexa(); size = pData.size(); if (pData.tag() != null) { tag = EmvTags.find(BytesUtils.fromString(pData.tag())); } }
[ "public", "void", "initFromAnnotation", "(", "final", "Data", "pData", ")", "{", "dateStandard", "=", "pData", ".", "dateStandard", "(", ")", ";", "format", "=", "pData", ".", "format", "(", ")", ";", "index", "=", "pData", ".", "index", "(", ")", ";", "readHexa", "=", "pData", ".", "readHexa", "(", ")", ";", "size", "=", "pData", ".", "size", "(", ")", ";", "if", "(", "pData", ".", "tag", "(", ")", "!=", "null", ")", "{", "tag", "=", "EmvTags", ".", "find", "(", "BytesUtils", ".", "fromString", "(", "pData", ".", "tag", "(", ")", ")", ")", ";", "}", "}" ]
Initialization from annotation @param pData annotation data
[ "Initialization", "from", "annotation" ]
bfbd3960708689154a7a75c8a9a934197d738a5b
https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/annotation/AnnotationData.java#L184-L193
25,599
devnied/EMV-NFC-Paycard-Enrollment
library/src/main/java/com/github/devnied/emvnfccard/utils/CPLCUtils.java
CPLCUtils.parse
public static CPLC parse(byte[] raw) { CPLC ret = null; if (raw != null) { byte[] cplc = null; // try to interpret as raw data (not TLV) if (raw.length == CPLC.SIZE + 2) { cplc = raw; } // or maybe it's prepended with CPLC tag: else if (raw.length == CPLC.SIZE + 5) { cplc = TlvUtil.getValue(raw, CPLC_TAG); } else { LOGGER.error("CPLC data not valid"); return null; } ret = new CPLC(); ret.parse(cplc,null); } return ret; }
java
public static CPLC parse(byte[] raw) { CPLC ret = null; if (raw != null) { byte[] cplc = null; // try to interpret as raw data (not TLV) if (raw.length == CPLC.SIZE + 2) { cplc = raw; } // or maybe it's prepended with CPLC tag: else if (raw.length == CPLC.SIZE + 5) { cplc = TlvUtil.getValue(raw, CPLC_TAG); } else { LOGGER.error("CPLC data not valid"); return null; } ret = new CPLC(); ret.parse(cplc,null); } return ret; }
[ "public", "static", "CPLC", "parse", "(", "byte", "[", "]", "raw", ")", "{", "CPLC", "ret", "=", "null", ";", "if", "(", "raw", "!=", "null", ")", "{", "byte", "[", "]", "cplc", "=", "null", ";", "// try to interpret as raw data (not TLV)", "if", "(", "raw", ".", "length", "==", "CPLC", ".", "SIZE", "+", "2", ")", "{", "cplc", "=", "raw", ";", "}", "// or maybe it's prepended with CPLC tag:", "else", "if", "(", "raw", ".", "length", "==", "CPLC", ".", "SIZE", "+", "5", ")", "{", "cplc", "=", "TlvUtil", ".", "getValue", "(", "raw", ",", "CPLC_TAG", ")", ";", "}", "else", "{", "LOGGER", ".", "error", "(", "\"CPLC data not valid\"", ")", ";", "return", "null", ";", "}", "ret", "=", "new", "CPLC", "(", ")", ";", "ret", ".", "parse", "(", "cplc", ",", "null", ")", ";", "}", "return", "ret", ";", "}" ]
Method used to parse and extract CPLC data @param raw raw data @return CPLC data
[ "Method", "used", "to", "parse", "and", "extract", "CPLC", "data" ]
bfbd3960708689154a7a75c8a9a934197d738a5b
https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/utils/CPLCUtils.java#L47-L66