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
partition
stringclasses
1 value
datastax/java-driver
examples/src/main/java/com/datastax/oss/driver/examples/basic/CreateAndPopulateKeyspace.java
CreateAndPopulateKeyspace.querySchema
public void querySchema() { ResultSet results = session.execute( "SELECT * FROM simplex.playlists " + "WHERE id = 2cc9ccb7-6221-4ccb-8387-f22b6a1b354d;"); System.out.printf("%-30s\t%-20s\t%-20s%n", "title", "album", "artist"); System.out.println( "-------------------------------+-----------------------+--------------------"); for (Row row : results) { System.out.printf( "%-30s\t%-20s\t%-20s%n", row.getString("title"), row.getString("album"), row.getString("artist")); } }
java
public void querySchema() { ResultSet results = session.execute( "SELECT * FROM simplex.playlists " + "WHERE id = 2cc9ccb7-6221-4ccb-8387-f22b6a1b354d;"); System.out.printf("%-30s\t%-20s\t%-20s%n", "title", "album", "artist"); System.out.println( "-------------------------------+-----------------------+--------------------"); for (Row row : results) { System.out.printf( "%-30s\t%-20s\t%-20s%n", row.getString("title"), row.getString("album"), row.getString("artist")); } }
[ "public", "void", "querySchema", "(", ")", "{", "ResultSet", "results", "=", "session", ".", "execute", "(", "\"SELECT * FROM simplex.playlists \"", "+", "\"WHERE id = 2cc9ccb7-6221-4ccb-8387-f22b6a1b354d;\"", ")", ";", "System", ".", "out", ".", "printf", "(", "\"%-30s\\t%-20s\\t%-20s%n\"", ",", "\"title\"", ",", "\"album\"", ",", "\"artist\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"-------------------------------+-----------------------+--------------------\"", ")", ";", "for", "(", "Row", "row", ":", "results", ")", "{", "System", ".", "out", ".", "printf", "(", "\"%-30s\\t%-20s\\t%-20s%n\"", ",", "row", ".", "getString", "(", "\"title\"", ")", ",", "row", ".", "getString", "(", "\"album\"", ")", ",", "row", ".", "getString", "(", "\"artist\"", ")", ")", ";", "}", "}" ]
Queries and displays data.
[ "Queries", "and", "displays", "data", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/examples/src/main/java/com/datastax/oss/driver/examples/basic/CreateAndPopulateKeyspace.java#L127-L144
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/util/Reflection.java
Reflection.loadClass
public static Class<?> loadClass(ClassLoader classLoader, String className) { try { // If input classLoader is null, use current thread's ClassLoader, if that is null, use // default (calling class') ClassLoader. ClassLoader cl = classLoader != null ? classLoader : Thread.currentThread().getContextClassLoader(); if (cl != null) { return Class.forName(className, true, cl); } else { return Class.forName(className); } } catch (ClassNotFoundException e) { return null; } }
java
public static Class<?> loadClass(ClassLoader classLoader, String className) { try { // If input classLoader is null, use current thread's ClassLoader, if that is null, use // default (calling class') ClassLoader. ClassLoader cl = classLoader != null ? classLoader : Thread.currentThread().getContextClassLoader(); if (cl != null) { return Class.forName(className, true, cl); } else { return Class.forName(className); } } catch (ClassNotFoundException e) { return null; } }
[ "public", "static", "Class", "<", "?", ">", "loadClass", "(", "ClassLoader", "classLoader", ",", "String", "className", ")", "{", "try", "{", "// If input classLoader is null, use current thread's ClassLoader, if that is null, use", "// default (calling class') ClassLoader.", "ClassLoader", "cl", "=", "classLoader", "!=", "null", "?", "classLoader", ":", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ";", "if", "(", "cl", "!=", "null", ")", "{", "return", "Class", ".", "forName", "(", "className", ",", "true", ",", "cl", ")", ";", "}", "else", "{", "return", "Class", ".", "forName", "(", "className", ")", ";", "}", "}", "catch", "(", "ClassNotFoundException", "e", ")", "{", "return", "null", ";", "}", "}" ]
Loads a class by name. <p>This methods tries first with the current thread's context class loader (the intent is that if the driver is in a low-level loader of an application server -- e.g. bootstrap or system -- it can still find classes in the application's class loader). If it is null, it defaults to the class loader that loaded the class calling this method. @return null if the class does not exist.
[ "Loads", "a", "class", "by", "name", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/Reflection.java#L49-L63
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/util/Reflection.java
Reflection.buildFromConfig
public static <ComponentT> Optional<ComponentT> buildFromConfig( InternalDriverContext context, DriverOption classNameOption, Class<ComponentT> expectedSuperType, String... defaultPackages) { return buildFromConfig(context, null, classNameOption, expectedSuperType, defaultPackages); }
java
public static <ComponentT> Optional<ComponentT> buildFromConfig( InternalDriverContext context, DriverOption classNameOption, Class<ComponentT> expectedSuperType, String... defaultPackages) { return buildFromConfig(context, null, classNameOption, expectedSuperType, defaultPackages); }
[ "public", "static", "<", "ComponentT", ">", "Optional", "<", "ComponentT", ">", "buildFromConfig", "(", "InternalDriverContext", "context", ",", "DriverOption", "classNameOption", ",", "Class", "<", "ComponentT", ">", "expectedSuperType", ",", "String", "...", "defaultPackages", ")", "{", "return", "buildFromConfig", "(", "context", ",", "null", ",", "classNameOption", ",", "expectedSuperType", ",", "defaultPackages", ")", ";", "}" ]
Tries to create an instance of a class, given an option defined in the driver configuration. <p>For example: <pre> my-policy.class = my.package.MyPolicyImpl </pre> The class will be instantiated via reflection, it must have a constructor that takes a {@link DriverContext} argument. @param context the driver context. @param classNameOption the option that indicates the class. It will be looked up in the default profile of the configuration stored in the context. @param expectedSuperType a super-type that the class is expected to implement/extend. @param defaultPackages the default packages to prepend to the class name if it's not qualified. They will be tried in order, the first one that matches an existing class will be used. @return the new instance, or empty if {@code classNameOption} is not defined in the configuration.
[ "Tries", "to", "create", "an", "instance", "of", "a", "class", "given", "an", "option", "defined", "in", "the", "driver", "configuration", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/Reflection.java#L86-L92
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/util/Reflection.java
Reflection.buildFromConfigProfiles
public static <ComponentT> Map<String, ComponentT> buildFromConfigProfiles( InternalDriverContext context, DriverOption rootOption, Class<ComponentT> expectedSuperType, String... defaultPackages) { // Find out how many distinct configurations we have ListMultimap<Object, String> profilesByConfig = MultimapBuilder.hashKeys().arrayListValues().build(); for (DriverExecutionProfile profile : context.getConfig().getProfiles().values()) { profilesByConfig.put(profile.getComparisonKey(rootOption), profile.getName()); } // Instantiate each distinct configuration, and associate it with the corresponding profiles ImmutableMap.Builder<String, ComponentT> result = ImmutableMap.builder(); for (Collection<String> profiles : profilesByConfig.asMap().values()) { // Since all profiles use the same config, we can use any of them String profileName = profiles.iterator().next(); ComponentT policy = buildFromConfig( context, profileName, classOption(rootOption), expectedSuperType, defaultPackages) .orElseThrow( () -> new IllegalArgumentException( String.format( "Missing configuration for %s in profile %s", rootOption.getPath(), profileName))); for (String profile : profiles) { result.put(profile, policy); } } return result.build(); }
java
public static <ComponentT> Map<String, ComponentT> buildFromConfigProfiles( InternalDriverContext context, DriverOption rootOption, Class<ComponentT> expectedSuperType, String... defaultPackages) { // Find out how many distinct configurations we have ListMultimap<Object, String> profilesByConfig = MultimapBuilder.hashKeys().arrayListValues().build(); for (DriverExecutionProfile profile : context.getConfig().getProfiles().values()) { profilesByConfig.put(profile.getComparisonKey(rootOption), profile.getName()); } // Instantiate each distinct configuration, and associate it with the corresponding profiles ImmutableMap.Builder<String, ComponentT> result = ImmutableMap.builder(); for (Collection<String> profiles : profilesByConfig.asMap().values()) { // Since all profiles use the same config, we can use any of them String profileName = profiles.iterator().next(); ComponentT policy = buildFromConfig( context, profileName, classOption(rootOption), expectedSuperType, defaultPackages) .orElseThrow( () -> new IllegalArgumentException( String.format( "Missing configuration for %s in profile %s", rootOption.getPath(), profileName))); for (String profile : profiles) { result.put(profile, policy); } } return result.build(); }
[ "public", "static", "<", "ComponentT", ">", "Map", "<", "String", ",", "ComponentT", ">", "buildFromConfigProfiles", "(", "InternalDriverContext", "context", ",", "DriverOption", "rootOption", ",", "Class", "<", "ComponentT", ">", "expectedSuperType", ",", "String", "...", "defaultPackages", ")", "{", "// Find out how many distinct configurations we have", "ListMultimap", "<", "Object", ",", "String", ">", "profilesByConfig", "=", "MultimapBuilder", ".", "hashKeys", "(", ")", ".", "arrayListValues", "(", ")", ".", "build", "(", ")", ";", "for", "(", "DriverExecutionProfile", "profile", ":", "context", ".", "getConfig", "(", ")", ".", "getProfiles", "(", ")", ".", "values", "(", ")", ")", "{", "profilesByConfig", ".", "put", "(", "profile", ".", "getComparisonKey", "(", "rootOption", ")", ",", "profile", ".", "getName", "(", ")", ")", ";", "}", "// Instantiate each distinct configuration, and associate it with the corresponding profiles", "ImmutableMap", ".", "Builder", "<", "String", ",", "ComponentT", ">", "result", "=", "ImmutableMap", ".", "builder", "(", ")", ";", "for", "(", "Collection", "<", "String", ">", "profiles", ":", "profilesByConfig", ".", "asMap", "(", ")", ".", "values", "(", ")", ")", "{", "// Since all profiles use the same config, we can use any of them", "String", "profileName", "=", "profiles", ".", "iterator", "(", ")", ".", "next", "(", ")", ";", "ComponentT", "policy", "=", "buildFromConfig", "(", "context", ",", "profileName", ",", "classOption", "(", "rootOption", ")", ",", "expectedSuperType", ",", "defaultPackages", ")", ".", "orElseThrow", "(", "(", ")", "->", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Missing configuration for %s in profile %s\"", ",", "rootOption", ".", "getPath", "(", ")", ",", "profileName", ")", ")", ")", ";", "for", "(", "String", "profile", ":", "profiles", ")", "{", "result", ".", "put", "(", "profile", ",", "policy", ")", ";", "}", "}", "return", "result", ".", "build", "(", ")", ";", "}" ]
Tries to create multiple instances of a class, given options defined in the driver configuration and possibly overridden in profiles. <p>For example: <pre> my-policy.class = package1.PolicyImpl1 profiles { my-profile { my-policy.class = package2.PolicyImpl2 } } </pre> The class will be instantiated via reflection, it must have a constructor that takes two arguments: the {@link DriverContext}, and a string representing the profile name. <p>This method assumes the policy is mandatory, the class option must be present at least for the default profile. @param context the driver context. @param rootOption the root option for the policy (my-policy in the example above). The class name is assumed to be in a 'class' child option. @param expectedSuperType a super-type that the class is expected to implement/extend. @param defaultPackages the default packages to prepend to the class name if it's not qualified. They will be tried in order, the first one that matches an existing class will be used. @return the policy instances by profile name. If multiple profiles share the same configuration, a single instance will be shared by all their entries.
[ "Tries", "to", "create", "multiple", "instances", "of", "a", "class", "given", "options", "defined", "in", "the", "driver", "configuration", "and", "possibly", "overridden", "in", "profiles", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/Reflection.java#L122-L154
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/UserDefinedTypeParser.java
UserDefinedTypeParser.parse
public Map<CqlIdentifier, UserDefinedType> parse( Collection<AdminRow> typeRows, CqlIdentifier keyspaceId) { if (typeRows.isEmpty()) { return Collections.emptyMap(); } else { Map<CqlIdentifier, UserDefinedType> types = new LinkedHashMap<>(); for (AdminRow row : topologicalSort(typeRows, keyspaceId)) { UserDefinedType type = parseType(row, keyspaceId, types); types.put(type.getName(), type); } return ImmutableMap.copyOf(types); } }
java
public Map<CqlIdentifier, UserDefinedType> parse( Collection<AdminRow> typeRows, CqlIdentifier keyspaceId) { if (typeRows.isEmpty()) { return Collections.emptyMap(); } else { Map<CqlIdentifier, UserDefinedType> types = new LinkedHashMap<>(); for (AdminRow row : topologicalSort(typeRows, keyspaceId)) { UserDefinedType type = parseType(row, keyspaceId, types); types.put(type.getName(), type); } return ImmutableMap.copyOf(types); } }
[ "public", "Map", "<", "CqlIdentifier", ",", "UserDefinedType", ">", "parse", "(", "Collection", "<", "AdminRow", ">", "typeRows", ",", "CqlIdentifier", "keyspaceId", ")", "{", "if", "(", "typeRows", ".", "isEmpty", "(", ")", ")", "{", "return", "Collections", ".", "emptyMap", "(", ")", ";", "}", "else", "{", "Map", "<", "CqlIdentifier", ",", "UserDefinedType", ">", "types", "=", "new", "LinkedHashMap", "<>", "(", ")", ";", "for", "(", "AdminRow", "row", ":", "topologicalSort", "(", "typeRows", ",", "keyspaceId", ")", ")", "{", "UserDefinedType", "type", "=", "parseType", "(", "row", ",", "keyspaceId", ",", "types", ")", ";", "types", ".", "put", "(", "type", ".", "getName", "(", ")", ",", "type", ")", ";", "}", "return", "ImmutableMap", ".", "copyOf", "(", "types", ")", ";", "}", "}" ]
Contrary to other element parsers, this one processes all the types of a keyspace in one go. UDTs can depend on each other, but the system table returns them in alphabetical order. In order to properly build the definitions, we need to do a topological sort of the rows first, so that each type is parsed after its dependencies.
[ "Contrary", "to", "other", "element", "parsers", "this", "one", "processes", "all", "the", "types", "of", "a", "keyspace", "in", "one", "go", ".", "UDTs", "can", "depend", "on", "each", "other", "but", "the", "system", "table", "returns", "them", "in", "alphabetical", "order", ".", "In", "order", "to", "properly", "build", "the", "definitions", "we", "need", "to", "do", "a", "topological", "sort", "of", "the", "rows", "first", "so", "that", "each", "type", "is", "parsed", "after", "its", "dependencies", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/UserDefinedTypeParser.java#L57-L69
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/control/ControlConnection.java
ControlConnection.init
public CompletionStage<Void> init( boolean listenToClusterEvents, boolean reconnectOnFailure, boolean useInitialReconnectionSchedule) { RunOrSchedule.on( adminExecutor, () -> singleThreaded.init( listenToClusterEvents, reconnectOnFailure, useInitialReconnectionSchedule)); return singleThreaded.initFuture; }
java
public CompletionStage<Void> init( boolean listenToClusterEvents, boolean reconnectOnFailure, boolean useInitialReconnectionSchedule) { RunOrSchedule.on( adminExecutor, () -> singleThreaded.init( listenToClusterEvents, reconnectOnFailure, useInitialReconnectionSchedule)); return singleThreaded.initFuture; }
[ "public", "CompletionStage", "<", "Void", ">", "init", "(", "boolean", "listenToClusterEvents", ",", "boolean", "reconnectOnFailure", ",", "boolean", "useInitialReconnectionSchedule", ")", "{", "RunOrSchedule", ".", "on", "(", "adminExecutor", ",", "(", ")", "->", "singleThreaded", ".", "init", "(", "listenToClusterEvents", ",", "reconnectOnFailure", ",", "useInitialReconnectionSchedule", ")", ")", ";", "return", "singleThreaded", ".", "initFuture", ";", "}" ]
Initializes the control connection. If it is already initialized, this is a no-op and all parameters are ignored. @param listenToClusterEvents whether to register for TOPOLOGY_CHANGE and STATUS_CHANGE events. If the control connection has already initialized with another value, this is ignored. SCHEMA_CHANGE events are always registered. @param reconnectOnFailure whether to schedule a reconnection if the initial attempt fails (this does not affect the returned future, which always represent the outcome of the initial attempt only). @param useInitialReconnectionSchedule if no node can be reached, the type of reconnection schedule to use. In other words, the value that will be passed to {@link ReconnectionPolicy#newControlConnectionSchedule(boolean)}. Note that this parameter is only relevant if {@code reconnectOnFailure} is true, otherwise it is not used.
[ "Initializes", "the", "control", "connection", ".", "If", "it", "is", "already", "initialized", "this", "is", "a", "no", "-", "op", "and", "all", "parameters", "are", "ignored", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/control/ControlConnection.java#L113-L123
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/pool/ChannelPool.java
ChannelPool.setKeyspace
public CompletionStage<Void> setKeyspace(CqlIdentifier newKeyspaceName) { return RunOrSchedule.on(adminExecutor, () -> singleThreaded.setKeyspace(newKeyspaceName)); }
java
public CompletionStage<Void> setKeyspace(CqlIdentifier newKeyspaceName) { return RunOrSchedule.on(adminExecutor, () -> singleThreaded.setKeyspace(newKeyspaceName)); }
[ "public", "CompletionStage", "<", "Void", ">", "setKeyspace", "(", "CqlIdentifier", "newKeyspaceName", ")", "{", "return", "RunOrSchedule", ".", "on", "(", "adminExecutor", ",", "(", ")", "->", "singleThreaded", ".", "setKeyspace", "(", "newKeyspaceName", ")", ")", ";", "}" ]
Changes the keyspace name on all the channels in this pool. <p>Note that this is not called directly by the user, but happens only on a SetKeyspace response after a successful "USE ..." query, so the name should be valid. If the keyspace switch fails on any channel, that channel is closed and a reconnection is started.
[ "Changes", "the", "keyspace", "name", "on", "all", "the", "channels", "in", "this", "pool", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/pool/ChannelPool.java#L196-L198
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/api/core/Version.java
Version.getPreReleaseLabels
public List<String> getPreReleaseLabels() { return preReleases == null ? null : Collections.unmodifiableList(Arrays.asList(preReleases)); }
java
public List<String> getPreReleaseLabels() { return preReleases == null ? null : Collections.unmodifiableList(Arrays.asList(preReleases)); }
[ "public", "List", "<", "String", ">", "getPreReleaseLabels", "(", ")", "{", "return", "preReleases", "==", "null", "?", "null", ":", "Collections", ".", "unmodifiableList", "(", "Arrays", ".", "asList", "(", "preReleases", ")", ")", ";", "}" ]
The pre-release labels if relevant, i.e. label1 and label2 in X.Y.Z-label1-lable2. @return the pre-release labels. The return list will be {@code null} if the version number doesn't have any.
[ "The", "pre", "-", "release", "labels", "if", "relevant", "i", ".", "e", ".", "label1", "and", "label2", "in", "X", ".", "Y", ".", "Z", "-", "label1", "-", "lable2", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/api/core/Version.java#L172-L174
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/metadata/LoadBalancingPolicyWrapper.java
LoadBalancingPolicyWrapper.processNodeStateEvent
private void processNodeStateEvent(NodeStateEvent event) { switch (stateRef.get()) { case BEFORE_INIT: case DURING_INIT: throw new AssertionError("Filter should not be marked ready until LBP init"); case CLOSING: return; // ignore case RUNNING: for (LoadBalancingPolicy policy : policies) { if (event.newState == NodeState.UP) { policy.onUp(event.node); } else if (event.newState == NodeState.DOWN || event.newState == NodeState.FORCED_DOWN) { policy.onDown(event.node); } else if (event.newState == NodeState.UNKNOWN) { policy.onAdd(event.node); } else if (event.newState == null) { policy.onRemove(event.node); } else { LOG.warn("[{}] Unsupported event: {}", logPrefix, event); } } break; } }
java
private void processNodeStateEvent(NodeStateEvent event) { switch (stateRef.get()) { case BEFORE_INIT: case DURING_INIT: throw new AssertionError("Filter should not be marked ready until LBP init"); case CLOSING: return; // ignore case RUNNING: for (LoadBalancingPolicy policy : policies) { if (event.newState == NodeState.UP) { policy.onUp(event.node); } else if (event.newState == NodeState.DOWN || event.newState == NodeState.FORCED_DOWN) { policy.onDown(event.node); } else if (event.newState == NodeState.UNKNOWN) { policy.onAdd(event.node); } else if (event.newState == null) { policy.onRemove(event.node); } else { LOG.warn("[{}] Unsupported event: {}", logPrefix, event); } } break; } }
[ "private", "void", "processNodeStateEvent", "(", "NodeStateEvent", "event", ")", "{", "switch", "(", "stateRef", ".", "get", "(", ")", ")", "{", "case", "BEFORE_INIT", ":", "case", "DURING_INIT", ":", "throw", "new", "AssertionError", "(", "\"Filter should not be marked ready until LBP init\"", ")", ";", "case", "CLOSING", ":", "return", ";", "// ignore", "case", "RUNNING", ":", "for", "(", "LoadBalancingPolicy", "policy", ":", "policies", ")", "{", "if", "(", "event", ".", "newState", "==", "NodeState", ".", "UP", ")", "{", "policy", ".", "onUp", "(", "event", ".", "node", ")", ";", "}", "else", "if", "(", "event", ".", "newState", "==", "NodeState", ".", "DOWN", "||", "event", ".", "newState", "==", "NodeState", ".", "FORCED_DOWN", ")", "{", "policy", ".", "onDown", "(", "event", ".", "node", ")", ";", "}", "else", "if", "(", "event", ".", "newState", "==", "NodeState", ".", "UNKNOWN", ")", "{", "policy", ".", "onAdd", "(", "event", ".", "node", ")", ";", "}", "else", "if", "(", "event", ".", "newState", "==", "null", ")", "{", "policy", ".", "onRemove", "(", "event", ".", "node", ")", ";", "}", "else", "{", "LOG", ".", "warn", "(", "\"[{}] Unsupported event: {}\"", ",", "logPrefix", ",", "event", ")", ";", "}", "}", "break", ";", "}", "}" ]
once it has gone through the filter
[ "once", "it", "has", "gone", "through", "the", "filter" ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/LoadBalancingPolicyWrapper.java#L172-L195
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/Ec2MultiRegionAddressTranslator.java
Ec2MultiRegionAddressTranslator.reverse
@VisibleForTesting static String reverse(InetAddress address) { byte[] bytes = address.getAddress(); if (bytes.length == 4) return reverseIpv4(bytes); else return reverseIpv6(bytes); }
java
@VisibleForTesting static String reverse(InetAddress address) { byte[] bytes = address.getAddress(); if (bytes.length == 4) return reverseIpv4(bytes); else return reverseIpv6(bytes); }
[ "@", "VisibleForTesting", "static", "String", "reverse", "(", "InetAddress", "address", ")", "{", "byte", "[", "]", "bytes", "=", "address", ".", "getAddress", "(", ")", ";", "if", "(", "bytes", ".", "length", "==", "4", ")", "return", "reverseIpv4", "(", "bytes", ")", ";", "else", "return", "reverseIpv6", "(", "bytes", ")", ";", "}" ]
Builds the "reversed" domain name in the ARPA domain to perform the reverse lookup
[ "Builds", "the", "reversed", "domain", "name", "in", "the", "ARPA", "domain", "to", "perform", "the", "reverse", "lookup" ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/Ec2MultiRegionAddressTranslator.java#L127-L132
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/data/IdentifierIndex.java
IdentifierIndex.firstIndexOf
public int firstIndexOf(CqlIdentifier id) { Integer index = byId.get(id); return (index == null) ? -1 : index; }
java
public int firstIndexOf(CqlIdentifier id) { Integer index = byId.get(id); return (index == null) ? -1 : index; }
[ "public", "int", "firstIndexOf", "(", "CqlIdentifier", "id", ")", "{", "Integer", "index", "=", "byId", ".", "get", "(", "id", ")", ";", "return", "(", "index", "==", "null", ")", "?", "-", "1", ":", "index", ";", "}" ]
Returns the first occurrence of a given identifier, or -1 if it's not in the list.
[ "Returns", "the", "first", "occurrence", "of", "a", "given", "identifier", "or", "-", "1", "if", "it", "s", "not", "in", "the", "list", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/data/IdentifierIndex.java#L68-L71
train
datastax/java-driver
examples/src/main/java/com/datastax/oss/driver/examples/json/PlainTextJson.java
PlainTextJson.insertWithCoreApi
private static void insertWithCoreApi(CqlSession session) { // Bind in a simple statement: session.execute( SimpleStatement.newInstance( "INSERT INTO examples.querybuilder_json JSON ?", "{ \"id\": 1, \"name\": \"Mouse\", \"specs\": { \"color\": \"silver\" } }")); // Bind in a prepared statement: // (subsequent calls to the prepare() method will return cached statement) PreparedStatement pst = session.prepare("INSERT INTO examples.querybuilder_json JSON :payload"); session.execute( pst.bind() .setString( "payload", "{ \"id\": 2, \"name\": \"Keyboard\", \"specs\": { \"layout\": \"qwerty\" } }")); // fromJson lets you provide individual columns as JSON: session.execute( SimpleStatement.newInstance( "INSERT INTO examples.querybuilder_json " + "(id, name, specs) VALUES (?, ?, fromJson(?))", 3, "Screen", "{ \"size\": \"24-inch\" }")); }
java
private static void insertWithCoreApi(CqlSession session) { // Bind in a simple statement: session.execute( SimpleStatement.newInstance( "INSERT INTO examples.querybuilder_json JSON ?", "{ \"id\": 1, \"name\": \"Mouse\", \"specs\": { \"color\": \"silver\" } }")); // Bind in a prepared statement: // (subsequent calls to the prepare() method will return cached statement) PreparedStatement pst = session.prepare("INSERT INTO examples.querybuilder_json JSON :payload"); session.execute( pst.bind() .setString( "payload", "{ \"id\": 2, \"name\": \"Keyboard\", \"specs\": { \"layout\": \"qwerty\" } }")); // fromJson lets you provide individual columns as JSON: session.execute( SimpleStatement.newInstance( "INSERT INTO examples.querybuilder_json " + "(id, name, specs) VALUES (?, ?, fromJson(?))", 3, "Screen", "{ \"size\": \"24-inch\" }")); }
[ "private", "static", "void", "insertWithCoreApi", "(", "CqlSession", "session", ")", "{", "// Bind in a simple statement:", "session", ".", "execute", "(", "SimpleStatement", ".", "newInstance", "(", "\"INSERT INTO examples.querybuilder_json JSON ?\"", ",", "\"{ \\\"id\\\": 1, \\\"name\\\": \\\"Mouse\\\", \\\"specs\\\": { \\\"color\\\": \\\"silver\\\" } }\"", ")", ")", ";", "// Bind in a prepared statement:", "// (subsequent calls to the prepare() method will return cached statement)", "PreparedStatement", "pst", "=", "session", ".", "prepare", "(", "\"INSERT INTO examples.querybuilder_json JSON :payload\"", ")", ";", "session", ".", "execute", "(", "pst", ".", "bind", "(", ")", ".", "setString", "(", "\"payload\"", ",", "\"{ \\\"id\\\": 2, \\\"name\\\": \\\"Keyboard\\\", \\\"specs\\\": { \\\"layout\\\": \\\"qwerty\\\" } }\"", ")", ")", ";", "// fromJson lets you provide individual columns as JSON:", "session", ".", "execute", "(", "SimpleStatement", ".", "newInstance", "(", "\"INSERT INTO examples.querybuilder_json \"", "+", "\"(id, name, specs) VALUES (?, ?, fromJson(?))\"", ",", "3", ",", "\"Screen\"", ",", "\"{ \\\"size\\\": \\\"24-inch\\\" }\"", ")", ")", ";", "}" ]
Demonstrates data insertion with the "core" API, i.e. providing the full query strings.
[ "Demonstrates", "data", "insertion", "with", "the", "core", "API", "i", ".", "e", ".", "providing", "the", "full", "query", "strings", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/examples/src/main/java/com/datastax/oss/driver/examples/json/PlainTextJson.java#L79-L103
train
datastax/java-driver
examples/src/main/java/com/datastax/oss/driver/examples/json/PlainTextJson.java
PlainTextJson.selectWithCoreApi
private static void selectWithCoreApi(CqlSession session) { // Reading the whole row as a JSON object: Row row = session .execute( SimpleStatement.newInstance( "SELECT JSON * FROM examples.querybuilder_json WHERE id = ?", 1)) .one(); assert row != null; System.out.printf("Entry #1 as JSON: %s%n", row.getString("[json]")); // Extracting a particular column as JSON: row = session .execute( SimpleStatement.newInstance( "SELECT id, toJson(specs) AS json_specs FROM examples.querybuilder_json WHERE id = ?", 2)) .one(); assert row != null; System.out.printf( "Entry #%d's specs as JSON: %s%n", row.getInt("id"), row.getString("json_specs")); }
java
private static void selectWithCoreApi(CqlSession session) { // Reading the whole row as a JSON object: Row row = session .execute( SimpleStatement.newInstance( "SELECT JSON * FROM examples.querybuilder_json WHERE id = ?", 1)) .one(); assert row != null; System.out.printf("Entry #1 as JSON: %s%n", row.getString("[json]")); // Extracting a particular column as JSON: row = session .execute( SimpleStatement.newInstance( "SELECT id, toJson(specs) AS json_specs FROM examples.querybuilder_json WHERE id = ?", 2)) .one(); assert row != null; System.out.printf( "Entry #%d's specs as JSON: %s%n", row.getInt("id"), row.getString("json_specs")); }
[ "private", "static", "void", "selectWithCoreApi", "(", "CqlSession", "session", ")", "{", "// Reading the whole row as a JSON object:", "Row", "row", "=", "session", ".", "execute", "(", "SimpleStatement", ".", "newInstance", "(", "\"SELECT JSON * FROM examples.querybuilder_json WHERE id = ?\"", ",", "1", ")", ")", ".", "one", "(", ")", ";", "assert", "row", "!=", "null", ";", "System", ".", "out", ".", "printf", "(", "\"Entry #1 as JSON: %s%n\"", ",", "row", ".", "getString", "(", "\"[json]\"", ")", ")", ";", "// Extracting a particular column as JSON:", "row", "=", "session", ".", "execute", "(", "SimpleStatement", ".", "newInstance", "(", "\"SELECT id, toJson(specs) AS json_specs FROM examples.querybuilder_json WHERE id = ?\"", ",", "2", ")", ")", ".", "one", "(", ")", ";", "assert", "row", "!=", "null", ";", "System", ".", "out", ".", "printf", "(", "\"Entry #%d's specs as JSON: %s%n\"", ",", "row", ".", "getInt", "(", "\"id\"", ")", ",", "row", ".", "getString", "(", "\"json_specs\"", ")", ")", ";", "}" ]
Demonstrates data retrieval with the "core" API, i.e. providing the full query strings.
[ "Demonstrates", "data", "retrieval", "with", "the", "core", "API", "i", ".", "e", ".", "providing", "the", "full", "query", "strings", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/examples/src/main/java/com/datastax/oss/driver/examples/json/PlainTextJson.java#L106-L128
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/type/UserDefinedTypeBuilder.java
UserDefinedTypeBuilder.withField
public UserDefinedTypeBuilder withField(CqlIdentifier name, DataType type) { fieldNames.add(name); fieldTypes.add(type); return this; }
java
public UserDefinedTypeBuilder withField(CqlIdentifier name, DataType type) { fieldNames.add(name); fieldTypes.add(type); return this; }
[ "public", "UserDefinedTypeBuilder", "withField", "(", "CqlIdentifier", "name", ",", "DataType", "type", ")", "{", "fieldNames", ".", "add", "(", "name", ")", ";", "fieldTypes", ".", "add", "(", "type", ")", ";", "return", "this", ";", "}" ]
Adds a new field. The fields in the resulting type will be in the order of the calls to this method.
[ "Adds", "a", "new", "field", ".", "The", "fields", "in", "the", "resulting", "type", "will", "be", "in", "the", "order", "of", "the", "calls", "to", "this", "method", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/type/UserDefinedTypeBuilder.java#L56-L60
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultMetadata.java
DefaultMetadata.withNodes
public DefaultMetadata withNodes( Map<UUID, Node> newNodes, boolean tokenMapEnabled, boolean tokensChanged, TokenFactory tokenFactory, InternalDriverContext context) { // Force a rebuild if at least one node has different tokens, or there are new or removed nodes. boolean forceFullRebuild = tokensChanged || !newNodes.equals(nodes); return new DefaultMetadata( ImmutableMap.copyOf(newNodes), this.keyspaces, rebuildTokenMap( newNodes, keyspaces, tokenMapEnabled, forceFullRebuild, tokenFactory, context)); }
java
public DefaultMetadata withNodes( Map<UUID, Node> newNodes, boolean tokenMapEnabled, boolean tokensChanged, TokenFactory tokenFactory, InternalDriverContext context) { // Force a rebuild if at least one node has different tokens, or there are new or removed nodes. boolean forceFullRebuild = tokensChanged || !newNodes.equals(nodes); return new DefaultMetadata( ImmutableMap.copyOf(newNodes), this.keyspaces, rebuildTokenMap( newNodes, keyspaces, tokenMapEnabled, forceFullRebuild, tokenFactory, context)); }
[ "public", "DefaultMetadata", "withNodes", "(", "Map", "<", "UUID", ",", "Node", ">", "newNodes", ",", "boolean", "tokenMapEnabled", ",", "boolean", "tokensChanged", ",", "TokenFactory", "tokenFactory", ",", "InternalDriverContext", "context", ")", "{", "// Force a rebuild if at least one node has different tokens, or there are new or removed nodes.", "boolean", "forceFullRebuild", "=", "tokensChanged", "||", "!", "newNodes", ".", "equals", "(", "nodes", ")", ";", "return", "new", "DefaultMetadata", "(", "ImmutableMap", ".", "copyOf", "(", "newNodes", ")", ",", "this", ".", "keyspaces", ",", "rebuildTokenMap", "(", "newNodes", ",", "keyspaces", ",", "tokenMapEnabled", ",", "forceFullRebuild", ",", "tokenFactory", ",", "context", ")", ")", ";", "}" ]
Refreshes the current metadata with the given list of nodes. @param tokenMapEnabled whether to rebuild the token map or not; if this is {@code false} the current token map will be copied into the new metadata without being recomputed. @param tokensChanged whether we observed a change of tokens for at least one node. This will require a full rebuild of the token map. @param tokenFactory only needed for the initial refresh, afterwards the existing one in the token map is used. @return the new metadata.
[ "Refreshes", "the", "current", "metadata", "with", "the", "given", "list", "of", "nodes", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultMetadata.java#L91-L106
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandler.java
CqlRequestHandler.sendRequest
private void sendRequest( Node retriedNode, Queue<Node> queryPlan, int currentExecutionIndex, int retryCount, boolean scheduleNextExecution) { if (result.isDone()) { return; } Node node = retriedNode; DriverChannel channel = null; if (node == null || (channel = session.getChannel(node, logPrefix)) == null) { while (!result.isDone() && (node = queryPlan.poll()) != null) { channel = session.getChannel(node, logPrefix); if (channel != null) { break; } } } if (channel == null) { // We've reached the end of the query plan without finding any node to write to if (!result.isDone() && activeExecutionsCount.decrementAndGet() == 0) { // We're the last execution so fail the result setFinalError(AllNodesFailedException.fromErrors(this.errors), null, -1); } } else { NodeResponseCallback nodeResponseCallback = new NodeResponseCallback( node, queryPlan, channel, currentExecutionIndex, retryCount, scheduleNextExecution, logPrefix); channel .write(message, statement.isTracing(), statement.getCustomPayload(), nodeResponseCallback) .addListener(nodeResponseCallback); } }
java
private void sendRequest( Node retriedNode, Queue<Node> queryPlan, int currentExecutionIndex, int retryCount, boolean scheduleNextExecution) { if (result.isDone()) { return; } Node node = retriedNode; DriverChannel channel = null; if (node == null || (channel = session.getChannel(node, logPrefix)) == null) { while (!result.isDone() && (node = queryPlan.poll()) != null) { channel = session.getChannel(node, logPrefix); if (channel != null) { break; } } } if (channel == null) { // We've reached the end of the query plan without finding any node to write to if (!result.isDone() && activeExecutionsCount.decrementAndGet() == 0) { // We're the last execution so fail the result setFinalError(AllNodesFailedException.fromErrors(this.errors), null, -1); } } else { NodeResponseCallback nodeResponseCallback = new NodeResponseCallback( node, queryPlan, channel, currentExecutionIndex, retryCount, scheduleNextExecution, logPrefix); channel .write(message, statement.isTracing(), statement.getCustomPayload(), nodeResponseCallback) .addListener(nodeResponseCallback); } }
[ "private", "void", "sendRequest", "(", "Node", "retriedNode", ",", "Queue", "<", "Node", ">", "queryPlan", ",", "int", "currentExecutionIndex", ",", "int", "retryCount", ",", "boolean", "scheduleNextExecution", ")", "{", "if", "(", "result", ".", "isDone", "(", ")", ")", "{", "return", ";", "}", "Node", "node", "=", "retriedNode", ";", "DriverChannel", "channel", "=", "null", ";", "if", "(", "node", "==", "null", "||", "(", "channel", "=", "session", ".", "getChannel", "(", "node", ",", "logPrefix", ")", ")", "==", "null", ")", "{", "while", "(", "!", "result", ".", "isDone", "(", ")", "&&", "(", "node", "=", "queryPlan", ".", "poll", "(", ")", ")", "!=", "null", ")", "{", "channel", "=", "session", ".", "getChannel", "(", "node", ",", "logPrefix", ")", ";", "if", "(", "channel", "!=", "null", ")", "{", "break", ";", "}", "}", "}", "if", "(", "channel", "==", "null", ")", "{", "// We've reached the end of the query plan without finding any node to write to", "if", "(", "!", "result", ".", "isDone", "(", ")", "&&", "activeExecutionsCount", ".", "decrementAndGet", "(", ")", "==", "0", ")", "{", "// We're the last execution so fail the result", "setFinalError", "(", "AllNodesFailedException", ".", "fromErrors", "(", "this", ".", "errors", ")", ",", "null", ",", "-", "1", ")", ";", "}", "}", "else", "{", "NodeResponseCallback", "nodeResponseCallback", "=", "new", "NodeResponseCallback", "(", "node", ",", "queryPlan", ",", "channel", ",", "currentExecutionIndex", ",", "retryCount", ",", "scheduleNextExecution", ",", "logPrefix", ")", ";", "channel", ".", "write", "(", "message", ",", "statement", ".", "isTracing", "(", ")", ",", "statement", ".", "getCustomPayload", "(", ")", ",", "nodeResponseCallback", ")", ".", "addListener", "(", "nodeResponseCallback", ")", ";", "}", "}" ]
Sends the request to the next available node. @param retriedNode if not null, it will be attempted first before the rest of the query plan. @param queryPlan the list of nodes to try (shared with all other executions) @param currentExecutionIndex 0 for the initial execution, 1 for the first speculative one, etc. @param retryCount the number of times that the retry policy was invoked for this execution already (note that some internal retries don't go through the policy, and therefore don't increment this counter) @param scheduleNextExecution whether to schedule the next speculative execution
[ "Sends", "the", "request", "to", "the", "next", "available", "node", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandler.java#L253-L292
train
datastax/java-driver
examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonRow.java
Jsr353JsonRow.selectJsonRow
private static void selectJsonRow(CqlSession session) { // Reading the whole row as a JSON object Statement stmt = selectFrom("examples", "json_jsr353_row") .json() .all() .whereColumn("id") .in(literal(1), literal(2)) .build(); ResultSet rows = session.execute(stmt); for (Row row : rows) { // SELECT JSON returns only one column for each row, of type VARCHAR, // containing the row as a JSON payload. // Note that the codec requires that the type passed to the get() method // be always JsonStructure, and not a subclass of it, such as JsonObject, // hence the need to downcast to JsonObject manually JsonObject user = (JsonObject) row.get(0, JsonStructure.class); System.out.printf("Retrieved user: %s%n", user); } }
java
private static void selectJsonRow(CqlSession session) { // Reading the whole row as a JSON object Statement stmt = selectFrom("examples", "json_jsr353_row") .json() .all() .whereColumn("id") .in(literal(1), literal(2)) .build(); ResultSet rows = session.execute(stmt); for (Row row : rows) { // SELECT JSON returns only one column for each row, of type VARCHAR, // containing the row as a JSON payload. // Note that the codec requires that the type passed to the get() method // be always JsonStructure, and not a subclass of it, such as JsonObject, // hence the need to downcast to JsonObject manually JsonObject user = (JsonObject) row.get(0, JsonStructure.class); System.out.printf("Retrieved user: %s%n", user); } }
[ "private", "static", "void", "selectJsonRow", "(", "CqlSession", "session", ")", "{", "// Reading the whole row as a JSON object", "Statement", "stmt", "=", "selectFrom", "(", "\"examples\"", ",", "\"json_jsr353_row\"", ")", ".", "json", "(", ")", ".", "all", "(", ")", ".", "whereColumn", "(", "\"id\"", ")", ".", "in", "(", "literal", "(", "1", ")", ",", "literal", "(", "2", ")", ")", ".", "build", "(", ")", ";", "ResultSet", "rows", "=", "session", ".", "execute", "(", "stmt", ")", ";", "for", "(", "Row", "row", ":", "rows", ")", "{", "// SELECT JSON returns only one column for each row, of type VARCHAR,", "// containing the row as a JSON payload.", "// Note that the codec requires that the type passed to the get() method", "// be always JsonStructure, and not a subclass of it, such as JsonObject,", "// hence the need to downcast to JsonObject manually", "JsonObject", "user", "=", "(", "JsonObject", ")", "row", ".", "get", "(", "0", ",", "JsonStructure", ".", "class", ")", ";", "System", ".", "out", ".", "printf", "(", "\"Retrieved user: %s%n\"", ",", "user", ")", ";", "}", "}" ]
Retrieving User instances from table rows using SELECT JSON
[ "Retrieving", "User", "instances", "from", "table", "rows", "using", "SELECT", "JSON" ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonRow.java#L133-L155
train
datastax/java-driver
examples/src/main/java/com/datastax/oss/driver/examples/datatypes/Blobs.java
Blobs.readAll
private static ByteBuffer readAll(File file) throws IOException { try (FileInputStream inputStream = new FileInputStream(file)) { FileChannel channel = inputStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate((int) channel.size()); channel.read(buffer); buffer.flip(); return buffer; } }
java
private static ByteBuffer readAll(File file) throws IOException { try (FileInputStream inputStream = new FileInputStream(file)) { FileChannel channel = inputStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate((int) channel.size()); channel.read(buffer); buffer.flip(); return buffer; } }
[ "private", "static", "ByteBuffer", "readAll", "(", "File", "file", ")", "throws", "IOException", "{", "try", "(", "FileInputStream", "inputStream", "=", "new", "FileInputStream", "(", "file", ")", ")", "{", "FileChannel", "channel", "=", "inputStream", ".", "getChannel", "(", ")", ";", "ByteBuffer", "buffer", "=", "ByteBuffer", ".", "allocate", "(", "(", "int", ")", "channel", ".", "size", "(", ")", ")", ";", "channel", ".", "read", "(", "buffer", ")", ";", "buffer", ".", "flip", "(", ")", ";", "return", "buffer", ";", "}", "}" ]
probably not insert it into Cassandra either ;)
[ "probably", "not", "insert", "it", "into", "Cassandra", "either", ";", ")" ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/Blobs.java#L239-L247
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/util/Sizes.java
Sizes.minimumRequestSize
public static int minimumRequestSize(Request request) { // Header and payload are common inside a Frame at the protocol level // Frame header has a fixed size of 9 for protocol version >= V3, which includes Frame flags // size int size = FrameCodec.headerEncodedSize(); if (!request.getCustomPayload().isEmpty()) { // Custom payload is not supported in v3, but assume user won't have a custom payload set if // they use this version size += PrimitiveSizes.sizeOfBytesMap(request.getCustomPayload()); } return size; }
java
public static int minimumRequestSize(Request request) { // Header and payload are common inside a Frame at the protocol level // Frame header has a fixed size of 9 for protocol version >= V3, which includes Frame flags // size int size = FrameCodec.headerEncodedSize(); if (!request.getCustomPayload().isEmpty()) { // Custom payload is not supported in v3, but assume user won't have a custom payload set if // they use this version size += PrimitiveSizes.sizeOfBytesMap(request.getCustomPayload()); } return size; }
[ "public", "static", "int", "minimumRequestSize", "(", "Request", "request", ")", "{", "// Header and payload are common inside a Frame at the protocol level", "// Frame header has a fixed size of 9 for protocol version >= V3, which includes Frame flags", "// size", "int", "size", "=", "FrameCodec", ".", "headerEncodedSize", "(", ")", ";", "if", "(", "!", "request", ".", "getCustomPayload", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "// Custom payload is not supported in v3, but assume user won't have a custom payload set if", "// they use this version", "size", "+=", "PrimitiveSizes", ".", "sizeOfBytesMap", "(", "request", ".", "getCustomPayload", "(", ")", ")", ";", "}", "return", "size", ";", "}" ]
Returns a common size for all kinds of Request implementations.
[ "Returns", "a", "common", "size", "for", "all", "kinds", "of", "Request", "implementations", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/Sizes.java#L41-L56
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/util/Sizes.java
Sizes.sizeOfSimpleStatementValues
public static int sizeOfSimpleStatementValues( SimpleStatement simpleStatement, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { int size = 0; if (!simpleStatement.getPositionalValues().isEmpty()) { List<ByteBuffer> positionalValues = new ArrayList<>(simpleStatement.getPositionalValues().size()); for (Object value : simpleStatement.getPositionalValues()) { positionalValues.add(Conversions.encode(value, codecRegistry, protocolVersion)); } size += Values.sizeOfPositionalValues(positionalValues); } else if (!simpleStatement.getNamedValues().isEmpty()) { Map<String, ByteBuffer> namedValues = new HashMap<>(simpleStatement.getNamedValues().size()); for (Map.Entry<CqlIdentifier, Object> value : simpleStatement.getNamedValues().entrySet()) { namedValues.put( value.getKey().asInternal(), Conversions.encode(value.getValue(), codecRegistry, protocolVersion)); } size += Values.sizeOfNamedValues(namedValues); } return size; }
java
public static int sizeOfSimpleStatementValues( SimpleStatement simpleStatement, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { int size = 0; if (!simpleStatement.getPositionalValues().isEmpty()) { List<ByteBuffer> positionalValues = new ArrayList<>(simpleStatement.getPositionalValues().size()); for (Object value : simpleStatement.getPositionalValues()) { positionalValues.add(Conversions.encode(value, codecRegistry, protocolVersion)); } size += Values.sizeOfPositionalValues(positionalValues); } else if (!simpleStatement.getNamedValues().isEmpty()) { Map<String, ByteBuffer> namedValues = new HashMap<>(simpleStatement.getNamedValues().size()); for (Map.Entry<CqlIdentifier, Object> value : simpleStatement.getNamedValues().entrySet()) { namedValues.put( value.getKey().asInternal(), Conversions.encode(value.getValue(), codecRegistry, protocolVersion)); } size += Values.sizeOfNamedValues(namedValues); } return size; }
[ "public", "static", "int", "sizeOfSimpleStatementValues", "(", "SimpleStatement", "simpleStatement", ",", "ProtocolVersion", "protocolVersion", ",", "CodecRegistry", "codecRegistry", ")", "{", "int", "size", "=", "0", ";", "if", "(", "!", "simpleStatement", ".", "getPositionalValues", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "List", "<", "ByteBuffer", ">", "positionalValues", "=", "new", "ArrayList", "<>", "(", "simpleStatement", ".", "getPositionalValues", "(", ")", ".", "size", "(", ")", ")", ";", "for", "(", "Object", "value", ":", "simpleStatement", ".", "getPositionalValues", "(", ")", ")", "{", "positionalValues", ".", "add", "(", "Conversions", ".", "encode", "(", "value", ",", "codecRegistry", ",", "protocolVersion", ")", ")", ";", "}", "size", "+=", "Values", ".", "sizeOfPositionalValues", "(", "positionalValues", ")", ";", "}", "else", "if", "(", "!", "simpleStatement", ".", "getNamedValues", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "Map", "<", "String", ",", "ByteBuffer", ">", "namedValues", "=", "new", "HashMap", "<>", "(", "simpleStatement", ".", "getNamedValues", "(", ")", ".", "size", "(", ")", ")", ";", "for", "(", "Map", ".", "Entry", "<", "CqlIdentifier", ",", "Object", ">", "value", ":", "simpleStatement", ".", "getNamedValues", "(", ")", ".", "entrySet", "(", ")", ")", "{", "namedValues", ".", "put", "(", "value", ".", "getKey", "(", ")", ".", "asInternal", "(", ")", ",", "Conversions", ".", "encode", "(", "value", ".", "getValue", "(", ")", ",", "codecRegistry", ",", "protocolVersion", ")", ")", ";", "}", "size", "+=", "Values", ".", "sizeOfNamedValues", "(", "namedValues", ")", ";", "}", "return", "size", ";", "}" ]
Returns the size in bytes of a simple statement's values, depending on whether the values are named or positional.
[ "Returns", "the", "size", "in", "bytes", "of", "a", "simple", "statement", "s", "values", "depending", "on", "whether", "the", "values", "are", "named", "or", "positional", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/Sizes.java#L75-L103
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/util/Sizes.java
Sizes.sizeOfInnerBatchStatementInBytes
public static Integer sizeOfInnerBatchStatementInBytes( BatchableStatement statement, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { int size = 0; size += PrimitiveSizes .BYTE; // for each inner statement, there is one byte for the "kind": prepared or string if (statement instanceof SimpleStatement) { size += PrimitiveSizes.sizeOfLongString(((SimpleStatement) statement).getQuery()); size += sizeOfSimpleStatementValues( ((SimpleStatement) statement), protocolVersion, codecRegistry); } else if (statement instanceof BoundStatement) { size += PrimitiveSizes.sizeOfShortBytes( ((BoundStatement) statement).getPreparedStatement().getId().array()); size += sizeOfBoundStatementValues(((BoundStatement) statement)); } return size; }
java
public static Integer sizeOfInnerBatchStatementInBytes( BatchableStatement statement, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { int size = 0; size += PrimitiveSizes .BYTE; // for each inner statement, there is one byte for the "kind": prepared or string if (statement instanceof SimpleStatement) { size += PrimitiveSizes.sizeOfLongString(((SimpleStatement) statement).getQuery()); size += sizeOfSimpleStatementValues( ((SimpleStatement) statement), protocolVersion, codecRegistry); } else if (statement instanceof BoundStatement) { size += PrimitiveSizes.sizeOfShortBytes( ((BoundStatement) statement).getPreparedStatement().getId().array()); size += sizeOfBoundStatementValues(((BoundStatement) statement)); } return size; }
[ "public", "static", "Integer", "sizeOfInnerBatchStatementInBytes", "(", "BatchableStatement", "statement", ",", "ProtocolVersion", "protocolVersion", ",", "CodecRegistry", "codecRegistry", ")", "{", "int", "size", "=", "0", ";", "size", "+=", "PrimitiveSizes", ".", "BYTE", ";", "// for each inner statement, there is one byte for the \"kind\": prepared or string", "if", "(", "statement", "instanceof", "SimpleStatement", ")", "{", "size", "+=", "PrimitiveSizes", ".", "sizeOfLongString", "(", "(", "(", "SimpleStatement", ")", "statement", ")", ".", "getQuery", "(", ")", ")", ";", "size", "+=", "sizeOfSimpleStatementValues", "(", "(", "(", "SimpleStatement", ")", "statement", ")", ",", "protocolVersion", ",", "codecRegistry", ")", ";", "}", "else", "if", "(", "statement", "instanceof", "BoundStatement", ")", "{", "size", "+=", "PrimitiveSizes", ".", "sizeOfShortBytes", "(", "(", "(", "BoundStatement", ")", "statement", ")", ".", "getPreparedStatement", "(", ")", ".", "getId", "(", ")", ".", "array", "(", ")", ")", ";", "size", "+=", "sizeOfBoundStatementValues", "(", "(", "(", "BoundStatement", ")", "statement", ")", ")", ";", "}", "return", "size", ";", "}" ]
The size of a statement inside a batch query is different from the size of a complete Statement. The inner batch statements only include the query or prepared ID, and the values of the statement.
[ "The", "size", "of", "a", "statement", "inside", "a", "batch", "query", "is", "different", "from", "the", "size", "of", "a", "complete", "Statement", ".", "The", "inner", "batch", "statements", "only", "include", "the", "query", "or", "prepared", "ID", "and", "the", "values", "of", "the", "statement", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/Sizes.java#L115-L135
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/util/DirectedGraph.java
DirectedGraph.topologicalSort
public List<VertexT> topologicalSort() { Preconditions.checkState(!wasSorted); wasSorted = true; Queue<VertexT> queue = new ArrayDeque<>(); for (Map.Entry<VertexT, Integer> entry : vertices.entrySet()) { if (entry.getValue() == 0) { queue.add(entry.getKey()); } } List<VertexT> result = Lists.newArrayList(); while (!queue.isEmpty()) { VertexT vertex = queue.remove(); result.add(vertex); for (VertexT successor : adjacencyList.get(vertex)) { if (decrementAndGetCount(successor) == 0) { queue.add(successor); } } } if (result.size() != vertices.size()) { throw new IllegalArgumentException("failed to perform topological sort, graph has a cycle"); } return result; }
java
public List<VertexT> topologicalSort() { Preconditions.checkState(!wasSorted); wasSorted = true; Queue<VertexT> queue = new ArrayDeque<>(); for (Map.Entry<VertexT, Integer> entry : vertices.entrySet()) { if (entry.getValue() == 0) { queue.add(entry.getKey()); } } List<VertexT> result = Lists.newArrayList(); while (!queue.isEmpty()) { VertexT vertex = queue.remove(); result.add(vertex); for (VertexT successor : adjacencyList.get(vertex)) { if (decrementAndGetCount(successor) == 0) { queue.add(successor); } } } if (result.size() != vertices.size()) { throw new IllegalArgumentException("failed to perform topological sort, graph has a cycle"); } return result; }
[ "public", "List", "<", "VertexT", ">", "topologicalSort", "(", ")", "{", "Preconditions", ".", "checkState", "(", "!", "wasSorted", ")", ";", "wasSorted", "=", "true", ";", "Queue", "<", "VertexT", ">", "queue", "=", "new", "ArrayDeque", "<>", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "VertexT", ",", "Integer", ">", "entry", ":", "vertices", ".", "entrySet", "(", ")", ")", "{", "if", "(", "entry", ".", "getValue", "(", ")", "==", "0", ")", "{", "queue", ".", "add", "(", "entry", ".", "getKey", "(", ")", ")", ";", "}", "}", "List", "<", "VertexT", ">", "result", "=", "Lists", ".", "newArrayList", "(", ")", ";", "while", "(", "!", "queue", ".", "isEmpty", "(", ")", ")", "{", "VertexT", "vertex", "=", "queue", ".", "remove", "(", ")", ";", "result", ".", "add", "(", "vertex", ")", ";", "for", "(", "VertexT", "successor", ":", "adjacencyList", ".", "get", "(", "vertex", ")", ")", "{", "if", "(", "decrementAndGetCount", "(", "successor", ")", "==", "0", ")", "{", "queue", ".", "add", "(", "successor", ")", ";", "}", "}", "}", "if", "(", "result", ".", "size", "(", ")", "!=", "vertices", ".", "size", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"failed to perform topological sort, graph has a cycle\"", ")", ";", "}", "return", "result", ";", "}" ]
one-time use only, calling this multiple times on the same graph won't work
[ "one", "-", "time", "use", "only", "calling", "this", "multiple", "times", "on", "the", "same", "graph", "won", "t", "work" ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/DirectedGraph.java#L68-L96
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/channel/DriverChannel.java
DriverChannel.cancel
public void cancel(ResponseCallback responseCallback) { // To avoid creating an extra message, we adopt the convention that writing the callback // directly means cancellation writeCoalescer.writeAndFlush(channel, responseCallback).addListener(UncaughtExceptions::log); }
java
public void cancel(ResponseCallback responseCallback) { // To avoid creating an extra message, we adopt the convention that writing the callback // directly means cancellation writeCoalescer.writeAndFlush(channel, responseCallback).addListener(UncaughtExceptions::log); }
[ "public", "void", "cancel", "(", "ResponseCallback", "responseCallback", ")", "{", "// To avoid creating an extra message, we adopt the convention that writing the callback", "// directly means cancellation", "writeCoalescer", ".", "writeAndFlush", "(", "channel", ",", "responseCallback", ")", ".", "addListener", "(", "UncaughtExceptions", "::", "log", ")", ";", "}" ]
Cancels a callback, indicating that the client that wrote it is no longer interested in the answer. <p>Note that this does not cancel the request server-side (but might in the future if Cassandra supports it).
[ "Cancels", "a", "callback", "indicating", "that", "the", "client", "that", "wrote", "it", "is", "no", "longer", "interested", "in", "the", "answer", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/channel/DriverChannel.java#L93-L97
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/refresh/SchemaRefresh.java
SchemaRefresh.computeEvents
private void computeEvents( KeyspaceMetadata oldKeyspace, KeyspaceMetadata newKeyspace, ImmutableList.Builder<Object> events) { if (oldKeyspace == null) { events.add(KeyspaceChangeEvent.created(newKeyspace)); } else { if (!shallowEquals(oldKeyspace, newKeyspace)) { events.add(KeyspaceChangeEvent.updated(oldKeyspace, newKeyspace)); } computeChildEvents(oldKeyspace, newKeyspace, events); } }
java
private void computeEvents( KeyspaceMetadata oldKeyspace, KeyspaceMetadata newKeyspace, ImmutableList.Builder<Object> events) { if (oldKeyspace == null) { events.add(KeyspaceChangeEvent.created(newKeyspace)); } else { if (!shallowEquals(oldKeyspace, newKeyspace)) { events.add(KeyspaceChangeEvent.updated(oldKeyspace, newKeyspace)); } computeChildEvents(oldKeyspace, newKeyspace, events); } }
[ "private", "void", "computeEvents", "(", "KeyspaceMetadata", "oldKeyspace", ",", "KeyspaceMetadata", "newKeyspace", ",", "ImmutableList", ".", "Builder", "<", "Object", ">", "events", ")", "{", "if", "(", "oldKeyspace", "==", "null", ")", "{", "events", ".", "add", "(", "KeyspaceChangeEvent", ".", "created", "(", "newKeyspace", ")", ")", ";", "}", "else", "{", "if", "(", "!", "shallowEquals", "(", "oldKeyspace", ",", "newKeyspace", ")", ")", "{", "events", ".", "add", "(", "KeyspaceChangeEvent", ".", "updated", "(", "oldKeyspace", ",", "newKeyspace", ")", ")", ";", "}", "computeChildEvents", "(", "oldKeyspace", ",", "newKeyspace", ",", "events", ")", ";", "}", "}" ]
Computes the exact set of events to emit when a keyspace has changed. <p>We can't simply emit {@link KeyspaceChangeEvent#updated(KeyspaceMetadata, KeyspaceMetadata)} because this method might be called as part of a full schema refresh, or a keyspace refresh initiated by coalesced child element refreshes. We need to traverse all children to check what has exactly changed.
[ "Computes", "the", "exact", "set", "of", "events", "to", "emit", "when", "a", "keyspace", "has", "changed", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/refresh/SchemaRefresh.java#L79-L91
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/Debouncer.java
Debouncer.receive
public void receive(IncomingT element) { assert adminExecutor.inEventLoop(); if (stopped) { return; } if (window.isZero() || maxEvents == 1) { LOG.debug( "Received {}, flushing immediately (window = {}, maxEvents = {})", element, window, maxEvents); onFlush.accept(coalescer.apply(ImmutableList.of(element))); } else { currentBatch.add(element); if (currentBatch.size() == maxEvents) { LOG.debug( "Received {}, flushing immediately (because {} accumulated events)", element, maxEvents); flushNow(); } else { LOG.debug("Received {}, scheduling next flush in {}", element, window); scheduleFlush(); } } }
java
public void receive(IncomingT element) { assert adminExecutor.inEventLoop(); if (stopped) { return; } if (window.isZero() || maxEvents == 1) { LOG.debug( "Received {}, flushing immediately (window = {}, maxEvents = {})", element, window, maxEvents); onFlush.accept(coalescer.apply(ImmutableList.of(element))); } else { currentBatch.add(element); if (currentBatch.size() == maxEvents) { LOG.debug( "Received {}, flushing immediately (because {} accumulated events)", element, maxEvents); flushNow(); } else { LOG.debug("Received {}, scheduling next flush in {}", element, window); scheduleFlush(); } } }
[ "public", "void", "receive", "(", "IncomingT", "element", ")", "{", "assert", "adminExecutor", ".", "inEventLoop", "(", ")", ";", "if", "(", "stopped", ")", "{", "return", ";", "}", "if", "(", "window", ".", "isZero", "(", ")", "||", "maxEvents", "==", "1", ")", "{", "LOG", ".", "debug", "(", "\"Received {}, flushing immediately (window = {}, maxEvents = {})\"", ",", "element", ",", "window", ",", "maxEvents", ")", ";", "onFlush", ".", "accept", "(", "coalescer", ".", "apply", "(", "ImmutableList", ".", "of", "(", "element", ")", ")", ")", ";", "}", "else", "{", "currentBatch", ".", "add", "(", "element", ")", ";", "if", "(", "currentBatch", ".", "size", "(", ")", "==", "maxEvents", ")", "{", "LOG", ".", "debug", "(", "\"Received {}, flushing immediately (because {} accumulated events)\"", ",", "element", ",", "maxEvents", ")", ";", "flushNow", "(", ")", ";", "}", "else", "{", "LOG", ".", "debug", "(", "\"Received {}, scheduling next flush in {}\"", ",", "element", ",", "window", ")", ";", "scheduleFlush", "(", ")", ";", "}", "}", "}" ]
This must be called on eventExecutor too.
[ "This", "must", "be", "called", "on", "eventExecutor", "too", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/Debouncer.java#L81-L106
train
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/api/core/session/SessionBuilder.java
SessionBuilder.buildAsync
@NonNull public CompletionStage<SessionT> buildAsync() { CompletionStage<CqlSession> buildStage = buildDefaultSessionAsync(); CompletionStage<SessionT> wrapStage = buildStage.thenApply(this::wrap); // thenApply does not propagate cancellation (!) CompletableFutures.propagateCancellation(wrapStage, buildStage); return wrapStage; }
java
@NonNull public CompletionStage<SessionT> buildAsync() { CompletionStage<CqlSession> buildStage = buildDefaultSessionAsync(); CompletionStage<SessionT> wrapStage = buildStage.thenApply(this::wrap); // thenApply does not propagate cancellation (!) CompletableFutures.propagateCancellation(wrapStage, buildStage); return wrapStage; }
[ "@", "NonNull", "public", "CompletionStage", "<", "SessionT", ">", "buildAsync", "(", ")", "{", "CompletionStage", "<", "CqlSession", ">", "buildStage", "=", "buildDefaultSessionAsync", "(", ")", ";", "CompletionStage", "<", "SessionT", ">", "wrapStage", "=", "buildStage", ".", "thenApply", "(", "this", "::", "wrap", ")", ";", "// thenApply does not propagate cancellation (!)", "CompletableFutures", ".", "propagateCancellation", "(", "wrapStage", ",", "buildStage", ")", ";", "return", "wrapStage", ";", "}" ]
Creates the session with the options set by this builder. @return a completion stage that completes with the session when it is fully initialized.
[ "Creates", "the", "session", "with", "the", "options", "set", "by", "this", "builder", "." ]
612a63f2525618e2020e86c9ad75ab37adba6132
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/api/core/session/SessionBuilder.java#L317-L324
train
monitorjbl/excel-streaming-reader
src/main/java/com/monitorjbl/xlsx/impl/StreamingSheetReader.java
StreamingSheetReader.getRow
private boolean getRow() { try { rowCache.clear(); while(rowCache.size() < rowCacheSize && parser.hasNext()) { handleEvent(parser.nextEvent()); } rowCacheIterator = rowCache.iterator(); return rowCacheIterator.hasNext(); } catch(XMLStreamException e) { throw new ParseException("Error reading XML stream", e); } }
java
private boolean getRow() { try { rowCache.clear(); while(rowCache.size() < rowCacheSize && parser.hasNext()) { handleEvent(parser.nextEvent()); } rowCacheIterator = rowCache.iterator(); return rowCacheIterator.hasNext(); } catch(XMLStreamException e) { throw new ParseException("Error reading XML stream", e); } }
[ "private", "boolean", "getRow", "(", ")", "{", "try", "{", "rowCache", ".", "clear", "(", ")", ";", "while", "(", "rowCache", ".", "size", "(", ")", "<", "rowCacheSize", "&&", "parser", ".", "hasNext", "(", ")", ")", "{", "handleEvent", "(", "parser", ".", "nextEvent", "(", ")", ")", ";", "}", "rowCacheIterator", "=", "rowCache", ".", "iterator", "(", ")", ";", "return", "rowCacheIterator", ".", "hasNext", "(", ")", ";", "}", "catch", "(", "XMLStreamException", "e", ")", "{", "throw", "new", "ParseException", "(", "\"Error reading XML stream\"", ",", "e", ")", ";", "}", "}" ]
Read through a number of rows equal to the rowCacheSize field or until there is no more data to read @return true if data was read
[ "Read", "through", "a", "number", "of", "rows", "equal", "to", "the", "rowCacheSize", "field", "or", "until", "there", "is", "no", "more", "data", "to", "read" ]
4e95c9aaaecf33685a09f8c267af3a578ba5e070
https://github.com/monitorjbl/excel-streaming-reader/blob/4e95c9aaaecf33685a09f8c267af3a578ba5e070/src/main/java/com/monitorjbl/xlsx/impl/StreamingSheetReader.java#L66-L77
train
monitorjbl/excel-streaming-reader
src/main/java/com/monitorjbl/xlsx/impl/StreamingSheetReader.java
StreamingSheetReader.setFormatString
void setFormatString(StartElement startElement, StreamingCell cell) { Attribute cellStyle = startElement.getAttributeByName(new QName("s")); String cellStyleString = (cellStyle != null) ? cellStyle.getValue() : null; XSSFCellStyle style = null; if(cellStyleString != null) { style = stylesTable.getStyleAt(Integer.parseInt(cellStyleString)); } else if(stylesTable.getNumCellStyles() > 0) { style = stylesTable.getStyleAt(0); } if(style != null) { cell.setNumericFormatIndex(style.getDataFormat()); String formatString = style.getDataFormatString(); if(formatString != null) { cell.setNumericFormat(formatString); } else { cell.setNumericFormat(BuiltinFormats.getBuiltinFormat(cell.getNumericFormatIndex())); } } else { cell.setNumericFormatIndex(null); cell.setNumericFormat(null); } }
java
void setFormatString(StartElement startElement, StreamingCell cell) { Attribute cellStyle = startElement.getAttributeByName(new QName("s")); String cellStyleString = (cellStyle != null) ? cellStyle.getValue() : null; XSSFCellStyle style = null; if(cellStyleString != null) { style = stylesTable.getStyleAt(Integer.parseInt(cellStyleString)); } else if(stylesTable.getNumCellStyles() > 0) { style = stylesTable.getStyleAt(0); } if(style != null) { cell.setNumericFormatIndex(style.getDataFormat()); String formatString = style.getDataFormatString(); if(formatString != null) { cell.setNumericFormat(formatString); } else { cell.setNumericFormat(BuiltinFormats.getBuiltinFormat(cell.getNumericFormatIndex())); } } else { cell.setNumericFormatIndex(null); cell.setNumericFormat(null); } }
[ "void", "setFormatString", "(", "StartElement", "startElement", ",", "StreamingCell", "cell", ")", "{", "Attribute", "cellStyle", "=", "startElement", ".", "getAttributeByName", "(", "new", "QName", "(", "\"s\"", ")", ")", ";", "String", "cellStyleString", "=", "(", "cellStyle", "!=", "null", ")", "?", "cellStyle", ".", "getValue", "(", ")", ":", "null", ";", "XSSFCellStyle", "style", "=", "null", ";", "if", "(", "cellStyleString", "!=", "null", ")", "{", "style", "=", "stylesTable", ".", "getStyleAt", "(", "Integer", ".", "parseInt", "(", "cellStyleString", ")", ")", ";", "}", "else", "if", "(", "stylesTable", ".", "getNumCellStyles", "(", ")", ">", "0", ")", "{", "style", "=", "stylesTable", ".", "getStyleAt", "(", "0", ")", ";", "}", "if", "(", "style", "!=", "null", ")", "{", "cell", ".", "setNumericFormatIndex", "(", "style", ".", "getDataFormat", "(", ")", ")", ";", "String", "formatString", "=", "style", ".", "getDataFormatString", "(", ")", ";", "if", "(", "formatString", "!=", "null", ")", "{", "cell", ".", "setNumericFormat", "(", "formatString", ")", ";", "}", "else", "{", "cell", ".", "setNumericFormat", "(", "BuiltinFormats", ".", "getBuiltinFormat", "(", "cell", ".", "getNumericFormatIndex", "(", ")", ")", ")", ";", "}", "}", "else", "{", "cell", ".", "setNumericFormatIndex", "(", "null", ")", ";", "cell", ".", "setNumericFormat", "(", "null", ")", ";", "}", "}" ]
Read the numeric format string out of the styles table for this cell. Stores the result in the Cell. @param startElement @param cell
[ "Read", "the", "numeric", "format", "string", "out", "of", "the", "styles", "table", "for", "this", "cell", ".", "Stores", "the", "result", "in", "the", "Cell", "." ]
4e95c9aaaecf33685a09f8c267af3a578ba5e070
https://github.com/monitorjbl/excel-streaming-reader/blob/4e95c9aaaecf33685a09f8c267af3a578ba5e070/src/main/java/com/monitorjbl/xlsx/impl/StreamingSheetReader.java#L265-L289
train
monitorjbl/excel-streaming-reader
src/main/java/com/monitorjbl/xlsx/impl/StreamingSheetReader.java
StreamingSheetReader.getFormatterForType
private Supplier getFormatterForType(String type) { switch(type) { case "s": //string stored in shared table if (!lastContents.isEmpty()) { int idx = Integer.parseInt(lastContents); return new StringSupplier(new XSSFRichTextString(sst.getEntryAt(idx)).toString()); } return new StringSupplier(lastContents); case "inlineStr": //inline string (not in sst) case "str": return new StringSupplier(new XSSFRichTextString(lastContents).toString()); case "e": //error type return new StringSupplier("ERROR: " + lastContents); case "n": //numeric type if(currentCell.getNumericFormat() != null && lastContents.length() > 0) { // the formatRawCellContents operation incurs a significant overhead on large sheets, // and we want to defer the execution of this method until the value is actually needed. // it is not needed in all cases.. final String currentLastContents = lastContents; final int currentNumericFormatIndex = currentCell.getNumericFormatIndex(); final String currentNumericFormat = currentCell.getNumericFormat(); return new Supplier() { String cachedContent; @Override public Object getContent() { if (cachedContent == null) { cachedContent = dataFormatter.formatRawCellContents( Double.parseDouble(currentLastContents), currentNumericFormatIndex, currentNumericFormat); } return cachedContent; } }; } else { return new StringSupplier(lastContents); } default: return new StringSupplier(lastContents); } }
java
private Supplier getFormatterForType(String type) { switch(type) { case "s": //string stored in shared table if (!lastContents.isEmpty()) { int idx = Integer.parseInt(lastContents); return new StringSupplier(new XSSFRichTextString(sst.getEntryAt(idx)).toString()); } return new StringSupplier(lastContents); case "inlineStr": //inline string (not in sst) case "str": return new StringSupplier(new XSSFRichTextString(lastContents).toString()); case "e": //error type return new StringSupplier("ERROR: " + lastContents); case "n": //numeric type if(currentCell.getNumericFormat() != null && lastContents.length() > 0) { // the formatRawCellContents operation incurs a significant overhead on large sheets, // and we want to defer the execution of this method until the value is actually needed. // it is not needed in all cases.. final String currentLastContents = lastContents; final int currentNumericFormatIndex = currentCell.getNumericFormatIndex(); final String currentNumericFormat = currentCell.getNumericFormat(); return new Supplier() { String cachedContent; @Override public Object getContent() { if (cachedContent == null) { cachedContent = dataFormatter.formatRawCellContents( Double.parseDouble(currentLastContents), currentNumericFormatIndex, currentNumericFormat); } return cachedContent; } }; } else { return new StringSupplier(lastContents); } default: return new StringSupplier(lastContents); } }
[ "private", "Supplier", "getFormatterForType", "(", "String", "type", ")", "{", "switch", "(", "type", ")", "{", "case", "\"s\"", ":", "//string stored in shared table", "if", "(", "!", "lastContents", ".", "isEmpty", "(", ")", ")", "{", "int", "idx", "=", "Integer", ".", "parseInt", "(", "lastContents", ")", ";", "return", "new", "StringSupplier", "(", "new", "XSSFRichTextString", "(", "sst", ".", "getEntryAt", "(", "idx", ")", ")", ".", "toString", "(", ")", ")", ";", "}", "return", "new", "StringSupplier", "(", "lastContents", ")", ";", "case", "\"inlineStr\"", ":", "//inline string (not in sst)", "case", "\"str\"", ":", "return", "new", "StringSupplier", "(", "new", "XSSFRichTextString", "(", "lastContents", ")", ".", "toString", "(", ")", ")", ";", "case", "\"e\"", ":", "//error type", "return", "new", "StringSupplier", "(", "\"ERROR: \"", "+", "lastContents", ")", ";", "case", "\"n\"", ":", "//numeric type", "if", "(", "currentCell", ".", "getNumericFormat", "(", ")", "!=", "null", "&&", "lastContents", ".", "length", "(", ")", ">", "0", ")", "{", "// the formatRawCellContents operation incurs a significant overhead on large sheets,", "// and we want to defer the execution of this method until the value is actually needed.", "// it is not needed in all cases..", "final", "String", "currentLastContents", "=", "lastContents", ";", "final", "int", "currentNumericFormatIndex", "=", "currentCell", ".", "getNumericFormatIndex", "(", ")", ";", "final", "String", "currentNumericFormat", "=", "currentCell", ".", "getNumericFormat", "(", ")", ";", "return", "new", "Supplier", "(", ")", "{", "String", "cachedContent", ";", "@", "Override", "public", "Object", "getContent", "(", ")", "{", "if", "(", "cachedContent", "==", "null", ")", "{", "cachedContent", "=", "dataFormatter", ".", "formatRawCellContents", "(", "Double", ".", "parseDouble", "(", "currentLastContents", ")", ",", "currentNumericFormatIndex", ",", "currentNumericFormat", ")", ";", "}", "return", "cachedContent", ";", "}", "}", ";", "}", "else", "{", "return", "new", "StringSupplier", "(", "lastContents", ")", ";", "}", "default", ":", "return", "new", "StringSupplier", "(", "lastContents", ")", ";", "}", "}" ]
Tries to format the contents of the last contents appropriately based on the provided type and the discovered numeric format. @return
[ "Tries", "to", "format", "the", "contents", "of", "the", "last", "contents", "appropriately", "based", "on", "the", "provided", "type", "and", "the", "discovered", "numeric", "format", "." ]
4e95c9aaaecf33685a09f8c267af3a578ba5e070
https://github.com/monitorjbl/excel-streaming-reader/blob/4e95c9aaaecf33685a09f8c267af3a578ba5e070/src/main/java/com/monitorjbl/xlsx/impl/StreamingSheetReader.java#L307-L350
train
monitorjbl/excel-streaming-reader
src/main/java/com/monitorjbl/xlsx/impl/StreamingSheetReader.java
StreamingSheetReader.unformattedContents
String unformattedContents() { switch(currentCell.getType()) { case "s": //string stored in shared table if (!lastContents.isEmpty()) { int idx = Integer.parseInt(lastContents); return new XSSFRichTextString(sst.getEntryAt(idx)).toString(); } return lastContents; case "inlineStr": //inline string (not in sst) return new XSSFRichTextString(lastContents).toString(); default: return lastContents; } }
java
String unformattedContents() { switch(currentCell.getType()) { case "s": //string stored in shared table if (!lastContents.isEmpty()) { int idx = Integer.parseInt(lastContents); return new XSSFRichTextString(sst.getEntryAt(idx)).toString(); } return lastContents; case "inlineStr": //inline string (not in sst) return new XSSFRichTextString(lastContents).toString(); default: return lastContents; } }
[ "String", "unformattedContents", "(", ")", "{", "switch", "(", "currentCell", ".", "getType", "(", ")", ")", "{", "case", "\"s\"", ":", "//string stored in shared table", "if", "(", "!", "lastContents", ".", "isEmpty", "(", ")", ")", "{", "int", "idx", "=", "Integer", ".", "parseInt", "(", "lastContents", ")", ";", "return", "new", "XSSFRichTextString", "(", "sst", ".", "getEntryAt", "(", "idx", ")", ")", ".", "toString", "(", ")", ";", "}", "return", "lastContents", ";", "case", "\"inlineStr\"", ":", "//inline string (not in sst)", "return", "new", "XSSFRichTextString", "(", "lastContents", ")", ".", "toString", "(", ")", ";", "default", ":", "return", "lastContents", ";", "}", "}" ]
Returns the contents of the cell, with no formatting applied @return
[ "Returns", "the", "contents", "of", "the", "cell", "with", "no", "formatting", "applied" ]
4e95c9aaaecf33685a09f8c267af3a578ba5e070
https://github.com/monitorjbl/excel-streaming-reader/blob/4e95c9aaaecf33685a09f8c267af3a578ba5e070/src/main/java/com/monitorjbl/xlsx/impl/StreamingSheetReader.java#L357-L370
train
monitorjbl/excel-streaming-reader
src/main/java/com/monitorjbl/xlsx/impl/StreamingCell.java
StreamingCell.getCellType
@Override public CellType getCellType() { if(formulaType) { return CellType.FORMULA; } else if(contentsSupplier.getContent() == null || type == null) { return CellType.BLANK; } else if("n".equals(type)) { return CellType.NUMERIC; } else if("s".equals(type) || "inlineStr".equals(type) || "str".equals(type)) { return CellType.STRING; } else if("str".equals(type)) { return CellType.FORMULA; } else if("b".equals(type)) { return CellType.BOOLEAN; } else if("e".equals(type)) { return CellType.ERROR; } else { throw new UnsupportedOperationException("Unsupported cell type '" + type + "'"); } }
java
@Override public CellType getCellType() { if(formulaType) { return CellType.FORMULA; } else if(contentsSupplier.getContent() == null || type == null) { return CellType.BLANK; } else if("n".equals(type)) { return CellType.NUMERIC; } else if("s".equals(type) || "inlineStr".equals(type) || "str".equals(type)) { return CellType.STRING; } else if("str".equals(type)) { return CellType.FORMULA; } else if("b".equals(type)) { return CellType.BOOLEAN; } else if("e".equals(type)) { return CellType.ERROR; } else { throw new UnsupportedOperationException("Unsupported cell type '" + type + "'"); } }
[ "@", "Override", "public", "CellType", "getCellType", "(", ")", "{", "if", "(", "formulaType", ")", "{", "return", "CellType", ".", "FORMULA", ";", "}", "else", "if", "(", "contentsSupplier", ".", "getContent", "(", ")", "==", "null", "||", "type", "==", "null", ")", "{", "return", "CellType", ".", "BLANK", ";", "}", "else", "if", "(", "\"n\"", ".", "equals", "(", "type", ")", ")", "{", "return", "CellType", ".", "NUMERIC", ";", "}", "else", "if", "(", "\"s\"", ".", "equals", "(", "type", ")", "||", "\"inlineStr\"", ".", "equals", "(", "type", ")", "||", "\"str\"", ".", "equals", "(", "type", ")", ")", "{", "return", "CellType", ".", "STRING", ";", "}", "else", "if", "(", "\"str\"", ".", "equals", "(", "type", ")", ")", "{", "return", "CellType", ".", "FORMULA", ";", "}", "else", "if", "(", "\"b\"", ".", "equals", "(", "type", ")", ")", "{", "return", "CellType", ".", "BOOLEAN", ";", "}", "else", "if", "(", "\"e\"", ".", "equals", "(", "type", ")", ")", "{", "return", "CellType", ".", "ERROR", ";", "}", "else", "{", "throw", "new", "UnsupportedOperationException", "(", "\"Unsupported cell type '\"", "+", "type", "+", "\"'\"", ")", ";", "}", "}" ]
Return the cell type. @return the cell type
[ "Return", "the", "cell", "type", "." ]
4e95c9aaaecf33685a09f8c267af3a578ba5e070
https://github.com/monitorjbl/excel-streaming-reader/blob/4e95c9aaaecf33685a09f8c267af3a578ba5e070/src/main/java/com/monitorjbl/xlsx/impl/StreamingCell.java#L144-L163
train
monitorjbl/excel-streaming-reader
src/main/java/com/monitorjbl/xlsx/impl/StreamingCell.java
StreamingCell.getStringCellValue
@Override public String getStringCellValue() { Object c = contentsSupplier.getContent(); return c == null ? "" : c.toString(); }
java
@Override public String getStringCellValue() { Object c = contentsSupplier.getContent(); return c == null ? "" : c.toString(); }
[ "@", "Override", "public", "String", "getStringCellValue", "(", ")", "{", "Object", "c", "=", "contentsSupplier", ".", "getContent", "(", ")", ";", "return", "c", "==", "null", "?", "\"\"", ":", "c", ".", "toString", "(", ")", ";", "}" ]
Get the value of the cell as a string. For blank cells we return an empty string. @return the value of the cell as a string
[ "Get", "the", "value", "of", "the", "cell", "as", "a", "string", ".", "For", "blank", "cells", "we", "return", "an", "empty", "string", "." ]
4e95c9aaaecf33685a09f8c267af3a578ba5e070
https://github.com/monitorjbl/excel-streaming-reader/blob/4e95c9aaaecf33685a09f8c267af3a578ba5e070/src/main/java/com/monitorjbl/xlsx/impl/StreamingCell.java#L183-L188
train
monitorjbl/excel-streaming-reader
src/main/java/com/monitorjbl/xlsx/impl/StreamingCell.java
StreamingCell.getDateCellValue
@Override public Date getDateCellValue() { if(getCellType() == CellType.STRING){ throw new IllegalStateException("Cell type cannot be CELL_TYPE_STRING"); } return rawContents == null ? null : HSSFDateUtil.getJavaDate(getNumericCellValue(), use1904Dates); }
java
@Override public Date getDateCellValue() { if(getCellType() == CellType.STRING){ throw new IllegalStateException("Cell type cannot be CELL_TYPE_STRING"); } return rawContents == null ? null : HSSFDateUtil.getJavaDate(getNumericCellValue(), use1904Dates); }
[ "@", "Override", "public", "Date", "getDateCellValue", "(", ")", "{", "if", "(", "getCellType", "(", ")", "==", "CellType", ".", "STRING", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Cell type cannot be CELL_TYPE_STRING\"", ")", ";", "}", "return", "rawContents", "==", "null", "?", "null", ":", "HSSFDateUtil", ".", "getJavaDate", "(", "getNumericCellValue", "(", ")", ",", "use1904Dates", ")", ";", "}" ]
Get the value of the cell as a date. For strings we throw an exception. For blank cells we return a null. @return the value of the cell as a date @throws IllegalStateException if the cell type returned by {@link #getCellType()} is CELL_TYPE_STRING @throws NumberFormatException if the cell value isn't a parsable <code>double</code>.
[ "Get", "the", "value", "of", "the", "cell", "as", "a", "date", ".", "For", "strings", "we", "throw", "an", "exception", ".", "For", "blank", "cells", "we", "return", "a", "null", "." ]
4e95c9aaaecf33685a09f8c267af3a578ba5e070
https://github.com/monitorjbl/excel-streaming-reader/blob/4e95c9aaaecf33685a09f8c267af3a578ba5e070/src/main/java/com/monitorjbl/xlsx/impl/StreamingCell.java#L210-L216
train
monitorjbl/excel-streaming-reader
src/main/java/com/monitorjbl/xlsx/impl/StreamingCell.java
StreamingCell.getBooleanCellValue
@Override public boolean getBooleanCellValue() { CellType cellType = getCellType(); switch(cellType) { case BLANK: return false; case BOOLEAN: return rawContents != null && TRUE_AS_STRING.equals(rawContents); case FORMULA: throw new NotSupportedException(); default: throw typeMismatch(CellType.BOOLEAN, cellType, false); } }
java
@Override public boolean getBooleanCellValue() { CellType cellType = getCellType(); switch(cellType) { case BLANK: return false; case BOOLEAN: return rawContents != null && TRUE_AS_STRING.equals(rawContents); case FORMULA: throw new NotSupportedException(); default: throw typeMismatch(CellType.BOOLEAN, cellType, false); } }
[ "@", "Override", "public", "boolean", "getBooleanCellValue", "(", ")", "{", "CellType", "cellType", "=", "getCellType", "(", ")", ";", "switch", "(", "cellType", ")", "{", "case", "BLANK", ":", "return", "false", ";", "case", "BOOLEAN", ":", "return", "rawContents", "!=", "null", "&&", "TRUE_AS_STRING", ".", "equals", "(", "rawContents", ")", ";", "case", "FORMULA", ":", "throw", "new", "NotSupportedException", "(", ")", ";", "default", ":", "throw", "typeMismatch", "(", "CellType", ".", "BOOLEAN", ",", "cellType", ",", "false", ")", ";", "}", "}" ]
Get the value of the cell as a boolean. For strings we throw an exception. For blank cells we return a false. @return the value of the cell as a date
[ "Get", "the", "value", "of", "the", "cell", "as", "a", "boolean", ".", "For", "strings", "we", "throw", "an", "exception", ".", "For", "blank", "cells", "we", "return", "a", "false", "." ]
4e95c9aaaecf33685a09f8c267af3a578ba5e070
https://github.com/monitorjbl/excel-streaming-reader/blob/4e95c9aaaecf33685a09f8c267af3a578ba5e070/src/main/java/com/monitorjbl/xlsx/impl/StreamingCell.java#L224-L237
train
monitorjbl/excel-streaming-reader
src/main/java/com/monitorjbl/xlsx/impl/StreamingCell.java
StreamingCell.getCellTypeName
private static String getCellTypeName(CellType cellType) { switch (cellType) { case BLANK: return "blank"; case STRING: return "text"; case BOOLEAN: return "boolean"; case ERROR: return "error"; case NUMERIC: return "numeric"; case FORMULA: return "formula"; } return "#unknown cell type (" + cellType + ")#"; }
java
private static String getCellTypeName(CellType cellType) { switch (cellType) { case BLANK: return "blank"; case STRING: return "text"; case BOOLEAN: return "boolean"; case ERROR: return "error"; case NUMERIC: return "numeric"; case FORMULA: return "formula"; } return "#unknown cell type (" + cellType + ")#"; }
[ "private", "static", "String", "getCellTypeName", "(", "CellType", "cellType", ")", "{", "switch", "(", "cellType", ")", "{", "case", "BLANK", ":", "return", "\"blank\"", ";", "case", "STRING", ":", "return", "\"text\"", ";", "case", "BOOLEAN", ":", "return", "\"boolean\"", ";", "case", "ERROR", ":", "return", "\"error\"", ";", "case", "NUMERIC", ":", "return", "\"numeric\"", ";", "case", "FORMULA", ":", "return", "\"formula\"", ";", "}", "return", "\"#unknown cell type (\"", "+", "cellType", "+", "\")#\"", ";", "}" ]
Used to help format error messages
[ "Used", "to", "help", "format", "error", "messages" ]
4e95c9aaaecf33685a09f8c267af3a578ba5e070
https://github.com/monitorjbl/excel-streaming-reader/blob/4e95c9aaaecf33685a09f8c267af3a578ba5e070/src/main/java/com/monitorjbl/xlsx/impl/StreamingCell.java#L249-L259
train
monitorjbl/excel-streaming-reader
src/main/java/com/monitorjbl/xlsx/impl/StreamingCell.java
StreamingCell.getCachedFormulaResultType
@Override public CellType getCachedFormulaResultType() { if (formulaType) { if(contentsSupplier.getContent() == null || type == null) { return CellType.BLANK; } else if("n".equals(type)) { return CellType.NUMERIC; } else if("s".equals(type) || "inlineStr".equals(type) || "str".equals(type)) { return CellType.STRING; } else if("b".equals(type)) { return CellType.BOOLEAN; } else if("e".equals(type)) { return CellType.ERROR; } else { throw new UnsupportedOperationException("Unsupported cell type '" + type + "'"); } } else { throw new IllegalStateException("Only formula cells have cached results"); } }
java
@Override public CellType getCachedFormulaResultType() { if (formulaType) { if(contentsSupplier.getContent() == null || type == null) { return CellType.BLANK; } else if("n".equals(type)) { return CellType.NUMERIC; } else if("s".equals(type) || "inlineStr".equals(type) || "str".equals(type)) { return CellType.STRING; } else if("b".equals(type)) { return CellType.BOOLEAN; } else if("e".equals(type)) { return CellType.ERROR; } else { throw new UnsupportedOperationException("Unsupported cell type '" + type + "'"); } } else { throw new IllegalStateException("Only formula cells have cached results"); } }
[ "@", "Override", "public", "CellType", "getCachedFormulaResultType", "(", ")", "{", "if", "(", "formulaType", ")", "{", "if", "(", "contentsSupplier", ".", "getContent", "(", ")", "==", "null", "||", "type", "==", "null", ")", "{", "return", "CellType", ".", "BLANK", ";", "}", "else", "if", "(", "\"n\"", ".", "equals", "(", "type", ")", ")", "{", "return", "CellType", ".", "NUMERIC", ";", "}", "else", "if", "(", "\"s\"", ".", "equals", "(", "type", ")", "||", "\"inlineStr\"", ".", "equals", "(", "type", ")", "||", "\"str\"", ".", "equals", "(", "type", ")", ")", "{", "return", "CellType", ".", "STRING", ";", "}", "else", "if", "(", "\"b\"", ".", "equals", "(", "type", ")", ")", "{", "return", "CellType", ".", "BOOLEAN", ";", "}", "else", "if", "(", "\"e\"", ".", "equals", "(", "type", ")", ")", "{", "return", "CellType", ".", "ERROR", ";", "}", "else", "{", "throw", "new", "UnsupportedOperationException", "(", "\"Unsupported cell type '\"", "+", "type", "+", "\"'\"", ")", ";", "}", "}", "else", "{", "throw", "new", "IllegalStateException", "(", "\"Only formula cells have cached results\"", ")", ";", "}", "}" ]
Only valid for formula cells @return one of ({@link CellType#NUMERIC}, {@link CellType#STRING}, {@link CellType#BOOLEAN}, {@link CellType#ERROR}) depending on the cached value of the formula
[ "Only", "valid", "for", "formula", "cells" ]
4e95c9aaaecf33685a09f8c267af3a578ba5e070
https://github.com/monitorjbl/excel-streaming-reader/blob/4e95c9aaaecf33685a09f8c267af3a578ba5e070/src/main/java/com/monitorjbl/xlsx/impl/StreamingCell.java#L288-L307
train
monitorjbl/excel-streaming-reader
src/main/java/com/monitorjbl/xlsx/StreamingReader.java
StreamingReader.close
@Override public void close() throws IOException { try { workbook.close(); } finally { if(tmp != null) { if (log.isDebugEnabled()) { log.debug("Deleting tmp file [" + tmp.getAbsolutePath() + "]"); } tmp.delete(); } } }
java
@Override public void close() throws IOException { try { workbook.close(); } finally { if(tmp != null) { if (log.isDebugEnabled()) { log.debug("Deleting tmp file [" + tmp.getAbsolutePath() + "]"); } tmp.delete(); } } }
[ "@", "Override", "public", "void", "close", "(", ")", "throws", "IOException", "{", "try", "{", "workbook", ".", "close", "(", ")", ";", "}", "finally", "{", "if", "(", "tmp", "!=", "null", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Deleting tmp file [\"", "+", "tmp", ".", "getAbsolutePath", "(", ")", "+", "\"]\"", ")", ";", "}", "tmp", ".", "delete", "(", ")", ";", "}", "}", "}" ]
Closes the streaming resource, attempting to clean up any temporary files created. @throws com.monitorjbl.xlsx.exceptions.CloseException if there is an issue closing the stream
[ "Closes", "the", "streaming", "resource", "attempting", "to", "clean", "up", "any", "temporary", "files", "created", "." ]
4e95c9aaaecf33685a09f8c267af3a578ba5e070
https://github.com/monitorjbl/excel-streaming-reader/blob/4e95c9aaaecf33685a09f8c267af3a578ba5e070/src/main/java/com/monitorjbl/xlsx/StreamingReader.java#L75-L87
train
JoanZapata/android-pdfview
android-pdfview/src/main/java/com/joanzapata/pdfview/CacheManager.java
CacheManager.containsThumbnail
public boolean containsThumbnail(int userPage, int page, float width, float height, RectF pageRelativeBounds) { PagePart fakePart = new PagePart(userPage, page, null, width, height, pageRelativeBounds, true, 0); for (PagePart part : thumbnails) { if (part.equals(fakePart)) { return true; } } return false; }
java
public boolean containsThumbnail(int userPage, int page, float width, float height, RectF pageRelativeBounds) { PagePart fakePart = new PagePart(userPage, page, null, width, height, pageRelativeBounds, true, 0); for (PagePart part : thumbnails) { if (part.equals(fakePart)) { return true; } } return false; }
[ "public", "boolean", "containsThumbnail", "(", "int", "userPage", ",", "int", "page", ",", "float", "width", ",", "float", "height", ",", "RectF", "pageRelativeBounds", ")", "{", "PagePart", "fakePart", "=", "new", "PagePart", "(", "userPage", ",", "page", ",", "null", ",", "width", ",", "height", ",", "pageRelativeBounds", ",", "true", ",", "0", ")", ";", "for", "(", "PagePart", "part", ":", "thumbnails", ")", "{", "if", "(", "part", ".", "equals", "(", "fakePart", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Return true if already contains the described PagePart
[ "Return", "true", "if", "already", "contains", "the", "described", "PagePart" ]
8f239bb91ab56ff3066739dc44bccf8b1753b0ba
https://github.com/JoanZapata/android-pdfview/blob/8f239bb91ab56ff3066739dc44bccf8b1753b0ba/android-pdfview/src/main/java/com/joanzapata/pdfview/CacheManager.java#L99-L107
train
JoanZapata/android-pdfview
android-pdfview/src/main/java/com/joanzapata/pdfview/util/DragPinchListener.java
DragPinchListener.distance
private float distance(MotionEvent event) { if (event.getPointerCount() < 2) { return 0; } return PointF.length(event.getX(POINTER1) - event.getX(POINTER2), // event.getY(POINTER1) - event.getY(POINTER2)); }
java
private float distance(MotionEvent event) { if (event.getPointerCount() < 2) { return 0; } return PointF.length(event.getX(POINTER1) - event.getX(POINTER2), // event.getY(POINTER1) - event.getY(POINTER2)); }
[ "private", "float", "distance", "(", "MotionEvent", "event", ")", "{", "if", "(", "event", ".", "getPointerCount", "(", ")", "<", "2", ")", "{", "return", "0", ";", "}", "return", "PointF", ".", "length", "(", "event", ".", "getX", "(", "POINTER1", ")", "-", "event", ".", "getX", "(", "POINTER2", ")", ",", "//\r", "event", ".", "getY", "(", "POINTER1", ")", "-", "event", ".", "getY", "(", "POINTER2", ")", ")", ";", "}" ]
Calculates the distance between the 2 current pointers
[ "Calculates", "the", "distance", "between", "the", "2", "current", "pointers" ]
8f239bb91ab56ff3066739dc44bccf8b1753b0ba
https://github.com/JoanZapata/android-pdfview/blob/8f239bb91ab56ff3066739dc44bccf8b1753b0ba/android-pdfview/src/main/java/com/joanzapata/pdfview/util/DragPinchListener.java#L256-L262
train
JoanZapata/android-pdfview
android-pdfview/src/main/java/com/joanzapata/pdfview/util/DragPinchListener.java
DragPinchListener.isClick
private boolean isClick(MotionEvent upEvent, float xDown, float yDown, float xUp, float yUp) { if (upEvent == null) return false; long time = upEvent.getEventTime() - upEvent.getDownTime(); float distance = PointF.length( // xDown - xUp, // yDown - yUp); return time < MAX_CLICK_TIME && distance < MAX_CLICK_DISTANCE; }
java
private boolean isClick(MotionEvent upEvent, float xDown, float yDown, float xUp, float yUp) { if (upEvent == null) return false; long time = upEvent.getEventTime() - upEvent.getDownTime(); float distance = PointF.length( // xDown - xUp, // yDown - yUp); return time < MAX_CLICK_TIME && distance < MAX_CLICK_DISTANCE; }
[ "private", "boolean", "isClick", "(", "MotionEvent", "upEvent", ",", "float", "xDown", ",", "float", "yDown", ",", "float", "xUp", ",", "float", "yUp", ")", "{", "if", "(", "upEvent", "==", "null", ")", "return", "false", ";", "long", "time", "=", "upEvent", ".", "getEventTime", "(", ")", "-", "upEvent", ".", "getDownTime", "(", ")", ";", "float", "distance", "=", "PointF", ".", "length", "(", "//\r", "xDown", "-", "xUp", ",", "//\r", "yDown", "-", "yUp", ")", ";", "return", "time", "<", "MAX_CLICK_TIME", "&&", "distance", "<", "MAX_CLICK_DISTANCE", ";", "}" ]
Test if a MotionEvent with the given start and end offsets can be considered as a "click". @param upEvent The final finger-up event. @param xDown The x-offset of the down event. @param yDown The y-offset of the down event. @param xUp The x-offset of the up event. @param yUp The y-offset of the up event. @return true if it's a click, false otherwise
[ "Test", "if", "a", "MotionEvent", "with", "the", "given", "start", "and", "end", "offsets", "can", "be", "considered", "as", "a", "click", "." ]
8f239bb91ab56ff3066739dc44bccf8b1753b0ba
https://github.com/JoanZapata/android-pdfview/blob/8f239bb91ab56ff3066739dc44bccf8b1753b0ba/android-pdfview/src/main/java/com/joanzapata/pdfview/util/DragPinchListener.java#L274-L281
train
JoanZapata/android-pdfview
android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java
PDFView.drawPart
private void drawPart(Canvas canvas, PagePart part) { // Can seem strange, but avoid lot of calls RectF pageRelativeBounds = part.getPageRelativeBounds(); Bitmap renderedBitmap = part.getRenderedBitmap(); // Move to the target page float localTranslationX = 0; float localTranslationY = 0; if (swipeVertical) localTranslationY = toCurrentScale(part.getUserPage() * optimalPageHeight); else localTranslationX = toCurrentScale(part.getUserPage() * optimalPageWidth); canvas.translate(localTranslationX, localTranslationY); Rect srcRect = new Rect(0, 0, renderedBitmap.getWidth(), // renderedBitmap.getHeight()); float offsetX = toCurrentScale(pageRelativeBounds.left * optimalPageWidth); float offsetY = toCurrentScale(pageRelativeBounds.top * optimalPageHeight); float width = toCurrentScale(pageRelativeBounds.width() * optimalPageWidth); float height = toCurrentScale(pageRelativeBounds.height() * optimalPageHeight); // If we use float values for this rectangle, there will be // a possible gap between page parts, especially when // the zoom level is high. RectF dstRect = new RectF((int) offsetX, (int) offsetY, // (int) (offsetX + width), // (int) (offsetY + height)); // Check if bitmap is in the screen float translationX = currentXOffset + localTranslationX; float translationY = currentYOffset + localTranslationY; if (translationX + dstRect.left >= getWidth() || translationX + dstRect.right <= 0 || translationY + dstRect.top >= getHeight() || translationY + dstRect.bottom <= 0) { canvas.translate(-localTranslationX, -localTranslationY); return; } canvas.drawBitmap(renderedBitmap, srcRect, dstRect, paint); if (Constants.DEBUG_MODE) { debugPaint.setColor(part.getUserPage() % 2 == 0 ? Color.RED : Color.BLUE); canvas.drawRect(dstRect, debugPaint); } // Restore the canvas position canvas.translate(-localTranslationX, -localTranslationY); }
java
private void drawPart(Canvas canvas, PagePart part) { // Can seem strange, but avoid lot of calls RectF pageRelativeBounds = part.getPageRelativeBounds(); Bitmap renderedBitmap = part.getRenderedBitmap(); // Move to the target page float localTranslationX = 0; float localTranslationY = 0; if (swipeVertical) localTranslationY = toCurrentScale(part.getUserPage() * optimalPageHeight); else localTranslationX = toCurrentScale(part.getUserPage() * optimalPageWidth); canvas.translate(localTranslationX, localTranslationY); Rect srcRect = new Rect(0, 0, renderedBitmap.getWidth(), // renderedBitmap.getHeight()); float offsetX = toCurrentScale(pageRelativeBounds.left * optimalPageWidth); float offsetY = toCurrentScale(pageRelativeBounds.top * optimalPageHeight); float width = toCurrentScale(pageRelativeBounds.width() * optimalPageWidth); float height = toCurrentScale(pageRelativeBounds.height() * optimalPageHeight); // If we use float values for this rectangle, there will be // a possible gap between page parts, especially when // the zoom level is high. RectF dstRect = new RectF((int) offsetX, (int) offsetY, // (int) (offsetX + width), // (int) (offsetY + height)); // Check if bitmap is in the screen float translationX = currentXOffset + localTranslationX; float translationY = currentYOffset + localTranslationY; if (translationX + dstRect.left >= getWidth() || translationX + dstRect.right <= 0 || translationY + dstRect.top >= getHeight() || translationY + dstRect.bottom <= 0) { canvas.translate(-localTranslationX, -localTranslationY); return; } canvas.drawBitmap(renderedBitmap, srcRect, dstRect, paint); if (Constants.DEBUG_MODE) { debugPaint.setColor(part.getUserPage() % 2 == 0 ? Color.RED : Color.BLUE); canvas.drawRect(dstRect, debugPaint); } // Restore the canvas position canvas.translate(-localTranslationX, -localTranslationY); }
[ "private", "void", "drawPart", "(", "Canvas", "canvas", ",", "PagePart", "part", ")", "{", "// Can seem strange, but avoid lot of calls\r", "RectF", "pageRelativeBounds", "=", "part", ".", "getPageRelativeBounds", "(", ")", ";", "Bitmap", "renderedBitmap", "=", "part", ".", "getRenderedBitmap", "(", ")", ";", "// Move to the target page\r", "float", "localTranslationX", "=", "0", ";", "float", "localTranslationY", "=", "0", ";", "if", "(", "swipeVertical", ")", "localTranslationY", "=", "toCurrentScale", "(", "part", ".", "getUserPage", "(", ")", "*", "optimalPageHeight", ")", ";", "else", "localTranslationX", "=", "toCurrentScale", "(", "part", ".", "getUserPage", "(", ")", "*", "optimalPageWidth", ")", ";", "canvas", ".", "translate", "(", "localTranslationX", ",", "localTranslationY", ")", ";", "Rect", "srcRect", "=", "new", "Rect", "(", "0", ",", "0", ",", "renderedBitmap", ".", "getWidth", "(", ")", ",", "//\r", "renderedBitmap", ".", "getHeight", "(", ")", ")", ";", "float", "offsetX", "=", "toCurrentScale", "(", "pageRelativeBounds", ".", "left", "*", "optimalPageWidth", ")", ";", "float", "offsetY", "=", "toCurrentScale", "(", "pageRelativeBounds", ".", "top", "*", "optimalPageHeight", ")", ";", "float", "width", "=", "toCurrentScale", "(", "pageRelativeBounds", ".", "width", "(", ")", "*", "optimalPageWidth", ")", ";", "float", "height", "=", "toCurrentScale", "(", "pageRelativeBounds", ".", "height", "(", ")", "*", "optimalPageHeight", ")", ";", "// If we use float values for this rectangle, there will be\r", "// a possible gap between page parts, especially when\r", "// the zoom level is high.\r", "RectF", "dstRect", "=", "new", "RectF", "(", "(", "int", ")", "offsetX", ",", "(", "int", ")", "offsetY", ",", "//\r", "(", "int", ")", "(", "offsetX", "+", "width", ")", ",", "//\r", "(", "int", ")", "(", "offsetY", "+", "height", ")", ")", ";", "// Check if bitmap is in the screen\r", "float", "translationX", "=", "currentXOffset", "+", "localTranslationX", ";", "float", "translationY", "=", "currentYOffset", "+", "localTranslationY", ";", "if", "(", "translationX", "+", "dstRect", ".", "left", ">=", "getWidth", "(", ")", "||", "translationX", "+", "dstRect", ".", "right", "<=", "0", "||", "translationY", "+", "dstRect", ".", "top", ">=", "getHeight", "(", ")", "||", "translationY", "+", "dstRect", ".", "bottom", "<=", "0", ")", "{", "canvas", ".", "translate", "(", "-", "localTranslationX", ",", "-", "localTranslationY", ")", ";", "return", ";", "}", "canvas", ".", "drawBitmap", "(", "renderedBitmap", ",", "srcRect", ",", "dstRect", ",", "paint", ")", ";", "if", "(", "Constants", ".", "DEBUG_MODE", ")", "{", "debugPaint", ".", "setColor", "(", "part", ".", "getUserPage", "(", ")", "%", "2", "==", "0", "?", "Color", ".", "RED", ":", "Color", ".", "BLUE", ")", ";", "canvas", ".", "drawRect", "(", "dstRect", ",", "debugPaint", ")", ";", "}", "// Restore the canvas position\r", "canvas", ".", "translate", "(", "-", "localTranslationX", ",", "-", "localTranslationY", ")", ";", "}" ]
Draw a given PagePart on the canvas
[ "Draw", "a", "given", "PagePart", "on", "the", "canvas" ]
8f239bb91ab56ff3066739dc44bccf8b1753b0ba
https://github.com/JoanZapata/android-pdfview/blob/8f239bb91ab56ff3066739dc44bccf8b1753b0ba/android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java#L414-L462
train
JoanZapata/android-pdfview
android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java
PDFView.loadPages
public void loadPages() { if (optimalPageWidth == 0 || optimalPageHeight == 0) { return; } // Cancel all current tasks renderingAsyncTask.removeAllTasks(); cacheManager.makeANewSet(); // Find current index in filtered user pages int index = currentPage; if (filteredUserPageIndexes != null) { index = filteredUserPageIndexes[currentPage]; } // Loop through the pages like [...][4][2][0][1][3][...] // loading as many parts as it can. int parts = 0; for (int i = 0; i <= Constants.LOADED_SIZE / 2 && parts < CACHE_SIZE; i++) { parts += loadPage(index + i, CACHE_SIZE - parts); if (i != 0 && parts < CACHE_SIZE) { parts += loadPage(index - i, CACHE_SIZE - parts); } } invalidate(); }
java
public void loadPages() { if (optimalPageWidth == 0 || optimalPageHeight == 0) { return; } // Cancel all current tasks renderingAsyncTask.removeAllTasks(); cacheManager.makeANewSet(); // Find current index in filtered user pages int index = currentPage; if (filteredUserPageIndexes != null) { index = filteredUserPageIndexes[currentPage]; } // Loop through the pages like [...][4][2][0][1][3][...] // loading as many parts as it can. int parts = 0; for (int i = 0; i <= Constants.LOADED_SIZE / 2 && parts < CACHE_SIZE; i++) { parts += loadPage(index + i, CACHE_SIZE - parts); if (i != 0 && parts < CACHE_SIZE) { parts += loadPage(index - i, CACHE_SIZE - parts); } } invalidate(); }
[ "public", "void", "loadPages", "(", ")", "{", "if", "(", "optimalPageWidth", "==", "0", "||", "optimalPageHeight", "==", "0", ")", "{", "return", ";", "}", "// Cancel all current tasks\r", "renderingAsyncTask", ".", "removeAllTasks", "(", ")", ";", "cacheManager", ".", "makeANewSet", "(", ")", ";", "// Find current index in filtered user pages\r", "int", "index", "=", "currentPage", ";", "if", "(", "filteredUserPageIndexes", "!=", "null", ")", "{", "index", "=", "filteredUserPageIndexes", "[", "currentPage", "]", ";", "}", "// Loop through the pages like [...][4][2][0][1][3][...]\r", "// loading as many parts as it can.\r", "int", "parts", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<=", "Constants", ".", "LOADED_SIZE", "/", "2", "&&", "parts", "<", "CACHE_SIZE", ";", "i", "++", ")", "{", "parts", "+=", "loadPage", "(", "index", "+", "i", ",", "CACHE_SIZE", "-", "parts", ")", ";", "if", "(", "i", "!=", "0", "&&", "parts", "<", "CACHE_SIZE", ")", "{", "parts", "+=", "loadPage", "(", "index", "-", "i", ",", "CACHE_SIZE", "-", "parts", ")", ";", "}", "}", "invalidate", "(", ")", ";", "}" ]
Load all the parts around the center of the screen, taking into account X and Y offsets, zoom level, and the current page displayed
[ "Load", "all", "the", "parts", "around", "the", "center", "of", "the", "screen", "taking", "into", "account", "X", "and", "Y", "offsets", "zoom", "level", "and", "the", "current", "page", "displayed" ]
8f239bb91ab56ff3066739dc44bccf8b1753b0ba
https://github.com/JoanZapata/android-pdfview/blob/8f239bb91ab56ff3066739dc44bccf8b1753b0ba/android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java#L474-L500
train
JoanZapata/android-pdfview
android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java
PDFView.loadComplete
public void loadComplete(DecodeService decodeService) { this.decodeService = decodeService; this.documentPageCount = decodeService.getPageCount(); // We assume all the pages are the same size this.pageWidth = decodeService.getPageWidth(0); this.pageHeight = decodeService.getPageHeight(0); state = State.LOADED; calculateOptimalWidthAndHeight(); // Notify the listener jumpTo(defaultPage); if (onLoadCompleteListener != null) { onLoadCompleteListener.loadComplete(documentPageCount); } }
java
public void loadComplete(DecodeService decodeService) { this.decodeService = decodeService; this.documentPageCount = decodeService.getPageCount(); // We assume all the pages are the same size this.pageWidth = decodeService.getPageWidth(0); this.pageHeight = decodeService.getPageHeight(0); state = State.LOADED; calculateOptimalWidthAndHeight(); // Notify the listener jumpTo(defaultPage); if (onLoadCompleteListener != null) { onLoadCompleteListener.loadComplete(documentPageCount); } }
[ "public", "void", "loadComplete", "(", "DecodeService", "decodeService", ")", "{", "this", ".", "decodeService", "=", "decodeService", ";", "this", ".", "documentPageCount", "=", "decodeService", ".", "getPageCount", "(", ")", ";", "// We assume all the pages are the same size\r", "this", ".", "pageWidth", "=", "decodeService", ".", "getPageWidth", "(", "0", ")", ";", "this", ".", "pageHeight", "=", "decodeService", ".", "getPageHeight", "(", "0", ")", ";", "state", "=", "State", ".", "LOADED", ";", "calculateOptimalWidthAndHeight", "(", ")", ";", "// Notify the listener\r", "jumpTo", "(", "defaultPage", ")", ";", "if", "(", "onLoadCompleteListener", "!=", "null", ")", "{", "onLoadCompleteListener", ".", "loadComplete", "(", "documentPageCount", ")", ";", "}", "}" ]
Called when the PDF is loaded
[ "Called", "when", "the", "PDF", "is", "loaded" ]
8f239bb91ab56ff3066739dc44bccf8b1753b0ba
https://github.com/JoanZapata/android-pdfview/blob/8f239bb91ab56ff3066739dc44bccf8b1753b0ba/android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java#L643-L658
train
JoanZapata/android-pdfview
android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java
PDFView.onBitmapRendered
public void onBitmapRendered(PagePart part) { if (part.isThumbnail()) { cacheManager.cacheThumbnail(part); } else { cacheManager.cachePart(part); } invalidate(); }
java
public void onBitmapRendered(PagePart part) { if (part.isThumbnail()) { cacheManager.cacheThumbnail(part); } else { cacheManager.cachePart(part); } invalidate(); }
[ "public", "void", "onBitmapRendered", "(", "PagePart", "part", ")", "{", "if", "(", "part", ".", "isThumbnail", "(", ")", ")", "{", "cacheManager", ".", "cacheThumbnail", "(", "part", ")", ";", "}", "else", "{", "cacheManager", ".", "cachePart", "(", "part", ")", ";", "}", "invalidate", "(", ")", ";", "}" ]
Called when a rendering task is over and a PagePart has been freshly created. @param part The created PagePart.
[ "Called", "when", "a", "rendering", "task", "is", "over", "and", "a", "PagePart", "has", "been", "freshly", "created", "." ]
8f239bb91ab56ff3066739dc44bccf8b1753b0ba
https://github.com/JoanZapata/android-pdfview/blob/8f239bb91ab56ff3066739dc44bccf8b1753b0ba/android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java#L665-L672
train
JoanZapata/android-pdfview
android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java
PDFView.determineValidPageNumberFrom
private int determineValidPageNumberFrom(int userPage) { if (userPage <= 0) { return 0; } if (originalUserPages != null) { if (userPage >= originalUserPages.length) { return originalUserPages.length - 1; } } else { if (userPage >= documentPageCount) { return documentPageCount - 1; } } return userPage; }
java
private int determineValidPageNumberFrom(int userPage) { if (userPage <= 0) { return 0; } if (originalUserPages != null) { if (userPage >= originalUserPages.length) { return originalUserPages.length - 1; } } else { if (userPage >= documentPageCount) { return documentPageCount - 1; } } return userPage; }
[ "private", "int", "determineValidPageNumberFrom", "(", "int", "userPage", ")", "{", "if", "(", "userPage", "<=", "0", ")", "{", "return", "0", ";", "}", "if", "(", "originalUserPages", "!=", "null", ")", "{", "if", "(", "userPage", ">=", "originalUserPages", ".", "length", ")", "{", "return", "originalUserPages", ".", "length", "-", "1", ";", "}", "}", "else", "{", "if", "(", "userPage", ">=", "documentPageCount", ")", "{", "return", "documentPageCount", "-", "1", ";", "}", "}", "return", "userPage", ";", "}" ]
Given the UserPage number, this method restrict it to be sure it's an existing page. It takes care of using the user defined pages if any. @param userPage A page number. @return A restricted valid page number (example : -2 => 0)
[ "Given", "the", "UserPage", "number", "this", "method", "restrict", "it", "to", "be", "sure", "it", "s", "an", "existing", "page", ".", "It", "takes", "care", "of", "using", "the", "user", "defined", "pages", "if", "any", "." ]
8f239bb91ab56ff3066739dc44bccf8b1753b0ba
https://github.com/JoanZapata/android-pdfview/blob/8f239bb91ab56ff3066739dc44bccf8b1753b0ba/android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java#L681-L695
train
JoanZapata/android-pdfview
android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java
PDFView.calculateOptimalWidthAndHeight
private void calculateOptimalWidthAndHeight() { if (state == State.DEFAULT || getWidth() == 0) { return; } float maxWidth = getWidth(), maxHeight = getHeight(); float w = pageWidth, h = pageHeight; float ratio = w / h; w = maxWidth; h = (float) Math.floor(maxWidth / ratio); if (h > maxHeight) { h = maxHeight; w = (float) Math.floor(maxHeight * ratio); } optimalPageWidth = w; optimalPageHeight = h; calculateMasksBounds(); calculateMinimapBounds(); }
java
private void calculateOptimalWidthAndHeight() { if (state == State.DEFAULT || getWidth() == 0) { return; } float maxWidth = getWidth(), maxHeight = getHeight(); float w = pageWidth, h = pageHeight; float ratio = w / h; w = maxWidth; h = (float) Math.floor(maxWidth / ratio); if (h > maxHeight) { h = maxHeight; w = (float) Math.floor(maxHeight * ratio); } optimalPageWidth = w; optimalPageHeight = h; calculateMasksBounds(); calculateMinimapBounds(); }
[ "private", "void", "calculateOptimalWidthAndHeight", "(", ")", "{", "if", "(", "state", "==", "State", ".", "DEFAULT", "||", "getWidth", "(", ")", "==", "0", ")", "{", "return", ";", "}", "float", "maxWidth", "=", "getWidth", "(", ")", ",", "maxHeight", "=", "getHeight", "(", ")", ";", "float", "w", "=", "pageWidth", ",", "h", "=", "pageHeight", ";", "float", "ratio", "=", "w", "/", "h", ";", "w", "=", "maxWidth", ";", "h", "=", "(", "float", ")", "Math", ".", "floor", "(", "maxWidth", "/", "ratio", ")", ";", "if", "(", "h", ">", "maxHeight", ")", "{", "h", "=", "maxHeight", ";", "w", "=", "(", "float", ")", "Math", ".", "floor", "(", "maxHeight", "*", "ratio", ")", ";", "}", "optimalPageWidth", "=", "w", ";", "optimalPageHeight", "=", "h", ";", "calculateMasksBounds", "(", ")", ";", "calculateMinimapBounds", "(", ")", ";", "}" ]
Calculate the optimal width and height of a page considering the area width and height
[ "Calculate", "the", "optimal", "width", "and", "height", "of", "a", "page", "considering", "the", "area", "width", "and", "height" ]
8f239bb91ab56ff3066739dc44bccf8b1753b0ba
https://github.com/JoanZapata/android-pdfview/blob/8f239bb91ab56ff3066739dc44bccf8b1753b0ba/android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java#L720-L740
train
JoanZapata/android-pdfview
android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java
PDFView.calculateMinimapBounds
private void calculateMinimapBounds() { float ratioX = Constants.MINIMAP_MAX_SIZE / optimalPageWidth; float ratioY = Constants.MINIMAP_MAX_SIZE / optimalPageHeight; float ratio = Math.min(ratioX, ratioY); float minimapWidth = optimalPageWidth * ratio; float minimapHeight = optimalPageHeight * ratio; minimapBounds = new RectF(getWidth() - 5 - minimapWidth, 5, getWidth() - 5, 5 + minimapHeight); calculateMinimapAreaBounds(); }
java
private void calculateMinimapBounds() { float ratioX = Constants.MINIMAP_MAX_SIZE / optimalPageWidth; float ratioY = Constants.MINIMAP_MAX_SIZE / optimalPageHeight; float ratio = Math.min(ratioX, ratioY); float minimapWidth = optimalPageWidth * ratio; float minimapHeight = optimalPageHeight * ratio; minimapBounds = new RectF(getWidth() - 5 - minimapWidth, 5, getWidth() - 5, 5 + minimapHeight); calculateMinimapAreaBounds(); }
[ "private", "void", "calculateMinimapBounds", "(", ")", "{", "float", "ratioX", "=", "Constants", ".", "MINIMAP_MAX_SIZE", "/", "optimalPageWidth", ";", "float", "ratioY", "=", "Constants", ".", "MINIMAP_MAX_SIZE", "/", "optimalPageHeight", ";", "float", "ratio", "=", "Math", ".", "min", "(", "ratioX", ",", "ratioY", ")", ";", "float", "minimapWidth", "=", "optimalPageWidth", "*", "ratio", ";", "float", "minimapHeight", "=", "optimalPageHeight", "*", "ratio", ";", "minimapBounds", "=", "new", "RectF", "(", "getWidth", "(", ")", "-", "5", "-", "minimapWidth", ",", "5", ",", "getWidth", "(", ")", "-", "5", ",", "5", "+", "minimapHeight", ")", ";", "calculateMinimapAreaBounds", "(", ")", ";", "}" ]
Place the minimap background considering the optimal width and height and the MINIMAP_MAX_SIZE.
[ "Place", "the", "minimap", "background", "considering", "the", "optimal", "width", "and", "height", "and", "the", "MINIMAP_MAX_SIZE", "." ]
8f239bb91ab56ff3066739dc44bccf8b1753b0ba
https://github.com/JoanZapata/android-pdfview/blob/8f239bb91ab56ff3066739dc44bccf8b1753b0ba/android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java#L746-L754
train
JoanZapata/android-pdfview
android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java
PDFView.calculateMasksBounds
private void calculateMasksBounds() { leftMask = new RectF(0, 0, getWidth() / 2 - toCurrentScale(optimalPageWidth) / 2, getHeight()); rightMask = new RectF(getWidth() / 2 + toCurrentScale(optimalPageWidth) / 2, 0, getWidth(), getHeight()); }
java
private void calculateMasksBounds() { leftMask = new RectF(0, 0, getWidth() / 2 - toCurrentScale(optimalPageWidth) / 2, getHeight()); rightMask = new RectF(getWidth() / 2 + toCurrentScale(optimalPageWidth) / 2, 0, getWidth(), getHeight()); }
[ "private", "void", "calculateMasksBounds", "(", ")", "{", "leftMask", "=", "new", "RectF", "(", "0", ",", "0", ",", "getWidth", "(", ")", "/", "2", "-", "toCurrentScale", "(", "optimalPageWidth", ")", "/", "2", ",", "getHeight", "(", ")", ")", ";", "rightMask", "=", "new", "RectF", "(", "getWidth", "(", ")", "/", "2", "+", "toCurrentScale", "(", "optimalPageWidth", ")", "/", "2", ",", "0", ",", "getWidth", "(", ")", ",", "getHeight", "(", ")", ")", ";", "}" ]
Place the left and right masks around the current page.
[ "Place", "the", "left", "and", "right", "masks", "around", "the", "current", "page", "." ]
8f239bb91ab56ff3066739dc44bccf8b1753b0ba
https://github.com/JoanZapata/android-pdfview/blob/8f239bb91ab56ff3066739dc44bccf8b1753b0ba/android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java#L782-L785
train
JoanZapata/android-pdfview
android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java
PDFView.moveTo
public void moveTo(float offsetX, float offsetY) { if (swipeVertical) { // Check X offset if (toCurrentScale(optimalPageWidth) < getWidth()) { offsetX = getWidth() / 2 - toCurrentScale(optimalPageWidth) / 2; } else { if (offsetX > 0) { offsetX = 0; } else if (offsetX + toCurrentScale(optimalPageWidth) < getWidth()) { offsetX = getWidth() - toCurrentScale(optimalPageWidth); } } // Check Y offset if (isZooming()) { if (toCurrentScale(optimalPageHeight) < getHeight()) { miniMapRequired = false; offsetY = getHeight() / 2 - toCurrentScale((currentFilteredPage + 0.5f) * optimalPageHeight); } else { miniMapRequired = true; if (offsetY + toCurrentScale(currentFilteredPage * optimalPageHeight) > 0) { offsetY = -toCurrentScale(currentFilteredPage * optimalPageHeight); } else if (offsetY + toCurrentScale((currentFilteredPage + 1) * optimalPageHeight) < getHeight()) { offsetY = getHeight() - toCurrentScale((currentFilteredPage + 1) * optimalPageHeight); } } } else { float maxY = calculateCenterOffsetForPage(currentFilteredPage + 1); float minY = calculateCenterOffsetForPage(currentFilteredPage - 1); if (offsetY < maxY) { offsetY = maxY; } else if (offsetY > minY) { offsetY = minY; } } } else { // Check Y offset if (toCurrentScale(optimalPageHeight) < getHeight()) { offsetY = getHeight() / 2 - toCurrentScale(optimalPageHeight) / 2; } else { if (offsetY > 0) { offsetY = 0; } else if (offsetY + toCurrentScale(optimalPageHeight) < getHeight()) { offsetY = getHeight() - toCurrentScale(optimalPageHeight); } } // Check X offset if (isZooming()) { if (toCurrentScale(optimalPageWidth) < getWidth()) { miniMapRequired = false; offsetX = getWidth() / 2 - toCurrentScale((currentFilteredPage + 0.5f) * optimalPageWidth); } else { miniMapRequired = true; if (offsetX + toCurrentScale(currentFilteredPage * optimalPageWidth) > 0) { offsetX = -toCurrentScale(currentFilteredPage * optimalPageWidth); } else if (offsetX + toCurrentScale((currentFilteredPage + 1) * optimalPageWidth) < getWidth()) { offsetX = getWidth() - toCurrentScale((currentFilteredPage + 1) * optimalPageWidth); } } } else { float maxX = calculateCenterOffsetForPage(currentFilteredPage + 1); float minX = calculateCenterOffsetForPage(currentFilteredPage - 1); if (offsetX < maxX) { offsetX = maxX; } else if (offsetX > minX) { offsetX = minX; } } } currentXOffset = offsetX; currentYOffset = offsetY; calculateMinimapAreaBounds(); invalidate(); }
java
public void moveTo(float offsetX, float offsetY) { if (swipeVertical) { // Check X offset if (toCurrentScale(optimalPageWidth) < getWidth()) { offsetX = getWidth() / 2 - toCurrentScale(optimalPageWidth) / 2; } else { if (offsetX > 0) { offsetX = 0; } else if (offsetX + toCurrentScale(optimalPageWidth) < getWidth()) { offsetX = getWidth() - toCurrentScale(optimalPageWidth); } } // Check Y offset if (isZooming()) { if (toCurrentScale(optimalPageHeight) < getHeight()) { miniMapRequired = false; offsetY = getHeight() / 2 - toCurrentScale((currentFilteredPage + 0.5f) * optimalPageHeight); } else { miniMapRequired = true; if (offsetY + toCurrentScale(currentFilteredPage * optimalPageHeight) > 0) { offsetY = -toCurrentScale(currentFilteredPage * optimalPageHeight); } else if (offsetY + toCurrentScale((currentFilteredPage + 1) * optimalPageHeight) < getHeight()) { offsetY = getHeight() - toCurrentScale((currentFilteredPage + 1) * optimalPageHeight); } } } else { float maxY = calculateCenterOffsetForPage(currentFilteredPage + 1); float minY = calculateCenterOffsetForPage(currentFilteredPage - 1); if (offsetY < maxY) { offsetY = maxY; } else if (offsetY > minY) { offsetY = minY; } } } else { // Check Y offset if (toCurrentScale(optimalPageHeight) < getHeight()) { offsetY = getHeight() / 2 - toCurrentScale(optimalPageHeight) / 2; } else { if (offsetY > 0) { offsetY = 0; } else if (offsetY + toCurrentScale(optimalPageHeight) < getHeight()) { offsetY = getHeight() - toCurrentScale(optimalPageHeight); } } // Check X offset if (isZooming()) { if (toCurrentScale(optimalPageWidth) < getWidth()) { miniMapRequired = false; offsetX = getWidth() / 2 - toCurrentScale((currentFilteredPage + 0.5f) * optimalPageWidth); } else { miniMapRequired = true; if (offsetX + toCurrentScale(currentFilteredPage * optimalPageWidth) > 0) { offsetX = -toCurrentScale(currentFilteredPage * optimalPageWidth); } else if (offsetX + toCurrentScale((currentFilteredPage + 1) * optimalPageWidth) < getWidth()) { offsetX = getWidth() - toCurrentScale((currentFilteredPage + 1) * optimalPageWidth); } } } else { float maxX = calculateCenterOffsetForPage(currentFilteredPage + 1); float minX = calculateCenterOffsetForPage(currentFilteredPage - 1); if (offsetX < maxX) { offsetX = maxX; } else if (offsetX > minX) { offsetX = minX; } } } currentXOffset = offsetX; currentYOffset = offsetY; calculateMinimapAreaBounds(); invalidate(); }
[ "public", "void", "moveTo", "(", "float", "offsetX", ",", "float", "offsetY", ")", "{", "if", "(", "swipeVertical", ")", "{", "// Check X offset\r", "if", "(", "toCurrentScale", "(", "optimalPageWidth", ")", "<", "getWidth", "(", ")", ")", "{", "offsetX", "=", "getWidth", "(", ")", "/", "2", "-", "toCurrentScale", "(", "optimalPageWidth", ")", "/", "2", ";", "}", "else", "{", "if", "(", "offsetX", ">", "0", ")", "{", "offsetX", "=", "0", ";", "}", "else", "if", "(", "offsetX", "+", "toCurrentScale", "(", "optimalPageWidth", ")", "<", "getWidth", "(", ")", ")", "{", "offsetX", "=", "getWidth", "(", ")", "-", "toCurrentScale", "(", "optimalPageWidth", ")", ";", "}", "}", "// Check Y offset\r", "if", "(", "isZooming", "(", ")", ")", "{", "if", "(", "toCurrentScale", "(", "optimalPageHeight", ")", "<", "getHeight", "(", ")", ")", "{", "miniMapRequired", "=", "false", ";", "offsetY", "=", "getHeight", "(", ")", "/", "2", "-", "toCurrentScale", "(", "(", "currentFilteredPage", "+", "0.5f", ")", "*", "optimalPageHeight", ")", ";", "}", "else", "{", "miniMapRequired", "=", "true", ";", "if", "(", "offsetY", "+", "toCurrentScale", "(", "currentFilteredPage", "*", "optimalPageHeight", ")", ">", "0", ")", "{", "offsetY", "=", "-", "toCurrentScale", "(", "currentFilteredPage", "*", "optimalPageHeight", ")", ";", "}", "else", "if", "(", "offsetY", "+", "toCurrentScale", "(", "(", "currentFilteredPage", "+", "1", ")", "*", "optimalPageHeight", ")", "<", "getHeight", "(", ")", ")", "{", "offsetY", "=", "getHeight", "(", ")", "-", "toCurrentScale", "(", "(", "currentFilteredPage", "+", "1", ")", "*", "optimalPageHeight", ")", ";", "}", "}", "}", "else", "{", "float", "maxY", "=", "calculateCenterOffsetForPage", "(", "currentFilteredPage", "+", "1", ")", ";", "float", "minY", "=", "calculateCenterOffsetForPage", "(", "currentFilteredPage", "-", "1", ")", ";", "if", "(", "offsetY", "<", "maxY", ")", "{", "offsetY", "=", "maxY", ";", "}", "else", "if", "(", "offsetY", ">", "minY", ")", "{", "offsetY", "=", "minY", ";", "}", "}", "}", "else", "{", "// Check Y offset\r", "if", "(", "toCurrentScale", "(", "optimalPageHeight", ")", "<", "getHeight", "(", ")", ")", "{", "offsetY", "=", "getHeight", "(", ")", "/", "2", "-", "toCurrentScale", "(", "optimalPageHeight", ")", "/", "2", ";", "}", "else", "{", "if", "(", "offsetY", ">", "0", ")", "{", "offsetY", "=", "0", ";", "}", "else", "if", "(", "offsetY", "+", "toCurrentScale", "(", "optimalPageHeight", ")", "<", "getHeight", "(", ")", ")", "{", "offsetY", "=", "getHeight", "(", ")", "-", "toCurrentScale", "(", "optimalPageHeight", ")", ";", "}", "}", "// Check X offset\r", "if", "(", "isZooming", "(", ")", ")", "{", "if", "(", "toCurrentScale", "(", "optimalPageWidth", ")", "<", "getWidth", "(", ")", ")", "{", "miniMapRequired", "=", "false", ";", "offsetX", "=", "getWidth", "(", ")", "/", "2", "-", "toCurrentScale", "(", "(", "currentFilteredPage", "+", "0.5f", ")", "*", "optimalPageWidth", ")", ";", "}", "else", "{", "miniMapRequired", "=", "true", ";", "if", "(", "offsetX", "+", "toCurrentScale", "(", "currentFilteredPage", "*", "optimalPageWidth", ")", ">", "0", ")", "{", "offsetX", "=", "-", "toCurrentScale", "(", "currentFilteredPage", "*", "optimalPageWidth", ")", ";", "}", "else", "if", "(", "offsetX", "+", "toCurrentScale", "(", "(", "currentFilteredPage", "+", "1", ")", "*", "optimalPageWidth", ")", "<", "getWidth", "(", ")", ")", "{", "offsetX", "=", "getWidth", "(", ")", "-", "toCurrentScale", "(", "(", "currentFilteredPage", "+", "1", ")", "*", "optimalPageWidth", ")", ";", "}", "}", "}", "else", "{", "float", "maxX", "=", "calculateCenterOffsetForPage", "(", "currentFilteredPage", "+", "1", ")", ";", "float", "minX", "=", "calculateCenterOffsetForPage", "(", "currentFilteredPage", "-", "1", ")", ";", "if", "(", "offsetX", "<", "maxX", ")", "{", "offsetX", "=", "maxX", ";", "}", "else", "if", "(", "offsetX", ">", "minX", ")", "{", "offsetX", "=", "minX", ";", "}", "}", "}", "currentXOffset", "=", "offsetX", ";", "currentYOffset", "=", "offsetY", ";", "calculateMinimapAreaBounds", "(", ")", ";", "invalidate", "(", ")", ";", "}" ]
Move to the given X and Y offsets, but check them ahead of time to be sure not to go outside the the big strip. @param offsetX The big strip X offset to use as the left border of the screen. @param offsetY The big strip Y offset to use as the right border of the screen.
[ "Move", "to", "the", "given", "X", "and", "Y", "offsets", "but", "check", "them", "ahead", "of", "time", "to", "be", "sure", "not", "to", "go", "outside", "the", "the", "big", "strip", "." ]
8f239bb91ab56ff3066739dc44bccf8b1753b0ba
https://github.com/JoanZapata/android-pdfview/blob/8f239bb91ab56ff3066739dc44bccf8b1753b0ba/android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java#L793-L872
train
JoanZapata/android-pdfview
android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java
PDFView.fromAsset
public Configurator fromAsset(String assetName) { try { File pdfFile = FileUtils.fileFromAsset(getContext(), assetName); return fromFile(pdfFile); } catch (IOException e) { throw new FileNotFoundException(assetName + " does not exist.", e); } }
java
public Configurator fromAsset(String assetName) { try { File pdfFile = FileUtils.fileFromAsset(getContext(), assetName); return fromFile(pdfFile); } catch (IOException e) { throw new FileNotFoundException(assetName + " does not exist.", e); } }
[ "public", "Configurator", "fromAsset", "(", "String", "assetName", ")", "{", "try", "{", "File", "pdfFile", "=", "FileUtils", ".", "fileFromAsset", "(", "getContext", "(", ")", ",", "assetName", ")", ";", "return", "fromFile", "(", "pdfFile", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "FileNotFoundException", "(", "assetName", "+", "\" does not exist.\"", ",", "e", ")", ";", "}", "}" ]
Use an asset file as the pdf source
[ "Use", "an", "asset", "file", "as", "the", "pdf", "source" ]
8f239bb91ab56ff3066739dc44bccf8b1753b0ba
https://github.com/JoanZapata/android-pdfview/blob/8f239bb91ab56ff3066739dc44bccf8b1753b0ba/android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java#L965-L972
train
JoanZapata/android-pdfview
android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java
PDFView.fromFile
public Configurator fromFile(File file) { if (!file.exists()) throw new FileNotFoundException(file.getAbsolutePath() + "does not exist."); return new Configurator(Uri.fromFile(file)); }
java
public Configurator fromFile(File file) { if (!file.exists()) throw new FileNotFoundException(file.getAbsolutePath() + "does not exist."); return new Configurator(Uri.fromFile(file)); }
[ "public", "Configurator", "fromFile", "(", "File", "file", ")", "{", "if", "(", "!", "file", ".", "exists", "(", ")", ")", "throw", "new", "FileNotFoundException", "(", "file", ".", "getAbsolutePath", "(", ")", "+", "\"does not exist.\"", ")", ";", "return", "new", "Configurator", "(", "Uri", ".", "fromFile", "(", "file", ")", ")", ";", "}" ]
Use a file as the pdf source
[ "Use", "a", "file", "as", "the", "pdf", "source" ]
8f239bb91ab56ff3066739dc44bccf8b1753b0ba
https://github.com/JoanZapata/android-pdfview/blob/8f239bb91ab56ff3066739dc44bccf8b1753b0ba/android-pdfview/src/main/java/com/joanzapata/pdfview/PDFView.java#L975-L978
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/SpanOperationsBenchmark.java
SpanOperationsBenchmark.putAttribute
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span putAttribute(Data data) { Span span = data.attributeSpan; for (int i = 0; i < data.size; i++) { span.putAttribute(data.attributeKeys[i], data.attributeValues[i]); } return span; }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span putAttribute(Data data) { Span span = data.attributeSpan; for (int i = 0; i < data.size; i++) { span.putAttribute(data.attributeKeys[i], data.attributeValues[i]); } return span; }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "Span", "putAttribute", "(", "Data", "data", ")", "{", "Span", "span", "=", "data", ".", "attributeSpan", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "size", ";", "i", "++", ")", "{", "span", ".", "putAttribute", "(", "data", ".", "attributeKeys", "[", "i", "]", ",", "data", ".", "attributeValues", "[", "i", "]", ")", ";", "}", "return", "span", ";", "}" ]
Add attributes individually.
[ "Add", "attributes", "individually", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/SpanOperationsBenchmark.java#L137-L146
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/SpanOperationsBenchmark.java
SpanOperationsBenchmark.putAttributes
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span putAttributes(Data data) { Span span = data.attributeSpan; span.putAttributes(data.attributeMap); return span; }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span putAttributes(Data data) { Span span = data.attributeSpan; span.putAttributes(data.attributeMap); return span; }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "Span", "putAttributes", "(", "Data", "data", ")", "{", "Span", "span", "=", "data", ".", "attributeSpan", ";", "span", ".", "putAttributes", "(", "data", ".", "attributeMap", ")", ";", "return", "span", ";", "}" ]
Add attributes as a map.
[ "Add", "attributes", "as", "a", "map", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/SpanOperationsBenchmark.java#L149-L156
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/SpanOperationsBenchmark.java
SpanOperationsBenchmark.addAnnotationEmpty
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span addAnnotationEmpty(Data data) { Span span = data.annotationSpanEmpty; span.addAnnotation(ANNOTATION_DESCRIPTION); return span; }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span addAnnotationEmpty(Data data) { Span span = data.annotationSpanEmpty; span.addAnnotation(ANNOTATION_DESCRIPTION); return span; }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "Span", "addAnnotationEmpty", "(", "Data", "data", ")", "{", "Span", "span", "=", "data", ".", "annotationSpanEmpty", ";", "span", ".", "addAnnotation", "(", "ANNOTATION_DESCRIPTION", ")", ";", "return", "span", ";", "}" ]
Add an annotation as description only.
[ "Add", "an", "annotation", "as", "description", "only", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/SpanOperationsBenchmark.java#L159-L166
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/SpanOperationsBenchmark.java
SpanOperationsBenchmark.addAnnotationWithAttributes
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span addAnnotationWithAttributes(Data data) { Span span = data.annotationSpanAttributes; span.addAnnotation(ANNOTATION_DESCRIPTION, data.attributeMap); return span; }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span addAnnotationWithAttributes(Data data) { Span span = data.annotationSpanAttributes; span.addAnnotation(ANNOTATION_DESCRIPTION, data.attributeMap); return span; }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "Span", "addAnnotationWithAttributes", "(", "Data", "data", ")", "{", "Span", "span", "=", "data", ".", "annotationSpanAttributes", ";", "span", ".", "addAnnotation", "(", "ANNOTATION_DESCRIPTION", ",", "data", ".", "attributeMap", ")", ";", "return", "span", ";", "}" ]
Add an annotation with attributes.
[ "Add", "an", "annotation", "with", "attributes", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/SpanOperationsBenchmark.java#L169-L176
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/SpanOperationsBenchmark.java
SpanOperationsBenchmark.addAnnotationWithAnnotation
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span addAnnotationWithAnnotation(Data data) { Span span = data.annotationSpanAnnotation; Annotation annotation = Annotation.fromDescriptionAndAttributes(ANNOTATION_DESCRIPTION, data.attributeMap); span.addAnnotation(annotation); return span; }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span addAnnotationWithAnnotation(Data data) { Span span = data.annotationSpanAnnotation; Annotation annotation = Annotation.fromDescriptionAndAttributes(ANNOTATION_DESCRIPTION, data.attributeMap); span.addAnnotation(annotation); return span; }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "Span", "addAnnotationWithAnnotation", "(", "Data", "data", ")", "{", "Span", "span", "=", "data", ".", "annotationSpanAnnotation", ";", "Annotation", "annotation", "=", "Annotation", ".", "fromDescriptionAndAttributes", "(", "ANNOTATION_DESCRIPTION", ",", "data", ".", "attributeMap", ")", ";", "span", ".", "addAnnotation", "(", "annotation", ")", ";", "return", "span", ";", "}" ]
Add an annotation with an annotation.
[ "Add", "an", "annotation", "with", "an", "annotation", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/SpanOperationsBenchmark.java#L179-L188
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/SpanOperationsBenchmark.java
SpanOperationsBenchmark.addMessageEvent
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span addMessageEvent(Data data) { Span span = data.messageEventSpan; for (int i = 0; i < data.size; i++) { span.addMessageEvent(data.messageEvents[i]); } return span; }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span addMessageEvent(Data data) { Span span = data.messageEventSpan; for (int i = 0; i < data.size; i++) { span.addMessageEvent(data.messageEvents[i]); } return span; }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "Span", "addMessageEvent", "(", "Data", "data", ")", "{", "Span", "span", "=", "data", ".", "messageEventSpan", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "size", ";", "i", "++", ")", "{", "span", ".", "addMessageEvent", "(", "data", ".", "messageEvents", "[", "i", "]", ")", ";", "}", "return", "span", ";", "}" ]
Add message events.
[ "Add", "message", "events", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/SpanOperationsBenchmark.java#L191-L200
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/SpanOperationsBenchmark.java
SpanOperationsBenchmark.addLink
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span addLink(Data data) { Span span = data.linkSpan; for (int i = 0; i < data.size; i++) { span.addLink(data.links[i]); } return span; }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span addLink(Data data) { Span span = data.linkSpan; for (int i = 0; i < data.size; i++) { span.addLink(data.links[i]); } return span; }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "Span", "addLink", "(", "Data", "data", ")", "{", "Span", "span", "=", "data", ".", "linkSpan", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "size", ";", "i", "++", ")", "{", "span", ".", "addLink", "(", "data", ".", "links", "[", "i", "]", ")", ";", "}", "return", "span", ";", "}" ]
Add links.
[ "Add", "links", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/SpanOperationsBenchmark.java#L203-L212
train
census-instrumentation/opencensus-java
contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthTracer.java
OpenCensusSleuthTracer.wrap
@Override public <V> Callable<V> wrap(Callable<V> callable) { if (isTracing()) { return new SpanContinuingTraceCallable<V>(this, this.traceKeys, this.spanNamer, callable); } return callable; }
java
@Override public <V> Callable<V> wrap(Callable<V> callable) { if (isTracing()) { return new SpanContinuingTraceCallable<V>(this, this.traceKeys, this.spanNamer, callable); } return callable; }
[ "@", "Override", "public", "<", "V", ">", "Callable", "<", "V", ">", "wrap", "(", "Callable", "<", "V", ">", "callable", ")", "{", "if", "(", "isTracing", "(", ")", ")", "{", "return", "new", "SpanContinuingTraceCallable", "<", "V", ">", "(", "this", ",", "this", ".", "traceKeys", ",", "this", ".", "spanNamer", ",", "callable", ")", ";", "}", "return", "callable", ";", "}" ]
Wrap the callable in a TraceCallable, if tracing. @return The callable provided, wrapped if tracing, 'callable' if not.
[ "Wrap", "the", "callable", "in", "a", "TraceCallable", "if", "tracing", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthTracer.java#L309-L315
train
census-instrumentation/opencensus-java
contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthTracer.java
OpenCensusSleuthTracer.wrap
@Override public Runnable wrap(Runnable runnable) { if (isTracing()) { return new SpanContinuingTraceRunnable(this, this.traceKeys, this.spanNamer, runnable); } return runnable; }
java
@Override public Runnable wrap(Runnable runnable) { if (isTracing()) { return new SpanContinuingTraceRunnable(this, this.traceKeys, this.spanNamer, runnable); } return runnable; }
[ "@", "Override", "public", "Runnable", "wrap", "(", "Runnable", "runnable", ")", "{", "if", "(", "isTracing", "(", ")", ")", "{", "return", "new", "SpanContinuingTraceRunnable", "(", "this", ",", "this", ".", "traceKeys", ",", "this", ".", "spanNamer", ",", "runnable", ")", ";", "}", "return", "runnable", ";", "}" ]
Wrap the runnable in a TraceRunnable, if tracing. @return The runnable provided, wrapped if tracing, 'runnable' if not.
[ "Wrap", "the", "runnable", "in", "a", "TraceRunnable", "if", "tracing", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthTracer.java#L322-L328
train
census-instrumentation/opencensus-java
contrib/agent/src/main/java/io/opencensus/contrib/agent/AgentMain.java
AgentMain.premain
public static void premain(String agentArgs, Instrumentation instrumentation) throws Exception { checkNotNull(instrumentation, "instrumentation"); logger.fine("Initializing."); // The classes in bootstrap.jar, such as ContextManger and ContextStrategy, will be referenced // from classes loaded by the bootstrap classloader. Thus, these classes have to be loaded by // the bootstrap classloader, too. instrumentation.appendToBootstrapClassLoaderSearch( new JarFile(Resources.getResourceAsTempFile("bootstrap.jar"))); checkLoadedByBootstrapClassloader(ContextTrampoline.class); checkLoadedByBootstrapClassloader(ContextStrategy.class); Settings settings = Settings.load(); AgentBuilder agentBuilder = new AgentBuilder.Default() .disableClassFormatChanges() .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION) .with(new AgentBuilderListener()) .ignore(none()); for (Instrumenter instrumenter : ServiceLoader.load(Instrumenter.class)) { agentBuilder = instrumenter.instrument(agentBuilder, settings); } agentBuilder.installOn(instrumentation); logger.fine("Initialized."); }
java
public static void premain(String agentArgs, Instrumentation instrumentation) throws Exception { checkNotNull(instrumentation, "instrumentation"); logger.fine("Initializing."); // The classes in bootstrap.jar, such as ContextManger and ContextStrategy, will be referenced // from classes loaded by the bootstrap classloader. Thus, these classes have to be loaded by // the bootstrap classloader, too. instrumentation.appendToBootstrapClassLoaderSearch( new JarFile(Resources.getResourceAsTempFile("bootstrap.jar"))); checkLoadedByBootstrapClassloader(ContextTrampoline.class); checkLoadedByBootstrapClassloader(ContextStrategy.class); Settings settings = Settings.load(); AgentBuilder agentBuilder = new AgentBuilder.Default() .disableClassFormatChanges() .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION) .with(new AgentBuilderListener()) .ignore(none()); for (Instrumenter instrumenter : ServiceLoader.load(Instrumenter.class)) { agentBuilder = instrumenter.instrument(agentBuilder, settings); } agentBuilder.installOn(instrumentation); logger.fine("Initialized."); }
[ "public", "static", "void", "premain", "(", "String", "agentArgs", ",", "Instrumentation", "instrumentation", ")", "throws", "Exception", "{", "checkNotNull", "(", "instrumentation", ",", "\"instrumentation\"", ")", ";", "logger", ".", "fine", "(", "\"Initializing.\"", ")", ";", "// The classes in bootstrap.jar, such as ContextManger and ContextStrategy, will be referenced", "// from classes loaded by the bootstrap classloader. Thus, these classes have to be loaded by", "// the bootstrap classloader, too.", "instrumentation", ".", "appendToBootstrapClassLoaderSearch", "(", "new", "JarFile", "(", "Resources", ".", "getResourceAsTempFile", "(", "\"bootstrap.jar\"", ")", ")", ")", ";", "checkLoadedByBootstrapClassloader", "(", "ContextTrampoline", ".", "class", ")", ";", "checkLoadedByBootstrapClassloader", "(", "ContextStrategy", ".", "class", ")", ";", "Settings", "settings", "=", "Settings", ".", "load", "(", ")", ";", "AgentBuilder", "agentBuilder", "=", "new", "AgentBuilder", ".", "Default", "(", ")", ".", "disableClassFormatChanges", "(", ")", ".", "with", "(", "AgentBuilder", ".", "RedefinitionStrategy", ".", "RETRANSFORMATION", ")", ".", "with", "(", "new", "AgentBuilderListener", "(", ")", ")", ".", "ignore", "(", "none", "(", ")", ")", ";", "for", "(", "Instrumenter", "instrumenter", ":", "ServiceLoader", ".", "load", "(", "Instrumenter", ".", "class", ")", ")", "{", "agentBuilder", "=", "instrumenter", ".", "instrument", "(", "agentBuilder", ",", "settings", ")", ";", "}", "agentBuilder", ".", "installOn", "(", "instrumentation", ")", ";", "logger", ".", "fine", "(", "\"Initialized.\"", ")", ";", "}" ]
Initializes the OpenCensus Agent for Java. @param agentArgs agent options, passed as a single string by the JVM @param instrumentation the {@link Instrumentation} object provided by the JVM for instrumenting Java programming language code @throws Exception if initialization of the agent fails @see java.lang.instrument @since 0.6
[ "Initializes", "the", "OpenCensus", "Agent", "for", "Java", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/agent/src/main/java/io/opencensus/contrib/agent/AgentMain.java#L64-L91
train
census-instrumentation/opencensus-java
exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentTraceExporterHandler.java
OcAgentTraceExporterHandler.getTraceServiceStub
private static TraceServiceGrpc.TraceServiceStub getTraceServiceStub( String endPoint, Boolean useInsecure, SslContext sslContext) { ManagedChannelBuilder<?> channelBuilder; if (useInsecure) { channelBuilder = ManagedChannelBuilder.forTarget(endPoint).usePlaintext(); } else { channelBuilder = NettyChannelBuilder.forTarget(endPoint) .negotiationType(NegotiationType.TLS) .sslContext(sslContext); } ManagedChannel channel = channelBuilder.build(); return TraceServiceGrpc.newStub(channel); }
java
private static TraceServiceGrpc.TraceServiceStub getTraceServiceStub( String endPoint, Boolean useInsecure, SslContext sslContext) { ManagedChannelBuilder<?> channelBuilder; if (useInsecure) { channelBuilder = ManagedChannelBuilder.forTarget(endPoint).usePlaintext(); } else { channelBuilder = NettyChannelBuilder.forTarget(endPoint) .negotiationType(NegotiationType.TLS) .sslContext(sslContext); } ManagedChannel channel = channelBuilder.build(); return TraceServiceGrpc.newStub(channel); }
[ "private", "static", "TraceServiceGrpc", ".", "TraceServiceStub", "getTraceServiceStub", "(", "String", "endPoint", ",", "Boolean", "useInsecure", ",", "SslContext", "sslContext", ")", "{", "ManagedChannelBuilder", "<", "?", ">", "channelBuilder", ";", "if", "(", "useInsecure", ")", "{", "channelBuilder", "=", "ManagedChannelBuilder", ".", "forTarget", "(", "endPoint", ")", ".", "usePlaintext", "(", ")", ";", "}", "else", "{", "channelBuilder", "=", "NettyChannelBuilder", ".", "forTarget", "(", "endPoint", ")", ".", "negotiationType", "(", "NegotiationType", ".", "TLS", ")", ".", "sslContext", "(", "sslContext", ")", ";", "}", "ManagedChannel", "channel", "=", "channelBuilder", ".", "build", "(", ")", ";", "return", "TraceServiceGrpc", ".", "newStub", "(", "channel", ")", ";", "}" ]
One stub can be used for both Export RPC and Config RPC.
[ "One", "stub", "can", "be", "used", "for", "both", "Export", "RPC", "and", "Config", "RPC", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentTraceExporterHandler.java#L124-L137
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/stats/RecordBatchedBenchmark.java
RecordBatchedBenchmark.recordBatchedDoubleCount
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public MeasureMap recordBatchedDoubleCount(Data data) { MeasureMap map = data.recorder.newMeasureMap(); for (int i = 0; i < data.numValues; i++) { map.put(StatsBenchmarksUtil.DOUBLE_COUNT_MEASURES[i], (double) i); } map.record(data.tags); return map; }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public MeasureMap recordBatchedDoubleCount(Data data) { MeasureMap map = data.recorder.newMeasureMap(); for (int i = 0; i < data.numValues; i++) { map.put(StatsBenchmarksUtil.DOUBLE_COUNT_MEASURES[i], (double) i); } map.record(data.tags); return map; }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "MeasureMap", "recordBatchedDoubleCount", "(", "Data", "data", ")", "{", "MeasureMap", "map", "=", "data", ".", "recorder", ".", "newMeasureMap", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "numValues", ";", "i", "++", ")", "{", "map", ".", "put", "(", "StatsBenchmarksUtil", ".", "DOUBLE_COUNT_MEASURES", "[", "i", "]", ",", "(", "double", ")", "i", ")", ";", "}", "map", ".", "record", "(", "data", ".", "tags", ")", ";", "return", "map", ";", "}" ]
Record batched double count measures.
[ "Record", "batched", "double", "count", "measures", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/stats/RecordBatchedBenchmark.java#L68-L78
train
census-instrumentation/opencensus-java
contrib/agent/src/main/java/io/opencensus/contrib/agent/Resources.java
Resources.getResourceAsTempFile
static File getResourceAsTempFile(String resourceName) throws IOException { checkArgument(!Strings.isNullOrEmpty(resourceName), "resourceName"); File file = File.createTempFile(resourceName, ".tmp"); OutputStream os = new FileOutputStream(file); try { getResourceAsTempFile(resourceName, file, os); return file; } finally { os.close(); } }
java
static File getResourceAsTempFile(String resourceName) throws IOException { checkArgument(!Strings.isNullOrEmpty(resourceName), "resourceName"); File file = File.createTempFile(resourceName, ".tmp"); OutputStream os = new FileOutputStream(file); try { getResourceAsTempFile(resourceName, file, os); return file; } finally { os.close(); } }
[ "static", "File", "getResourceAsTempFile", "(", "String", "resourceName", ")", "throws", "IOException", "{", "checkArgument", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "resourceName", ")", ",", "\"resourceName\"", ")", ";", "File", "file", "=", "File", ".", "createTempFile", "(", "resourceName", ",", "\".tmp\"", ")", ";", "OutputStream", "os", "=", "new", "FileOutputStream", "(", "file", ")", ";", "try", "{", "getResourceAsTempFile", "(", "resourceName", ",", "file", ",", "os", ")", ";", "return", "file", ";", "}", "finally", "{", "os", ".", "close", "(", ")", ";", "}", "}" ]
Returns a resource of the given name as a temporary file. @param resourceName name of the resource @return a temporary {@link File} containing a copy of the resource @throws FileNotFoundException if no resource of the given name is found @throws IOException if an I/O error occurs
[ "Returns", "a", "resource", "of", "the", "given", "name", "as", "a", "temporary", "file", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/agent/src/main/java/io/opencensus/contrib/agent/Resources.java#L43-L54
train
census-instrumentation/opencensus-java
exporters/trace/datadog/src/main/java/io/opencensus/exporter/trace/datadog/DatadogTraceExporter.java
DatadogTraceExporter.createAndRegister
public static void createAndRegister(DatadogTraceConfiguration configuration) throws MalformedURLException { synchronized (monitor) { checkState(handler == null, "Datadog exporter is already registered."); String agentEndpoint = configuration.getAgentEndpoint(); String service = configuration.getService(); String type = configuration.getType(); final DatadogExporterHandler exporterHandler = new DatadogExporterHandler(agentEndpoint, service, type); handler = exporterHandler; Tracing.getExportComponent() .getSpanExporter() .registerHandler(REGISTER_NAME, exporterHandler); } }
java
public static void createAndRegister(DatadogTraceConfiguration configuration) throws MalformedURLException { synchronized (monitor) { checkState(handler == null, "Datadog exporter is already registered."); String agentEndpoint = configuration.getAgentEndpoint(); String service = configuration.getService(); String type = configuration.getType(); final DatadogExporterHandler exporterHandler = new DatadogExporterHandler(agentEndpoint, service, type); handler = exporterHandler; Tracing.getExportComponent() .getSpanExporter() .registerHandler(REGISTER_NAME, exporterHandler); } }
[ "public", "static", "void", "createAndRegister", "(", "DatadogTraceConfiguration", "configuration", ")", "throws", "MalformedURLException", "{", "synchronized", "(", "monitor", ")", "{", "checkState", "(", "handler", "==", "null", ",", "\"Datadog exporter is already registered.\"", ")", ";", "String", "agentEndpoint", "=", "configuration", ".", "getAgentEndpoint", "(", ")", ";", "String", "service", "=", "configuration", ".", "getService", "(", ")", ";", "String", "type", "=", "configuration", ".", "getType", "(", ")", ";", "final", "DatadogExporterHandler", "exporterHandler", "=", "new", "DatadogExporterHandler", "(", "agentEndpoint", ",", "service", ",", "type", ")", ";", "handler", "=", "exporterHandler", ";", "Tracing", ".", "getExportComponent", "(", ")", ".", "getSpanExporter", "(", ")", ".", "registerHandler", "(", "REGISTER_NAME", ",", "exporterHandler", ")", ";", "}", "}" ]
Creates and registers the Datadog Trace exporter to the OpenCensus library. Only one Datadog exporter can be registered at any point. @param configuration the {@code DatadogTraceConfiguration} used to create the exporter. @throws MalformedURLException if the agent URL is invalid. @since 0.19
[ "Creates", "and", "registers", "the", "Datadog", "Trace", "exporter", "to", "the", "OpenCensus", "library", ".", "Only", "one", "Datadog", "exporter", "can", "be", "registered", "at", "any", "point", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/datadog/src/main/java/io/opencensus/exporter/trace/datadog/DatadogTraceExporter.java#L65-L81
train
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java
StackdriverStatsExporter.createAndRegisterWithCredentialsAndProjectId
@Deprecated public static void createAndRegisterWithCredentialsAndProjectId( Credentials credentials, String projectId, Duration exportInterval) throws IOException { checkNotNull(credentials, "credentials"); checkNotNull(projectId, "projectId"); checkNotNull(exportInterval, "exportInterval"); createInternal( credentials, projectId, exportInterval, DEFAULT_RESOURCE, null, DEFAULT_CONSTANT_LABELS); }
java
@Deprecated public static void createAndRegisterWithCredentialsAndProjectId( Credentials credentials, String projectId, Duration exportInterval) throws IOException { checkNotNull(credentials, "credentials"); checkNotNull(projectId, "projectId"); checkNotNull(exportInterval, "exportInterval"); createInternal( credentials, projectId, exportInterval, DEFAULT_RESOURCE, null, DEFAULT_CONSTANT_LABELS); }
[ "@", "Deprecated", "public", "static", "void", "createAndRegisterWithCredentialsAndProjectId", "(", "Credentials", "credentials", ",", "String", "projectId", ",", "Duration", "exportInterval", ")", "throws", "IOException", "{", "checkNotNull", "(", "credentials", ",", "\"credentials\"", ")", ";", "checkNotNull", "(", "projectId", ",", "\"projectId\"", ")", ";", "checkNotNull", "(", "exportInterval", ",", "\"exportInterval\"", ")", ";", "createInternal", "(", "credentials", ",", "projectId", ",", "exportInterval", ",", "DEFAULT_RESOURCE", ",", "null", ",", "DEFAULT_CONSTANT_LABELS", ")", ";", "}" ]
Creates a StackdriverStatsExporter for an explicit project ID and using explicit credentials, with default Monitored Resource. <p>Only one Stackdriver exporter can be created. @param credentials a credentials used to authenticate API calls. @param projectId the cloud project id. @param exportInterval the interval between pushing stats to StackDriver. @throws IllegalStateException if a Stackdriver exporter already exists. @deprecated in favor of {@link #createAndRegister(StackdriverStatsConfiguration)}. @since 0.9
[ "Creates", "a", "StackdriverStatsExporter", "for", "an", "explicit", "project", "ID", "and", "using", "explicit", "credentials", "with", "default", "Monitored", "Resource", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java#L132-L140
train
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java
StackdriverStatsExporter.createAndRegisterWithProjectId
@Deprecated public static void createAndRegisterWithProjectId(String projectId, Duration exportInterval) throws IOException { checkNotNull(projectId, "projectId"); checkNotNull(exportInterval, "exportInterval"); createInternal( null, projectId, exportInterval, DEFAULT_RESOURCE, null, DEFAULT_CONSTANT_LABELS); }
java
@Deprecated public static void createAndRegisterWithProjectId(String projectId, Duration exportInterval) throws IOException { checkNotNull(projectId, "projectId"); checkNotNull(exportInterval, "exportInterval"); createInternal( null, projectId, exportInterval, DEFAULT_RESOURCE, null, DEFAULT_CONSTANT_LABELS); }
[ "@", "Deprecated", "public", "static", "void", "createAndRegisterWithProjectId", "(", "String", "projectId", ",", "Duration", "exportInterval", ")", "throws", "IOException", "{", "checkNotNull", "(", "projectId", ",", "\"projectId\"", ")", ";", "checkNotNull", "(", "exportInterval", ",", "\"exportInterval\"", ")", ";", "createInternal", "(", "null", ",", "projectId", ",", "exportInterval", ",", "DEFAULT_RESOURCE", ",", "null", ",", "DEFAULT_CONSTANT_LABELS", ")", ";", "}" ]
Creates a Stackdriver Stats exporter for an explicit project ID, with default Monitored Resource. <p>Only one Stackdriver exporter can be created. <p>This uses the default application credentials. See {@link GoogleCredentials#getApplicationDefault}. <p>This is equivalent with: <pre>{@code StackdriverStatsExporter.createWithCredentialsAndProjectId( GoogleCredentials.getApplicationDefault(), projectId); }</pre> @param projectId the cloud project id. @param exportInterval the interval between pushing stats to StackDriver. @throws IllegalStateException if a Stackdriver exporter is already created. @deprecated in favor of {@link #createAndRegister(StackdriverStatsConfiguration)}. @since 0.9
[ "Creates", "a", "Stackdriver", "Stats", "exporter", "for", "an", "explicit", "project", "ID", "with", "default", "Monitored", "Resource", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java#L164-L171
train
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java
StackdriverStatsExporter.createAndRegister
@Deprecated public static void createAndRegister(Duration exportInterval) throws IOException { checkNotNull(exportInterval, "exportInterval"); checkArgument( !DEFAULT_PROJECT_ID.isEmpty(), "Cannot find a project ID from application default."); createInternal( null, DEFAULT_PROJECT_ID, exportInterval, DEFAULT_RESOURCE, null, DEFAULT_CONSTANT_LABELS); }
java
@Deprecated public static void createAndRegister(Duration exportInterval) throws IOException { checkNotNull(exportInterval, "exportInterval"); checkArgument( !DEFAULT_PROJECT_ID.isEmpty(), "Cannot find a project ID from application default."); createInternal( null, DEFAULT_PROJECT_ID, exportInterval, DEFAULT_RESOURCE, null, DEFAULT_CONSTANT_LABELS); }
[ "@", "Deprecated", "public", "static", "void", "createAndRegister", "(", "Duration", "exportInterval", ")", "throws", "IOException", "{", "checkNotNull", "(", "exportInterval", ",", "\"exportInterval\"", ")", ";", "checkArgument", "(", "!", "DEFAULT_PROJECT_ID", ".", "isEmpty", "(", ")", ",", "\"Cannot find a project ID from application default.\"", ")", ";", "createInternal", "(", "null", ",", "DEFAULT_PROJECT_ID", ",", "exportInterval", ",", "DEFAULT_RESOURCE", ",", "null", ",", "DEFAULT_CONSTANT_LABELS", ")", ";", "}" ]
Creates a Stackdriver Stats exporter with default Monitored Resource. <p>Only one Stackdriver exporter can be created. <p>This uses the default application credentials. See {@link GoogleCredentials#getApplicationDefault}. <p>This uses the default project ID configured see {@link ServiceOptions#getDefaultProjectId}. <p>This is equivalent with: <pre>{@code StackdriverStatsExporter.createWithProjectId(ServiceOptions.getDefaultProjectId()); }</pre> @param exportInterval the interval between pushing stats to StackDriver. @throws IllegalStateException if a Stackdriver exporter is already created. @deprecated in favor of {@link #createAndRegister(StackdriverStatsConfiguration)}. @since 0.9
[ "Creates", "a", "Stackdriver", "Stats", "exporter", "with", "default", "Monitored", "Resource", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java#L263-L270
train
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java
StackdriverStatsExporter.createAndRegisterWithProjectIdAndMonitoredResource
@Deprecated public static void createAndRegisterWithProjectIdAndMonitoredResource( String projectId, Duration exportInterval, MonitoredResource monitoredResource) throws IOException { checkNotNull(projectId, "projectId"); checkNotNull(exportInterval, "exportInterval"); checkNotNull(monitoredResource, "monitoredResource"); createInternal( null, projectId, exportInterval, monitoredResource, null, DEFAULT_CONSTANT_LABELS); }
java
@Deprecated public static void createAndRegisterWithProjectIdAndMonitoredResource( String projectId, Duration exportInterval, MonitoredResource monitoredResource) throws IOException { checkNotNull(projectId, "projectId"); checkNotNull(exportInterval, "exportInterval"); checkNotNull(monitoredResource, "monitoredResource"); createInternal( null, projectId, exportInterval, monitoredResource, null, DEFAULT_CONSTANT_LABELS); }
[ "@", "Deprecated", "public", "static", "void", "createAndRegisterWithProjectIdAndMonitoredResource", "(", "String", "projectId", ",", "Duration", "exportInterval", ",", "MonitoredResource", "monitoredResource", ")", "throws", "IOException", "{", "checkNotNull", "(", "projectId", ",", "\"projectId\"", ")", ";", "checkNotNull", "(", "exportInterval", ",", "\"exportInterval\"", ")", ";", "checkNotNull", "(", "monitoredResource", ",", "\"monitoredResource\"", ")", ";", "createInternal", "(", "null", ",", "projectId", ",", "exportInterval", ",", "monitoredResource", ",", "null", ",", "DEFAULT_CONSTANT_LABELS", ")", ";", "}" ]
Creates a Stackdriver Stats exporter with an explicit project ID and a custom Monitored Resource. <p>Only one Stackdriver exporter can be created. <p>Please refer to cloud.google.com/monitoring/custom-metrics/creating-metrics#which-resource for a list of valid {@code MonitoredResource}s. <p>This uses the default application credentials. See {@link GoogleCredentials#getApplicationDefault}. @param projectId the cloud project id. @param exportInterval the interval between pushing stats to StackDriver. @param monitoredResource the Monitored Resource used by exporter. @throws IllegalStateException if a Stackdriver exporter is already created. @deprecated in favor of {@link #createAndRegister(StackdriverStatsConfiguration)}. @since 0.10
[ "Creates", "a", "Stackdriver", "Stats", "exporter", "with", "an", "explicit", "project", "ID", "and", "a", "custom", "Monitored", "Resource", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java#L291-L300
train
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java
StackdriverStatsExporter.createAndRegisterWithMonitoredResource
@Deprecated public static void createAndRegisterWithMonitoredResource( Duration exportInterval, MonitoredResource monitoredResource) throws IOException { checkNotNull(exportInterval, "exportInterval"); checkNotNull(monitoredResource, "monitoredResource"); checkArgument( !DEFAULT_PROJECT_ID.isEmpty(), "Cannot find a project ID from application default."); createInternal( null, DEFAULT_PROJECT_ID, exportInterval, monitoredResource, null, DEFAULT_CONSTANT_LABELS); }
java
@Deprecated public static void createAndRegisterWithMonitoredResource( Duration exportInterval, MonitoredResource monitoredResource) throws IOException { checkNotNull(exportInterval, "exportInterval"); checkNotNull(monitoredResource, "monitoredResource"); checkArgument( !DEFAULT_PROJECT_ID.isEmpty(), "Cannot find a project ID from application default."); createInternal( null, DEFAULT_PROJECT_ID, exportInterval, monitoredResource, null, DEFAULT_CONSTANT_LABELS); }
[ "@", "Deprecated", "public", "static", "void", "createAndRegisterWithMonitoredResource", "(", "Duration", "exportInterval", ",", "MonitoredResource", "monitoredResource", ")", "throws", "IOException", "{", "checkNotNull", "(", "exportInterval", ",", "\"exportInterval\"", ")", ";", "checkNotNull", "(", "monitoredResource", ",", "\"monitoredResource\"", ")", ";", "checkArgument", "(", "!", "DEFAULT_PROJECT_ID", ".", "isEmpty", "(", ")", ",", "\"Cannot find a project ID from application default.\"", ")", ";", "createInternal", "(", "null", ",", "DEFAULT_PROJECT_ID", ",", "exportInterval", ",", "monitoredResource", ",", "null", ",", "DEFAULT_CONSTANT_LABELS", ")", ";", "}" ]
Creates a Stackdriver Stats exporter with a custom Monitored Resource. <p>Only one Stackdriver exporter can be created. <p>Please refer to cloud.google.com/monitoring/custom-metrics/creating-metrics#which-resource for a list of valid {@code MonitoredResource}s. <p>This uses the default application credentials. See {@link GoogleCredentials#getApplicationDefault}. <p>This uses the default project ID configured see {@link ServiceOptions#getDefaultProjectId}. @param exportInterval the interval between pushing stats to StackDriver. @param monitoredResource the Monitored Resource used by exporter. @throws IllegalStateException if a Stackdriver exporter is already created. @deprecated in favor of {@link #createAndRegister(StackdriverStatsConfiguration)}. @since 0.10
[ "Creates", "a", "Stackdriver", "Stats", "exporter", "with", "a", "custom", "Monitored", "Resource", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java#L321-L330
train
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java
StackdriverStatsExporter.unsafeResetExporter
@VisibleForTesting static void unsafeResetExporter() { synchronized (monitor) { if (instance != null) { instance.intervalMetricReader.stop(); } instance = null; } }
java
@VisibleForTesting static void unsafeResetExporter() { synchronized (monitor) { if (instance != null) { instance.intervalMetricReader.stop(); } instance = null; } }
[ "@", "VisibleForTesting", "static", "void", "unsafeResetExporter", "(", ")", "{", "synchronized", "(", "monitor", ")", "{", "if", "(", "instance", "!=", "null", ")", "{", "instance", ".", "intervalMetricReader", ".", "stop", "(", ")", ";", "}", "instance", "=", "null", ";", "}", "}" ]
Resets exporter to null. Used only for unit tests.
[ "Resets", "exporter", "to", "null", ".", "Used", "only", "for", "unit", "tests", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java#L372-L380
train
census-instrumentation/opencensus-java
exporters/metrics/ocagent/src/main/java/io/opencensus/exporter/metrics/ocagent/OcAgentMetricsExporterWorker.java
OcAgentMetricsExporterWorker.export
private void export() { if (exportRpcHandler == null || exportRpcHandler.isCompleted()) { return; } ArrayList<Metric> metricsList = Lists.newArrayList(); for (MetricProducer metricProducer : metricProducerManager.getAllMetricProducer()) { metricsList.addAll(metricProducer.getMetrics()); } List<io.opencensus.proto.metrics.v1.Metric> metricProtos = Lists.newArrayList(); for (Metric metric : metricsList) { // TODO(songya): determine if we should make the optimization on not sending already-existed // MetricDescriptors. // boolean registered = true; // if (!registeredDescriptors.contains(metric.getMetricDescriptor())) { // registered = false; // registeredDescriptors.add(metric.getMetricDescriptor()); // } metricProtos.add(MetricsProtoUtils.toMetricProto(metric, null)); } exportRpcHandler.onExport( // For now don't include Resource in the following messages, i.e don't allow Resource to // mutate after the initial message. ExportMetricsServiceRequest.newBuilder().addAllMetrics(metricProtos).build()); }
java
private void export() { if (exportRpcHandler == null || exportRpcHandler.isCompleted()) { return; } ArrayList<Metric> metricsList = Lists.newArrayList(); for (MetricProducer metricProducer : metricProducerManager.getAllMetricProducer()) { metricsList.addAll(metricProducer.getMetrics()); } List<io.opencensus.proto.metrics.v1.Metric> metricProtos = Lists.newArrayList(); for (Metric metric : metricsList) { // TODO(songya): determine if we should make the optimization on not sending already-existed // MetricDescriptors. // boolean registered = true; // if (!registeredDescriptors.contains(metric.getMetricDescriptor())) { // registered = false; // registeredDescriptors.add(metric.getMetricDescriptor()); // } metricProtos.add(MetricsProtoUtils.toMetricProto(metric, null)); } exportRpcHandler.onExport( // For now don't include Resource in the following messages, i.e don't allow Resource to // mutate after the initial message. ExportMetricsServiceRequest.newBuilder().addAllMetrics(metricProtos).build()); }
[ "private", "void", "export", "(", ")", "{", "if", "(", "exportRpcHandler", "==", "null", "||", "exportRpcHandler", ".", "isCompleted", "(", ")", ")", "{", "return", ";", "}", "ArrayList", "<", "Metric", ">", "metricsList", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "MetricProducer", "metricProducer", ":", "metricProducerManager", ".", "getAllMetricProducer", "(", ")", ")", "{", "metricsList", ".", "addAll", "(", "metricProducer", ".", "getMetrics", "(", ")", ")", ";", "}", "List", "<", "io", ".", "opencensus", ".", "proto", ".", "metrics", ".", "v1", ".", "Metric", ">", "metricProtos", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "Metric", "metric", ":", "metricsList", ")", "{", "// TODO(songya): determine if we should make the optimization on not sending already-existed", "// MetricDescriptors.", "// boolean registered = true;", "// if (!registeredDescriptors.contains(metric.getMetricDescriptor())) {", "// registered = false;", "// registeredDescriptors.add(metric.getMetricDescriptor());", "// }", "metricProtos", ".", "add", "(", "MetricsProtoUtils", ".", "toMetricProto", "(", "metric", ",", "null", ")", ")", ";", "}", "exportRpcHandler", ".", "onExport", "(", "// For now don't include Resource in the following messages, i.e don't allow Resource to", "// mutate after the initial message.", "ExportMetricsServiceRequest", ".", "newBuilder", "(", ")", ".", "addAllMetrics", "(", "metricProtos", ")", ".", "build", "(", ")", ")", ";", "}" ]
converts them to proto, then exports them to OC-Agent.
[ "converts", "them", "to", "proto", "then", "exports", "them", "to", "OC", "-", "Agent", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/metrics/ocagent/src/main/java/io/opencensus/exporter/metrics/ocagent/OcAgentMetricsExporterWorker.java#L121-L147
train
census-instrumentation/opencensus-java
contrib/agent/src/main/java/io/opencensus/contrib/agent/bootstrap/TraceTrampoline.java
TraceTrampoline.setTraceStrategy
public static void setTraceStrategy(TraceStrategy traceStrategy) { if (TraceTrampoline.traceStrategy != null) { throw new IllegalStateException("traceStrategy was already set"); } if (traceStrategy == null) { throw new NullPointerException("traceStrategy"); } TraceTrampoline.traceStrategy = traceStrategy; }
java
public static void setTraceStrategy(TraceStrategy traceStrategy) { if (TraceTrampoline.traceStrategy != null) { throw new IllegalStateException("traceStrategy was already set"); } if (traceStrategy == null) { throw new NullPointerException("traceStrategy"); } TraceTrampoline.traceStrategy = traceStrategy; }
[ "public", "static", "void", "setTraceStrategy", "(", "TraceStrategy", "traceStrategy", ")", "{", "if", "(", "TraceTrampoline", ".", "traceStrategy", "!=", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"traceStrategy was already set\"", ")", ";", "}", "if", "(", "traceStrategy", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"traceStrategy\"", ")", ";", "}", "TraceTrampoline", ".", "traceStrategy", "=", "traceStrategy", ";", "}" ]
Sets the concrete strategy for creating and manipulating trace spans. <p>NB: The agent is responsible for setting the trace strategy once before any other method of this class is called. @param traceStrategy the concrete strategy for creating and manipulating trace spans @since 0.9
[ "Sets", "the", "concrete", "strategy", "for", "creating", "and", "manipulating", "trace", "spans", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/agent/src/main/java/io/opencensus/contrib/agent/bootstrap/TraceTrampoline.java#L60-L70
train
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/internal/Provider.java
Provider.createInstance
public static <T> T createInstance(Class<?> rawClass, Class<T> superclass) { try { return rawClass.asSubclass(superclass).getConstructor().newInstance(); } catch (Exception e) { throw new ServiceConfigurationError( "Provider " + rawClass.getName() + " could not be instantiated.", e); } }
java
public static <T> T createInstance(Class<?> rawClass, Class<T> superclass) { try { return rawClass.asSubclass(superclass).getConstructor().newInstance(); } catch (Exception e) { throw new ServiceConfigurationError( "Provider " + rawClass.getName() + " could not be instantiated.", e); } }
[ "public", "static", "<", "T", ">", "T", "createInstance", "(", "Class", "<", "?", ">", "rawClass", ",", "Class", "<", "T", ">", "superclass", ")", "{", "try", "{", "return", "rawClass", ".", "asSubclass", "(", "superclass", ")", ".", "getConstructor", "(", ")", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "ServiceConfigurationError", "(", "\"Provider \"", "+", "rawClass", ".", "getName", "(", ")", "+", "\" could not be instantiated.\"", ",", "e", ")", ";", "}", "}" ]
Tries to create an instance of the given rawClass as a subclass of the given superclass. @param rawClass The class that is initialized. @param superclass The initialized class must be a subclass of this. @return an instance of the class given rawClass which is a subclass of the given superclass. @throws ServiceConfigurationError if any error happens.
[ "Tries", "to", "create", "an", "instance", "of", "the", "given", "rawClass", "as", "a", "subclass", "of", "the", "given", "superclass", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/internal/Provider.java#L41-L48
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/tags/propagation/BinarySerializationUtils.java
BinarySerializationUtils.createTagKey
private static final TagKey createTagKey(String name) throws TagContextDeserializationException { try { return TagKey.create(name); } catch (IllegalArgumentException e) { throw new TagContextDeserializationException("Invalid tag key: " + name, e); } }
java
private static final TagKey createTagKey(String name) throws TagContextDeserializationException { try { return TagKey.create(name); } catch (IllegalArgumentException e) { throw new TagContextDeserializationException("Invalid tag key: " + name, e); } }
[ "private", "static", "final", "TagKey", "createTagKey", "(", "String", "name", ")", "throws", "TagContextDeserializationException", "{", "try", "{", "return", "TagKey", ".", "create", "(", "name", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "TagContextDeserializationException", "(", "\"Invalid tag key: \"", "+", "name", ",", "e", ")", ";", "}", "}" ]
IllegalArgumentException here.
[ "IllegalArgumentException", "here", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/tags/propagation/BinarySerializationUtils.java#L155-L161
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/tags/propagation/BinarySerializationUtils.java
BinarySerializationUtils.createTagValue
private static final TagValue createTagValue(TagKey key, String value) throws TagContextDeserializationException { try { return TagValue.create(value); } catch (IllegalArgumentException e) { throw new TagContextDeserializationException( "Invalid tag value for key " + key + ": " + value, e); } }
java
private static final TagValue createTagValue(TagKey key, String value) throws TagContextDeserializationException { try { return TagValue.create(value); } catch (IllegalArgumentException e) { throw new TagContextDeserializationException( "Invalid tag value for key " + key + ": " + value, e); } }
[ "private", "static", "final", "TagValue", "createTagValue", "(", "TagKey", "key", ",", "String", "value", ")", "throws", "TagContextDeserializationException", "{", "try", "{", "return", "TagValue", ".", "create", "(", "value", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "TagContextDeserializationException", "(", "\"Invalid tag value for key \"", "+", "key", "+", "\": \"", "+", "value", ",", "e", ")", ";", "}", "}" ]
an IllegalArgumentException here.
[ "an", "IllegalArgumentException", "here", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/tags/propagation/BinarySerializationUtils.java#L165-L173
train
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/CreateMetricDescriptorExporter.java
CreateMetricDescriptorExporter.registerMetricDescriptor
private boolean registerMetricDescriptor( io.opencensus.metrics.export.MetricDescriptor metricDescriptor) { String metricName = metricDescriptor.getName(); io.opencensus.metrics.export.MetricDescriptor existingMetricDescriptor = registeredMetricDescriptors.get(metricName); if (existingMetricDescriptor != null) { if (existingMetricDescriptor.equals(metricDescriptor)) { // Ignore metricDescriptor that are already registered. return true; } else { logger.log( Level.WARNING, "A different metric with the same name is already registered: " + existingMetricDescriptor); return false; } } registeredMetricDescriptors.put(metricName, metricDescriptor); if (isBuiltInMetric(metricName)) { return true; // skip creating metric descriptor for stackdriver built-in metrics. } Span span = tracer.getCurrentSpan(); span.addAnnotation("Create Stackdriver Metric."); MetricDescriptor stackDriverMetricDescriptor = StackdriverExportUtils.createMetricDescriptor( metricDescriptor, projectId, domain, displayNamePrefix, constantLabels); CreateMetricDescriptorRequest request = CreateMetricDescriptorRequest.newBuilder() .setName(projectName.toString()) .setMetricDescriptor(stackDriverMetricDescriptor) .build(); try { metricServiceClient.createMetricDescriptor(request); span.addAnnotation("Finish creating MetricDescriptor."); return true; } catch (ApiException e) { logger.log(Level.WARNING, "ApiException thrown when creating MetricDescriptor.", e); span.setStatus( Status.CanonicalCode.valueOf(e.getStatusCode().getCode().name()) .toStatus() .withDescription( "ApiException thrown when creating MetricDescriptor: " + StackdriverExportUtils.exceptionMessage(e))); return false; } catch (Throwable e) { logger.log(Level.WARNING, "Exception thrown when creating MetricDescriptor.", e); span.setStatus( Status.UNKNOWN.withDescription( "Exception thrown when creating MetricDescriptor: " + StackdriverExportUtils.exceptionMessage(e))); return false; } }
java
private boolean registerMetricDescriptor( io.opencensus.metrics.export.MetricDescriptor metricDescriptor) { String metricName = metricDescriptor.getName(); io.opencensus.metrics.export.MetricDescriptor existingMetricDescriptor = registeredMetricDescriptors.get(metricName); if (existingMetricDescriptor != null) { if (existingMetricDescriptor.equals(metricDescriptor)) { // Ignore metricDescriptor that are already registered. return true; } else { logger.log( Level.WARNING, "A different metric with the same name is already registered: " + existingMetricDescriptor); return false; } } registeredMetricDescriptors.put(metricName, metricDescriptor); if (isBuiltInMetric(metricName)) { return true; // skip creating metric descriptor for stackdriver built-in metrics. } Span span = tracer.getCurrentSpan(); span.addAnnotation("Create Stackdriver Metric."); MetricDescriptor stackDriverMetricDescriptor = StackdriverExportUtils.createMetricDescriptor( metricDescriptor, projectId, domain, displayNamePrefix, constantLabels); CreateMetricDescriptorRequest request = CreateMetricDescriptorRequest.newBuilder() .setName(projectName.toString()) .setMetricDescriptor(stackDriverMetricDescriptor) .build(); try { metricServiceClient.createMetricDescriptor(request); span.addAnnotation("Finish creating MetricDescriptor."); return true; } catch (ApiException e) { logger.log(Level.WARNING, "ApiException thrown when creating MetricDescriptor.", e); span.setStatus( Status.CanonicalCode.valueOf(e.getStatusCode().getCode().name()) .toStatus() .withDescription( "ApiException thrown when creating MetricDescriptor: " + StackdriverExportUtils.exceptionMessage(e))); return false; } catch (Throwable e) { logger.log(Level.WARNING, "Exception thrown when creating MetricDescriptor.", e); span.setStatus( Status.UNKNOWN.withDescription( "Exception thrown when creating MetricDescriptor: " + StackdriverExportUtils.exceptionMessage(e))); return false; } }
[ "private", "boolean", "registerMetricDescriptor", "(", "io", ".", "opencensus", ".", "metrics", ".", "export", ".", "MetricDescriptor", "metricDescriptor", ")", "{", "String", "metricName", "=", "metricDescriptor", ".", "getName", "(", ")", ";", "io", ".", "opencensus", ".", "metrics", ".", "export", ".", "MetricDescriptor", "existingMetricDescriptor", "=", "registeredMetricDescriptors", ".", "get", "(", "metricName", ")", ";", "if", "(", "existingMetricDescriptor", "!=", "null", ")", "{", "if", "(", "existingMetricDescriptor", ".", "equals", "(", "metricDescriptor", ")", ")", "{", "// Ignore metricDescriptor that are already registered.", "return", "true", ";", "}", "else", "{", "logger", ".", "log", "(", "Level", ".", "WARNING", ",", "\"A different metric with the same name is already registered: \"", "+", "existingMetricDescriptor", ")", ";", "return", "false", ";", "}", "}", "registeredMetricDescriptors", ".", "put", "(", "metricName", ",", "metricDescriptor", ")", ";", "if", "(", "isBuiltInMetric", "(", "metricName", ")", ")", "{", "return", "true", ";", "// skip creating metric descriptor for stackdriver built-in metrics.", "}", "Span", "span", "=", "tracer", ".", "getCurrentSpan", "(", ")", ";", "span", ".", "addAnnotation", "(", "\"Create Stackdriver Metric.\"", ")", ";", "MetricDescriptor", "stackDriverMetricDescriptor", "=", "StackdriverExportUtils", ".", "createMetricDescriptor", "(", "metricDescriptor", ",", "projectId", ",", "domain", ",", "displayNamePrefix", ",", "constantLabels", ")", ";", "CreateMetricDescriptorRequest", "request", "=", "CreateMetricDescriptorRequest", ".", "newBuilder", "(", ")", ".", "setName", "(", "projectName", ".", "toString", "(", ")", ")", ".", "setMetricDescriptor", "(", "stackDriverMetricDescriptor", ")", ".", "build", "(", ")", ";", "try", "{", "metricServiceClient", ".", "createMetricDescriptor", "(", "request", ")", ";", "span", ".", "addAnnotation", "(", "\"Finish creating MetricDescriptor.\"", ")", ";", "return", "true", ";", "}", "catch", "(", "ApiException", "e", ")", "{", "logger", ".", "log", "(", "Level", ".", "WARNING", ",", "\"ApiException thrown when creating MetricDescriptor.\"", ",", "e", ")", ";", "span", ".", "setStatus", "(", "Status", ".", "CanonicalCode", ".", "valueOf", "(", "e", ".", "getStatusCode", "(", ")", ".", "getCode", "(", ")", ".", "name", "(", ")", ")", ".", "toStatus", "(", ")", ".", "withDescription", "(", "\"ApiException thrown when creating MetricDescriptor: \"", "+", "StackdriverExportUtils", ".", "exceptionMessage", "(", "e", ")", ")", ")", ";", "return", "false", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "logger", ".", "log", "(", "Level", ".", "WARNING", ",", "\"Exception thrown when creating MetricDescriptor.\"", ",", "e", ")", ";", "span", ".", "setStatus", "(", "Status", ".", "UNKNOWN", ".", "withDescription", "(", "\"Exception thrown when creating MetricDescriptor: \"", "+", "StackdriverExportUtils", ".", "exceptionMessage", "(", "e", ")", ")", ")", ";", "return", "false", ";", "}", "}" ]
exact same metric has already been registered. Returns false otherwise.
[ "exact", "same", "metric", "has", "already", "been", "registered", ".", "Returns", "false", "otherwise", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/CreateMetricDescriptorExporter.java#L78-L132
train
census-instrumentation/opencensus-java
contrib/dropwizard5/src/main/java/io/opencensus/contrib/dropwizard5/DropWizardUtils.java
DropWizardUtils.generateFullMetricName
static String generateFullMetricName(String name, String type) { return SOURCE + DELIMITER + name + DELIMITER + type; }
java
static String generateFullMetricName(String name, String type) { return SOURCE + DELIMITER + name + DELIMITER + type; }
[ "static", "String", "generateFullMetricName", "(", "String", "name", ",", "String", "type", ")", "{", "return", "SOURCE", "+", "DELIMITER", "+", "name", "+", "DELIMITER", "+", "type", ";", "}" ]
Returns the metric name. @param name the initial metric name @param type the initial type of the metric. @return a string the unique metric name
[ "Returns", "the", "metric", "name", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/dropwizard5/src/main/java/io/opencensus/contrib/dropwizard5/DropWizardUtils.java#L40-L42
train
census-instrumentation/opencensus-java
contrib/dropwizard5/src/main/java/io/opencensus/contrib/dropwizard5/DropWizardUtils.java
DropWizardUtils.generateFullMetricDescription
static String generateFullMetricDescription(String metricName, Metric metric) { return "Collected from " + SOURCE + " (metric=" + metricName + ", type=" + metric.getClass().getName() + ")"; }
java
static String generateFullMetricDescription(String metricName, Metric metric) { return "Collected from " + SOURCE + " (metric=" + metricName + ", type=" + metric.getClass().getName() + ")"; }
[ "static", "String", "generateFullMetricDescription", "(", "String", "metricName", ",", "Metric", "metric", ")", "{", "return", "\"Collected from \"", "+", "SOURCE", "+", "\" (metric=\"", "+", "metricName", "+", "\", type=\"", "+", "metric", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\")\"", ";", "}" ]
Returns the metric description. @param metricName the initial metric name @param metric the codahale metric class. @return a String the custom metric description
[ "Returns", "the", "metric", "description", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/dropwizard5/src/main/java/io/opencensus/contrib/dropwizard5/DropWizardUtils.java#L51-L59
train
census-instrumentation/opencensus-java
contrib/agent/src/main/java/io/opencensus/contrib/agent/bootstrap/ContextTrampoline.java
ContextTrampoline.setContextStrategy
public static void setContextStrategy(ContextStrategy contextStrategy) { if (ContextTrampoline.contextStrategy != null) { throw new IllegalStateException("contextStrategy was already set"); } if (contextStrategy == null) { throw new NullPointerException("contextStrategy"); } ContextTrampoline.contextStrategy = contextStrategy; }
java
public static void setContextStrategy(ContextStrategy contextStrategy) { if (ContextTrampoline.contextStrategy != null) { throw new IllegalStateException("contextStrategy was already set"); } if (contextStrategy == null) { throw new NullPointerException("contextStrategy"); } ContextTrampoline.contextStrategy = contextStrategy; }
[ "public", "static", "void", "setContextStrategy", "(", "ContextStrategy", "contextStrategy", ")", "{", "if", "(", "ContextTrampoline", ".", "contextStrategy", "!=", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"contextStrategy was already set\"", ")", ";", "}", "if", "(", "contextStrategy", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"contextStrategy\"", ")", ";", "}", "ContextTrampoline", ".", "contextStrategy", "=", "contextStrategy", ";", "}" ]
Sets the concrete strategy for accessing and manipulating the context. <p>NB: The agent is responsible for setting the context strategy once before any other method of this class is called. @param contextStrategy the concrete strategy for accessing and manipulating the context @since 0.9
[ "Sets", "the", "concrete", "strategy", "for", "accessing", "and", "manipulating", "the", "context", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/agent/src/main/java/io/opencensus/contrib/agent/bootstrap/ContextTrampoline.java#L56-L66
train
census-instrumentation/opencensus-java
exporters/trace/stackdriver/src/main/java/io/opencensus/exporter/trace/stackdriver/StackdriverV2ExporterHandler.java
StackdriverV2ExporterHandler.toAttributesProto
private static Attributes toAttributesProto( io.opencensus.trace.export.SpanData.Attributes attributes, Map<String, AttributeValue> resourceLabels, Map<String, AttributeValue> fixedAttributes) { Attributes.Builder attributesBuilder = toAttributesBuilderProto( attributes.getAttributeMap(), attributes.getDroppedAttributesCount()); attributesBuilder.putAttributeMap(AGENT_LABEL_KEY, AGENT_LABEL_VALUE); for (Entry<String, AttributeValue> entry : resourceLabels.entrySet()) { attributesBuilder.putAttributeMap(entry.getKey(), entry.getValue()); } for (Entry<String, AttributeValue> entry : fixedAttributes.entrySet()) { attributesBuilder.putAttributeMap(entry.getKey(), entry.getValue()); } return attributesBuilder.build(); }
java
private static Attributes toAttributesProto( io.opencensus.trace.export.SpanData.Attributes attributes, Map<String, AttributeValue> resourceLabels, Map<String, AttributeValue> fixedAttributes) { Attributes.Builder attributesBuilder = toAttributesBuilderProto( attributes.getAttributeMap(), attributes.getDroppedAttributesCount()); attributesBuilder.putAttributeMap(AGENT_LABEL_KEY, AGENT_LABEL_VALUE); for (Entry<String, AttributeValue> entry : resourceLabels.entrySet()) { attributesBuilder.putAttributeMap(entry.getKey(), entry.getValue()); } for (Entry<String, AttributeValue> entry : fixedAttributes.entrySet()) { attributesBuilder.putAttributeMap(entry.getKey(), entry.getValue()); } return attributesBuilder.build(); }
[ "private", "static", "Attributes", "toAttributesProto", "(", "io", ".", "opencensus", ".", "trace", ".", "export", ".", "SpanData", ".", "Attributes", "attributes", ",", "Map", "<", "String", ",", "AttributeValue", ">", "resourceLabels", ",", "Map", "<", "String", ",", "AttributeValue", ">", "fixedAttributes", ")", "{", "Attributes", ".", "Builder", "attributesBuilder", "=", "toAttributesBuilderProto", "(", "attributes", ".", "getAttributeMap", "(", ")", ",", "attributes", ".", "getDroppedAttributesCount", "(", ")", ")", ";", "attributesBuilder", ".", "putAttributeMap", "(", "AGENT_LABEL_KEY", ",", "AGENT_LABEL_VALUE", ")", ";", "for", "(", "Entry", "<", "String", ",", "AttributeValue", ">", "entry", ":", "resourceLabels", ".", "entrySet", "(", ")", ")", "{", "attributesBuilder", ".", "putAttributeMap", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "for", "(", "Entry", "<", "String", ",", "AttributeValue", ">", "entry", ":", "fixedAttributes", ".", "entrySet", "(", ")", ")", "{", "attributesBuilder", ".", "putAttributeMap", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "return", "attributesBuilder", ".", "build", "(", ")", ";", "}" ]
These are the attributes of the Span, where usually we may add more attributes like the agent.
[ "These", "are", "the", "attributes", "of", "the", "Span", "where", "usually", "we", "may", "add", "more", "attributes", "like", "the", "agent", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/stackdriver/src/main/java/io/opencensus/exporter/trace/stackdriver/StackdriverV2ExporterHandler.java#L285-L300
train
census-instrumentation/opencensus-java
exporters/trace/instana/src/main/java/io/opencensus/exporter/trace/instana/InstanaTraceExporter.java
InstanaTraceExporter.createAndRegister
public static void createAndRegister(String agentEndpoint) throws MalformedURLException { synchronized (monitor) { checkState(handler == null, "Instana exporter is already registered."); Handler newHandler = new InstanaExporterHandler(new URL(agentEndpoint)); handler = newHandler; register(Tracing.getExportComponent().getSpanExporter(), newHandler); } }
java
public static void createAndRegister(String agentEndpoint) throws MalformedURLException { synchronized (monitor) { checkState(handler == null, "Instana exporter is already registered."); Handler newHandler = new InstanaExporterHandler(new URL(agentEndpoint)); handler = newHandler; register(Tracing.getExportComponent().getSpanExporter(), newHandler); } }
[ "public", "static", "void", "createAndRegister", "(", "String", "agentEndpoint", ")", "throws", "MalformedURLException", "{", "synchronized", "(", "monitor", ")", "{", "checkState", "(", "handler", "==", "null", ",", "\"Instana exporter is already registered.\"", ")", ";", "Handler", "newHandler", "=", "new", "InstanaExporterHandler", "(", "new", "URL", "(", "agentEndpoint", ")", ")", ";", "handler", "=", "newHandler", ";", "register", "(", "Tracing", ".", "getExportComponent", "(", ")", ".", "getSpanExporter", "(", ")", ",", "newHandler", ")", ";", "}", "}" ]
Creates and registers the Instana Trace exporter to the OpenCensus library. Only one Instana exporter can be registered at any point. @param agentEndpoint Ex http://localhost:42699/com.instana.plugin.generic.trace @throws MalformedURLException if the agentEndpoint is not a valid http url. @throws IllegalStateException if a Instana exporter is already registered. @since 0.12
[ "Creates", "and", "registers", "the", "Instana", "Trace", "exporter", "to", "the", "OpenCensus", "library", ".", "Only", "one", "Instana", "exporter", "can", "be", "registered", "at", "any", "point", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/instana/src/main/java/io/opencensus/exporter/trace/instana/InstanaTraceExporter.java#L64-L71
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/trace/internal/ConcurrentIntrusiveList.java
ConcurrentIntrusiveList.getAll
public synchronized Collection<T> getAll() { List<T> all = new ArrayList<T>(size); for (T e = head; e != null; e = e.getNext()) { all.add(e); } return all; }
java
public synchronized Collection<T> getAll() { List<T> all = new ArrayList<T>(size); for (T e = head; e != null; e = e.getNext()) { all.add(e); } return all; }
[ "public", "synchronized", "Collection", "<", "T", ">", "getAll", "(", ")", "{", "List", "<", "T", ">", "all", "=", "new", "ArrayList", "<", "T", ">", "(", "size", ")", ";", "for", "(", "T", "e", "=", "head", ";", "e", "!=", "null", ";", "e", "=", "e", ".", "getNext", "(", ")", ")", "{", "all", ".", "add", "(", "e", ")", ";", "}", "return", "all", ";", "}" ]
Returns all the elements from this list. @return all the elements from this list.
[ "Returns", "all", "the", "elements", "from", "this", "list", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/trace/internal/ConcurrentIntrusiveList.java#L136-L142
train
census-instrumentation/opencensus-java
contrib/http_util/src/main/java/io/opencensus/contrib/http/AbstractHttpHandler.java
AbstractHttpHandler.handleMessageSent
public final void handleMessageSent(HttpRequestContext context, long bytes) { checkNotNull(context, "context"); context.sentMessageSize.addAndGet(bytes); if (context.span.getOptions().contains(Options.RECORD_EVENTS)) { // record compressed size recordMessageEvent(context.span, context.sentSeqId.addAndGet(1L), Type.SENT, bytes, 0L); } }
java
public final void handleMessageSent(HttpRequestContext context, long bytes) { checkNotNull(context, "context"); context.sentMessageSize.addAndGet(bytes); if (context.span.getOptions().contains(Options.RECORD_EVENTS)) { // record compressed size recordMessageEvent(context.span, context.sentSeqId.addAndGet(1L), Type.SENT, bytes, 0L); } }
[ "public", "final", "void", "handleMessageSent", "(", "HttpRequestContext", "context", ",", "long", "bytes", ")", "{", "checkNotNull", "(", "context", ",", "\"context\"", ")", ";", "context", ".", "sentMessageSize", ".", "addAndGet", "(", "bytes", ")", ";", "if", "(", "context", ".", "span", ".", "getOptions", "(", ")", ".", "contains", "(", "Options", ".", "RECORD_EVENTS", ")", ")", "{", "// record compressed size", "recordMessageEvent", "(", "context", ".", "span", ",", "context", ".", "sentSeqId", ".", "addAndGet", "(", "1L", ")", ",", "Type", ".", "SENT", ",", "bytes", ",", "0L", ")", ";", "}", "}" ]
Instrument an HTTP span after a message is sent. Typically called for every chunk of request or response is sent. @param context request specific {@link HttpRequestContext} @param bytes bytes sent. @since 0.19
[ "Instrument", "an", "HTTP", "span", "after", "a", "message", "is", "sent", ".", "Typically", "called", "for", "every", "chunk", "of", "request", "or", "response", "is", "sent", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/http_util/src/main/java/io/opencensus/contrib/http/AbstractHttpHandler.java#L77-L84
train
census-instrumentation/opencensus-java
contrib/http_util/src/main/java/io/opencensus/contrib/http/AbstractHttpHandler.java
AbstractHttpHandler.handleMessageReceived
public final void handleMessageReceived(HttpRequestContext context, long bytes) { checkNotNull(context, "context"); context.receiveMessageSize.addAndGet(bytes); if (context.span.getOptions().contains(Options.RECORD_EVENTS)) { // record compressed size recordMessageEvent( context.span, context.receviedSeqId.addAndGet(1L), Type.RECEIVED, bytes, 0L); } }
java
public final void handleMessageReceived(HttpRequestContext context, long bytes) { checkNotNull(context, "context"); context.receiveMessageSize.addAndGet(bytes); if (context.span.getOptions().contains(Options.RECORD_EVENTS)) { // record compressed size recordMessageEvent( context.span, context.receviedSeqId.addAndGet(1L), Type.RECEIVED, bytes, 0L); } }
[ "public", "final", "void", "handleMessageReceived", "(", "HttpRequestContext", "context", ",", "long", "bytes", ")", "{", "checkNotNull", "(", "context", ",", "\"context\"", ")", ";", "context", ".", "receiveMessageSize", ".", "addAndGet", "(", "bytes", ")", ";", "if", "(", "context", ".", "span", ".", "getOptions", "(", ")", ".", "contains", "(", "Options", ".", "RECORD_EVENTS", ")", ")", "{", "// record compressed size", "recordMessageEvent", "(", "context", ".", "span", ",", "context", ".", "receviedSeqId", ".", "addAndGet", "(", "1L", ")", ",", "Type", ".", "RECEIVED", ",", "bytes", ",", "0L", ")", ";", "}", "}" ]
Instrument an HTTP span after a message is received. Typically called for every chunk of request or response is received. @param context request specific {@link HttpRequestContext} @param bytes bytes received. @since 0.19
[ "Instrument", "an", "HTTP", "span", "after", "a", "message", "is", "received", ".", "Typically", "called", "for", "every", "chunk", "of", "request", "or", "response", "is", "received", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/http_util/src/main/java/io/opencensus/contrib/http/AbstractHttpHandler.java#L94-L102
train
census-instrumentation/opencensus-java
contrib/zpages/src/main/java/io/opencensus/contrib/zpages/StatszZPageHandler.java
StatszZPageHandler.findNode
@GuardedBy("monitor") private /*@Nullable*/ TreeNode findNode(/*@Nullable*/ String path) { if (Strings.isNullOrEmpty(path) || "/".equals(path)) { // Go back to the root directory. return root; } else { List<String> dirs = PATH_SPLITTER.splitToList(path); TreeNode node = root; for (int i = 0; i < dirs.size(); i++) { String dir = dirs.get(i); if ("".equals(dir) && i == 0) { continue; // Skip the first "", the path of root node. } if (!node.children.containsKey(dir)) { return null; } else { node = node.children.get(dir); } } return node; } }
java
@GuardedBy("monitor") private /*@Nullable*/ TreeNode findNode(/*@Nullable*/ String path) { if (Strings.isNullOrEmpty(path) || "/".equals(path)) { // Go back to the root directory. return root; } else { List<String> dirs = PATH_SPLITTER.splitToList(path); TreeNode node = root; for (int i = 0; i < dirs.size(); i++) { String dir = dirs.get(i); if ("".equals(dir) && i == 0) { continue; // Skip the first "", the path of root node. } if (!node.children.containsKey(dir)) { return null; } else { node = node.children.get(dir); } } return node; } }
[ "@", "GuardedBy", "(", "\"monitor\"", ")", "private", "/*@Nullable*/", "TreeNode", "findNode", "(", "/*@Nullable*/", "String", "path", ")", "{", "if", "(", "Strings", ".", "isNullOrEmpty", "(", "path", ")", "||", "\"/\"", ".", "equals", "(", "path", ")", ")", "{", "// Go back to the root directory.", "return", "root", ";", "}", "else", "{", "List", "<", "String", ">", "dirs", "=", "PATH_SPLITTER", ".", "splitToList", "(", "path", ")", ";", "TreeNode", "node", "=", "root", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "dirs", ".", "size", "(", ")", ";", "i", "++", ")", "{", "String", "dir", "=", "dirs", ".", "get", "(", "i", ")", ";", "if", "(", "\"\"", ".", "equals", "(", "dir", ")", "&&", "i", "==", "0", ")", "{", "continue", ";", "// Skip the first \"\", the path of root node.", "}", "if", "(", "!", "node", ".", "children", ".", "containsKey", "(", "dir", ")", ")", "{", "return", "null", ";", "}", "else", "{", "node", "=", "node", ".", "children", ".", "get", "(", "dir", ")", ";", "}", "}", "return", "node", ";", "}", "}" ]
Returns null if such a TreeNode doesn't exist.
[ "Returns", "null", "if", "such", "a", "TreeNode", "doesn", "t", "exist", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/zpages/src/main/java/io/opencensus/contrib/zpages/StatszZPageHandler.java#L264-L284
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/stats/IntervalBucket.java
IntervalBucket.record
void record( List</*@Nullable*/ TagValue> tagValues, double value, Map<String, AttachmentValue> attachments, Timestamp timestamp) { if (!tagValueAggregationMap.containsKey(tagValues)) { tagValueAggregationMap.put( tagValues, RecordUtils.createMutableAggregation(aggregation, measure)); } tagValueAggregationMap.get(tagValues).add(value, attachments, timestamp); }
java
void record( List</*@Nullable*/ TagValue> tagValues, double value, Map<String, AttachmentValue> attachments, Timestamp timestamp) { if (!tagValueAggregationMap.containsKey(tagValues)) { tagValueAggregationMap.put( tagValues, RecordUtils.createMutableAggregation(aggregation, measure)); } tagValueAggregationMap.get(tagValues).add(value, attachments, timestamp); }
[ "void", "record", "(", "List", "<", "/*@Nullable*/", "TagValue", ">", "tagValues", ",", "double", "value", ",", "Map", "<", "String", ",", "AttachmentValue", ">", "attachments", ",", "Timestamp", "timestamp", ")", "{", "if", "(", "!", "tagValueAggregationMap", ".", "containsKey", "(", "tagValues", ")", ")", "{", "tagValueAggregationMap", ".", "put", "(", "tagValues", ",", "RecordUtils", ".", "createMutableAggregation", "(", "aggregation", ",", "measure", ")", ")", ";", "}", "tagValueAggregationMap", ".", "get", "(", "tagValues", ")", ".", "add", "(", "value", ",", "attachments", ",", "timestamp", ")", ";", "}" ]
Puts a new value into the internal MutableAggregations, based on the TagValues.
[ "Puts", "a", "new", "value", "into", "the", "internal", "MutableAggregations", "based", "on", "the", "TagValues", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/stats/IntervalBucket.java#L65-L75
train
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java
StackdriverExportUtils.createMetricDescriptor
static MetricDescriptor createMetricDescriptor( io.opencensus.metrics.export.MetricDescriptor metricDescriptor, String projectId, String domain, String displayNamePrefix, Map<LabelKey, LabelValue> constantLabels) { MetricDescriptor.Builder builder = MetricDescriptor.newBuilder(); String type = generateType(metricDescriptor.getName(), domain); // Name format refers to // cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors/create builder.setName("projects/" + projectId + "/metricDescriptors/" + type); builder.setType(type); builder.setDescription(metricDescriptor.getDescription()); builder.setDisplayName(createDisplayName(metricDescriptor.getName(), displayNamePrefix)); for (LabelKey labelKey : metricDescriptor.getLabelKeys()) { builder.addLabels(createLabelDescriptor(labelKey)); } for (LabelKey labelKey : constantLabels.keySet()) { builder.addLabels(createLabelDescriptor(labelKey)); } builder.setUnit(metricDescriptor.getUnit()); builder.setMetricKind(createMetricKind(metricDescriptor.getType())); builder.setValueType(createValueType(metricDescriptor.getType())); return builder.build(); }
java
static MetricDescriptor createMetricDescriptor( io.opencensus.metrics.export.MetricDescriptor metricDescriptor, String projectId, String domain, String displayNamePrefix, Map<LabelKey, LabelValue> constantLabels) { MetricDescriptor.Builder builder = MetricDescriptor.newBuilder(); String type = generateType(metricDescriptor.getName(), domain); // Name format refers to // cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors/create builder.setName("projects/" + projectId + "/metricDescriptors/" + type); builder.setType(type); builder.setDescription(metricDescriptor.getDescription()); builder.setDisplayName(createDisplayName(metricDescriptor.getName(), displayNamePrefix)); for (LabelKey labelKey : metricDescriptor.getLabelKeys()) { builder.addLabels(createLabelDescriptor(labelKey)); } for (LabelKey labelKey : constantLabels.keySet()) { builder.addLabels(createLabelDescriptor(labelKey)); } builder.setUnit(metricDescriptor.getUnit()); builder.setMetricKind(createMetricKind(metricDescriptor.getType())); builder.setValueType(createValueType(metricDescriptor.getType())); return builder.build(); }
[ "static", "MetricDescriptor", "createMetricDescriptor", "(", "io", ".", "opencensus", ".", "metrics", ".", "export", ".", "MetricDescriptor", "metricDescriptor", ",", "String", "projectId", ",", "String", "domain", ",", "String", "displayNamePrefix", ",", "Map", "<", "LabelKey", ",", "LabelValue", ">", "constantLabels", ")", "{", "MetricDescriptor", ".", "Builder", "builder", "=", "MetricDescriptor", ".", "newBuilder", "(", ")", ";", "String", "type", "=", "generateType", "(", "metricDescriptor", ".", "getName", "(", ")", ",", "domain", ")", ";", "// Name format refers to", "// cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors/create", "builder", ".", "setName", "(", "\"projects/\"", "+", "projectId", "+", "\"/metricDescriptors/\"", "+", "type", ")", ";", "builder", ".", "setType", "(", "type", ")", ";", "builder", ".", "setDescription", "(", "metricDescriptor", ".", "getDescription", "(", ")", ")", ";", "builder", ".", "setDisplayName", "(", "createDisplayName", "(", "metricDescriptor", ".", "getName", "(", ")", ",", "displayNamePrefix", ")", ")", ";", "for", "(", "LabelKey", "labelKey", ":", "metricDescriptor", ".", "getLabelKeys", "(", ")", ")", "{", "builder", ".", "addLabels", "(", "createLabelDescriptor", "(", "labelKey", ")", ")", ";", "}", "for", "(", "LabelKey", "labelKey", ":", "constantLabels", ".", "keySet", "(", ")", ")", "{", "builder", ".", "addLabels", "(", "createLabelDescriptor", "(", "labelKey", ")", ")", ";", "}", "builder", ".", "setUnit", "(", "metricDescriptor", ".", "getUnit", "(", ")", ")", ";", "builder", ".", "setMetricKind", "(", "createMetricKind", "(", "metricDescriptor", ".", "getType", "(", ")", ")", ")", ";", "builder", ".", "setValueType", "(", "createValueType", "(", "metricDescriptor", ".", "getType", "(", ")", ")", ")", ";", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Convert a OpenCensus MetricDescriptor to a StackDriver MetricDescriptor
[ "Convert", "a", "OpenCensus", "MetricDescriptor", "to", "a", "StackDriver", "MetricDescriptor" ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java#L212-L238
train
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java
StackdriverExportUtils.createLabelDescriptor
@VisibleForTesting static LabelDescriptor createLabelDescriptor(LabelKey labelKey) { LabelDescriptor.Builder builder = LabelDescriptor.newBuilder(); builder.setKey(labelKey.getKey()); builder.setDescription(labelKey.getDescription()); // Now we only support String tags builder.setValueType(ValueType.STRING); return builder.build(); }
java
@VisibleForTesting static LabelDescriptor createLabelDescriptor(LabelKey labelKey) { LabelDescriptor.Builder builder = LabelDescriptor.newBuilder(); builder.setKey(labelKey.getKey()); builder.setDescription(labelKey.getDescription()); // Now we only support String tags builder.setValueType(ValueType.STRING); return builder.build(); }
[ "@", "VisibleForTesting", "static", "LabelDescriptor", "createLabelDescriptor", "(", "LabelKey", "labelKey", ")", "{", "LabelDescriptor", ".", "Builder", "builder", "=", "LabelDescriptor", ".", "newBuilder", "(", ")", ";", "builder", ".", "setKey", "(", "labelKey", ".", "getKey", "(", ")", ")", ";", "builder", ".", "setDescription", "(", "labelKey", ".", "getDescription", "(", ")", ")", ";", "// Now we only support String tags", "builder", ".", "setValueType", "(", "ValueType", ".", "STRING", ")", ";", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Construct a LabelDescriptor from a LabelKey
[ "Construct", "a", "LabelDescriptor", "from", "a", "LabelKey" ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java#L249-L257
train
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java
StackdriverExportUtils.createMetricKind
@VisibleForTesting static MetricKind createMetricKind(Type type) { if (type == Type.GAUGE_INT64 || type == Type.GAUGE_DOUBLE) { return MetricKind.GAUGE; } else if (type == Type.CUMULATIVE_INT64 || type == Type.CUMULATIVE_DOUBLE || type == Type.CUMULATIVE_DISTRIBUTION) { return MetricKind.CUMULATIVE; } return MetricKind.UNRECOGNIZED; }
java
@VisibleForTesting static MetricKind createMetricKind(Type type) { if (type == Type.GAUGE_INT64 || type == Type.GAUGE_DOUBLE) { return MetricKind.GAUGE; } else if (type == Type.CUMULATIVE_INT64 || type == Type.CUMULATIVE_DOUBLE || type == Type.CUMULATIVE_DISTRIBUTION) { return MetricKind.CUMULATIVE; } return MetricKind.UNRECOGNIZED; }
[ "@", "VisibleForTesting", "static", "MetricKind", "createMetricKind", "(", "Type", "type", ")", "{", "if", "(", "type", "==", "Type", ".", "GAUGE_INT64", "||", "type", "==", "Type", ".", "GAUGE_DOUBLE", ")", "{", "return", "MetricKind", ".", "GAUGE", ";", "}", "else", "if", "(", "type", "==", "Type", ".", "CUMULATIVE_INT64", "||", "type", "==", "Type", ".", "CUMULATIVE_DOUBLE", "||", "type", "==", "Type", ".", "CUMULATIVE_DISTRIBUTION", ")", "{", "return", "MetricKind", ".", "CUMULATIVE", ";", "}", "return", "MetricKind", ".", "UNRECOGNIZED", ";", "}" ]
Convert a OpenCensus Type to a StackDriver MetricKind
[ "Convert", "a", "OpenCensus", "Type", "to", "a", "StackDriver", "MetricKind" ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java#L260-L270
train
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java
StackdriverExportUtils.createValueType
@VisibleForTesting static MetricDescriptor.ValueType createValueType(Type type) { if (type == Type.CUMULATIVE_DOUBLE || type == Type.GAUGE_DOUBLE) { return MetricDescriptor.ValueType.DOUBLE; } else if (type == Type.GAUGE_INT64 || type == Type.CUMULATIVE_INT64) { return MetricDescriptor.ValueType.INT64; } else if (type == Type.GAUGE_DISTRIBUTION || type == Type.CUMULATIVE_DISTRIBUTION) { return MetricDescriptor.ValueType.DISTRIBUTION; } return MetricDescriptor.ValueType.UNRECOGNIZED; }
java
@VisibleForTesting static MetricDescriptor.ValueType createValueType(Type type) { if (type == Type.CUMULATIVE_DOUBLE || type == Type.GAUGE_DOUBLE) { return MetricDescriptor.ValueType.DOUBLE; } else if (type == Type.GAUGE_INT64 || type == Type.CUMULATIVE_INT64) { return MetricDescriptor.ValueType.INT64; } else if (type == Type.GAUGE_DISTRIBUTION || type == Type.CUMULATIVE_DISTRIBUTION) { return MetricDescriptor.ValueType.DISTRIBUTION; } return MetricDescriptor.ValueType.UNRECOGNIZED; }
[ "@", "VisibleForTesting", "static", "MetricDescriptor", ".", "ValueType", "createValueType", "(", "Type", "type", ")", "{", "if", "(", "type", "==", "Type", ".", "CUMULATIVE_DOUBLE", "||", "type", "==", "Type", ".", "GAUGE_DOUBLE", ")", "{", "return", "MetricDescriptor", ".", "ValueType", ".", "DOUBLE", ";", "}", "else", "if", "(", "type", "==", "Type", ".", "GAUGE_INT64", "||", "type", "==", "Type", ".", "CUMULATIVE_INT64", ")", "{", "return", "MetricDescriptor", ".", "ValueType", ".", "INT64", ";", "}", "else", "if", "(", "type", "==", "Type", ".", "GAUGE_DISTRIBUTION", "||", "type", "==", "Type", ".", "CUMULATIVE_DISTRIBUTION", ")", "{", "return", "MetricDescriptor", ".", "ValueType", ".", "DISTRIBUTION", ";", "}", "return", "MetricDescriptor", ".", "ValueType", ".", "UNRECOGNIZED", ";", "}" ]
Convert a OpenCensus Type to a StackDriver ValueType
[ "Convert", "a", "OpenCensus", "Type", "to", "a", "StackDriver", "ValueType" ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java#L273-L283
train
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java
StackdriverExportUtils.createMetric
@VisibleForTesting static Metric createMetric( io.opencensus.metrics.export.MetricDescriptor metricDescriptor, List<LabelValue> labelValues, String domain, Map<LabelKey, LabelValue> constantLabels) { Metric.Builder builder = Metric.newBuilder(); builder.setType(generateType(metricDescriptor.getName(), domain)); Map<String, String> stringTagMap = Maps.newHashMap(); List<LabelKey> labelKeys = metricDescriptor.getLabelKeys(); for (int i = 0; i < labelValues.size(); i++) { String value = labelValues.get(i).getValue(); if (value == null) { continue; } stringTagMap.put(labelKeys.get(i).getKey(), value); } for (Map.Entry<LabelKey, LabelValue> constantLabel : constantLabels.entrySet()) { String constantLabelKey = constantLabel.getKey().getKey(); String constantLabelValue = constantLabel.getValue().getValue(); constantLabelValue = constantLabelValue == null ? "" : constantLabelValue; stringTagMap.put(constantLabelKey, constantLabelValue); } builder.putAllLabels(stringTagMap); return builder.build(); }
java
@VisibleForTesting static Metric createMetric( io.opencensus.metrics.export.MetricDescriptor metricDescriptor, List<LabelValue> labelValues, String domain, Map<LabelKey, LabelValue> constantLabels) { Metric.Builder builder = Metric.newBuilder(); builder.setType(generateType(metricDescriptor.getName(), domain)); Map<String, String> stringTagMap = Maps.newHashMap(); List<LabelKey> labelKeys = metricDescriptor.getLabelKeys(); for (int i = 0; i < labelValues.size(); i++) { String value = labelValues.get(i).getValue(); if (value == null) { continue; } stringTagMap.put(labelKeys.get(i).getKey(), value); } for (Map.Entry<LabelKey, LabelValue> constantLabel : constantLabels.entrySet()) { String constantLabelKey = constantLabel.getKey().getKey(); String constantLabelValue = constantLabel.getValue().getValue(); constantLabelValue = constantLabelValue == null ? "" : constantLabelValue; stringTagMap.put(constantLabelKey, constantLabelValue); } builder.putAllLabels(stringTagMap); return builder.build(); }
[ "@", "VisibleForTesting", "static", "Metric", "createMetric", "(", "io", ".", "opencensus", ".", "metrics", ".", "export", ".", "MetricDescriptor", "metricDescriptor", ",", "List", "<", "LabelValue", ">", "labelValues", ",", "String", "domain", ",", "Map", "<", "LabelKey", ",", "LabelValue", ">", "constantLabels", ")", "{", "Metric", ".", "Builder", "builder", "=", "Metric", ".", "newBuilder", "(", ")", ";", "builder", ".", "setType", "(", "generateType", "(", "metricDescriptor", ".", "getName", "(", ")", ",", "domain", ")", ")", ";", "Map", "<", "String", ",", "String", ">", "stringTagMap", "=", "Maps", ".", "newHashMap", "(", ")", ";", "List", "<", "LabelKey", ">", "labelKeys", "=", "metricDescriptor", ".", "getLabelKeys", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "labelValues", ".", "size", "(", ")", ";", "i", "++", ")", "{", "String", "value", "=", "labelValues", ".", "get", "(", "i", ")", ".", "getValue", "(", ")", ";", "if", "(", "value", "==", "null", ")", "{", "continue", ";", "}", "stringTagMap", ".", "put", "(", "labelKeys", ".", "get", "(", "i", ")", ".", "getKey", "(", ")", ",", "value", ")", ";", "}", "for", "(", "Map", ".", "Entry", "<", "LabelKey", ",", "LabelValue", ">", "constantLabel", ":", "constantLabels", ".", "entrySet", "(", ")", ")", "{", "String", "constantLabelKey", "=", "constantLabel", ".", "getKey", "(", ")", ".", "getKey", "(", ")", ";", "String", "constantLabelValue", "=", "constantLabel", ".", "getValue", "(", ")", ".", "getValue", "(", ")", ";", "constantLabelValue", "=", "constantLabelValue", "==", "null", "?", "\"\"", ":", "constantLabelValue", ";", "stringTagMap", ".", "put", "(", "constantLabelKey", ",", "constantLabelValue", ")", ";", "}", "builder", ".", "putAllLabels", "(", "stringTagMap", ")", ";", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Create a Metric using the LabelKeys and LabelValues.
[ "Create", "a", "Metric", "using", "the", "LabelKeys", "and", "LabelValues", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java#L323-L348
train
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java
StackdriverExportUtils.createTypedValue
@VisibleForTesting static TypedValue createTypedValue(Value value) { return value.match( typedValueDoubleFunction, typedValueLongFunction, typedValueDistributionFunction, typedValueSummaryFunction, Functions.<TypedValue>throwIllegalArgumentException()); }
java
@VisibleForTesting static TypedValue createTypedValue(Value value) { return value.match( typedValueDoubleFunction, typedValueLongFunction, typedValueDistributionFunction, typedValueSummaryFunction, Functions.<TypedValue>throwIllegalArgumentException()); }
[ "@", "VisibleForTesting", "static", "TypedValue", "createTypedValue", "(", "Value", "value", ")", "{", "return", "value", ".", "match", "(", "typedValueDoubleFunction", ",", "typedValueLongFunction", ",", "typedValueDistributionFunction", ",", "typedValueSummaryFunction", ",", "Functions", ".", "<", "TypedValue", ">", "throwIllegalArgumentException", "(", ")", ")", ";", "}" ]
Note TypedValue is "A single strongly-typed value", i.e only one field should be set.
[ "Note", "TypedValue", "is", "A", "single", "strongly", "-", "typed", "value", "i", ".", "e", "only", "one", "field", "should", "be", "set", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java#L369-L377
train
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java
StackdriverExportUtils.createDistribution
@VisibleForTesting static Distribution createDistribution(io.opencensus.metrics.export.Distribution distribution) { Distribution.Builder builder = Distribution.newBuilder() .setBucketOptions(createBucketOptions(distribution.getBucketOptions())) .setCount(distribution.getCount()) .setMean( distribution.getCount() == 0 ? 0 : distribution.getSum() / distribution.getCount()) .setSumOfSquaredDeviation(distribution.getSumOfSquaredDeviations()); setBucketCountsAndExemplars(distribution.getBuckets(), builder); return builder.build(); }
java
@VisibleForTesting static Distribution createDistribution(io.opencensus.metrics.export.Distribution distribution) { Distribution.Builder builder = Distribution.newBuilder() .setBucketOptions(createBucketOptions(distribution.getBucketOptions())) .setCount(distribution.getCount()) .setMean( distribution.getCount() == 0 ? 0 : distribution.getSum() / distribution.getCount()) .setSumOfSquaredDeviation(distribution.getSumOfSquaredDeviations()); setBucketCountsAndExemplars(distribution.getBuckets(), builder); return builder.build(); }
[ "@", "VisibleForTesting", "static", "Distribution", "createDistribution", "(", "io", ".", "opencensus", ".", "metrics", ".", "export", ".", "Distribution", "distribution", ")", "{", "Distribution", ".", "Builder", "builder", "=", "Distribution", ".", "newBuilder", "(", ")", ".", "setBucketOptions", "(", "createBucketOptions", "(", "distribution", ".", "getBucketOptions", "(", ")", ")", ")", ".", "setCount", "(", "distribution", ".", "getCount", "(", ")", ")", ".", "setMean", "(", "distribution", ".", "getCount", "(", ")", "==", "0", "?", "0", ":", "distribution", ".", "getSum", "(", ")", "/", "distribution", ".", "getCount", "(", ")", ")", ".", "setSumOfSquaredDeviation", "(", "distribution", ".", "getSumOfSquaredDeviations", "(", ")", ")", ";", "setBucketCountsAndExemplars", "(", "distribution", ".", "getBuckets", "(", ")", ",", "builder", ")", ";", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Convert a OpenCensus Distribution to a StackDriver Distribution
[ "Convert", "a", "OpenCensus", "Distribution", "to", "a", "StackDriver", "Distribution" ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java#L380-L391
train
census-instrumentation/opencensus-java
exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java
StackdriverExportUtils.convertTimestamp
@VisibleForTesting static Timestamp convertTimestamp(io.opencensus.common.Timestamp censusTimestamp) { if (censusTimestamp.getSeconds() < 0) { // StackDriver doesn't handle negative timestamps. return Timestamp.newBuilder().build(); } return Timestamp.newBuilder() .setSeconds(censusTimestamp.getSeconds()) .setNanos(censusTimestamp.getNanos()) .build(); }
java
@VisibleForTesting static Timestamp convertTimestamp(io.opencensus.common.Timestamp censusTimestamp) { if (censusTimestamp.getSeconds() < 0) { // StackDriver doesn't handle negative timestamps. return Timestamp.newBuilder().build(); } return Timestamp.newBuilder() .setSeconds(censusTimestamp.getSeconds()) .setNanos(censusTimestamp.getNanos()) .build(); }
[ "@", "VisibleForTesting", "static", "Timestamp", "convertTimestamp", "(", "io", ".", "opencensus", ".", "common", ".", "Timestamp", "censusTimestamp", ")", "{", "if", "(", "censusTimestamp", ".", "getSeconds", "(", ")", "<", "0", ")", "{", "// StackDriver doesn't handle negative timestamps.", "return", "Timestamp", ".", "newBuilder", "(", ")", ".", "build", "(", ")", ";", "}", "return", "Timestamp", ".", "newBuilder", "(", ")", ".", "setSeconds", "(", "censusTimestamp", ".", "getSeconds", "(", ")", ")", ".", "setNanos", "(", "censusTimestamp", ".", "getNanos", "(", ")", ")", ".", "build", "(", ")", ";", "}" ]
Convert a OpenCensus Timestamp to a StackDriver Timestamp
[ "Convert", "a", "OpenCensus", "Timestamp", "to", "a", "StackDriver", "Timestamp" ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverExportUtils.java#L477-L487
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagContextBenchmark.java
TagContextBenchmark.tagContextCreation
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public TagContext tagContextCreation(Data data) { return TagsBenchmarksUtil.createTagContext(data.tagger.emptyBuilder(), data.numTags); }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public TagContext tagContextCreation(Data data) { return TagsBenchmarksUtil.createTagContext(data.tagger.emptyBuilder(), data.numTags); }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "TagContext", "tagContextCreation", "(", "Data", "data", ")", "{", "return", "TagsBenchmarksUtil", ".", "createTagContext", "(", "data", ".", "tagger", ".", "emptyBuilder", "(", ")", ",", "data", ".", "numTags", ")", ";", "}" ]
Create a tag context.
[ "Create", "a", "tag", "context", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagContextBenchmark.java#L65-L70
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagContextBenchmark.java
TagContextBenchmark.scopeTagContext
@BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Scope scopeTagContext(Data data) { Scope scope = data.tagger.withTagContext(data.tagContext); scope.close(); return scope; }
java
@BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Scope scopeTagContext(Data data) { Scope scope = data.tagger.withTagContext(data.tagContext); scope.close(); return scope; }
[ "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "Scope", "scopeTagContext", "(", "Data", "data", ")", "{", "Scope", "scope", "=", "data", ".", "tagger", ".", "withTagContext", "(", "data", ".", "tagContext", ")", ";", "scope", ".", "close", "(", ")", ";", "return", "scope", ";", "}" ]
Open and close a tag context scope.
[ "Open", "and", "close", "a", "tag", "context", "scope", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagContextBenchmark.java#L73-L79
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagContextBenchmark.java
TagContextBenchmark.getCurrentTagContext
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public TagContext getCurrentTagContext(Data data) { return data.tagger.getCurrentTagContext(); }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public TagContext getCurrentTagContext(Data data) { return data.tagger.getCurrentTagContext(); }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "TagContext", "getCurrentTagContext", "(", "Data", "data", ")", "{", "return", "data", ".", "tagger", ".", "getCurrentTagContext", "(", ")", ";", "}" ]
Get the current tag context.
[ "Get", "the", "current", "tag", "context", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagContextBenchmark.java#L82-L87
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagContextBenchmark.java
TagContextBenchmark.serializeTagContext
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public byte[] serializeTagContext(Data data) throws Exception { return data.serializer.toByteArray(data.tagContext); }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public byte[] serializeTagContext(Data data) throws Exception { return data.serializer.toByteArray(data.tagContext); }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "byte", "[", "]", "serializeTagContext", "(", "Data", "data", ")", "throws", "Exception", "{", "return", "data", ".", "serializer", ".", "toByteArray", "(", "data", ".", "tagContext", ")", ";", "}" ]
Serialize a tag context.
[ "Serialize", "a", "tag", "context", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagContextBenchmark.java#L90-L95
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagContextBenchmark.java
TagContextBenchmark.deserializeTagContext
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public TagContext deserializeTagContext(Data data) throws Exception { return data.serializer.fromByteArray(data.serializedTagContext); }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public TagContext deserializeTagContext(Data data) throws Exception { return data.serializer.fromByteArray(data.serializedTagContext); }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "TagContext", "deserializeTagContext", "(", "Data", "data", ")", "throws", "Exception", "{", "return", "data", ".", "serializer", ".", "fromByteArray", "(", "data", ".", "serializedTagContext", ")", ";", "}" ]
Deserialize a tag context.
[ "Deserialize", "a", "tag", "context", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagContextBenchmark.java#L98-L103
train