code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { @Deprecated static void field(final Field field, final Object obj, final Object value) throws ReflectiveOperationException { if (!field.isAccessible()) { field.setAccessible(true); } final Class<?> type = field.getType(); if (type.isPrimitive()) { if (value == null) { // @todo: WARN return; } if (type == boolean.class) { field.setBoolean(obj, (Boolean) value); return; } if (type == byte.class) { field.setByte(obj, (Byte) value); return; } if (type == char.class) { field.setChar(obj, (Character) value); return; } if (type == double.class) { field.setDouble(obj, (Double) value); return; } if (type == float.class) { field.setFloat(obj, (Float) value); return; } if (type == int.class) { field.setInt(obj, (Integer) value); return; } if (type == long.class) { // field.setLong(obj, (Long) value); if (value instanceof Number) { field.setLong(obj, ((Number) value).longValue()); return; } return; } if (type == short.class) { if (value instanceof Number) { field.setShort(obj, ((Number) value).shortValue()); return; } } } try { field.set(obj, value); } catch (final IllegalArgumentException iae) { if (type == Boolean.class) { } if (type == Byte.class) { } if (type == Short.class) { if (value instanceof Number) { field.set(obj, ((Number) value).shortValue()); return; } } if (type == Integer.class) { if (value instanceof Number) { field.set(obj, ((Number) value).intValue()); return; } } if (type == Long.class) { } if (type == Character.class) { } if (type == Float.class) { } if (type == Double.class) { } throw iae; } } }
public class class_name { @Deprecated static void field(final Field field, final Object obj, final Object value) throws ReflectiveOperationException { if (!field.isAccessible()) { field.setAccessible(true); } final Class<?> type = field.getType(); if (type.isPrimitive()) { if (value == null) { // @todo: WARN return; } if (type == boolean.class) { field.setBoolean(obj, (Boolean) value); return; } if (type == byte.class) { field.setByte(obj, (Byte) value); return; } if (type == char.class) { field.setChar(obj, (Character) value); return; } if (type == double.class) { field.setDouble(obj, (Double) value); return; } if (type == float.class) { field.setFloat(obj, (Float) value); return; } if (type == int.class) { field.setInt(obj, (Integer) value); return; } if (type == long.class) { // field.setLong(obj, (Long) value); if (value instanceof Number) { field.setLong(obj, ((Number) value).longValue()); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } return; } if (type == short.class) { if (value instanceof Number) { field.setShort(obj, ((Number) value).shortValue()); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } } } try { field.set(obj, value); } catch (final IllegalArgumentException iae) { if (type == Boolean.class) { } if (type == Byte.class) { } if (type == Short.class) { if (value instanceof Number) { field.set(obj, ((Number) value).shortValue()); return; } } if (type == Integer.class) { if (value instanceof Number) { field.set(obj, ((Number) value).intValue()); return; } } if (type == Long.class) { } if (type == Character.class) { } if (type == Float.class) { } if (type == Double.class) { } throw iae; } } }
public class class_name { @Nonnull public static FileIOError createDir (@Nonnull final File aDir) { ValueEnforcer.notNull (aDir, "Directory"); // Does the directory already exist? if (aDir.exists ()) return EFileIOErrorCode.TARGET_ALREADY_EXISTS.getAsIOError (EFileIOOperation.CREATE_DIR, aDir); // Is the parent directory writable? final File aParentDir = aDir.getParentFile (); if (aParentDir != null && aParentDir.exists () && !aParentDir.canWrite ()) return EFileIOErrorCode.SOURCE_PARENT_NOT_WRITABLE.getAsIOError (EFileIOOperation.CREATE_DIR, aDir); try { final EFileIOErrorCode eError = aDir.mkdir () ? EFileIOErrorCode.NO_ERROR : EFileIOErrorCode.OPERATION_FAILED; return eError.getAsIOError (EFileIOOperation.CREATE_DIR, aDir); } catch (final SecurityException ex) { return EFileIOErrorCode.getSecurityAsIOError (EFileIOOperation.CREATE_DIR, ex); } } }
public class class_name { @Nonnull public static FileIOError createDir (@Nonnull final File aDir) { ValueEnforcer.notNull (aDir, "Directory"); // Does the directory already exist? if (aDir.exists ()) return EFileIOErrorCode.TARGET_ALREADY_EXISTS.getAsIOError (EFileIOOperation.CREATE_DIR, aDir); // Is the parent directory writable? final File aParentDir = aDir.getParentFile (); if (aParentDir != null && aParentDir.exists () && !aParentDir.canWrite ()) return EFileIOErrorCode.SOURCE_PARENT_NOT_WRITABLE.getAsIOError (EFileIOOperation.CREATE_DIR, aDir); try { final EFileIOErrorCode eError = aDir.mkdir () ? EFileIOErrorCode.NO_ERROR : EFileIOErrorCode.OPERATION_FAILED; return eError.getAsIOError (EFileIOOperation.CREATE_DIR, aDir); // depends on control dependency: [try], data = [none] } catch (final SecurityException ex) { return EFileIOErrorCode.getSecurityAsIOError (EFileIOOperation.CREATE_DIR, ex); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static ByteAmount fromMegabytes(long megabytes) { if (megabytes >= MAX_MB) { return new ByteAmount(Long.MAX_VALUE); } else { return new ByteAmount(megabytes * MB); } } }
public class class_name { public static ByteAmount fromMegabytes(long megabytes) { if (megabytes >= MAX_MB) { return new ByteAmount(Long.MAX_VALUE); // depends on control dependency: [if], data = [none] } else { return new ByteAmount(megabytes * MB); // depends on control dependency: [if], data = [(megabytes] } } }
public class class_name { public List<String> getTables(String keyspace) { ArrayList<String> result = new ArrayList<String>(); this.metadata = this.cluster.getMetadata(); if ((!existsKeyspace(keyspace, false)) || (this.metadata.getKeyspace(keyspace).getTables().isEmpty())) { return result; } for (TableMetadata t : this.metadata.getKeyspace(keyspace).getTables()) { result.add(t.getName()); } return result; } }
public class class_name { public List<String> getTables(String keyspace) { ArrayList<String> result = new ArrayList<String>(); this.metadata = this.cluster.getMetadata(); if ((!existsKeyspace(keyspace, false)) || (this.metadata.getKeyspace(keyspace).getTables().isEmpty())) { return result; // depends on control dependency: [if], data = [none] } for (TableMetadata t : this.metadata.getKeyspace(keyspace).getTables()) { result.add(t.getName()); // depends on control dependency: [for], data = [t] } return result; } }
public class class_name { public void unbind() { if (itemView == null || controller == null) { return; } if (data != null) { this.controller.unmountView(data, itemView); } } }
public class class_name { public void unbind() { if (itemView == null || controller == null) { return; // depends on control dependency: [if], data = [none] } if (data != null) { this.controller.unmountView(data, itemView); // depends on control dependency: [if], data = [(data] } } }
public class class_name { private boolean buildRegexpParser() { // Convert wildcard string mask to regular expression String regexp = convertWildcardExpressionToRegularExpression(mStringMask); if (regexp == null) { out.println(DebugUtil.getPrefixErrorMessage(this) + "irregularity in regexp conversion - now not able to parse any strings, all strings will be rejected!"); return false; } // Instantiate a regular expression parser try { mRegexpParser = Pattern.compile(regexp); } catch (PatternSyntaxException e) { if (mDebugging) { out.println(DebugUtil.getPrefixErrorMessage(this) + "RESyntaxException \"" + e.getMessage() + "\" caught - now not able to parse any strings, all strings will be rejected!"); } if (mDebugging) { e.printStackTrace(System.err); } return false; } if (mDebugging) { out.println(DebugUtil.getPrefixDebugMessage(this) + "regular expression parser from regular expression " + regexp + " extracted from wildcard string mask " + mStringMask + "."); } return true; } }
public class class_name { private boolean buildRegexpParser() { // Convert wildcard string mask to regular expression String regexp = convertWildcardExpressionToRegularExpression(mStringMask); if (regexp == null) { out.println(DebugUtil.getPrefixErrorMessage(this) + "irregularity in regexp conversion - now not able to parse any strings, all strings will be rejected!"); // depends on control dependency: [if], data = [none] return false; // depends on control dependency: [if], data = [none] } // Instantiate a regular expression parser try { mRegexpParser = Pattern.compile(regexp); // depends on control dependency: [try], data = [none] } catch (PatternSyntaxException e) { if (mDebugging) { out.println(DebugUtil.getPrefixErrorMessage(this) + "RESyntaxException \"" + e.getMessage() + "\" caught - now not able to parse any strings, all strings will be rejected!"); // depends on control dependency: [if], data = [none] } if (mDebugging) { e.printStackTrace(System.err); // depends on control dependency: [if], data = [none] } return false; } // depends on control dependency: [catch], data = [none] if (mDebugging) { out.println(DebugUtil.getPrefixDebugMessage(this) + "regular expression parser from regular expression " + regexp + " extracted from wildcard string mask " + mStringMask + "."); // depends on control dependency: [if], data = [none] } return true; } }
public class class_name { public String[] query_device() throws DevFailed { Util.out4.println("In QueryDevice command"); final int nb_class = class_list.size(); final Vector tmp_name = new Vector(); for (int i = 0; i < nb_class; i++) { final int nb_dev = ((DeviceClass) class_list.elementAt(i)).get_device_list().size(); for (int j = 0; j < nb_dev; j++) { tmp_name.addElement(((DeviceImpl) ((DeviceClass) class_list.elementAt(i)) .get_device_list().elementAt(j)).get_name()); } } String[] ret = null; try { ret = new String[tmp_name.size()]; for (int i = 0; i < tmp_name.size(); i++) { ret[i] = (String) tmp_name.elementAt(i); } } catch (final BAD_OPERATION ex) { Util.out3.println("Memory Allocation error in DServer.query_device method"); Except.throw_exception("API_MemoryAllocation", "Can't allocate memory in server", "DServer.query_device"); } return ret; } }
public class class_name { public String[] query_device() throws DevFailed { Util.out4.println("In QueryDevice command"); final int nb_class = class_list.size(); final Vector tmp_name = new Vector(); for (int i = 0; i < nb_class; i++) { final int nb_dev = ((DeviceClass) class_list.elementAt(i)).get_device_list().size(); for (int j = 0; j < nb_dev; j++) { tmp_name.addElement(((DeviceImpl) ((DeviceClass) class_list.elementAt(i)) .get_device_list().elementAt(j)).get_name()); } } String[] ret = null; try { ret = new String[tmp_name.size()]; for (int i = 0; i < tmp_name.size(); i++) { ret[i] = (String) tmp_name.elementAt(i); // depends on control dependency: [for], data = [i] } } catch (final BAD_OPERATION ex) { Util.out3.println("Memory Allocation error in DServer.query_device method"); Except.throw_exception("API_MemoryAllocation", "Can't allocate memory in server", "DServer.query_device"); } return ret; } }
public class class_name { public void setEnvironmentVariablesOverride(java.util.Collection<EnvironmentVariable> environmentVariablesOverride) { if (environmentVariablesOverride == null) { this.environmentVariablesOverride = null; return; } this.environmentVariablesOverride = new java.util.ArrayList<EnvironmentVariable>(environmentVariablesOverride); } }
public class class_name { public void setEnvironmentVariablesOverride(java.util.Collection<EnvironmentVariable> environmentVariablesOverride) { if (environmentVariablesOverride == null) { this.environmentVariablesOverride = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.environmentVariablesOverride = new java.util.ArrayList<EnvironmentVariable>(environmentVariablesOverride); } }
public class class_name { private void updateManeuverView(String maneuverViewType, String maneuverViewModifier, @Nullable Double roundaboutAngle) { upcomingManeuverView.setManeuverTypeAndModifier(maneuverViewType, maneuverViewModifier); if (roundaboutAngle != null) { upcomingManeuverView.setRoundaboutAngle(roundaboutAngle.floatValue()); } } }
public class class_name { private void updateManeuverView(String maneuverViewType, String maneuverViewModifier, @Nullable Double roundaboutAngle) { upcomingManeuverView.setManeuverTypeAndModifier(maneuverViewType, maneuverViewModifier); if (roundaboutAngle != null) { upcomingManeuverView.setRoundaboutAngle(roundaboutAngle.floatValue()); // depends on control dependency: [if], data = [(roundaboutAngle] } } }
public class class_name { protected void removeEntry(HashEntry<K, V> entry, int hashIndex, HashEntry<K, V> previous) { if (previous == null) { data[hashIndex] = entry.next; } else { previous.next = entry.next; } } }
public class class_name { protected void removeEntry(HashEntry<K, V> entry, int hashIndex, HashEntry<K, V> previous) { if (previous == null) { data[hashIndex] = entry.next; // depends on control dependency: [if], data = [none] } else { previous.next = entry.next; // depends on control dependency: [if], data = [none] } } }
public class class_name { public void applicationRemoved(String appId, boolean cleanupLocalDirs) { logger.info("Application {} removed, cleanupLocalDirs = {}", appId, cleanupLocalDirs); Iterator<Map.Entry<AppExecId, ExecutorShuffleInfo>> it = executors.entrySet().iterator(); while (it.hasNext()) { Map.Entry<AppExecId, ExecutorShuffleInfo> entry = it.next(); AppExecId fullId = entry.getKey(); final ExecutorShuffleInfo executor = entry.getValue(); // Only touch executors associated with the appId that was removed. if (appId.equals(fullId.appId)) { it.remove(); if (db != null) { try { db.delete(dbAppExecKey(fullId)); } catch (IOException e) { logger.error("Error deleting {} from executor state db", appId, e); } } if (cleanupLocalDirs) { logger.info("Cleaning up executor {}'s {} local dirs", fullId, executor.localDirs.length); // Execute the actual deletion in a different thread, as it may take some time. directoryCleaner.execute(() -> deleteExecutorDirs(executor.localDirs)); } } } } }
public class class_name { public void applicationRemoved(String appId, boolean cleanupLocalDirs) { logger.info("Application {} removed, cleanupLocalDirs = {}", appId, cleanupLocalDirs); Iterator<Map.Entry<AppExecId, ExecutorShuffleInfo>> it = executors.entrySet().iterator(); while (it.hasNext()) { Map.Entry<AppExecId, ExecutorShuffleInfo> entry = it.next(); AppExecId fullId = entry.getKey(); final ExecutorShuffleInfo executor = entry.getValue(); // Only touch executors associated with the appId that was removed. if (appId.equals(fullId.appId)) { it.remove(); // depends on control dependency: [if], data = [none] if (db != null) { try { db.delete(dbAppExecKey(fullId)); // depends on control dependency: [try], data = [none] } catch (IOException e) { logger.error("Error deleting {} from executor state db", appId, e); } // depends on control dependency: [catch], data = [none] } if (cleanupLocalDirs) { logger.info("Cleaning up executor {}'s {} local dirs", fullId, executor.localDirs.length); // depends on control dependency: [if], data = [none] // Execute the actual deletion in a different thread, as it may take some time. directoryCleaner.execute(() -> deleteExecutorDirs(executor.localDirs)); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { public GlobalProperties getGlobalProperties() { if (this.globalProps == null) { this.globalProps = this.source.getGlobalProperties().clone(); switch (this.shipStrategy) { case BROADCAST: this.globalProps.clearUniqueFieldCombinations(); this.globalProps.setFullyReplicated(); break; case PARTITION_HASH: this.globalProps.setHashPartitioned(this.shipKeys); break; case PARTITION_RANGE: this.globalProps.setRangePartitioned(Utils.createOrdering(this.shipKeys, this.shipSortOrder)); break; case FORWARD: break; case PARTITION_RANDOM: this.globalProps.reset(); break; case PARTITION_LOCAL_HASH: if (getSource().getGlobalProperties().isPartitionedOnFields(this.shipKeys)) { // after a local hash partitioning, we can only state that the data is somehow // partitioned. even if we had a hash partitioning before over 8 partitions, // locally rehashing that onto 16 partitions (each one partition into two) gives you // a different result than directly hashing to 16 partitions. the hash-partitioning // property is only valid, if the assumed built in hash function is directly used. // hence, we can only state that this is some form of partitioning. this.globalProps.setAnyPartitioning(this.shipKeys); } else { this.globalProps.reset(); } break; case NONE: throw new CompilerException("Cannot produce GlobalProperties before ship strategy is set."); } } return this.globalProps; } }
public class class_name { public GlobalProperties getGlobalProperties() { if (this.globalProps == null) { this.globalProps = this.source.getGlobalProperties().clone(); // depends on control dependency: [if], data = [none] switch (this.shipStrategy) { case BROADCAST: this.globalProps.clearUniqueFieldCombinations(); // depends on control dependency: [if], data = [none] this.globalProps.setFullyReplicated(); // depends on control dependency: [if], data = [none] break; case PARTITION_HASH: this.globalProps.setHashPartitioned(this.shipKeys); // depends on control dependency: [if], data = [none] break; case PARTITION_RANGE: this.globalProps.setRangePartitioned(Utils.createOrdering(this.shipKeys, this.shipSortOrder)); // depends on control dependency: [if], data = [none] break; case FORWARD: break; case PARTITION_RANDOM: this.globalProps.reset(); // depends on control dependency: [if], data = [none] break; case PARTITION_LOCAL_HASH: if (getSource().getGlobalProperties().isPartitionedOnFields(this.shipKeys)) { // after a local hash partitioning, we can only state that the data is somehow // partitioned. even if we had a hash partitioning before over 8 partitions, // locally rehashing that onto 16 partitions (each one partition into two) gives you // a different result than directly hashing to 16 partitions. the hash-partitioning // property is only valid, if the assumed built in hash function is directly used. // hence, we can only state that this is some form of partitioning. this.globalProps.setAnyPartitioning(this.shipKeys); // depends on control dependency: [if], data = [none] } else { this.globalProps.reset(); // depends on control dependency: [if], data = [none] } break; case NONE: throw new CompilerException("Cannot produce GlobalProperties before ship strategy is set."); } } return this.globalProps; } }
public class class_name { private synchronized CompletableFuture<Void> join() { joinFuture = new CompletableFuture<>(); context.getThreadContext().executor().execute(() -> { // Transition the server to the appropriate state for the local member type. context.transition(member.type()); // Attempt to join the cluster. If the local member is ACTIVE then failing to join the cluster // will result in the member attempting to get elected. This allows initial clusters to form. List<MemberState> activeMembers = getActiveMemberStates(); if (!activeMembers.isEmpty()) { join(getActiveMemberStates().iterator()); } else { joinFuture.complete(null); } }); return joinFuture.whenComplete((result, error) -> joinFuture = null); } }
public class class_name { private synchronized CompletableFuture<Void> join() { joinFuture = new CompletableFuture<>(); context.getThreadContext().executor().execute(() -> { // Transition the server to the appropriate state for the local member type. context.transition(member.type()); // Attempt to join the cluster. If the local member is ACTIVE then failing to join the cluster // will result in the member attempting to get elected. This allows initial clusters to form. List<MemberState> activeMembers = getActiveMemberStates(); if (!activeMembers.isEmpty()) { join(getActiveMemberStates().iterator()); // depends on control dependency: [if], data = [none] } else { joinFuture.complete(null); // depends on control dependency: [if], data = [none] } }); return joinFuture.whenComplete((result, error) -> joinFuture = null); } }
public class class_name { public Observable<ServiceResponse<ImageAnalysis>> analyzeImageInStreamWithServiceResponseAsync(byte[] image, List<VisualFeatureTypes> visualFeatures, String details, String language) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (image == null) { throw new IllegalArgumentException("Parameter image is required and cannot be null."); } Validator.validate(visualFeatures); String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint()); String visualFeaturesConverted = this.client.serializerAdapter().serializeList(visualFeatures, CollectionFormat.CSV); RequestBody imageConverted = RequestBody.create(MediaType.parse("application/octet-stream"), image); return service.analyzeImageInStream(visualFeaturesConverted, details, language, imageConverted, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ImageAnalysis>>>() { @Override public Observable<ServiceResponse<ImageAnalysis>> call(Response<ResponseBody> response) { try { ServiceResponse<ImageAnalysis> clientResponse = analyzeImageInStreamDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } }
public class class_name { public Observable<ServiceResponse<ImageAnalysis>> analyzeImageInStreamWithServiceResponseAsync(byte[] image, List<VisualFeatureTypes> visualFeatures, String details, String language) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (image == null) { throw new IllegalArgumentException("Parameter image is required and cannot be null."); } Validator.validate(visualFeatures); String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint()); String visualFeaturesConverted = this.client.serializerAdapter().serializeList(visualFeatures, CollectionFormat.CSV); RequestBody imageConverted = RequestBody.create(MediaType.parse("application/octet-stream"), image); return service.analyzeImageInStream(visualFeaturesConverted, details, language, imageConverted, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ImageAnalysis>>>() { @Override public Observable<ServiceResponse<ImageAnalysis>> call(Response<ResponseBody> response) { try { ServiceResponse<ImageAnalysis> clientResponse = analyzeImageInStreamDelegate(response); return Observable.just(clientResponse); // depends on control dependency: [try], data = [none] } catch (Throwable t) { return Observable.error(t); } // depends on control dependency: [catch], data = [none] } }); } }
public class class_name { public boolean isValid(String value) { if (value == null) { return false; } for (Pattern pattern : patterns) { if (pattern.matcher(value).matches()) { return true; } } return false; } }
public class class_name { public boolean isValid(String value) { if (value == null) { return false; // depends on control dependency: [if], data = [none] } for (Pattern pattern : patterns) { if (pattern.matcher(value).matches()) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { public static int getScope(String scope) { int ret = PageContext.PAGE_SCOPE; // default if (REQUEST.equalsIgnoreCase(scope)) { ret = PageContext.REQUEST_SCOPE; } else if (SESSION.equalsIgnoreCase(scope)) { ret = PageContext.SESSION_SCOPE; } else if (APPLICATION.equalsIgnoreCase(scope)) { ret = PageContext.APPLICATION_SCOPE; } return ret; } }
public class class_name { public static int getScope(String scope) { int ret = PageContext.PAGE_SCOPE; // default if (REQUEST.equalsIgnoreCase(scope)) { ret = PageContext.REQUEST_SCOPE; // depends on control dependency: [if], data = [none] } else if (SESSION.equalsIgnoreCase(scope)) { ret = PageContext.SESSION_SCOPE; // depends on control dependency: [if], data = [none] } else if (APPLICATION.equalsIgnoreCase(scope)) { ret = PageContext.APPLICATION_SCOPE; // depends on control dependency: [if], data = [none] } return ret; } }
public class class_name { public OutputContext borrowOutputContext() { if (!hasOutput()) { return null; } OutputContext ctx = new OutputContext(pending); pending = null; return ctx; } }
public class class_name { public OutputContext borrowOutputContext() { if (!hasOutput()) { return null; // depends on control dependency: [if], data = [none] } OutputContext ctx = new OutputContext(pending); pending = null; return ctx; } }
public class class_name { public void write(InputStream is, boolean escape, boolean noBackslashEscapes) throws IOException { byte[] array = new byte[4096]; int len; if (escape) { while ((len = is.read(array)) > 0) { writeBytesEscaped(array, len, noBackslashEscapes); } } else { while ((len = is.read(array)) > 0) { write(array, 0, len); } } } }
public class class_name { public void write(InputStream is, boolean escape, boolean noBackslashEscapes) throws IOException { byte[] array = new byte[4096]; int len; if (escape) { while ((len = is.read(array)) > 0) { writeBytesEscaped(array, len, noBackslashEscapes); // depends on control dependency: [while], data = [none] } } else { while ((len = is.read(array)) > 0) { write(array, 0, len); // depends on control dependency: [while], data = [none] } } } }
public class class_name { public static Set<JavaClassAndMethod> resolveMethodCallTargets(InvokeInstruction invokeInstruction, TypeFrame typeFrame, ConstantPoolGen cpg) throws DataflowAnalysisException, ClassNotFoundException { short opcode = invokeInstruction.getOpcode(); if (opcode == Const.INVOKESTATIC) { HashSet<JavaClassAndMethod> result = new HashSet<>(); JavaClassAndMethod targetMethod = findInvocationLeastUpperBound(invokeInstruction, cpg, CONCRETE_METHOD); if (targetMethod != null) { result.add(targetMethod); } return result; } if (!typeFrame.isValid()) { return new HashSet<>(); } Type receiverType; boolean receiverTypeIsExact; if (opcode == Const.INVOKESPECIAL) { // invokespecial instructions are dispatched to EXACTLY // the class specified by the instruction receiverType = ObjectTypeFactory.getInstance(invokeInstruction.getClassName(cpg)); receiverTypeIsExact = false; // Doesn't actually matter } else if (opcode == Const.INVOKEDYNAMIC) { // XXX handle INVOKEDYNAMIC return new HashSet<>(); } else { // For invokevirtual and invokeinterface instructions, we have // virtual dispatch. By taking the receiver type (which may be a // subtype of the class specified by the instruction), // we may get a more precise set of call targets. int instanceStackLocation = typeFrame.getInstanceStackLocation(invokeInstruction, cpg); receiverType = typeFrame.getStackValue(instanceStackLocation); if (!(receiverType instanceof ReferenceType)) { return new HashSet<>(); } receiverTypeIsExact = typeFrame.isExact(instanceStackLocation); } if (DEBUG_METHOD_LOOKUP) { System.out.println("[receiver type is " + receiverType + ", " + (receiverTypeIsExact ? "exact]" : " not exact]")); } return resolveMethodCallTargets((ReferenceType) receiverType, invokeInstruction, cpg, receiverTypeIsExact); } }
public class class_name { public static Set<JavaClassAndMethod> resolveMethodCallTargets(InvokeInstruction invokeInstruction, TypeFrame typeFrame, ConstantPoolGen cpg) throws DataflowAnalysisException, ClassNotFoundException { short opcode = invokeInstruction.getOpcode(); if (opcode == Const.INVOKESTATIC) { HashSet<JavaClassAndMethod> result = new HashSet<>(); JavaClassAndMethod targetMethod = findInvocationLeastUpperBound(invokeInstruction, cpg, CONCRETE_METHOD); if (targetMethod != null) { result.add(targetMethod); // depends on control dependency: [if], data = [(targetMethod] } return result; } if (!typeFrame.isValid()) { return new HashSet<>(); } Type receiverType; boolean receiverTypeIsExact; if (opcode == Const.INVOKESPECIAL) { // invokespecial instructions are dispatched to EXACTLY // the class specified by the instruction receiverType = ObjectTypeFactory.getInstance(invokeInstruction.getClassName(cpg)); receiverTypeIsExact = false; // Doesn't actually matter } else if (opcode == Const.INVOKEDYNAMIC) { // XXX handle INVOKEDYNAMIC return new HashSet<>(); } else { // For invokevirtual and invokeinterface instructions, we have // virtual dispatch. By taking the receiver type (which may be a // subtype of the class specified by the instruction), // we may get a more precise set of call targets. int instanceStackLocation = typeFrame.getInstanceStackLocation(invokeInstruction, cpg); receiverType = typeFrame.getStackValue(instanceStackLocation); if (!(receiverType instanceof ReferenceType)) { return new HashSet<>(); } receiverTypeIsExact = typeFrame.isExact(instanceStackLocation); } if (DEBUG_METHOD_LOOKUP) { System.out.println("[receiver type is " + receiverType + ", " + (receiverTypeIsExact ? "exact]" : " not exact]")); } return resolveMethodCallTargets((ReferenceType) receiverType, invokeInstruction, cpg, receiverTypeIsExact); } }
public class class_name { public void setProgressBar(final ProgressBar progressBar,final int progress) { if(progressBar != null){ Activity activity = activityUtils.getCurrentActivity(false); if(activity != null){ activity.runOnUiThread(new Runnable() { public void run() { try{ progressBar.setProgress(progress); }catch (Exception ignored){} } }); } } } }
public class class_name { public void setProgressBar(final ProgressBar progressBar,final int progress) { if(progressBar != null){ Activity activity = activityUtils.getCurrentActivity(false); if(activity != null){ activity.runOnUiThread(new Runnable() { public void run() { try{ progressBar.setProgress(progress); // depends on control dependency: [try], data = [none] }catch (Exception ignored){} // depends on control dependency: [catch], data = [none] } }); // depends on control dependency: [if], data = [none] } } } }
public class class_name { @Override public RetryInfo evaluate(RetryContext retryContext, OperationContext operationContext) { boolean secondaryNotFound = this.evaluateLastAttemptAndSecondaryNotFound(retryContext); if (retryContext.getCurrentRetryCount() < this.maximumAttempts) { // If this method is called after a successful response, it means // we failed during the response body download. So, we should not // check for success codes here. int statusCode = retryContext.getLastRequestResult().getStatusCode(); if ((!secondaryNotFound && statusCode >= 300 && statusCode < 500 && statusCode != 408) || statusCode == HttpURLConnection.HTTP_NOT_IMPLEMENTED || statusCode == HttpURLConnection.HTTP_VERSION) { return null; } // Calculate backoff Interval between 80% and 120% of the desired // backoff, multiply by 2^n -1 for exponential double incrementDelta = (Math.pow(2, retryContext.getCurrentRetryCount()) - 1); final int boundedRandDelta = (int) (this.deltaBackoffIntervalInMs * 0.8) + this.randRef.nextInt((int) (this.deltaBackoffIntervalInMs * 1.2) - (int) (this.deltaBackoffIntervalInMs * 0.8)); incrementDelta *= boundedRandDelta; final long retryInterval = (int) Math.round(Math.min(this.resolvedMinBackoff + incrementDelta, this.resolvedMaxBackoff)); return this.evaluateRetryInfo(retryContext, secondaryNotFound, retryInterval); } return null; } }
public class class_name { @Override public RetryInfo evaluate(RetryContext retryContext, OperationContext operationContext) { boolean secondaryNotFound = this.evaluateLastAttemptAndSecondaryNotFound(retryContext); if (retryContext.getCurrentRetryCount() < this.maximumAttempts) { // If this method is called after a successful response, it means // we failed during the response body download. So, we should not // check for success codes here. int statusCode = retryContext.getLastRequestResult().getStatusCode(); if ((!secondaryNotFound && statusCode >= 300 && statusCode < 500 && statusCode != 408) || statusCode == HttpURLConnection.HTTP_NOT_IMPLEMENTED || statusCode == HttpURLConnection.HTTP_VERSION) { return null; // depends on control dependency: [if], data = [none] } // Calculate backoff Interval between 80% and 120% of the desired // backoff, multiply by 2^n -1 for exponential double incrementDelta = (Math.pow(2, retryContext.getCurrentRetryCount()) - 1); final int boundedRandDelta = (int) (this.deltaBackoffIntervalInMs * 0.8) + this.randRef.nextInt((int) (this.deltaBackoffIntervalInMs * 1.2) - (int) (this.deltaBackoffIntervalInMs * 0.8)); incrementDelta *= boundedRandDelta; // depends on control dependency: [if], data = [none] final long retryInterval = (int) Math.round(Math.min(this.resolvedMinBackoff + incrementDelta, this.resolvedMaxBackoff)); return this.evaluateRetryInfo(retryContext, secondaryNotFound, retryInterval); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { public List<AtomContact> getContactsWithinDistance(double distance) { List<AtomContact> list = new ArrayList<AtomContact>(); for (AtomContact contact:this.atomContacts) { if (contact.getDistance()<distance) { list.add(contact); } } return list; } }
public class class_name { public List<AtomContact> getContactsWithinDistance(double distance) { List<AtomContact> list = new ArrayList<AtomContact>(); for (AtomContact contact:this.atomContacts) { if (contact.getDistance()<distance) { list.add(contact); // depends on control dependency: [if], data = [none] } } return list; } }
public class class_name { private static IRingSet walkRingSystem(IRingSet rs, IRing ring, IRingSet newRs) { IRing tempRing; IRingSet tempRings = rs.getConnectedRings(ring); // logger.debug("walkRingSystem -> tempRings.size(): " + tempRings.size()); rs.removeAtomContainer(ring); for (IAtomContainer container : tempRings.atomContainers()) { tempRing = (IRing) container; if (!newRs.contains(tempRing)) { newRs.addAtomContainer(tempRing); newRs.add(walkRingSystem(rs, tempRing, newRs)); } } return newRs; } }
public class class_name { private static IRingSet walkRingSystem(IRingSet rs, IRing ring, IRingSet newRs) { IRing tempRing; IRingSet tempRings = rs.getConnectedRings(ring); // logger.debug("walkRingSystem -> tempRings.size(): " + tempRings.size()); rs.removeAtomContainer(ring); for (IAtomContainer container : tempRings.atomContainers()) { tempRing = (IRing) container; // depends on control dependency: [for], data = [container] if (!newRs.contains(tempRing)) { newRs.addAtomContainer(tempRing); // depends on control dependency: [if], data = [none] newRs.add(walkRingSystem(rs, tempRing, newRs)); // depends on control dependency: [if], data = [none] } } return newRs; } }
public class class_name { private final void reconnectToNewJobTracker(int connectNum) throws IOException { if (connectNum >= CONNECT_MAX_NUMBER) { LOG.error("reconnectToNewJobTracker has reached its max number."); throw new IOException("reconnectToNewJobTracker has reached its max number."); } InetSocketAddress secondaryTracker = getSecondaryTracker(); JobConf conf = getConf(); InetSocketAddress oldAddress = getCurrentClientAddress(); LOG.info("Falling back from " + oldAddress + " to secondary tracker at " + secondaryTracker + " with " + connectNum + " try"); if (secondaryTracker == null) throw new IOException("Secondary address not provided."); shutdown(); InterCoronaJobTrackerProtocol secondaryClient = RPC.waitForProxy( InterCoronaJobTrackerProtocol.class, InterCoronaJobTrackerProtocol.versionID, secondaryTracker, conf, SECONDARY_TRACKER_CONNECT_TIMEOUT); // Obtain new address InetSocketAddressWritable oldAddrWritable = new InetSocketAddressWritable( oldAddress); InetSocketAddressWritable newAddress = null; int retryNum = 0; do { newAddress = secondaryClient.getNewJobTrackerAddress(oldAddrWritable); try { waitRetry(); } catch (InterruptedException e) { LOG.error("Fallback interrupted, taking next retry."); } ++retryNum; } while (newAddress == null && predRetry(retryNum)); if (newAddress == null || newAddress.getAddress() == null) throw new IOException("Failed to obtain new job tracker address."); RPC.stopProxy(secondaryClient); try { connect(newAddress.getAddress()); LOG.info("Fallback process successful: " + newAddress.getAddress()); } catch (IOException e) { LOG.error("Fallback connect to " + newAddress.getAddress() + " failed for ", e); reconnectToNewJobTracker(++connectNum); } } }
public class class_name { private final void reconnectToNewJobTracker(int connectNum) throws IOException { if (connectNum >= CONNECT_MAX_NUMBER) { LOG.error("reconnectToNewJobTracker has reached its max number."); throw new IOException("reconnectToNewJobTracker has reached its max number."); } InetSocketAddress secondaryTracker = getSecondaryTracker(); JobConf conf = getConf(); InetSocketAddress oldAddress = getCurrentClientAddress(); LOG.info("Falling back from " + oldAddress + " to secondary tracker at " + secondaryTracker + " with " + connectNum + " try"); if (secondaryTracker == null) throw new IOException("Secondary address not provided."); shutdown(); InterCoronaJobTrackerProtocol secondaryClient = RPC.waitForProxy( InterCoronaJobTrackerProtocol.class, InterCoronaJobTrackerProtocol.versionID, secondaryTracker, conf, SECONDARY_TRACKER_CONNECT_TIMEOUT); // Obtain new address InetSocketAddressWritable oldAddrWritable = new InetSocketAddressWritable( oldAddress); InetSocketAddressWritable newAddress = null; int retryNum = 0; do { newAddress = secondaryClient.getNewJobTrackerAddress(oldAddrWritable); try { waitRetry(); // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { LOG.error("Fallback interrupted, taking next retry."); } // depends on control dependency: [catch], data = [none] ++retryNum; } while (newAddress == null && predRetry(retryNum)); if (newAddress == null || newAddress.getAddress() == null) throw new IOException("Failed to obtain new job tracker address."); RPC.stopProxy(secondaryClient); try { connect(newAddress.getAddress()); LOG.info("Fallback process successful: " + newAddress.getAddress()); } catch (IOException e) { LOG.error("Fallback connect to " + newAddress.getAddress() + " failed for ", e); reconnectToNewJobTracker(++connectNum); } } }
public class class_name { @Override public LocalDate minus(TemporalAmount amountToSubtract) { if (amountToSubtract instanceof Period) { Period periodToSubtract = (Period) amountToSubtract; return minusMonths(periodToSubtract.toTotalMonths()).minusDays(periodToSubtract.getDays()); } Objects.requireNonNull(amountToSubtract, "amountToSubtract"); return (LocalDate) amountToSubtract.subtractFrom(this); } }
public class class_name { @Override public LocalDate minus(TemporalAmount amountToSubtract) { if (amountToSubtract instanceof Period) { Period periodToSubtract = (Period) amountToSubtract; return minusMonths(periodToSubtract.toTotalMonths()).minusDays(periodToSubtract.getDays()); // depends on control dependency: [if], data = [none] } Objects.requireNonNull(amountToSubtract, "amountToSubtract"); return (LocalDate) amountToSubtract.subtractFrom(this); } }
public class class_name { public ModuleMarshal[] marshalArgs(ParameterAmp [] sourceTypes) { if (sourceTypes == null) { return new ModuleMarshal[0]; } ModuleMarshal[] marshal = new ModuleMarshal[sourceTypes.length]; for (int i = 0; i < marshal.length; i++) { marshal[i] = marshal(sourceTypes[i].rawClass()); } return marshal; } }
public class class_name { public ModuleMarshal[] marshalArgs(ParameterAmp [] sourceTypes) { if (sourceTypes == null) { return new ModuleMarshal[0]; // depends on control dependency: [if], data = [none] } ModuleMarshal[] marshal = new ModuleMarshal[sourceTypes.length]; for (int i = 0; i < marshal.length; i++) { marshal[i] = marshal(sourceTypes[i].rawClass()); // depends on control dependency: [for], data = [i] } return marshal; } }
public class class_name { private long monthRange() { ValueRange startRange = chrono.range(MONTH_OF_YEAR); if (startRange.isFixed() && startRange.isIntValue()) { return startRange.getMaximum() - startRange.getMinimum() + 1; } return -1; } }
public class class_name { private long monthRange() { ValueRange startRange = chrono.range(MONTH_OF_YEAR); if (startRange.isFixed() && startRange.isIntValue()) { return startRange.getMaximum() - startRange.getMinimum() + 1; // depends on control dependency: [if], data = [none] } return -1; } }
public class class_name { public Actions clickAndHold() { if (isBuildingActions()) { action.addAction(new ClickAndHoldAction(jsonMouse, null)); } return tick(defaultMouse.createPointerDown(LEFT.asArg())); } }
public class class_name { public Actions clickAndHold() { if (isBuildingActions()) { action.addAction(new ClickAndHoldAction(jsonMouse, null)); // depends on control dependency: [if], data = [none] } return tick(defaultMouse.createPointerDown(LEFT.asArg())); } }
public class class_name { @Transient public RequirementSummary getSummary() { RequirementSummary summary = new RequirementSummary(); for(Reference ref : references) { if(ref.getLastExecution() != null) { summary.addErrors(ref.getLastExecution().getErrors()); summary.addException(ref.getLastExecution().hasException()); summary.addFailures(ref.getLastExecution().getFailures()); summary.addSuccess(ref.getLastExecution().getSuccess()); summary.addErrors(ref.getLastExecution().getErrors()); } } summary.setReferencesSize(references.size()); return summary; } }
public class class_name { @Transient public RequirementSummary getSummary() { RequirementSummary summary = new RequirementSummary(); for(Reference ref : references) { if(ref.getLastExecution() != null) { summary.addErrors(ref.getLastExecution().getErrors()); // depends on control dependency: [if], data = [(ref.getLastExecution()] summary.addException(ref.getLastExecution().hasException()); // depends on control dependency: [if], data = [(ref.getLastExecution()] summary.addFailures(ref.getLastExecution().getFailures()); // depends on control dependency: [if], data = [(ref.getLastExecution()] summary.addSuccess(ref.getLastExecution().getSuccess()); // depends on control dependency: [if], data = [(ref.getLastExecution()] summary.addErrors(ref.getLastExecution().getErrors()); // depends on control dependency: [if], data = [(ref.getLastExecution()] } } summary.setReferencesSize(references.size()); return summary; } }
public class class_name { int nextCharLL() { int ch; if (fNextIndex >= fRB.fRules.length()) { return -1; } ch = UTF16.charAt(fRB.fRules, fNextIndex); fNextIndex = UTF16.moveCodePointOffset(fRB.fRules, fNextIndex, 1); if (ch == '\r' || ch == chNEL || ch == chLS || ch == '\n' && fLastChar != '\r') { // Character is starting a new line. Bump up the line number, and // reset the column to 0. fLineNum++; fCharNum = 0; if (fQuoteMode) { error(RBBIRuleBuilder.U_BRK_NEW_LINE_IN_QUOTED_STRING); fQuoteMode = false; } } else { // Character is not starting a new line. Except in the case of a // LF following a CR, increment the column position. if (ch != '\n') { fCharNum++; } } fLastChar = ch; return ch; } }
public class class_name { int nextCharLL() { int ch; if (fNextIndex >= fRB.fRules.length()) { return -1; // depends on control dependency: [if], data = [none] } ch = UTF16.charAt(fRB.fRules, fNextIndex); fNextIndex = UTF16.moveCodePointOffset(fRB.fRules, fNextIndex, 1); if (ch == '\r' || ch == chNEL || ch == chLS || ch == '\n' && fLastChar != '\r') { // Character is starting a new line. Bump up the line number, and // reset the column to 0. fLineNum++; // depends on control dependency: [if], data = [none] fCharNum = 0; // depends on control dependency: [if], data = [none] if (fQuoteMode) { error(RBBIRuleBuilder.U_BRK_NEW_LINE_IN_QUOTED_STRING); // depends on control dependency: [if], data = [none] fQuoteMode = false; // depends on control dependency: [if], data = [none] } } else { // Character is not starting a new line. Except in the case of a // LF following a CR, increment the column position. if (ch != '\n') { fCharNum++; // depends on control dependency: [if], data = [none] } } fLastChar = ch; return ch; } }
public class class_name { private static boolean updateFilePartition(final boolean isGrib1, final FeatureCollectionConfig config, final CollectionUpdateType updateType, boolean isTop, final Logger logger, Path dirPath) throws IOException { long start = System.currentTimeMillis(); final Formatter errlog = new Formatter(); CollectionSpecParser specp = config.getCollectionSpecParser(errlog); try (FilePartition partition = new FilePartition(config.collectionName, dirPath, isTop, config.olderThan, logger)) { partition.putAuxInfo(FeatureCollectionConfig.AUX_CONFIG, config); if (specp.getFilter() != null) partition.setStreamFilter(new StreamFilter(specp.getFilter(), specp.getFilterOnName())); logger.debug("GribCdmIndex.updateFilePartition %s %s%n", partition.getCollectionName(), updateType); if (!isUpdateNeeded(partition.getIndexFilename(NCX_SUFFIX), updateType, (isGrib1 ? GribCollectionType.Partition1 : GribCollectionType.Partition2), logger)) return false; final AtomicBoolean anyChange = new AtomicBoolean(false); // just need a mutable boolean we can declare final // redo the children here if (updateType != CollectionUpdateType.testIndexOnly) { // skip children on testIndexOnly partition.iterateOverMFileCollection(mfile -> { MCollection part = new CollectionSingleFile(mfile, logger); part.putAuxInfo(FeatureCollectionConfig.AUX_CONFIG, config); try { boolean changed = updateGribCollection(isGrib1, part, updateType, FeatureCollectionConfig.PartitionType.file, logger, errlog); if (changed) anyChange.set(true); } catch (IllegalStateException t) { logger.warn("Error making partition {} '{}'", part.getRoot(), t.getMessage()); partition.removePartition(part); // keep on truckin; can happen if directory is empty } catch (Throwable t) { logger.error("Error making partition " + part.getRoot(), t); partition.removePartition(part); } }); } // LOOK what if theres only one file? try { // redo partition index if needed, will detect if children have changed boolean recreated = updatePartition(isGrib1, partition, updateType, logger, errlog); long took = System.currentTimeMillis() - start; if (recreated) logger.info("RewriteFilePartition {} took {} msecs", partition.getCollectionName(), took); return recreated; } catch (IllegalStateException t) { logger.warn("Error making partition {} '{}'", partition.getRoot(), t.getMessage()); return false; } catch (Throwable t) { logger.error("Error making partition " + partition.getRoot(), t); return false; } } } }
public class class_name { private static boolean updateFilePartition(final boolean isGrib1, final FeatureCollectionConfig config, final CollectionUpdateType updateType, boolean isTop, final Logger logger, Path dirPath) throws IOException { long start = System.currentTimeMillis(); final Formatter errlog = new Formatter(); CollectionSpecParser specp = config.getCollectionSpecParser(errlog); try (FilePartition partition = new FilePartition(config.collectionName, dirPath, isTop, config.olderThan, logger)) { partition.putAuxInfo(FeatureCollectionConfig.AUX_CONFIG, config); if (specp.getFilter() != null) partition.setStreamFilter(new StreamFilter(specp.getFilter(), specp.getFilterOnName())); logger.debug("GribCdmIndex.updateFilePartition %s %s%n", partition.getCollectionName(), updateType); if (!isUpdateNeeded(partition.getIndexFilename(NCX_SUFFIX), updateType, (isGrib1 ? GribCollectionType.Partition1 : GribCollectionType.Partition2), logger)) return false; final AtomicBoolean anyChange = new AtomicBoolean(false); // just need a mutable boolean we can declare final // redo the children here if (updateType != CollectionUpdateType.testIndexOnly) { // skip children on testIndexOnly partition.iterateOverMFileCollection(mfile -> { MCollection part = new CollectionSingleFile(mfile, logger); // depends on control dependency: [if], data = [none] part.putAuxInfo(FeatureCollectionConfig.AUX_CONFIG, config); // depends on control dependency: [if], data = [none] try { boolean changed = updateGribCollection(isGrib1, part, updateType, FeatureCollectionConfig.PartitionType.file, logger, errlog); if (changed) anyChange.set(true); } catch (IllegalStateException t) { logger.warn("Error making partition {} '{}'", part.getRoot(), t.getMessage()); partition.removePartition(part); // keep on truckin; can happen if directory is empty } catch (Throwable t) { // depends on control dependency: [catch], data = [none] logger.error("Error making partition " + part.getRoot(), t); partition.removePartition(part); } // depends on control dependency: [catch], data = [none] }); } // LOOK what if theres only one file? try { // redo partition index if needed, will detect if children have changed boolean recreated = updatePartition(isGrib1, partition, updateType, logger, errlog); long took = System.currentTimeMillis() - start; if (recreated) logger.info("RewriteFilePartition {} took {} msecs", partition.getCollectionName(), took); return recreated; } catch (IllegalStateException t) { logger.warn("Error making partition {} '{}'", partition.getRoot(), t.getMessage()); return false; } catch (Throwable t) { logger.error("Error making partition " + partition.getRoot(), t); return false; } } } }
public class class_name { public static Vector getLocales(HttpServletRequest req) { init(); String acceptLanguage = req.getHeader("Accept-Language"); if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { logger.logp(Level.FINE, CLASS_NAME,"getLocales", "Accept-Language --> " + acceptLanguage); } // Short circuit with an empty enumeration if null header if ((acceptLanguage == null)|| (acceptLanguage.trim().length() ==0)) { Vector def = new Vector(); def.addElement(Locale.getDefault()); if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { logger.logp(Level.FINE, CLASS_NAME,"getLocales", "processed Locales --> ", def); } return def; } // Check cache Vector langList = null; langList = (Vector) localesCache.get(acceptLanguage); if (langList == null) { // Create and add to cache langList = processAcceptLanguage(acceptLanguage); if(WCCustomProperties.VALIDATE_LOCALE_VALUES){ langList = extractLocales(langList , true); } else langList = extractLocales(langList , false); localesCache.put(acceptLanguage, langList); } if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { logger.logp(Level.FINE, CLASS_NAME,"getLocales", "processed Locales --> " + langList); } return langList; } }
public class class_name { public static Vector getLocales(HttpServletRequest req) { init(); String acceptLanguage = req.getHeader("Accept-Language"); if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { logger.logp(Level.FINE, CLASS_NAME,"getLocales", "Accept-Language --> " + acceptLanguage); // depends on control dependency: [if], data = [none] } // Short circuit with an empty enumeration if null header if ((acceptLanguage == null)|| (acceptLanguage.trim().length() ==0)) { Vector def = new Vector(); def.addElement(Locale.getDefault()); // depends on control dependency: [if], data = [none] if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { logger.logp(Level.FINE, CLASS_NAME,"getLocales", "processed Locales --> ", def); // depends on control dependency: [if], data = [none] } return def; // depends on control dependency: [if], data = [none] } // Check cache Vector langList = null; langList = (Vector) localesCache.get(acceptLanguage); if (langList == null) { // Create and add to cache langList = processAcceptLanguage(acceptLanguage); // depends on control dependency: [if], data = [none] if(WCCustomProperties.VALIDATE_LOCALE_VALUES){ langList = extractLocales(langList , true); // depends on control dependency: [if], data = [none] } else langList = extractLocales(langList , false); localesCache.put(acceptLanguage, langList); // depends on control dependency: [if], data = [none] } if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { logger.logp(Level.FINE, CLASS_NAME,"getLocales", "processed Locales --> " + langList); // depends on control dependency: [if], data = [none] } return langList; } }
public class class_name { @Override public void taskCompletedWithProblems(Executor executor, Queue.Task task, long durationMS, Throwable problems) { super.taskCompletedWithProblems(executor, task, durationMS, problems); if (launcher instanceof ExecutorListener) { ((ExecutorListener)launcher).taskCompletedWithProblems(executor, task, durationMS, problems); } RetentionStrategy r = getRetentionStrategy(); if (r instanceof ExecutorListener) { ((ExecutorListener) r).taskCompletedWithProblems(executor, task, durationMS, problems); } } }
public class class_name { @Override public void taskCompletedWithProblems(Executor executor, Queue.Task task, long durationMS, Throwable problems) { super.taskCompletedWithProblems(executor, task, durationMS, problems); if (launcher instanceof ExecutorListener) { ((ExecutorListener)launcher).taskCompletedWithProblems(executor, task, durationMS, problems); // depends on control dependency: [if], data = [none] } RetentionStrategy r = getRetentionStrategy(); if (r instanceof ExecutorListener) { ((ExecutorListener) r).taskCompletedWithProblems(executor, task, durationMS, problems); // depends on control dependency: [if], data = [none] } } }
public class class_name { public Set<String> getVisibleIDs(String matchID) { Set<String> result = getVisibleIDMap().keySet(); Key fallbackKey = createKey(matchID); if (fallbackKey != null) { Set<String> temp = new HashSet<String>(result.size()); for (String id : result) { if (fallbackKey.isFallbackOf(id)) { temp.add(id); } } result = temp; } return result; } }
public class class_name { public Set<String> getVisibleIDs(String matchID) { Set<String> result = getVisibleIDMap().keySet(); Key fallbackKey = createKey(matchID); if (fallbackKey != null) { Set<String> temp = new HashSet<String>(result.size()); for (String id : result) { if (fallbackKey.isFallbackOf(id)) { temp.add(id); // depends on control dependency: [if], data = [none] } } result = temp; // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { public final List<ElasticTypeAndId> searchAndConvertHitsToIdsOnly( QueryBuilder qbParam, String indexParam, int offsetParam, int limitParam, Long ... formTypesParam) { SearchHits searchHits = this.searchWithHits( qbParam, indexParam, true, offsetParam, limitParam, formTypesParam); List<ElasticTypeAndId> returnVal = null; long totalHits; if (searchHits != null && (totalHits = searchHits.getTotalHits()) > 0) { returnVal = new ArrayList(); if((searchHits.getHits().length != totalHits) && (searchHits.getHits().length != limitParam)) { throw new FluidElasticSearchException( "The Hits and fetch count has mismatch. Total hits is '"+totalHits +"' while hits is '"+ searchHits.getHits().length+"'."); } long iterationMax = totalHits; if(limitParam > 0 && totalHits > limitParam) { iterationMax = limitParam; } //Iterate... for(int index = 0;index < iterationMax;index++) { SearchHit searchHit = searchHits.getAt(index); String idAsString; if((idAsString = searchHit.getId()) == null) { continue; } returnVal.add(new ElasticTypeAndId( this.toLongSafe(idAsString), searchHit.getType())); } } return returnVal; } }
public class class_name { public final List<ElasticTypeAndId> searchAndConvertHitsToIdsOnly( QueryBuilder qbParam, String indexParam, int offsetParam, int limitParam, Long ... formTypesParam) { SearchHits searchHits = this.searchWithHits( qbParam, indexParam, true, offsetParam, limitParam, formTypesParam); List<ElasticTypeAndId> returnVal = null; long totalHits; if (searchHits != null && (totalHits = searchHits.getTotalHits()) > 0) { returnVal = new ArrayList(); // depends on control dependency: [if], data = [none] if((searchHits.getHits().length != totalHits) && (searchHits.getHits().length != limitParam)) { throw new FluidElasticSearchException( "The Hits and fetch count has mismatch. Total hits is '"+totalHits +"' while hits is '"+ searchHits.getHits().length+"'."); } long iterationMax = totalHits; if(limitParam > 0 && totalHits > limitParam) { iterationMax = limitParam; // depends on control dependency: [if], data = [none] } //Iterate... for(int index = 0;index < iterationMax;index++) { SearchHit searchHit = searchHits.getAt(index); String idAsString; if((idAsString = searchHit.getId()) == null) { continue; } returnVal.add(new ElasticTypeAndId( this.toLongSafe(idAsString), searchHit.getType())); // depends on control dependency: [for], data = [none] } } return returnVal; } }
public class class_name { public CollisionGroup getCollisionGroup(String name) { if (groups.containsKey(name)) { return groups.get(name); } throw new LionEngineException(ERROR_FORMULA + name); } }
public class class_name { public CollisionGroup getCollisionGroup(String name) { if (groups.containsKey(name)) { return groups.get(name); // depends on control dependency: [if], data = [none] } throw new LionEngineException(ERROR_FORMULA + name); } }
public class class_name { private void appendPopulateMethod(List<CStructDescriptor> messages) { writer.formatln("public static final %s populateConfig(%s %s, int %s) {", Config.class.getName(), Config.class.getName(), CONFIG, PORTABLE_VERSION) .begin() .formatln("%s %s = new %s();", FACTORY_IMPL, INSTANCE, FACTORY_IMPL) .formatln("%s.getSerializationConfig().addPortableFactory(%s, %s);", CONFIG, FACTORY_ID, INSTANCE) .formatln("%s.getSerializationConfig().setPortableVersion(%s);", CONFIG, PORTABLE_VERSION) .appendln() .formatln("%s.getSerializationConfig()", CONFIG) .begin() .begin(); for (CStructDescriptor struct : messages) { writer.formatln(".addClassDefinition(%s.%s(%s))", INSTANCE, camelCase("get", struct.getName() + "Definition"), PORTABLE_VERSION); } writer.append(";") .end() .end() .formatln("return %s;", CONFIG) .end() .appendln("}") .newline(); } }
public class class_name { private void appendPopulateMethod(List<CStructDescriptor> messages) { writer.formatln("public static final %s populateConfig(%s %s, int %s) {", Config.class.getName(), Config.class.getName(), CONFIG, PORTABLE_VERSION) .begin() .formatln("%s %s = new %s();", FACTORY_IMPL, INSTANCE, FACTORY_IMPL) .formatln("%s.getSerializationConfig().addPortableFactory(%s, %s);", CONFIG, FACTORY_ID, INSTANCE) .formatln("%s.getSerializationConfig().setPortableVersion(%s);", CONFIG, PORTABLE_VERSION) .appendln() .formatln("%s.getSerializationConfig()", CONFIG) .begin() .begin(); for (CStructDescriptor struct : messages) { writer.formatln(".addClassDefinition(%s.%s(%s))", INSTANCE, // depends on control dependency: [for], data = [none] camelCase("get", struct.getName() + "Definition"), PORTABLE_VERSION); // depends on control dependency: [for], data = [none] } writer.append(";") .end() .end() .formatln("return %s;", CONFIG) .end() .appendln("}") .newline(); } }
public class class_name { public AppConfigurationEntry createAppConfigurationEntry(JAASLoginModuleConfig loginModule, String loginContextEntryName) { String loginModuleClassName = loginModule.getClassName(); LoginModuleControlFlag controlFlag = loginModule.getControlFlag(); Map<String, Object> options = new HashMap<String, Object>(); options.putAll(loginModule.getOptions()); if (JaasLoginConfigConstants.APPLICATION_WSLOGIN.equals(loginContextEntryName)) { options.put(WAS_IGNORE_CLIENT_CONTAINER_DD, true); } else { options.put(WAS_IGNORE_CLIENT_CONTAINER_DD, false); } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "loginModuleClassName: " + loginModuleClassName + " options: " + options.toString() + " controlFlag: " + controlFlag.toString()); } AppConfigurationEntry loginModuleEntry = new AppConfigurationEntry(loginModuleClassName, controlFlag, options); return loginModuleEntry; } }
public class class_name { public AppConfigurationEntry createAppConfigurationEntry(JAASLoginModuleConfig loginModule, String loginContextEntryName) { String loginModuleClassName = loginModule.getClassName(); LoginModuleControlFlag controlFlag = loginModule.getControlFlag(); Map<String, Object> options = new HashMap<String, Object>(); options.putAll(loginModule.getOptions()); if (JaasLoginConfigConstants.APPLICATION_WSLOGIN.equals(loginContextEntryName)) { options.put(WAS_IGNORE_CLIENT_CONTAINER_DD, true); // depends on control dependency: [if], data = [none] } else { options.put(WAS_IGNORE_CLIENT_CONTAINER_DD, false); // depends on control dependency: [if], data = [none] } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "loginModuleClassName: " + loginModuleClassName + " options: " + options.toString() + " controlFlag: " + controlFlag.toString()); // depends on control dependency: [if], data = [none] } AppConfigurationEntry loginModuleEntry = new AppConfigurationEntry(loginModuleClassName, controlFlag, options); return loginModuleEntry; } }
public class class_name { public void paintMedia (Graphics2D gfx, int layer, Rectangle dirty) { if (layer == FRONT) { _spritemgr.paint(gfx, layer, dirty); _animmgr.paint(gfx, layer, dirty); } else { _animmgr.paint(gfx, layer, dirty); _spritemgr.paint(gfx, layer, dirty); } } }
public class class_name { public void paintMedia (Graphics2D gfx, int layer, Rectangle dirty) { if (layer == FRONT) { _spritemgr.paint(gfx, layer, dirty); // depends on control dependency: [if], data = [none] _animmgr.paint(gfx, layer, dirty); // depends on control dependency: [if], data = [none] } else { _animmgr.paint(gfx, layer, dirty); // depends on control dependency: [if], data = [none] _spritemgr.paint(gfx, layer, dirty); // depends on control dependency: [if], data = [none] } } }
public class class_name { public Injector createInjector() { for (final TypeLiteral<?> typeLiteral : _inheritedTypeLiterals) { final Key<?> key = Key.get(typeLiteral); final Binding<?> binding = _parentInjector.getExistingBinding(key); if (binding != null) { if (!_adHocModule.hasBindingFor(typeLiteral)) { // Bind entry if not already bound in adhoc module!!! _adHocModule.bind(typeLiteral, binding.getProvider()); } } } final Module module = Modules.override(_parentModule).with(_adHocModule); return Guice.createInjector(module); } }
public class class_name { public Injector createInjector() { for (final TypeLiteral<?> typeLiteral : _inheritedTypeLiterals) { final Key<?> key = Key.get(typeLiteral); final Binding<?> binding = _parentInjector.getExistingBinding(key); if (binding != null) { if (!_adHocModule.hasBindingFor(typeLiteral)) { // Bind entry if not already bound in adhoc module!!! _adHocModule.bind(typeLiteral, binding.getProvider()); // depends on control dependency: [if], data = [none] } } } final Module module = Modules.override(_parentModule).with(_adHocModule); return Guice.createInjector(module); } }
public class class_name { public static ScanResult fromJSON(final String json) { final Matcher matcher = Pattern.compile("\\{[\\n\\r ]*\"format\"[ ]?:[ ]?\"([^\"]+)\"").matcher(json); if (!matcher.find()) { throw new IllegalArgumentException("JSON is not in correct format"); } if (!CURRENT_SERIALIZATION_FORMAT.equals(matcher.group(1))) { throw new IllegalArgumentException( "JSON was serialized in a different format from the format used by the current version of " + "ClassGraph -- please serialize and deserialize your ScanResult using " + "the same version of ClassGraph"); } // Deserialize the JSON final SerializationFormat deserialized = JSONDeserializer.deserializeObject(SerializationFormat.class, json); if (!deserialized.format.equals(CURRENT_SERIALIZATION_FORMAT)) { // Probably the deserialization failed before now anyway, if fields have changed, etc. throw new IllegalArgumentException("JSON was serialized by newer version of ClassGraph"); } // Perform a new "scan" with performScan set to false, which resolves all the ClasspathElement objects // and scans classpath element paths (needed for classloading), but does not scan the actual classfiles final ClassGraph classGraph = new ClassGraph(); classGraph.scanSpec = deserialized.scanSpec; classGraph.scanSpec.performScan = false; if (classGraph.scanSpec.overrideClasspath == null) { // Use the same classpath as before, if classpath was not overridden classGraph.overrideClasspath(deserialized.classpath); } final ScanResult scanResult = classGraph.scan(); scanResult.rawClasspathEltOrderStrs = deserialized.classpath; scanResult.scanSpec.performScan = true; // Set the fields related to ClassInfo in the new ScanResult, based on the deserialized JSON scanResult.scanSpec = deserialized.scanSpec; scanResult.classNameToClassInfo = new HashMap<>(); if (deserialized.classInfo != null) { for (final ClassInfo ci : deserialized.classInfo) { scanResult.classNameToClassInfo.put(ci.getName(), ci); ci.setScanResult(scanResult); } } scanResult.moduleNameToModuleInfo = new HashMap<>(); if (deserialized.moduleInfo != null) { for (final ModuleInfo mi : deserialized.moduleInfo) { scanResult.moduleNameToModuleInfo.put(mi.getName(), mi); } } scanResult.packageNameToPackageInfo = new HashMap<>(); if (deserialized.packageInfo != null) { for (final PackageInfo pi : deserialized.packageInfo) { scanResult.packageNameToPackageInfo.put(pi.getName(), pi); } } // Index Resource and ClassInfo objects scanResult.indexResourcesAndClassInfo(); scanResult.isObtainedFromDeserialization = true; return scanResult; } }
public class class_name { public static ScanResult fromJSON(final String json) { final Matcher matcher = Pattern.compile("\\{[\\n\\r ]*\"format\"[ ]?:[ ]?\"([^\"]+)\"").matcher(json); if (!matcher.find()) { throw new IllegalArgumentException("JSON is not in correct format"); } if (!CURRENT_SERIALIZATION_FORMAT.equals(matcher.group(1))) { throw new IllegalArgumentException( "JSON was serialized in a different format from the format used by the current version of " + "ClassGraph -- please serialize and deserialize your ScanResult using " + "the same version of ClassGraph"); } // Deserialize the JSON final SerializationFormat deserialized = JSONDeserializer.deserializeObject(SerializationFormat.class, json); if (!deserialized.format.equals(CURRENT_SERIALIZATION_FORMAT)) { // Probably the deserialization failed before now anyway, if fields have changed, etc. throw new IllegalArgumentException("JSON was serialized by newer version of ClassGraph"); } // Perform a new "scan" with performScan set to false, which resolves all the ClasspathElement objects // and scans classpath element paths (needed for classloading), but does not scan the actual classfiles final ClassGraph classGraph = new ClassGraph(); classGraph.scanSpec = deserialized.scanSpec; classGraph.scanSpec.performScan = false; if (classGraph.scanSpec.overrideClasspath == null) { // Use the same classpath as before, if classpath was not overridden classGraph.overrideClasspath(deserialized.classpath); // depends on control dependency: [if], data = [none] } final ScanResult scanResult = classGraph.scan(); scanResult.rawClasspathEltOrderStrs = deserialized.classpath; scanResult.scanSpec.performScan = true; // Set the fields related to ClassInfo in the new ScanResult, based on the deserialized JSON scanResult.scanSpec = deserialized.scanSpec; scanResult.classNameToClassInfo = new HashMap<>(); if (deserialized.classInfo != null) { for (final ClassInfo ci : deserialized.classInfo) { scanResult.classNameToClassInfo.put(ci.getName(), ci); // depends on control dependency: [for], data = [ci] ci.setScanResult(scanResult); // depends on control dependency: [for], data = [ci] } } scanResult.moduleNameToModuleInfo = new HashMap<>(); if (deserialized.moduleInfo != null) { for (final ModuleInfo mi : deserialized.moduleInfo) { scanResult.moduleNameToModuleInfo.put(mi.getName(), mi); // depends on control dependency: [for], data = [mi] } } scanResult.packageNameToPackageInfo = new HashMap<>(); if (deserialized.packageInfo != null) { for (final PackageInfo pi : deserialized.packageInfo) { scanResult.packageNameToPackageInfo.put(pi.getName(), pi); // depends on control dependency: [for], data = [pi] } } // Index Resource and ClassInfo objects scanResult.indexResourcesAndClassInfo(); scanResult.isObtainedFromDeserialization = true; return scanResult; } }
public class class_name { public void addScreenControls(Container parent) { FieldList record = this.getFieldList(); FieldTable table = record.getTable(); try { int iRowCount = 0; int iColumnCount = 0; table.close(); while (table.hasNext()) { table.next(); GridBagConstraints gbConstraints = this.getGBConstraints(); gbConstraints.gridx = iRowCount; gbConstraints.gridy = iColumnCount; gbConstraints.anchor = GridBagConstraints.NORTHWEST; JComponent button = this.makeMenuButton(record); GridBagLayout gridbag = (GridBagLayout)this.getScreenLayout(); gridbag.setConstraints(button, gbConstraints); parent.add(button); iRowCount++; if (iRowCount == 3) { iRowCount = 0; iColumnCount++; } } } catch (Exception ex) { ex.printStackTrace(); } } }
public class class_name { public void addScreenControls(Container parent) { FieldList record = this.getFieldList(); FieldTable table = record.getTable(); try { int iRowCount = 0; int iColumnCount = 0; table.close(); // depends on control dependency: [try], data = [none] while (table.hasNext()) { table.next(); // depends on control dependency: [while], data = [none] GridBagConstraints gbConstraints = this.getGBConstraints(); gbConstraints.gridx = iRowCount; // depends on control dependency: [while], data = [none] gbConstraints.gridy = iColumnCount; // depends on control dependency: [while], data = [none] gbConstraints.anchor = GridBagConstraints.NORTHWEST; // depends on control dependency: [while], data = [none] JComponent button = this.makeMenuButton(record); GridBagLayout gridbag = (GridBagLayout)this.getScreenLayout(); gridbag.setConstraints(button, gbConstraints); // depends on control dependency: [while], data = [none] parent.add(button); // depends on control dependency: [while], data = [none] iRowCount++; // depends on control dependency: [while], data = [none] if (iRowCount == 3) { iRowCount = 0; // depends on control dependency: [if], data = [none] iColumnCount++; // depends on control dependency: [if], data = [none] } } } catch (Exception ex) { ex.printStackTrace(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public String toBitString() { StringBuffer sb = new StringBuffer(); final int shift = this.bytes.length * 8 - this.bitLength; final byte[] shiftRight = shiftRight(this.bytes, shift); for (final byte b : shiftRight) { String asString = Integer.toBinaryString(b & 0xFF); while (asString.length() < 8) { asString = "0" + asString; } sb.append(asString); } if (sb.length() >= this.bitLength) { return sb.substring(sb.length() - this.bitLength, sb.length()); } else { final String n = sb.toString(); sb = new StringBuffer(); while (sb.length() + n.length() < this.bitLength) { sb.append("0"); } return sb + n; } } }
public class class_name { public String toBitString() { StringBuffer sb = new StringBuffer(); final int shift = this.bytes.length * 8 - this.bitLength; final byte[] shiftRight = shiftRight(this.bytes, shift); for (final byte b : shiftRight) { String asString = Integer.toBinaryString(b & 0xFF); while (asString.length() < 8) { asString = "0" + asString; // depends on control dependency: [while], data = [none] } sb.append(asString); // depends on control dependency: [for], data = [b] } if (sb.length() >= this.bitLength) { return sb.substring(sb.length() - this.bitLength, sb.length()); // depends on control dependency: [if], data = [(sb.length()] } else { final String n = sb.toString(); sb = new StringBuffer(); // depends on control dependency: [if], data = [none] while (sb.length() + n.length() < this.bitLength) { sb.append("0"); // depends on control dependency: [while], data = [none] } return sb + n; // depends on control dependency: [if], data = [none] } } }
public class class_name { public void removePortletRegistration(IPerson person, PortletDefinitionForm form) { /* TODO: Service-Layer Security Reboot (great need of refactoring with a community-approved plan in place) */ // Arguably a check here is redundant since -- in the current // portlet-manager webflow -- you can't get to this point in the // conversation with out first obtaining a PortletDefinitionForm; but // it makes sense to check permissions here as well since the route(s) // to reach this method could evolve in the future. // Let's enforce the policy that you may only delete a portlet thet's // currently in a lifecycle state you have permission to MANAGE. // (They're hierarchical.) if (!hasLifecyclePermission(person, form.getLifecycleState(), form.getCategories())) { logger.warn( "User '" + person.getUserName() + "' attempted to remove portlet '" + form.getFname() + "' without the proper MANAGE permission"); throw new SecurityException("Not Authorized"); } IPortletDefinition def = portletDefinitionRegistry.getPortletDefinition(form.getId()); /* * It's very important to remove portlets via the portletPublishingService * because that API cleans up details like category memberships and permissions. */ portletPublishingService.removePortletDefinition(def, person); } }
public class class_name { public void removePortletRegistration(IPerson person, PortletDefinitionForm form) { /* TODO: Service-Layer Security Reboot (great need of refactoring with a community-approved plan in place) */ // Arguably a check here is redundant since -- in the current // portlet-manager webflow -- you can't get to this point in the // conversation with out first obtaining a PortletDefinitionForm; but // it makes sense to check permissions here as well since the route(s) // to reach this method could evolve in the future. // Let's enforce the policy that you may only delete a portlet thet's // currently in a lifecycle state you have permission to MANAGE. // (They're hierarchical.) if (!hasLifecyclePermission(person, form.getLifecycleState(), form.getCategories())) { logger.warn( "User '" + person.getUserName() + "' attempted to remove portlet '" + form.getFname() + "' without the proper MANAGE permission"); // depends on control dependency: [if], data = [none] throw new SecurityException("Not Authorized"); } IPortletDefinition def = portletDefinitionRegistry.getPortletDefinition(form.getId()); /* * It's very important to remove portlets via the portletPublishingService * because that API cleans up details like category memberships and permissions. */ portletPublishingService.removePortletDefinition(def, person); } }
public class class_name { @SuppressWarnings("deprecation") public void destroy() { lock.lock(); try { if (httpClient != null) { httpClient.getConnectionManager().shutdown(); } } finally { cfg = null; httpClient = null; lock.unlock(); } } }
public class class_name { @SuppressWarnings("deprecation") public void destroy() { lock.lock(); try { if (httpClient != null) { httpClient.getConnectionManager().shutdown(); // depends on control dependency: [if], data = [none] } } finally { cfg = null; httpClient = null; lock.unlock(); } } }
public class class_name { public static Charset getStringEncodingCharset() { if (currentStringEncoding == null) { final String value = JanusConfig.getSystemProperty(BYTE_ARRAY_STRING_CHARSET_NAME, null); if (value != null) { try { currentStringEncoding = Charset.forName(value); if (currentStringEncoding == null) { currentStringEncoding = BYTE_ARRAY_STRING_CHARSET_VALUE; } } catch (Throwable exception) { currentStringEncoding = BYTE_ARRAY_STRING_CHARSET_VALUE; } } else { currentStringEncoding = BYTE_ARRAY_STRING_CHARSET_VALUE; } } return currentStringEncoding; } }
public class class_name { public static Charset getStringEncodingCharset() { if (currentStringEncoding == null) { final String value = JanusConfig.getSystemProperty(BYTE_ARRAY_STRING_CHARSET_NAME, null); if (value != null) { try { currentStringEncoding = Charset.forName(value); // depends on control dependency: [try], data = [none] if (currentStringEncoding == null) { currentStringEncoding = BYTE_ARRAY_STRING_CHARSET_VALUE; // depends on control dependency: [if], data = [none] } } catch (Throwable exception) { currentStringEncoding = BYTE_ARRAY_STRING_CHARSET_VALUE; } // depends on control dependency: [catch], data = [none] } else { currentStringEncoding = BYTE_ARRAY_STRING_CHARSET_VALUE; // depends on control dependency: [if], data = [none] } } return currentStringEncoding; } }
public class class_name { public void loadIsChecked () { FlatParagraphTools flatPara = new FlatParagraphTools(xContext); isChecked = flatPara.isChecked(); if (debugMode > 0) { int nChecked = 0; for (boolean bChecked : isChecked) { if(bChecked) { nChecked++; } } MessageHandler.printToLogFile("Checked parapraphs: docID: " + docID + ", Number of Paragraphs: " + isChecked.size() + ", Checked: " + nChecked + logLineBreak); } } }
public class class_name { public void loadIsChecked () { FlatParagraphTools flatPara = new FlatParagraphTools(xContext); isChecked = flatPara.isChecked(); if (debugMode > 0) { int nChecked = 0; for (boolean bChecked : isChecked) { if(bChecked) { nChecked++; // depends on control dependency: [if], data = [none] } } MessageHandler.printToLogFile("Checked parapraphs: docID: " + docID + ", Number of Paragraphs: " + isChecked.size() + ", Checked: " + nChecked + logLineBreak); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static BufferedImage convertTo(GrayU8 src, BufferedImage dst) { dst = checkInputs(src, dst); DataBuffer buffer = dst.getRaster().getDataBuffer(); try { if (buffer.getDataType() == DataBuffer.TYPE_BYTE && isKnownByteFormat(dst) ) { ConvertRaster.grayToBuffered(src, (DataBufferByte)buffer, dst.getRaster()); } else if (buffer.getDataType() == DataBuffer.TYPE_INT) { ConvertRaster.grayToBuffered(src, (DataBufferInt)buffer, dst.getRaster()); } else { ConvertRaster.grayToBuffered(src, dst); } // hack so that it knows the buffer has been modified dst.setRGB(0,0,dst.getRGB(0,0)); } catch( java.security.AccessControlException e) { ConvertRaster.grayToBuffered(src, dst); } return dst; } }
public class class_name { public static BufferedImage convertTo(GrayU8 src, BufferedImage dst) { dst = checkInputs(src, dst); DataBuffer buffer = dst.getRaster().getDataBuffer(); try { if (buffer.getDataType() == DataBuffer.TYPE_BYTE && isKnownByteFormat(dst) ) { ConvertRaster.grayToBuffered(src, (DataBufferByte)buffer, dst.getRaster()); // depends on control dependency: [if], data = [none] } else if (buffer.getDataType() == DataBuffer.TYPE_INT) { ConvertRaster.grayToBuffered(src, (DataBufferInt)buffer, dst.getRaster()); // depends on control dependency: [if], data = [none] } else { ConvertRaster.grayToBuffered(src, dst); // depends on control dependency: [if], data = [none] } // hack so that it knows the buffer has been modified dst.setRGB(0,0,dst.getRGB(0,0)); // depends on control dependency: [try], data = [none] } catch( java.security.AccessControlException e) { ConvertRaster.grayToBuffered(src, dst); } // depends on control dependency: [catch], data = [none] return dst; } }
public class class_name { public void openDialog( final I_CmsEditableData editableData, final boolean isNew, final String dependingElementId, final String mode, final CmsEditHandlerData handlerDataForNew) { if (!m_editorOpened) { m_editorOpened = true; m_handler.disableToolbarButtons(); m_handler.deactivateCurrentButton(); if (!isNew && (editableData.getStructureId() != null) && editableData.hasEditHandler()) { final String elementId = CmsContentEditor.getClientIdForEditable(editableData); m_handler.m_controller.getEditOptions( elementId, true, new I_CmsSimpleCallback<CmsDialogOptionsAndInfo>() { public void execute(CmsDialogOptionsAndInfo editOptions) { final I_CmsSimpleCallback<CmsUUID> editCallBack = new I_CmsSimpleCallback<CmsUUID>() { public void execute(CmsUUID arg) { I_CmsEditableData data = editableData; if (!data.getStructureId().equals(arg)) { // the content structure ID has changed, change the editableData data = new CmsEditableData(data); ((CmsEditableData)data).setStructureId(arg); } internalOpenDialog(data, isNew, dependingElementId, mode, null); } }; if (editOptions == null) { internalOpenDialog(editableData, isNew, dependingElementId, mode, null); } else if (editOptions.getOptions().getOptions().size() == 1) { m_handler.m_controller.prepareForEdit( elementId, editOptions.getOptions().getOptions().get(0).getValue(), editCallBack); } else { CmsOptionDialog dialog = new CmsOptionDialog( Messages.get().key(Messages.GUI_EDIT_HANDLER_SELECT_EDIT_OPTION_0), editOptions.getOptions(), editOptions.getInfo(), new I_CmsSimpleCallback<String>() { public void execute(String arg) { m_handler.m_controller.prepareForEdit(elementId, arg, editCallBack); } }); dialog.addDialogClose(new Command() { public void execute() { cancelEdit(); } }); dialog.center(); } } }); } else { internalOpenDialog(editableData, isNew, dependingElementId, mode, handlerDataForNew); } } else { CmsDebugLog.getInstance().printLine("Editor is already being opened."); } } }
public class class_name { public void openDialog( final I_CmsEditableData editableData, final boolean isNew, final String dependingElementId, final String mode, final CmsEditHandlerData handlerDataForNew) { if (!m_editorOpened) { m_editorOpened = true; // depends on control dependency: [if], data = [none] m_handler.disableToolbarButtons(); // depends on control dependency: [if], data = [none] m_handler.deactivateCurrentButton(); // depends on control dependency: [if], data = [none] if (!isNew && (editableData.getStructureId() != null) && editableData.hasEditHandler()) { final String elementId = CmsContentEditor.getClientIdForEditable(editableData); m_handler.m_controller.getEditOptions( elementId, true, new I_CmsSimpleCallback<CmsDialogOptionsAndInfo>() { public void execute(CmsDialogOptionsAndInfo editOptions) { final I_CmsSimpleCallback<CmsUUID> editCallBack = new I_CmsSimpleCallback<CmsUUID>() { public void execute(CmsUUID arg) { I_CmsEditableData data = editableData; if (!data.getStructureId().equals(arg)) { // the content structure ID has changed, change the editableData data = new CmsEditableData(data); // depends on control dependency: [if], data = [none] ((CmsEditableData)data).setStructureId(arg); // depends on control dependency: [if], data = [none] } internalOpenDialog(data, isNew, dependingElementId, mode, null); } }; if (editOptions == null) { internalOpenDialog(editableData, isNew, dependingElementId, mode, null); // depends on control dependency: [if], data = [null)] } else if (editOptions.getOptions().getOptions().size() == 1) { m_handler.m_controller.prepareForEdit( elementId, editOptions.getOptions().getOptions().get(0).getValue(), editCallBack); // depends on control dependency: [if], data = [none] } else { CmsOptionDialog dialog = new CmsOptionDialog( Messages.get().key(Messages.GUI_EDIT_HANDLER_SELECT_EDIT_OPTION_0), editOptions.getOptions(), editOptions.getInfo(), new I_CmsSimpleCallback<String>() { public void execute(String arg) { m_handler.m_controller.prepareForEdit(elementId, arg, editCallBack); } }); dialog.addDialogClose(new Command() { public void execute() { cancelEdit(); } }); // depends on control dependency: [if], data = [none] dialog.center(); // depends on control dependency: [if], data = [none] } } }); // depends on control dependency: [if], data = [none] } else { internalOpenDialog(editableData, isNew, dependingElementId, mode, handlerDataForNew); // depends on control dependency: [if], data = [none] } } else { CmsDebugLog.getInstance().printLine("Editor is already being opened."); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public BigInteger getBigInteger(final String key, final BigInteger defaultValue) { try { String value = get(key); if (value == null) { return defaultValue; } return new BigInteger(value); } catch (NumberFormatException ex) { throw new ConversionException(ex); } } }
public class class_name { @Override public BigInteger getBigInteger(final String key, final BigInteger defaultValue) { try { String value = get(key); if (value == null) { return defaultValue; // depends on control dependency: [if], data = [none] } return new BigInteger(value); // depends on control dependency: [try], data = [none] } catch (NumberFormatException ex) { throw new ConversionException(ex); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static <T> List<T> last(List<T> elements, int limit) { ArrayList<T> res = new ArrayList<T>(); for (int i = 0; i < elements.size(); i++) { if (res.size() >= limit) { break; } res.add(elements.get(elements.size() - 1 - i)); } return res; } }
public class class_name { public static <T> List<T> last(List<T> elements, int limit) { ArrayList<T> res = new ArrayList<T>(); for (int i = 0; i < elements.size(); i++) { if (res.size() >= limit) { break; } res.add(elements.get(elements.size() - 1 - i)); // depends on control dependency: [for], data = [i] } return res; } }
public class class_name { public void addArgsFor(String[] variables, DifferentialFunction function) { if (function.getOwnName() == null) throw new ND4JIllegalStateException("Instance id can not be null. Function not initialized properly"); //double check if function contains placeholder args for (val varName : variables) { if (isPlaceHolder(varName)) { placeHolderFunctions.add(function.getOwnName()); } } incomingArgs.put(variables, function); incomingArgsReverse.put(function.getOwnName(), variables); for (val variableName : variables) { List<DifferentialFunction> funcs = functionsArgsFor.get(variableName); if (funcs == null) { funcs = new ArrayList<>(); functionsArgsFor.put(variableName, funcs); } funcs.add(function); } } }
public class class_name { public void addArgsFor(String[] variables, DifferentialFunction function) { if (function.getOwnName() == null) throw new ND4JIllegalStateException("Instance id can not be null. Function not initialized properly"); //double check if function contains placeholder args for (val varName : variables) { if (isPlaceHolder(varName)) { placeHolderFunctions.add(function.getOwnName()); // depends on control dependency: [if], data = [none] } } incomingArgs.put(variables, function); incomingArgsReverse.put(function.getOwnName(), variables); for (val variableName : variables) { List<DifferentialFunction> funcs = functionsArgsFor.get(variableName); if (funcs == null) { funcs = new ArrayList<>(); // depends on control dependency: [if], data = [none] functionsArgsFor.put(variableName, funcs); // depends on control dependency: [if], data = [none] } funcs.add(function); // depends on control dependency: [for], data = [none] } } }
public class class_name { public void addIndexes(StorableInfo<S> info, Direction defaultDirection) { for (int i=info.getIndexCount(); --i>=0; ) { add(info.getIndex(i).setDefaultDirection(defaultDirection)); } } }
public class class_name { public void addIndexes(StorableInfo<S> info, Direction defaultDirection) { for (int i=info.getIndexCount(); --i>=0; ) { add(info.getIndex(i).setDefaultDirection(defaultDirection)); // depends on control dependency: [for], data = [i] } } }
public class class_name { private void registerObject(DigitalObject obj) throws StorageDeviceException { String theLabel = "the label field is no longer used"; String ownerID = "the ownerID field is no longer used"; String pid = obj.getPid(); Connection conn = null; PreparedStatement st = null; try { conn = m_connectionPool.getReadWriteConnection(); st = conn.prepareStatement(INSERT_PID_QUERY); st.setString(1, pid); st.setString(2, ownerID); st.setString(3, theLabel); st.executeUpdate(); } catch (SQLException sqle) { // clean up if the INSERT didn't succeeed try { unregisterObject(obj); } catch (Throwable th) { } // ...then notify the caller with the original exception throw new StorageDeviceException( "Unexpected error from SQL database while registering object: " + sqle.getMessage(), sqle); } finally { try { if (st != null) { st.close(); } if (conn != null) { m_connectionPool.free(conn); } } catch (Exception sqle) { throw new StorageDeviceException( "Unexpected error from SQL database while registering object: " + sqle.getMessage(), sqle); } finally { st = null; } } } }
public class class_name { private void registerObject(DigitalObject obj) throws StorageDeviceException { String theLabel = "the label field is no longer used"; String ownerID = "the ownerID field is no longer used"; String pid = obj.getPid(); Connection conn = null; PreparedStatement st = null; try { conn = m_connectionPool.getReadWriteConnection(); st = conn.prepareStatement(INSERT_PID_QUERY); st.setString(1, pid); st.setString(2, ownerID); st.setString(3, theLabel); st.executeUpdate(); } catch (SQLException sqle) { // clean up if the INSERT didn't succeeed try { unregisterObject(obj); // depends on control dependency: [try], data = [none] } catch (Throwable th) { } // depends on control dependency: [catch], data = [none] // ...then notify the caller with the original exception throw new StorageDeviceException( "Unexpected error from SQL database while registering object: " + sqle.getMessage(), sqle); } finally { try { if (st != null) { st.close(); // depends on control dependency: [if], data = [none] } if (conn != null) { m_connectionPool.free(conn); // depends on control dependency: [if], data = [(conn] } } catch (Exception sqle) { throw new StorageDeviceException( "Unexpected error from SQL database while registering object: " + sqle.getMessage(), sqle); } finally { // depends on control dependency: [catch], data = [none] st = null; } } } }
public class class_name { public Status initialize() { Date createdOn = getCreatedOn(); // set the CreatedOn date if it's not already set if (createdOn == null) { createdOn = new Date(); setCreatedOn(createdOn); } //@FIXME for now we activate on creation, unless date is supplied if (getActivationTime() == null) { setActivationTime(createdOn); } setStatus(Status.Created); return Status.Created; } }
public class class_name { public Status initialize() { Date createdOn = getCreatedOn(); // set the CreatedOn date if it's not already set if (createdOn == null) { createdOn = new Date(); // depends on control dependency: [if], data = [none] setCreatedOn(createdOn); // depends on control dependency: [if], data = [(createdOn] } //@FIXME for now we activate on creation, unless date is supplied if (getActivationTime() == null) { setActivationTime(createdOn); // depends on control dependency: [if], data = [none] } setStatus(Status.Created); return Status.Created; } }
public class class_name { @Override public void visitCode(Code obj) { Method method = getMethod(); if (prescreen(method)) { stack.resetForMethodEntry(this); regPriorities.clear(); int[] parmRegs = RegisterUtils.getParameterRegisters(method); for (int reg : parmRegs) { regPriorities.put(Integer.valueOf(reg), Values.NORMAL_BUG_PRIORITY); } if (!method.isStatic()) { regPriorities.put(Values.ZERO, Values.LOW_BUG_PRIORITY); } super.visitCode(obj); } } }
public class class_name { @Override public void visitCode(Code obj) { Method method = getMethod(); if (prescreen(method)) { stack.resetForMethodEntry(this); // depends on control dependency: [if], data = [none] regPriorities.clear(); // depends on control dependency: [if], data = [none] int[] parmRegs = RegisterUtils.getParameterRegisters(method); for (int reg : parmRegs) { regPriorities.put(Integer.valueOf(reg), Values.NORMAL_BUG_PRIORITY); // depends on control dependency: [for], data = [reg] } if (!method.isStatic()) { regPriorities.put(Values.ZERO, Values.LOW_BUG_PRIORITY); // depends on control dependency: [if], data = [none] } super.visitCode(obj); // depends on control dependency: [if], data = [none] } } }
public class class_name { private List<Event> toEvents(Collection<Item> items) { if (items.isEmpty()) { return ImmutableList.of(); } // Sort the items to match the order of their events in an attempt to get first-in-first-out. return items.stream().sorted().map(Item::toEvent).collect(Collectors.toList()); } }
public class class_name { private List<Event> toEvents(Collection<Item> items) { if (items.isEmpty()) { return ImmutableList.of(); // depends on control dependency: [if], data = [none] } // Sort the items to match the order of their events in an attempt to get first-in-first-out. return items.stream().sorted().map(Item::toEvent).collect(Collectors.toList()); } }
public class class_name { public DescribeProductAsAdminResult withProvisioningArtifactSummaries(ProvisioningArtifactSummary... provisioningArtifactSummaries) { if (this.provisioningArtifactSummaries == null) { setProvisioningArtifactSummaries(new java.util.ArrayList<ProvisioningArtifactSummary>(provisioningArtifactSummaries.length)); } for (ProvisioningArtifactSummary ele : provisioningArtifactSummaries) { this.provisioningArtifactSummaries.add(ele); } return this; } }
public class class_name { public DescribeProductAsAdminResult withProvisioningArtifactSummaries(ProvisioningArtifactSummary... provisioningArtifactSummaries) { if (this.provisioningArtifactSummaries == null) { setProvisioningArtifactSummaries(new java.util.ArrayList<ProvisioningArtifactSummary>(provisioningArtifactSummaries.length)); // depends on control dependency: [if], data = [none] } for (ProvisioningArtifactSummary ele : provisioningArtifactSummaries) { this.provisioningArtifactSummaries.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { @Override public EClass getIfcValveType() { if (ifcValveTypeEClass == null) { ifcValveTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(748); } return ifcValveTypeEClass; } }
public class class_name { @Override public EClass getIfcValveType() { if (ifcValveTypeEClass == null) { ifcValveTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(748); // depends on control dependency: [if], data = [none] } return ifcValveTypeEClass; } }
public class class_name { public static KeyStore newKeyStore(final String type, final String password, final File keystoreFile, final boolean newEmpty) throws NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyStoreException { final KeyStore keyStore = KeyStore.getInstance(type); if (newEmpty) { keyStore.load(null, password.toCharArray()); if (!keystoreFile.exists()) { keystoreFile.createNewFile(); } OutputStream out = new FileOutputStream(keystoreFile); keyStore.store(out, password.toCharArray()); return keyStore; } keyStore.load(new FileInputStream(keystoreFile), password.toCharArray()); return keyStore; } }
public class class_name { public static KeyStore newKeyStore(final String type, final String password, final File keystoreFile, final boolean newEmpty) throws NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyStoreException { final KeyStore keyStore = KeyStore.getInstance(type); if (newEmpty) { keyStore.load(null, password.toCharArray()); if (!keystoreFile.exists()) { keystoreFile.createNewFile(); // depends on control dependency: [if], data = [none] } OutputStream out = new FileOutputStream(keystoreFile); keyStore.store(out, password.toCharArray()); return keyStore; } keyStore.load(new FileInputStream(keystoreFile), password.toCharArray()); return keyStore; } }
public class class_name { private void fillToolBar(final I_CmsAppUIContext context) { context.setAppTitle(m_messages.key(Messages.GUI_APP_TITLE_0)); // create components Component publishBtn = createPublishButton(); m_saveBtn = createSaveButton(); m_saveExitBtn = createSaveExitButton(); Component closeBtn = createCloseButton(); context.enableDefaultToolbarButtons(false); context.addToolbarButtonRight(closeBtn); context.addToolbarButton(publishBtn); context.addToolbarButton(m_saveExitBtn); context.addToolbarButton(m_saveBtn); Component addDescriptorBtn = createAddDescriptorButton(); if (m_model.hasDescriptor() || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) { addDescriptorBtn.setEnabled(false); } context.addToolbarButton(addDescriptorBtn); if (m_model.getBundleType().equals(BundleType.XML)) { Component convertToPropertyBundleBtn = createConvertToPropertyBundleButton(); context.addToolbarButton(convertToPropertyBundleBtn); } } }
public class class_name { private void fillToolBar(final I_CmsAppUIContext context) { context.setAppTitle(m_messages.key(Messages.GUI_APP_TITLE_0)); // create components Component publishBtn = createPublishButton(); m_saveBtn = createSaveButton(); m_saveExitBtn = createSaveExitButton(); Component closeBtn = createCloseButton(); context.enableDefaultToolbarButtons(false); context.addToolbarButtonRight(closeBtn); context.addToolbarButton(publishBtn); context.addToolbarButton(m_saveExitBtn); context.addToolbarButton(m_saveBtn); Component addDescriptorBtn = createAddDescriptorButton(); if (m_model.hasDescriptor() || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) { addDescriptorBtn.setEnabled(false); // depends on control dependency: [if], data = [none] } context.addToolbarButton(addDescriptorBtn); if (m_model.getBundleType().equals(BundleType.XML)) { Component convertToPropertyBundleBtn = createConvertToPropertyBundleButton(); context.addToolbarButton(convertToPropertyBundleBtn); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void execute() throws IOException { // Future todo: Use JNI and librsync library? Runtime run = Runtime.getRuntime(); try { String command ; if(excludeDir != null && !excludeDir.isEmpty()) { command= "rsync -rv --delete --exclude "+ excludeDir + " " + src + " " + dst; } else { command= "rsync -rv --delete " + src + " " + dst; } if (LOG.isDebugEnabled()) { LOG.debug("Rsync job started: " + command); } if (userName != null && password != null) { String[] envProperties = new String[]{RSYNC_USER_SYSTEM_PROPERTY + "=" + userName, RSYNC_PASSWORD_SYSTEM_PROPERTY + "=" + password}; process = run.exec(command, envProperties); } else { process = run.exec(command); } // Handle process Standard and Error output InputStream stderr = process.getErrorStream(); InputStreamReader isrErr = new InputStreamReader(stderr); BufferedReader brErr = new BufferedReader(isrErr); InputStream stdout = process.getInputStream(); InputStreamReader isrStd = new InputStreamReader(stdout); BufferedReader brStd = new BufferedReader(isrStd); String val = null; StringBuilder stringBuilderErr = new StringBuilder(); StringBuilder stringBuilderStd = new StringBuilder(); while ((val = brStd.readLine()) != null) { stringBuilderStd.append(val); stringBuilderStd.append('\n'); } while ((val = brErr.readLine()) != null) { stringBuilderErr.append(val); stringBuilderErr.append('\n'); } Integer returnCode = null; // wait for thread while (returnCode == null) { try { returnCode = process.waitFor(); } catch (InterruptedException e) { // oops, this can happen sometimes } } if (LOG.isDebugEnabled()) { LOG.debug("Rsync job finished: " + returnCode + ". Error stream output \n" + stringBuilderErr.toString() + " Standard stream output \n" + stringBuilderStd.toString()); } if (returnCode != 0) { throw new IOException("RSync job finished with exit code is " + returnCode + ". Error stream output: \n" + stringBuilderErr.toString()); } } finally { process = null; } } }
public class class_name { public void execute() throws IOException { // Future todo: Use JNI and librsync library? Runtime run = Runtime.getRuntime(); try { String command ; if(excludeDir != null && !excludeDir.isEmpty()) { command= "rsync -rv --delete --exclude "+ excludeDir + " " + src + " " + dst; // depends on control dependency: [if], data = [none] } else { command= "rsync -rv --delete " + src + " " + dst; // depends on control dependency: [if], data = [none] } if (LOG.isDebugEnabled()) { LOG.debug("Rsync job started: " + command); // depends on control dependency: [if], data = [none] } if (userName != null && password != null) { String[] envProperties = new String[]{RSYNC_USER_SYSTEM_PROPERTY + "=" + userName, RSYNC_PASSWORD_SYSTEM_PROPERTY + "=" + password}; process = run.exec(command, envProperties); // depends on control dependency: [if], data = [none] } else { process = run.exec(command); // depends on control dependency: [if], data = [none] } // Handle process Standard and Error output InputStream stderr = process.getErrorStream(); InputStreamReader isrErr = new InputStreamReader(stderr); BufferedReader brErr = new BufferedReader(isrErr); InputStream stdout = process.getInputStream(); InputStreamReader isrStd = new InputStreamReader(stdout); BufferedReader brStd = new BufferedReader(isrStd); String val = null; StringBuilder stringBuilderErr = new StringBuilder(); StringBuilder stringBuilderStd = new StringBuilder(); while ((val = brStd.readLine()) != null) { stringBuilderStd.append(val); // depends on control dependency: [while], data = [none] stringBuilderStd.append('\n'); // depends on control dependency: [while], data = [none] } while ((val = brErr.readLine()) != null) { stringBuilderErr.append(val); // depends on control dependency: [while], data = [none] stringBuilderErr.append('\n'); // depends on control dependency: [while], data = [none] } Integer returnCode = null; // wait for thread while (returnCode == null) { try { returnCode = process.waitFor(); // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { // oops, this can happen sometimes } // depends on control dependency: [catch], data = [none] } if (LOG.isDebugEnabled()) { LOG.debug("Rsync job finished: " + returnCode + ". Error stream output \n" + stringBuilderErr.toString() + " Standard stream output \n" + stringBuilderStd.toString()); // depends on control dependency: [if], data = [none] } if (returnCode != 0) { throw new IOException("RSync job finished with exit code is " + returnCode + ". Error stream output: \n" + stringBuilderErr.toString()); } } finally { process = null; } } }
public class class_name { public void setDeliveryChannelNames(java.util.Collection<String> deliveryChannelNames) { if (deliveryChannelNames == null) { this.deliveryChannelNames = null; return; } this.deliveryChannelNames = new com.amazonaws.internal.SdkInternalList<String>(deliveryChannelNames); } }
public class class_name { public void setDeliveryChannelNames(java.util.Collection<String> deliveryChannelNames) { if (deliveryChannelNames == null) { this.deliveryChannelNames = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.deliveryChannelNames = new com.amazonaws.internal.SdkInternalList<String>(deliveryChannelNames); } }
public class class_name { @Override public String resolveAdditionalQueryParametersFromTxtRecords(final String host) { String additionalQueryParameters = ""; InitialDirContext dirContext = createDnsDirContext(); try { Attributes attributes = dirContext.getAttributes(host, new String[]{"TXT"}); Attribute attribute = attributes.get("TXT"); if (attribute != null) { NamingEnumeration<?> txtRecordEnumeration = attribute.getAll(); if (txtRecordEnumeration.hasMore()) { // Remove all space characters, as the DNS resolver for TXT records inserts a space character // between each character-string in a single TXT record. That whitespace is spurious in // this context and must be removed additionalQueryParameters = ((String) txtRecordEnumeration.next()).replaceAll("\\s", ""); if (txtRecordEnumeration.hasMore()) { throw new MongoConfigurationException(format("Multiple TXT records found for host '%s'. Only one is permitted", host)); } } } } catch (NamingException e) { throw new MongoConfigurationException("Unable to look up TXT record for host " + host, e); } finally { try { dirContext.close(); } catch (NamingException e) { // ignore } } return additionalQueryParameters; } }
public class class_name { @Override public String resolveAdditionalQueryParametersFromTxtRecords(final String host) { String additionalQueryParameters = ""; InitialDirContext dirContext = createDnsDirContext(); try { Attributes attributes = dirContext.getAttributes(host, new String[]{"TXT"}); Attribute attribute = attributes.get("TXT"); if (attribute != null) { NamingEnumeration<?> txtRecordEnumeration = attribute.getAll(); if (txtRecordEnumeration.hasMore()) { // Remove all space characters, as the DNS resolver for TXT records inserts a space character // between each character-string in a single TXT record. That whitespace is spurious in // this context and must be removed additionalQueryParameters = ((String) txtRecordEnumeration.next()).replaceAll("\\s", ""); // depends on control dependency: [if], data = [none] if (txtRecordEnumeration.hasMore()) { throw new MongoConfigurationException(format("Multiple TXT records found for host '%s'. Only one is permitted", host)); } } } } catch (NamingException e) { throw new MongoConfigurationException("Unable to look up TXT record for host " + host, e); } finally { // depends on control dependency: [catch], data = [none] try { dirContext.close(); // depends on control dependency: [try], data = [none] } catch (NamingException e) { // ignore } // depends on control dependency: [catch], data = [none] } return additionalQueryParameters; } }
public class class_name { public MDFeEvento mdfeEventoParaObjeto(final String xml) { try { return this.persister.read(MDFeEvento.class, xml); } catch (final Exception e) { throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage())); } } }
public class class_name { public MDFeEvento mdfeEventoParaObjeto(final String xml) { try { return this.persister.read(MDFeEvento.class, xml); // depends on control dependency: [try], data = [none] } catch (final Exception e) { throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage())); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private synchronized boolean addPeer(final PeerInfo peer) { final String uuid = peer.getUuid(); if (!peers.containsKey(uuid)) { peers.put(uuid, peer); peer.setLastSeen(System.currentTimeMillis()); onAddPeer(peer); return true; } // not added return false; } }
public class class_name { private synchronized boolean addPeer(final PeerInfo peer) { final String uuid = peer.getUuid(); if (!peers.containsKey(uuid)) { peers.put(uuid, peer); // depends on control dependency: [if], data = [none] peer.setLastSeen(System.currentTimeMillis()); // depends on control dependency: [if], data = [none] onAddPeer(peer); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } // not added return false; } }
public class class_name { synchronized static public void loadLibrary(String name, Options options, Integer majorVersion) { // search for specific library File f = null; try { f = findLibrary(name, options, majorVersion); } catch (Exception e) { log.debug("exception while finding library: " + e.getMessage()); throw new UnsatisfiedLinkError("Unable to cleanly find (or extract) library [" + name + "] as resource"); } // temporarily prepend library path to load library if found if (f != null) { // since loading of dependencies of a library cannot dynamically happen // and the user would be required to provide a valid LD_LIBRARY_PATH when // launching the java process -- we don't need to do use loadLibrary // and can just tell it to load a specific library file log.debug("System.load(" + f.getAbsolutePath() + ")"); System.load(f.getAbsolutePath()); } else { log.debug("falling back to System.loadLibrary(" + name + ")"); // fallback to java method System.loadLibrary(name); } log.debug("library [" + name + "] loaded!"); } }
public class class_name { synchronized static public void loadLibrary(String name, Options options, Integer majorVersion) { // search for specific library File f = null; try { f = findLibrary(name, options, majorVersion); // depends on control dependency: [try], data = [none] } catch (Exception e) { log.debug("exception while finding library: " + e.getMessage()); throw new UnsatisfiedLinkError("Unable to cleanly find (or extract) library [" + name + "] as resource"); } // depends on control dependency: [catch], data = [none] // temporarily prepend library path to load library if found if (f != null) { // since loading of dependencies of a library cannot dynamically happen // and the user would be required to provide a valid LD_LIBRARY_PATH when // launching the java process -- we don't need to do use loadLibrary // and can just tell it to load a specific library file log.debug("System.load(" + f.getAbsolutePath() + ")"); System.load(f.getAbsolutePath()); } else { log.debug("falling back to System.loadLibrary(" + name + ")"); // fallback to java method System.loadLibrary(name); } log.debug("library [" + name + "] loaded!"); } }
public class class_name { public Set<Entry<String, String>> getParameters() { Map<String,String> retval = new HashMap<String,String> (); for(Entry<String, String> nameValue : this.parameters.entrySet()) { retval.put(nameValue.getKey(), (RFC2396UrlDecoder.decode(nameValue.getValue()))); } return retval.entrySet(); } }
public class class_name { public Set<Entry<String, String>> getParameters() { Map<String,String> retval = new HashMap<String,String> (); for(Entry<String, String> nameValue : this.parameters.entrySet()) { retval.put(nameValue.getKey(), (RFC2396UrlDecoder.decode(nameValue.getValue()))); // depends on control dependency: [for], data = [nameValue] } return retval.entrySet(); } }
public class class_name { public void setAssessmentTargets(java.util.Collection<AssessmentTarget> assessmentTargets) { if (assessmentTargets == null) { this.assessmentTargets = null; return; } this.assessmentTargets = new java.util.ArrayList<AssessmentTarget>(assessmentTargets); } }
public class class_name { public void setAssessmentTargets(java.util.Collection<AssessmentTarget> assessmentTargets) { if (assessmentTargets == null) { this.assessmentTargets = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.assessmentTargets = new java.util.ArrayList<AssessmentTarget>(assessmentTargets); } }
public class class_name { @Override public String toSql(QueryData queryData, String indent) { Assert.notEmpty(queryData.getAlternatives(), "BUG: no alternatives"); StringBuffer sb = new StringBuffer(); List<String> alternatives = new ArrayList<>(); for (List<QueryNode> alternative : queryData.getAlternatives()) { alternatives.add(createSqlForAlternative(queryData, alternative, indent)); } sb.append(StringUtils.join(alternatives, "\n" + indent + "UNION ")); // ORDER BY and LIMIT/OFFSET clauses cannot depend on alternative? appendOrderByClause(sb, queryData, null, indent); appendLimitOffsetClause(sb, queryData, null, indent); return sb.toString(); } }
public class class_name { @Override public String toSql(QueryData queryData, String indent) { Assert.notEmpty(queryData.getAlternatives(), "BUG: no alternatives"); StringBuffer sb = new StringBuffer(); List<String> alternatives = new ArrayList<>(); for (List<QueryNode> alternative : queryData.getAlternatives()) { alternatives.add(createSqlForAlternative(queryData, alternative, indent)); // depends on control dependency: [for], data = [alternative] } sb.append(StringUtils.join(alternatives, "\n" + indent + "UNION ")); // ORDER BY and LIMIT/OFFSET clauses cannot depend on alternative? appendOrderByClause(sb, queryData, null, indent); appendLimitOffsetClause(sb, queryData, null, indent); return sb.toString(); } }
public class class_name { public void addCondition(final Condition condition) { if (conditions_ == null) { conditions_ = new ArrayList<>(); } conditions_.add(condition); } }
public class class_name { public void addCondition(final Condition condition) { if (conditions_ == null) { conditions_ = new ArrayList<>(); // depends on control dependency: [if], data = [none] } conditions_.add(condition); } }
public class class_name { @Override public void beforeStep(StepExecution stepExecution) { super.beforeStep(stepExecution); clearErrors(); try { new Retrier().execute(new Retriable() { /* * (non-Javadoc) * * @see org.duracloud.common.retry.Retriable#retry() */ @Override public Object retry() throws Exception { RestoreStatus newStatus = RestoreStatus.VERIFYING_TRANSFERRED_CONTENT; restoreManager.transitionRestoreStatus(restoreId, newStatus, ""); return null; } }); } catch (Exception ex) { addError("failed to transition status to " + RestoreStatus.VERIFYING_TRANSFERRED_CONTENT + ": " + ex.getMessage()); stepExecution.addFailureException(ex); } } }
public class class_name { @Override public void beforeStep(StepExecution stepExecution) { super.beforeStep(stepExecution); clearErrors(); try { new Retrier().execute(new Retriable() { /* * (non-Javadoc) * * @see org.duracloud.common.retry.Retriable#retry() */ @Override public Object retry() throws Exception { RestoreStatus newStatus = RestoreStatus.VERIFYING_TRANSFERRED_CONTENT; restoreManager.transitionRestoreStatus(restoreId, newStatus, ""); return null; } }); // depends on control dependency: [try], data = [none] } catch (Exception ex) { addError("failed to transition status to " + RestoreStatus.VERIFYING_TRANSFERRED_CONTENT + ": " + ex.getMessage()); stepExecution.addFailureException(ex); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public int parseMaxAge(String maxAgeStr) { if (maxAgeStr == null) { showFormatError(maxAgeStr); return -1; } maxAgeStr = maxAgeStr.toLowerCase().trim(); String[] tokens = maxAgeStr.split(" +"); if ((tokens.length != 2)) { showFormatError(maxAgeStr); return -1; } int number = 0; try { number = Integer.parseInt(tokens[0]); } catch (NumberFormatException e) { showFormatError(maxAgeStr); return -1; } String unit = tokens[1]; if ("d".equals(unit) || unit.startsWith("day")) { return 24 * number; } else if ("h".equals(unit) || unit.startsWith("hour")) { return number; } else if ("w".equals(unit) || unit.startsWith("week")) { return 7 * 24 * number; } else { showFormatError(maxAgeStr); return -1; } } }
public class class_name { public int parseMaxAge(String maxAgeStr) { if (maxAgeStr == null) { showFormatError(maxAgeStr); // depends on control dependency: [if], data = [(maxAgeStr] return -1; // depends on control dependency: [if], data = [none] } maxAgeStr = maxAgeStr.toLowerCase().trim(); String[] tokens = maxAgeStr.split(" +"); if ((tokens.length != 2)) { showFormatError(maxAgeStr); // depends on control dependency: [if], data = [none] return -1; // depends on control dependency: [if], data = [none] } int number = 0; try { number = Integer.parseInt(tokens[0]); // depends on control dependency: [try], data = [none] } catch (NumberFormatException e) { showFormatError(maxAgeStr); return -1; } // depends on control dependency: [catch], data = [none] String unit = tokens[1]; if ("d".equals(unit) || unit.startsWith("day")) { return 24 * number; // depends on control dependency: [if], data = [none] } else if ("h".equals(unit) || unit.startsWith("hour")) { return number; // depends on control dependency: [if], data = [none] } else if ("w".equals(unit) || unit.startsWith("week")) { return 7 * 24 * number; // depends on control dependency: [if], data = [none] } else { showFormatError(maxAgeStr); // depends on control dependency: [if], data = [none] return -1; // depends on control dependency: [if], data = [none] } } }
public class class_name { void outOfScope() { final String methodName = "outOfScope"; if (TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName); } _outOfScope = true; try { // Close cloned connection so that it, and any resource created // from it, also throw SIObjectClosedException _connectionClone.close(); } catch (final SIException exception) { FFDCFilter .processException( exception, "com.ibm.ws.sib.ra.inbound.impl.SibRaAbstractConsumerSession.outOfScope", FFDC_PROBE_1, this); if (TRACE.isEventEnabled()) { SibTr.exception(this, TRACE, exception); } // Swallow exception } catch (final SIErrorException exception) { FFDCFilter .processException( exception, "com.ibm.ws.sib.ra.inbound.impl.SibRaAbstractConsumerSession.outOfScope", FFDC_PROBE_2, this); if (TRACE.isEventEnabled()) { SibTr.exception(this, TRACE, exception); } // Swallow exception } if (TRACE.isEntryEnabled()) { SibTr.exit(this, TRACE, methodName); } } }
public class class_name { void outOfScope() { final String methodName = "outOfScope"; if (TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName); // depends on control dependency: [if], data = [none] } _outOfScope = true; try { // Close cloned connection so that it, and any resource created // from it, also throw SIObjectClosedException _connectionClone.close(); // depends on control dependency: [try], data = [none] } catch (final SIException exception) { FFDCFilter .processException( exception, "com.ibm.ws.sib.ra.inbound.impl.SibRaAbstractConsumerSession.outOfScope", FFDC_PROBE_1, this); if (TRACE.isEventEnabled()) { SibTr.exception(this, TRACE, exception); // depends on control dependency: [if], data = [none] } // Swallow exception } catch (final SIErrorException exception) { // depends on control dependency: [catch], data = [none] FFDCFilter .processException( exception, "com.ibm.ws.sib.ra.inbound.impl.SibRaAbstractConsumerSession.outOfScope", FFDC_PROBE_2, this); if (TRACE.isEventEnabled()) { SibTr.exception(this, TRACE, exception); // depends on control dependency: [if], data = [none] } // Swallow exception } // depends on control dependency: [catch], data = [none] if (TRACE.isEntryEnabled()) { SibTr.exit(this, TRACE, methodName); // depends on control dependency: [if], data = [none] } } }
public class class_name { void destroyProxy(String name, boolean publishEvent) { final DistributedObjectFuture proxyFuture = proxies.remove(name); if (proxyFuture == null) { return; } DistributedObject proxy; try { proxy = proxyFuture.get(); } catch (Throwable t) { proxyService.logger.warning("Cannot destroy proxy [" + serviceName + ":" + name + "], since its creation is failed with " + t.getClass().getName() + ": " + t.getMessage()); return; } InternalEventService eventService = proxyService.nodeEngine.getEventService(); ProxyEventProcessor callback = new ProxyEventProcessor(proxyService.listeners.values(), DESTROYED, serviceName, name, proxy); eventService.executeEventCallback(callback); if (publishEvent) { publish(new DistributedObjectEventPacket(DESTROYED, serviceName, name)); } } }
public class class_name { void destroyProxy(String name, boolean publishEvent) { final DistributedObjectFuture proxyFuture = proxies.remove(name); if (proxyFuture == null) { return; // depends on control dependency: [if], data = [none] } DistributedObject proxy; try { proxy = proxyFuture.get(); // depends on control dependency: [try], data = [none] } catch (Throwable t) { proxyService.logger.warning("Cannot destroy proxy [" + serviceName + ":" + name + "], since its creation is failed with " + t.getClass().getName() + ": " + t.getMessage()); return; } // depends on control dependency: [catch], data = [none] InternalEventService eventService = proxyService.nodeEngine.getEventService(); ProxyEventProcessor callback = new ProxyEventProcessor(proxyService.listeners.values(), DESTROYED, serviceName, name, proxy); eventService.executeEventCallback(callback); if (publishEvent) { publish(new DistributedObjectEventPacket(DESTROYED, serviceName, name)); // depends on control dependency: [if], data = [none] } } }
public class class_name { public CmsContainerPageElementPanel createElement( CmsContainerElementData containerElement, I_CmsDropContainer container, boolean isNew) throws Exception { if (containerElement.isGroupContainer() || containerElement.isInheritContainer()) { List<CmsContainerElementData> subElements = new ArrayList<CmsContainerElementData>(); for (String subId : containerElement.getSubItems()) { CmsContainerElementData element = m_controller.getCachedElement(subId); if (element != null) { subElements.add(element); } else { CmsDebugLog.getInstance().printLine("Cached element not found"); } } return createGroupcontainerElement(containerElement, subElements, container); } Element element = CmsDomUtil.createElement(containerElement.getContents().get(container.getContainerId())); // ensure any embedded flash players are set opaque so UI elements may be placed above them CmsDomUtil.fixFlashZindex(element); if (isNew) { CmsContentEditor.replaceResourceIds( element, CmsUUID.getNullUUID().toString(), CmsContainerpageController.getServerId(containerElement.getClientId())); } CmsContainerPageElementPanel result = createElement(element, container, containerElement); if (!CmsContainerpageController.get().shouldShowInContext(containerElement)) { result.getElement().getStyle().setDisplay(Style.Display.NONE); result.addStyleName(CmsTemplateContextInfo.DUMMY_ELEMENT_MARKER); } return result; } }
public class class_name { public CmsContainerPageElementPanel createElement( CmsContainerElementData containerElement, I_CmsDropContainer container, boolean isNew) throws Exception { if (containerElement.isGroupContainer() || containerElement.isInheritContainer()) { List<CmsContainerElementData> subElements = new ArrayList<CmsContainerElementData>(); for (String subId : containerElement.getSubItems()) { CmsContainerElementData element = m_controller.getCachedElement(subId); if (element != null) { subElements.add(element); // depends on control dependency: [if], data = [(element] } else { CmsDebugLog.getInstance().printLine("Cached element not found"); // depends on control dependency: [if], data = [none] } } return createGroupcontainerElement(containerElement, subElements, container); } Element element = CmsDomUtil.createElement(containerElement.getContents().get(container.getContainerId())); // ensure any embedded flash players are set opaque so UI elements may be placed above them CmsDomUtil.fixFlashZindex(element); if (isNew) { CmsContentEditor.replaceResourceIds( element, CmsUUID.getNullUUID().toString(), CmsContainerpageController.getServerId(containerElement.getClientId())); } CmsContainerPageElementPanel result = createElement(element, container, containerElement); if (!CmsContainerpageController.get().shouldShowInContext(containerElement)) { result.getElement().getStyle().setDisplay(Style.Display.NONE); result.addStyleName(CmsTemplateContextInfo.DUMMY_ELEMENT_MARKER); } return result; } }
public class class_name { @Override public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { // layout algorithm: // 1) by checking children and other variables, find an anchor coordinate and an anchor // item position. // 2) fill towards start, stacking from bottom // 3) fill towards end, stacking from top // 4) scroll to fulfill requirements like stack from bottom. // create render state if (DEBUG) { Log.d(TAG, "is pre layout:" + state.isPreLayout()); } if (mPendingSavedState != null) { setOrientation(mPendingSavedState.mOrientation); setReverseLayout(mPendingSavedState.mReverseLayout); setStackFromEnd(mPendingSavedState.mStackFromEnd); mPendingScrollPosition = mPendingSavedState.mAnchorPosition; } ensureRenderState(); // resolve layout direction resolveShouldLayoutReverse(); // validate scroll position if exists if (mPendingScrollPosition != RecyclerView.NO_POSITION) { // validate it if (mPendingScrollPosition < 0 || mPendingScrollPosition >= state.getItemCount()) { mPendingScrollPosition = RecyclerView.NO_POSITION; mPendingScrollPositionOffset = INVALID_OFFSET; if (DEBUG) { Log.e(TAG, "ignoring invalid scroll position " + mPendingScrollPosition); } } } // this value might be updated if there is a target scroll position without an offset boolean layoutFromEnd = mShouldReverseLayout ^ mStackFromEnd; final boolean stackFromEndChanged = mLastStackFromEnd != mStackFromEnd; int anchorCoordinate, anchorItemPosition; if (mPendingScrollPosition != RecyclerView.NO_POSITION) { // if child is visible, try to make it a reference child and ensure it is fully visible. // if child is not visible, align it depending on its virtual position. anchorItemPosition = mPendingScrollPosition; if (mPendingSavedState != null) { // Anchor offset depends on how that child was laid out. Here, we update it // according to our current view bounds layoutFromEnd = mPendingSavedState.mAnchorLayoutFromEnd; if (layoutFromEnd) { anchorCoordinate = mOrientationHelper.getEndAfterPadding() - mPendingSavedState.mAnchorOffset; } else { anchorCoordinate = mOrientationHelper.getStartAfterPadding() + mPendingSavedState.mAnchorOffset; } } else if (mPendingScrollPositionOffset == INVALID_OFFSET) { View child = findViewByPosition(mPendingScrollPosition); if (child != null) { final int startGap = mOrientationHelper.getDecoratedStart(child) - mOrientationHelper.getStartAfterPadding(); final int endGap = mOrientationHelper.getEndAfterPadding() - mOrientationHelper.getDecoratedEnd(child); final int childSize = mOrientationHelper.getDecoratedMeasurement(child); if (childSize > mOrientationHelper.getTotalSpace()) { // item does not fit. fix depending on layout direction anchorCoordinate = layoutFromEnd ? mOrientationHelper.getEndAfterPadding() : mOrientationHelper.getStartAfterPadding(); } else if (startGap < 0) { anchorCoordinate = mOrientationHelper.getStartAfterPadding(); layoutFromEnd = false; } else if (endGap < 0) { anchorCoordinate = mOrientationHelper.getEndAfterPadding(); layoutFromEnd = true; } else { anchorCoordinate = layoutFromEnd ? mOrientationHelper.getDecoratedEnd(child) : mOrientationHelper.getDecoratedStart(child); } } else { // item is not visible. if (getChildCount() > 0) { // get position of any child, does not matter int pos = getPosition(getChildAt(0)); if (mPendingScrollPosition < pos == mShouldReverseLayout) { anchorCoordinate = mOrientationHelper.getEndAfterPadding(); layoutFromEnd = true; } else { anchorCoordinate = mOrientationHelper.getStartAfterPadding(); layoutFromEnd = false; } } else { anchorCoordinate = layoutFromEnd ? mOrientationHelper.getEndAfterPadding() : mOrientationHelper.getStartAfterPadding(); } } } else { // override layout from end values for consistency if (mShouldReverseLayout) { anchorCoordinate = mOrientationHelper.getEndAfterPadding() - mPendingScrollPositionOffset; layoutFromEnd = true; } else { anchorCoordinate = mOrientationHelper.getStartAfterPadding() + mPendingScrollPositionOffset; layoutFromEnd = false; } } } else if (getChildCount() > 0 && !stackFromEndChanged) { if (layoutFromEnd) { View referenceChild = getChildClosestToEnd(); anchorCoordinate = mOrientationHelper.getDecoratedEnd(referenceChild); anchorItemPosition = getPosition(referenceChild); } else { View referenceChild = getChildClosestToStart(); anchorCoordinate = mOrientationHelper.getDecoratedStart(referenceChild); anchorItemPosition = getPosition(referenceChild); } } else { anchorCoordinate = layoutFromEnd ? mOrientationHelper.getEndAfterPadding() : mOrientationHelper.getStartAfterPadding(); anchorItemPosition = mStackFromEnd ? state.getItemCount() - 1 : 0; } detachAndScrapAttachedViews(recycler); final int extraForStart; final int extraForEnd; final int extra = getExtraLayoutSpace(state); boolean before = state.getTargetScrollPosition() < anchorItemPosition; if (before == mShouldReverseLayout) { extraForEnd = extra; extraForStart = 0; } else { extraForStart = extra; extraForEnd = 0; } // first fill towards start updateRenderStateToFillStart(anchorItemPosition, anchorCoordinate); mRenderState.mExtra = extraForStart; if (!layoutFromEnd) { mRenderState.mCurrentPosition += mRenderState.mItemDirection; } fill(recycler, mRenderState, state, false); int startOffset = mRenderState.mOffset; // fill towards end updateRenderStateToFillEnd(anchorItemPosition, anchorCoordinate); mRenderState.mExtra = extraForEnd; if (layoutFromEnd) { mRenderState.mCurrentPosition += mRenderState.mItemDirection; } fill(recycler, mRenderState, state, false); int endOffset = mRenderState.mOffset; // changes may cause gaps on the UI, try to fix them. if (getChildCount() > 0) { // because layout from end may be changed by scroll to position // we re-calculate it. // find which side we should check for gaps. if (mShouldReverseLayout ^ mStackFromEnd) { int fixOffset = fixLayoutEndGap(endOffset, recycler, state, true); startOffset += fixOffset; endOffset += fixOffset; fixOffset = fixLayoutStartGap(startOffset, recycler, state, false); startOffset += fixOffset; endOffset += fixOffset; } else { int fixOffset = fixLayoutStartGap(startOffset, recycler, state, true); startOffset += fixOffset; endOffset += fixOffset; fixOffset = fixLayoutEndGap(endOffset, recycler, state, false); startOffset += fixOffset; endOffset += fixOffset; } } // If there are scrap children that we did not layout, we need to find where they did go // and layout them accordingly so that animations can work as expected. // This case may happen if new views are added or an existing view expands and pushes // another view out of bounds. if (getChildCount() > 0 && !state.isPreLayout() && supportsPredictiveItemAnimations()) { // to make the logic simpler, we calculate the size of children and call fill. int scrapExtraStart = 0, scrapExtraEnd = 0; final List<RecyclerView.ViewHolder> scrapList = recycler.getScrapList(); final int scrapSize = scrapList.size(); final int firstChildPos = getPosition(getChildAt(0)); for (int i = 0; i < scrapSize; i++) { RecyclerView.ViewHolder scrap = scrapList.get(i); final int position = scrap.getPosition(); final int direction = position < firstChildPos != mShouldReverseLayout ? RenderState.LAYOUT_START : RenderState.LAYOUT_END; if (direction == RenderState.LAYOUT_START) { scrapExtraStart += mOrientationHelper.getDecoratedMeasurement(scrap.itemView); } else { scrapExtraEnd += mOrientationHelper.getDecoratedMeasurement(scrap.itemView); } } if (DEBUG) { Log.d(TAG, "for unused scrap, decided to add " + scrapExtraStart + " towards start and " + scrapExtraEnd + " towards end"); } mRenderState.mScrapList = scrapList; if (scrapExtraStart > 0) { View anchor = getChildClosestToStart(); updateRenderStateToFillStart(getPosition(anchor), startOffset); mRenderState.mExtra = scrapExtraStart; mRenderState.mAvailable = 0; mRenderState.mCurrentPosition += mShouldReverseLayout ? 1 : -1; fill(recycler, mRenderState, state, false); } if (scrapExtraEnd > 0) { View anchor = getChildClosestToEnd(); updateRenderStateToFillEnd(getPosition(anchor), endOffset); mRenderState.mExtra = scrapExtraEnd; mRenderState.mAvailable = 0; mRenderState.mCurrentPosition += mShouldReverseLayout ? -1 : 1; fill(recycler, mRenderState, state, false); } mRenderState.mScrapList = null; } mPendingScrollPosition = RecyclerView.NO_POSITION; mPendingScrollPositionOffset = INVALID_OFFSET; mLastStackFromEnd = mStackFromEnd; mPendingSavedState = null; // we don't need this anymore if (DEBUG) { validateChildOrder(); } } }
public class class_name { @Override public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { // layout algorithm: // 1) by checking children and other variables, find an anchor coordinate and an anchor // item position. // 2) fill towards start, stacking from bottom // 3) fill towards end, stacking from top // 4) scroll to fulfill requirements like stack from bottom. // create render state if (DEBUG) { Log.d(TAG, "is pre layout:" + state.isPreLayout()); // depends on control dependency: [if], data = [none] } if (mPendingSavedState != null) { setOrientation(mPendingSavedState.mOrientation); // depends on control dependency: [if], data = [(mPendingSavedState] setReverseLayout(mPendingSavedState.mReverseLayout); // depends on control dependency: [if], data = [(mPendingSavedState] setStackFromEnd(mPendingSavedState.mStackFromEnd); // depends on control dependency: [if], data = [(mPendingSavedState] mPendingScrollPosition = mPendingSavedState.mAnchorPosition; // depends on control dependency: [if], data = [none] } ensureRenderState(); // resolve layout direction resolveShouldLayoutReverse(); // validate scroll position if exists if (mPendingScrollPosition != RecyclerView.NO_POSITION) { // validate it if (mPendingScrollPosition < 0 || mPendingScrollPosition >= state.getItemCount()) { mPendingScrollPosition = RecyclerView.NO_POSITION; // depends on control dependency: [if], data = [none] mPendingScrollPositionOffset = INVALID_OFFSET; // depends on control dependency: [if], data = [none] if (DEBUG) { Log.e(TAG, "ignoring invalid scroll position " + mPendingScrollPosition); // depends on control dependency: [if], data = [none] } } } // this value might be updated if there is a target scroll position without an offset boolean layoutFromEnd = mShouldReverseLayout ^ mStackFromEnd; final boolean stackFromEndChanged = mLastStackFromEnd != mStackFromEnd; int anchorCoordinate, anchorItemPosition; if (mPendingScrollPosition != RecyclerView.NO_POSITION) { // if child is visible, try to make it a reference child and ensure it is fully visible. // if child is not visible, align it depending on its virtual position. anchorItemPosition = mPendingScrollPosition; // depends on control dependency: [if], data = [none] if (mPendingSavedState != null) { // Anchor offset depends on how that child was laid out. Here, we update it // according to our current view bounds layoutFromEnd = mPendingSavedState.mAnchorLayoutFromEnd; // depends on control dependency: [if], data = [none] if (layoutFromEnd) { anchorCoordinate = mOrientationHelper.getEndAfterPadding() - mPendingSavedState.mAnchorOffset; // depends on control dependency: [if], data = [none] } else { anchorCoordinate = mOrientationHelper.getStartAfterPadding() + mPendingSavedState.mAnchorOffset; // depends on control dependency: [if], data = [none] } } else if (mPendingScrollPositionOffset == INVALID_OFFSET) { View child = findViewByPosition(mPendingScrollPosition); if (child != null) { final int startGap = mOrientationHelper.getDecoratedStart(child) - mOrientationHelper.getStartAfterPadding(); final int endGap = mOrientationHelper.getEndAfterPadding() - mOrientationHelper.getDecoratedEnd(child); final int childSize = mOrientationHelper.getDecoratedMeasurement(child); if (childSize > mOrientationHelper.getTotalSpace()) { // item does not fit. fix depending on layout direction anchorCoordinate = layoutFromEnd ? mOrientationHelper.getEndAfterPadding() : mOrientationHelper.getStartAfterPadding(); // depends on control dependency: [if], data = [none] } else if (startGap < 0) { anchorCoordinate = mOrientationHelper.getStartAfterPadding(); // depends on control dependency: [if], data = [none] layoutFromEnd = false; // depends on control dependency: [if], data = [none] } else if (endGap < 0) { anchorCoordinate = mOrientationHelper.getEndAfterPadding(); // depends on control dependency: [if], data = [none] layoutFromEnd = true; // depends on control dependency: [if], data = [none] } else { anchorCoordinate = layoutFromEnd ? mOrientationHelper.getDecoratedEnd(child) : mOrientationHelper.getDecoratedStart(child); // depends on control dependency: [if], data = [none] } } else { // item is not visible. if (getChildCount() > 0) { // get position of any child, does not matter int pos = getPosition(getChildAt(0)); if (mPendingScrollPosition < pos == mShouldReverseLayout) { anchorCoordinate = mOrientationHelper.getEndAfterPadding(); // depends on control dependency: [if], data = [none] layoutFromEnd = true; // depends on control dependency: [if], data = [none] } else { anchorCoordinate = mOrientationHelper.getStartAfterPadding(); // depends on control dependency: [if], data = [none] layoutFromEnd = false; // depends on control dependency: [if], data = [none] } } else { anchorCoordinate = layoutFromEnd ? mOrientationHelper.getEndAfterPadding() : mOrientationHelper.getStartAfterPadding(); // depends on control dependency: [if], data = [none] } } } else { // override layout from end values for consistency if (mShouldReverseLayout) { anchorCoordinate = mOrientationHelper.getEndAfterPadding() - mPendingScrollPositionOffset; // depends on control dependency: [if], data = [none] layoutFromEnd = true; // depends on control dependency: [if], data = [none] } else { anchorCoordinate = mOrientationHelper.getStartAfterPadding() + mPendingScrollPositionOffset; // depends on control dependency: [if], data = [none] layoutFromEnd = false; // depends on control dependency: [if], data = [none] } } } else if (getChildCount() > 0 && !stackFromEndChanged) { if (layoutFromEnd) { View referenceChild = getChildClosestToEnd(); anchorCoordinate = mOrientationHelper.getDecoratedEnd(referenceChild); // depends on control dependency: [if], data = [none] anchorItemPosition = getPosition(referenceChild); // depends on control dependency: [if], data = [none] } else { View referenceChild = getChildClosestToStart(); anchorCoordinate = mOrientationHelper.getDecoratedStart(referenceChild); // depends on control dependency: [if], data = [none] anchorItemPosition = getPosition(referenceChild); // depends on control dependency: [if], data = [none] } } else { anchorCoordinate = layoutFromEnd ? mOrientationHelper.getEndAfterPadding() : mOrientationHelper.getStartAfterPadding(); // depends on control dependency: [if], data = [none] anchorItemPosition = mStackFromEnd ? state.getItemCount() - 1 : 0; // depends on control dependency: [if], data = [none] } detachAndScrapAttachedViews(recycler); final int extraForStart; final int extraForEnd; final int extra = getExtraLayoutSpace(state); boolean before = state.getTargetScrollPosition() < anchorItemPosition; if (before == mShouldReverseLayout) { extraForEnd = extra; // depends on control dependency: [if], data = [none] extraForStart = 0; // depends on control dependency: [if], data = [none] } else { extraForStart = extra; // depends on control dependency: [if], data = [none] extraForEnd = 0; // depends on control dependency: [if], data = [none] } // first fill towards start updateRenderStateToFillStart(anchorItemPosition, anchorCoordinate); mRenderState.mExtra = extraForStart; if (!layoutFromEnd) { mRenderState.mCurrentPosition += mRenderState.mItemDirection; // depends on control dependency: [if], data = [none] } fill(recycler, mRenderState, state, false); int startOffset = mRenderState.mOffset; // fill towards end updateRenderStateToFillEnd(anchorItemPosition, anchorCoordinate); mRenderState.mExtra = extraForEnd; if (layoutFromEnd) { mRenderState.mCurrentPosition += mRenderState.mItemDirection; // depends on control dependency: [if], data = [none] } fill(recycler, mRenderState, state, false); int endOffset = mRenderState.mOffset; // changes may cause gaps on the UI, try to fix them. if (getChildCount() > 0) { // because layout from end may be changed by scroll to position // we re-calculate it. // find which side we should check for gaps. if (mShouldReverseLayout ^ mStackFromEnd) { int fixOffset = fixLayoutEndGap(endOffset, recycler, state, true); startOffset += fixOffset; // depends on control dependency: [if], data = [none] endOffset += fixOffset; // depends on control dependency: [if], data = [none] fixOffset = fixLayoutStartGap(startOffset, recycler, state, false); // depends on control dependency: [if], data = [none] startOffset += fixOffset; // depends on control dependency: [if], data = [none] endOffset += fixOffset; // depends on control dependency: [if], data = [none] } else { int fixOffset = fixLayoutStartGap(startOffset, recycler, state, true); startOffset += fixOffset; // depends on control dependency: [if], data = [none] endOffset += fixOffset; // depends on control dependency: [if], data = [none] fixOffset = fixLayoutEndGap(endOffset, recycler, state, false); // depends on control dependency: [if], data = [none] startOffset += fixOffset; // depends on control dependency: [if], data = [none] endOffset += fixOffset; // depends on control dependency: [if], data = [none] } } // If there are scrap children that we did not layout, we need to find where they did go // and layout them accordingly so that animations can work as expected. // This case may happen if new views are added or an existing view expands and pushes // another view out of bounds. if (getChildCount() > 0 && !state.isPreLayout() && supportsPredictiveItemAnimations()) { // to make the logic simpler, we calculate the size of children and call fill. int scrapExtraStart = 0, scrapExtraEnd = 0; final List<RecyclerView.ViewHolder> scrapList = recycler.getScrapList(); final int scrapSize = scrapList.size(); final int firstChildPos = getPosition(getChildAt(0)); for (int i = 0; i < scrapSize; i++) { RecyclerView.ViewHolder scrap = scrapList.get(i); final int position = scrap.getPosition(); final int direction = position < firstChildPos != mShouldReverseLayout ? RenderState.LAYOUT_START : RenderState.LAYOUT_END; if (direction == RenderState.LAYOUT_START) { scrapExtraStart += mOrientationHelper.getDecoratedMeasurement(scrap.itemView); // depends on control dependency: [if], data = [none] } else { scrapExtraEnd += mOrientationHelper.getDecoratedMeasurement(scrap.itemView); // depends on control dependency: [if], data = [none] } } if (DEBUG) { Log.d(TAG, "for unused scrap, decided to add " + scrapExtraStart + " towards start and " + scrapExtraEnd + " towards end"); // depends on control dependency: [if], data = [none] } mRenderState.mScrapList = scrapList; // depends on control dependency: [if], data = [none] if (scrapExtraStart > 0) { View anchor = getChildClosestToStart(); updateRenderStateToFillStart(getPosition(anchor), startOffset); // depends on control dependency: [if], data = [none] mRenderState.mExtra = scrapExtraStart; // depends on control dependency: [if], data = [none] mRenderState.mAvailable = 0; // depends on control dependency: [if], data = [none] mRenderState.mCurrentPosition += mShouldReverseLayout ? 1 : -1; // depends on control dependency: [if], data = [none] fill(recycler, mRenderState, state, false); // depends on control dependency: [if], data = [none] } if (scrapExtraEnd > 0) { View anchor = getChildClosestToEnd(); updateRenderStateToFillEnd(getPosition(anchor), endOffset); // depends on control dependency: [if], data = [none] mRenderState.mExtra = scrapExtraEnd; // depends on control dependency: [if], data = [none] mRenderState.mAvailable = 0; // depends on control dependency: [if], data = [none] mRenderState.mCurrentPosition += mShouldReverseLayout ? -1 : 1; // depends on control dependency: [if], data = [none] fill(recycler, mRenderState, state, false); // depends on control dependency: [if], data = [none] } mRenderState.mScrapList = null; // depends on control dependency: [if], data = [none] } mPendingScrollPosition = RecyclerView.NO_POSITION; mPendingScrollPositionOffset = INVALID_OFFSET; mLastStackFromEnd = mStackFromEnd; mPendingSavedState = null; // we don't need this anymore if (DEBUG) { validateChildOrder(); // depends on control dependency: [if], data = [none] } } }
public class class_name { private static String cutOffValidationMatchersPrefix(String expression) { if (expression.startsWith(Citrus.VALIDATION_MATCHER_PREFIX) && expression.endsWith(Citrus.VALIDATION_MATCHER_SUFFIX)) { return expression.substring(Citrus.VALIDATION_MATCHER_PREFIX.length(), expression.length() - Citrus.VALIDATION_MATCHER_SUFFIX.length()); } return expression; } }
public class class_name { private static String cutOffValidationMatchersPrefix(String expression) { if (expression.startsWith(Citrus.VALIDATION_MATCHER_PREFIX) && expression.endsWith(Citrus.VALIDATION_MATCHER_SUFFIX)) { return expression.substring(Citrus.VALIDATION_MATCHER_PREFIX.length(), expression.length() - Citrus.VALIDATION_MATCHER_SUFFIX.length()); // depends on control dependency: [if], data = [none] } return expression; } }
public class class_name { public static void onDestroy(Activity context) { instance.onDestroy(context); if(socializeLifecycleListener != null) { socializeLifecycleListener.onDestroy(context); } } }
public class class_name { public static void onDestroy(Activity context) { instance.onDestroy(context); if(socializeLifecycleListener != null) { socializeLifecycleListener.onDestroy(context); // depends on control dependency: [if], data = [none] } } }
public class class_name { private CircuitState closeCircuit() { if (LOG.isDebugEnabled()) { LOG.debug("Closing Circuit Breaker [{}]", method); } time = System.currentTimeMillis(); lastError = null; this.childState = (MutableRetryState) retryStateBuilder.build(); try { return state.getAndSet(CircuitState.CLOSED); } finally { if (eventPublisher != null) { try { eventPublisher.publishEvent(new CircuitClosedEvent(method)); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error publishing CircuitClosedEvent: " + e.getMessage(), e); } } } } } }
public class class_name { private CircuitState closeCircuit() { if (LOG.isDebugEnabled()) { LOG.debug("Closing Circuit Breaker [{}]", method); } time = System.currentTimeMillis(); lastError = null; this.childState = (MutableRetryState) retryStateBuilder.build(); // depends on control dependency: [if], data = [none] try { return state.getAndSet(CircuitState.CLOSED); // depends on control dependency: [try], data = [none] } finally { if (eventPublisher != null) { try { eventPublisher.publishEvent(new CircuitClosedEvent(method)); // depends on control dependency: [try], data = [none] } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error publishing CircuitClosedEvent: " + e.getMessage(), e); // depends on control dependency: [if], data = [none] } } // depends on control dependency: [catch], data = [none] } } } }
public class class_name { protected synchronized void deleteFinalizedObjects () { if (_finalizedSources != null) { IntBuffer idbuf = BufferUtils.createIntBuffer(_finalizedSources.length); idbuf.put(_finalizedSources).rewind(); AL10.alDeleteSources(idbuf); _finalizedSources = null; } if (_finalizedBuffers != null) { IntBuffer idbuf = BufferUtils.createIntBuffer(_finalizedBuffers.length); idbuf.put(_finalizedBuffers).rewind(); AL10.alDeleteBuffers(idbuf); _finalizedBuffers = null; } } }
public class class_name { protected synchronized void deleteFinalizedObjects () { if (_finalizedSources != null) { IntBuffer idbuf = BufferUtils.createIntBuffer(_finalizedSources.length); idbuf.put(_finalizedSources).rewind(); // depends on control dependency: [if], data = [(_finalizedSources] AL10.alDeleteSources(idbuf); // depends on control dependency: [if], data = [none] _finalizedSources = null; // depends on control dependency: [if], data = [none] } if (_finalizedBuffers != null) { IntBuffer idbuf = BufferUtils.createIntBuffer(_finalizedBuffers.length); idbuf.put(_finalizedBuffers).rewind(); // depends on control dependency: [if], data = [(_finalizedBuffers] AL10.alDeleteBuffers(idbuf); // depends on control dependency: [if], data = [none] _finalizedBuffers = null; // depends on control dependency: [if], data = [none] } } }
public class class_name { private INode mkdirsInternal(String src, PermissionStatus permissions) throws IOException { src = dir.normalizePath(src); // tokenize the src into components String[] names = INodeDirectory.getPathNames(src); if (!pathValidator.isValidName(src, names)) { numInvalidFilePathOperations++; throw new IOException("Invalid directory name: " + src); } // check validity of the username checkUserName(permissions); // convert the names into an array of bytes w/o holding lock byte[][] components = INodeDirectory.getPathComponents(names); INode[] inodes = new INode[components.length]; writeLock(); try { if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug("DIR* NameSystem.mkdirs: " + src); } dir.rootDir.getExistingPathINodes(components, inodes); if (isPermissionEnabled && isPermissionCheckingEnabled(inodes)) { checkTraverse(src, inodes); } INode lastINode = inodes[inodes.length-1]; if (lastINode !=null && lastINode.isDirectory()) { // all the users of mkdirs() are used to expect 'true' even if // a new directory is not created. return lastINode; } if (isInSafeMode()) { throw new SafeModeException("Cannot create directory " + src, safeMode); } if (isPermissionEnabled && isPermissionCheckingEnabled(inodes)) { checkAncestorAccess(src, inodes, FsAction.WRITE); } // validate that we have enough inodes. This is, at best, a // heuristic because the mkdirs() operation migth need to // create multiple inodes. checkFsObjectLimit(); if (!dir.mkdirs(src, names, components, inodes, inodes.length, permissions, false, now())) { throw new IOException("Invalid directory name: " + src); } return inodes[inodes.length-1]; } finally { writeUnlock(); } } }
public class class_name { private INode mkdirsInternal(String src, PermissionStatus permissions) throws IOException { src = dir.normalizePath(src); // tokenize the src into components String[] names = INodeDirectory.getPathNames(src); if (!pathValidator.isValidName(src, names)) { numInvalidFilePathOperations++; throw new IOException("Invalid directory name: " + src); } // check validity of the username checkUserName(permissions); // convert the names into an array of bytes w/o holding lock byte[][] components = INodeDirectory.getPathComponents(names); INode[] inodes = new INode[components.length]; writeLock(); try { if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug("DIR* NameSystem.mkdirs: " + src); // depends on control dependency: [if], data = [none] } dir.rootDir.getExistingPathINodes(components, inodes); if (isPermissionEnabled && isPermissionCheckingEnabled(inodes)) { checkTraverse(src, inodes); // depends on control dependency: [if], data = [none] } INode lastINode = inodes[inodes.length-1]; if (lastINode !=null && lastINode.isDirectory()) { // all the users of mkdirs() are used to expect 'true' even if // a new directory is not created. return lastINode; // depends on control dependency: [if], data = [none] } if (isInSafeMode()) { throw new SafeModeException("Cannot create directory " + src, safeMode); } if (isPermissionEnabled && isPermissionCheckingEnabled(inodes)) { checkAncestorAccess(src, inodes, FsAction.WRITE); // depends on control dependency: [if], data = [none] } // validate that we have enough inodes. This is, at best, a // heuristic because the mkdirs() operation migth need to // create multiple inodes. checkFsObjectLimit(); if (!dir.mkdirs(src, names, components, inodes, inodes.length, permissions, false, now())) { throw new IOException("Invalid directory name: " + src); } return inodes[inodes.length-1]; } finally { writeUnlock(); } } }
public class class_name { public Set<String> getLanguages() { Set<String> result = new HashSet<String>(); for (QueryParser parser : parsers.values()) { result.add(parser.getLanguage()); } return Collections.unmodifiableSet(result); } }
public class class_name { public Set<String> getLanguages() { Set<String> result = new HashSet<String>(); for (QueryParser parser : parsers.values()) { result.add(parser.getLanguage()); // depends on control dependency: [for], data = [parser] } return Collections.unmodifiableSet(result); } }
public class class_name { public static String printBase64Binary(byte[] val) { Assert.notNull(val, "val must not be null!"); String encoded = DatatypeConverter.printBase64Binary(val); int length = encoded.length(); StringBuilder sb = new StringBuilder(length + length / RFC2849_MAX_BASE64_CHARS_PER_LINE); for (int i = 0, len = length; i < len; i++) { sb.append(encoded.charAt(i)); if ((i + 1) % RFC2849_MAX_BASE64_CHARS_PER_LINE == 0) { sb.append('\n'); sb.append(' '); } } return sb.toString(); } }
public class class_name { public static String printBase64Binary(byte[] val) { Assert.notNull(val, "val must not be null!"); String encoded = DatatypeConverter.printBase64Binary(val); int length = encoded.length(); StringBuilder sb = new StringBuilder(length + length / RFC2849_MAX_BASE64_CHARS_PER_LINE); for (int i = 0, len = length; i < len; i++) { sb.append(encoded.charAt(i)); // depends on control dependency: [for], data = [i] if ((i + 1) % RFC2849_MAX_BASE64_CHARS_PER_LINE == 0) { sb.append('\n'); // depends on control dependency: [if], data = [none] sb.append(' '); // depends on control dependency: [if], data = [none] } } return sb.toString(); } }
public class class_name { @Nullable public CloseableReference<V> get(final K key) { Preconditions.checkNotNull(key); Entry<K, V> oldExclusive; CloseableReference<V> clientRef = null; synchronized (this) { oldExclusive = mExclusiveEntries.remove(key); Entry<K, V> entry = mCachedEntries.get(key); if (entry != null) { clientRef = newClientReference(entry); } } maybeNotifyExclusiveEntryRemoval(oldExclusive); maybeUpdateCacheParams(); maybeEvictEntries(); return clientRef; } }
public class class_name { @Nullable public CloseableReference<V> get(final K key) { Preconditions.checkNotNull(key); Entry<K, V> oldExclusive; CloseableReference<V> clientRef = null; synchronized (this) { oldExclusive = mExclusiveEntries.remove(key); Entry<K, V> entry = mCachedEntries.get(key); if (entry != null) { clientRef = newClientReference(entry); // depends on control dependency: [if], data = [(entry] } } maybeNotifyExclusiveEntryRemoval(oldExclusive); maybeUpdateCacheParams(); maybeEvictEntries(); return clientRef; } }
public class class_name { @Override public void accept(final CEMI frame, final Configuration c) { final Cache cache = c.getCache(); if (cache == null || !(frame instanceof CEMILData)) return; final CEMILData f = (CEMILData) frame; if (!(f.getDestination() instanceof GroupAddress)) return; final GroupAddress dst = (GroupAddress) f.getDestination(); // check if we have a datapoint model, whether it contains the address, // and datapoint is command based final DatapointModel<?> m = c.getDatapointModel(); if (m != null) { final Datapoint dp = m.get(dst); if (dp == null || dp.isStateBased()) return; } final byte[] d = f.getPayload(); // filter for A-Group.write (0x80) and A-Group.res (0x40) services final int svc = d[0] & 0x03 | d[1] & 0xC0; if (svc != 0x40 && svc != 0x80) return; final CEMILData copy; try { copy = (CEMILData) CEMIFactory.create(CEMILData.MC_LDATA_IND, d, f); } catch (final KNXFormatException e) { LogService.getLogger("calimero").error("create L_Data.ind for network buffer: {}", f, e); return; } CacheObject co = cache.get(dst); if (co == null) co = new LDataObjectQueue(dst, true, 10, false, queueFull); cache.put(co); synchronized (indicationKeys) { indicationKeys.add(co); } // this might invoke queue listener, so do it after put and add ((LDataObjectQueue) co).setFrame(copy); } }
public class class_name { @Override public void accept(final CEMI frame, final Configuration c) { final Cache cache = c.getCache(); if (cache == null || !(frame instanceof CEMILData)) return; final CEMILData f = (CEMILData) frame; if (!(f.getDestination() instanceof GroupAddress)) return; final GroupAddress dst = (GroupAddress) f.getDestination(); // check if we have a datapoint model, whether it contains the address, // and datapoint is command based final DatapointModel<?> m = c.getDatapointModel(); if (m != null) { final Datapoint dp = m.get(dst); if (dp == null || dp.isStateBased()) return; } final byte[] d = f.getPayload(); // filter for A-Group.write (0x80) and A-Group.res (0x40) services final int svc = d[0] & 0x03 | d[1] & 0xC0; if (svc != 0x40 && svc != 0x80) return; final CEMILData copy; try { copy = (CEMILData) CEMIFactory.create(CEMILData.MC_LDATA_IND, d, f); // depends on control dependency: [try], data = [none] } catch (final KNXFormatException e) { LogService.getLogger("calimero").error("create L_Data.ind for network buffer: {}", f, e); return; } // depends on control dependency: [catch], data = [none] CacheObject co = cache.get(dst); if (co == null) co = new LDataObjectQueue(dst, true, 10, false, queueFull); cache.put(co); synchronized (indicationKeys) { indicationKeys.add(co); } // this might invoke queue listener, so do it after put and add ((LDataObjectQueue) co).setFrame(copy); } }
public class class_name { public boolean removeMap(String attribute, String key) { NameOpValue nv = rslTree.getParam(attribute); if (nv == null || nv.getOperator() != NameOpValue.EQ) return false; List values = nv.getValues(); Iterator iter = values.iterator(); Object obj; int i=0; int found = -1; while( iter.hasNext() ) { obj = iter.next(); if (obj instanceof List) { List vr = (List)obj; if (vr.size() > 0) { Object var = vr.get(0); if (var instanceof Value && ((Value)var).getValue().equals(key)) { found = i; break; } } } i++; } if (found != -1) { values.remove(found); return true; } else { return false; } } }
public class class_name { public boolean removeMap(String attribute, String key) { NameOpValue nv = rslTree.getParam(attribute); if (nv == null || nv.getOperator() != NameOpValue.EQ) return false; List values = nv.getValues(); Iterator iter = values.iterator(); Object obj; int i=0; int found = -1; while( iter.hasNext() ) { obj = iter.next(); // depends on control dependency: [while], data = [none] if (obj instanceof List) { List vr = (List)obj; if (vr.size() > 0) { Object var = vr.get(0); if (var instanceof Value && ((Value)var).getValue().equals(key)) { found = i; // depends on control dependency: [if], data = [none] break; } } } i++; // depends on control dependency: [while], data = [none] } if (found != -1) { values.remove(found); // depends on control dependency: [if], data = [(found] return true; // depends on control dependency: [if], data = [none] } else { return false; // depends on control dependency: [if], data = [none] } } }
public class class_name { private void checkMemoryManagementOption(MemoryManagementOption option) { if (memoryManagementOption != null && memoryManagementOption != option) { usage("Multiple memory management options cannot be set."); } setMemoryManagementOption(option); } }
public class class_name { private void checkMemoryManagementOption(MemoryManagementOption option) { if (memoryManagementOption != null && memoryManagementOption != option) { usage("Multiple memory management options cannot be set."); // depends on control dependency: [if], data = [none] } setMemoryManagementOption(option); } }
public class class_name { protected void checkLinkConcistency(CmsObject cms) { Locale masterLocale = CmsLocaleManager.MASTER_LOCALE; for (I_CmsXmlContentValue contentValue : getValues(masterLocale)) { if (contentValue instanceof CmsXmlVfsFileValue) { CmsLink link = ((CmsXmlVfsFileValue)contentValue).getLink(cms); link.checkConsistency(cms); } } initDocument(); } }
public class class_name { protected void checkLinkConcistency(CmsObject cms) { Locale masterLocale = CmsLocaleManager.MASTER_LOCALE; for (I_CmsXmlContentValue contentValue : getValues(masterLocale)) { if (contentValue instanceof CmsXmlVfsFileValue) { CmsLink link = ((CmsXmlVfsFileValue)contentValue).getLink(cms); link.checkConsistency(cms); // depends on control dependency: [if], data = [none] } } initDocument(); } }
public class class_name { public static void main(String[] args) { TreebankLanguagePack tlp = new PennTreebankLanguagePack(); System.out.println("Start symbol: " + tlp.startSymbol()); String start = tlp.startSymbol(); System.out.println("Should be true: " + (tlp.isStartSymbol(start))); String[] strs = {"-", "-LLB-", "NP-2", "NP=3", "NP-LGS", "NP-TMP=3"}; for (String str : strs) { System.out.println("String: " + str + " basic: " + tlp.basicCategory(str) + " basicAndFunc: " + tlp.categoryAndFunction(str)); } } }
public class class_name { public static void main(String[] args) { TreebankLanguagePack tlp = new PennTreebankLanguagePack(); System.out.println("Start symbol: " + tlp.startSymbol()); String start = tlp.startSymbol(); System.out.println("Should be true: " + (tlp.isStartSymbol(start))); String[] strs = {"-", "-LLB-", "NP-2", "NP=3", "NP-LGS", "NP-TMP=3"}; for (String str : strs) { System.out.println("String: " + str + " basic: " + tlp.basicCategory(str) + " basicAndFunc: " + tlp.categoryAndFunction(str)); // depends on control dependency: [for], data = [str] } } }
public class class_name { public ManagementVertex getGroupMember(final int index) { if (index < this.groupMembers.size()) { return this.groupMembers.get(index); } return null; } }
public class class_name { public ManagementVertex getGroupMember(final int index) { if (index < this.groupMembers.size()) { return this.groupMembers.get(index); // depends on control dependency: [if], data = [(index] } return null; } }
public class class_name { public static BaseFunction typeErrorThrower(Context cx) { if (cx.typeErrorThrower == null) { BaseFunction thrower = new BaseFunction() { private static final long serialVersionUID = -5891740962154902286L; @Override public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { throw typeError0("msg.op.not.allowed"); } @Override public int getLength() { return 0; } }; ScriptRuntime.setFunctionProtoAndParent(thrower, cx.topCallScope); thrower.preventExtensions(); cx.typeErrorThrower = thrower; } return cx.typeErrorThrower; } }
public class class_name { public static BaseFunction typeErrorThrower(Context cx) { if (cx.typeErrorThrower == null) { BaseFunction thrower = new BaseFunction() { private static final long serialVersionUID = -5891740962154902286L; @Override public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { throw typeError0("msg.op.not.allowed"); } @Override public int getLength() { return 0; } }; ScriptRuntime.setFunctionProtoAndParent(thrower, cx.topCallScope); // depends on control dependency: [if], data = [none] thrower.preventExtensions(); // depends on control dependency: [if], data = [none] cx.typeErrorThrower = thrower; // depends on control dependency: [if], data = [none] } return cx.typeErrorThrower; } }
public class class_name { public void setAliases(java.util.Collection<AliasConfiguration> aliases) { if (aliases == null) { this.aliases = null; return; } this.aliases = new com.amazonaws.internal.SdkInternalList<AliasConfiguration>(aliases); } }
public class class_name { public void setAliases(java.util.Collection<AliasConfiguration> aliases) { if (aliases == null) { this.aliases = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.aliases = new com.amazonaws.internal.SdkInternalList<AliasConfiguration>(aliases); } }
public class class_name { @Override public void addNumCol(int colIdx, double value) { if (Double.isNaN(value) || Double.isInfinite(value)) { addInvalidCol(colIdx); } else { if( colIdx < _nCols ) { _nvs[_col = colIdx].addNumDecompose(value); if(_ctypes != null && _ctypes[colIdx] == Vec.T_BAD ) _ctypes[colIdx] = Vec.T_NUM; } } } }
public class class_name { @Override public void addNumCol(int colIdx, double value) { if (Double.isNaN(value) || Double.isInfinite(value)) { addInvalidCol(colIdx); // depends on control dependency: [if], data = [none] } else { if( colIdx < _nCols ) { _nvs[_col = colIdx].addNumDecompose(value); // depends on control dependency: [if], data = [none] if(_ctypes != null && _ctypes[colIdx] == Vec.T_BAD ) _ctypes[colIdx] = Vec.T_NUM; } } } }
public class class_name { @SuppressWarnings("unchecked") static <T, R> boolean trySubscribeScalarMap(Publisher<? extends T> source, CoreSubscriber<? super R> s, Function<? super T, ? extends Publisher<? extends R>> mapper, boolean fuseableExpected) { if (source instanceof Callable) { T t; try { t = ((Callable<? extends T>) source).call(); } catch (Throwable e) { Operators.error(s, Operators.onOperatorError(e, s.currentContext())); return true; } if (t == null) { Operators.complete(s); return true; } Publisher<? extends R> p; try { p = Objects.requireNonNull(mapper.apply(t), "The mapper returned a null Publisher"); } catch (Throwable e) { Operators.error(s, Operators.onOperatorError(null, e, t, s.currentContext())); return true; } if (p instanceof Callable) { R v; try { v = ((Callable<R>) p).call(); } catch (Throwable e) { Operators.error(s, Operators.onOperatorError(null, e, t, s.currentContext())); return true; } if (v != null) { s.onSubscribe(Operators.scalarSubscription(s, v)); } else { Operators.complete(s); } } else { if (!fuseableExpected || p instanceof Fuseable) { p.subscribe(s); } else { p.subscribe(new FluxHide.SuppressFuseableSubscriber<>(s)); } } return true; } return false; } }
public class class_name { @SuppressWarnings("unchecked") static <T, R> boolean trySubscribeScalarMap(Publisher<? extends T> source, CoreSubscriber<? super R> s, Function<? super T, ? extends Publisher<? extends R>> mapper, boolean fuseableExpected) { if (source instanceof Callable) { T t; try { t = ((Callable<? extends T>) source).call(); // depends on control dependency: [try], data = [none] } catch (Throwable e) { Operators.error(s, Operators.onOperatorError(e, s.currentContext())); return true; } // depends on control dependency: [catch], data = [none] if (t == null) { Operators.complete(s); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } Publisher<? extends R> p; // depends on control dependency: [if], data = [none] try { p = Objects.requireNonNull(mapper.apply(t), "The mapper returned a null Publisher"); // depends on control dependency: [try], data = [none] } catch (Throwable e) { Operators.error(s, Operators.onOperatorError(null, e, t, s.currentContext())); return true; } // depends on control dependency: [catch], data = [none] if (p instanceof Callable) { R v; try { v = ((Callable<R>) p).call(); // depends on control dependency: [try], data = [none] } catch (Throwable e) { Operators.error(s, Operators.onOperatorError(null, e, t, s.currentContext())); return true; } // depends on control dependency: [catch], data = [none] if (v != null) { s.onSubscribe(Operators.scalarSubscription(s, v)); // depends on control dependency: [if], data = [none] } else { Operators.complete(s); // depends on control dependency: [if], data = [none] } } else { if (!fuseableExpected || p instanceof Fuseable) { p.subscribe(s); // depends on control dependency: [if], data = [none] } else { p.subscribe(new FluxHide.SuppressFuseableSubscriber<>(s)); // depends on control dependency: [if], data = [none] } } return true; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { private byte[] buildMultipartBody(Map<String, String> params, byte[] photoData, String boundary) throws JinxException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { String filename = params.get("filename"); if (JinxUtils.isNullOrEmpty(filename)) { filename = "image.jpg"; } String fileMimeType = params.get("filemimetype"); if (JinxUtils.isNullOrEmpty(fileMimeType)) { fileMimeType = "image/jpeg"; } buffer.write(("--" + boundary + "\r\n").getBytes(JinxConstants.UTF8)); for (Map.Entry<String, String> entry : params.entrySet()) { String key = entry.getKey(); if (!key.equals("filename") && !key.equals("filemimetype")) { buffer.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n").getBytes(JinxConstants.UTF8)); buffer.write((entry.getValue()).getBytes(JinxConstants.UTF8)); buffer.write(("\r\n" + "--" + boundary + "\r\n").getBytes(JinxConstants.UTF8)); } } buffer.write(("Content-Disposition: form-data; name=\"photo\"; filename=\"" + filename + "\";\r\n").getBytes(JinxConstants.UTF8)); buffer.write(("Content-Type: " + fileMimeType + "\r\n\r\n").getBytes(JinxConstants.UTF8)); buffer.write(photoData); buffer.write(("\r\n" + "--" + boundary + "--\r\n").getBytes(JinxConstants.UTF8)); // NOTE: last boundary has -- suffix } catch (Exception e) { throw new JinxException("Unable to build multipart body.", e); } if (this.isVerboseLogging() && this.isMultipartLogging()) { JinxLogger.getLogger().log("Multipart body: " + buffer.toString()); } return buffer.toByteArray(); } }
public class class_name { private byte[] buildMultipartBody(Map<String, String> params, byte[] photoData, String boundary) throws JinxException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { String filename = params.get("filename"); if (JinxUtils.isNullOrEmpty(filename)) { filename = "image.jpg"; // depends on control dependency: [if], data = [none] } String fileMimeType = params.get("filemimetype"); if (JinxUtils.isNullOrEmpty(fileMimeType)) { fileMimeType = "image/jpeg"; // depends on control dependency: [if], data = [none] } buffer.write(("--" + boundary + "\r\n").getBytes(JinxConstants.UTF8)); for (Map.Entry<String, String> entry : params.entrySet()) { String key = entry.getKey(); if (!key.equals("filename") && !key.equals("filemimetype")) { buffer.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n").getBytes(JinxConstants.UTF8)); // depends on control dependency: [if], data = [none] buffer.write((entry.getValue()).getBytes(JinxConstants.UTF8)); // depends on control dependency: [if], data = [none] buffer.write(("\r\n" + "--" + boundary + "\r\n").getBytes(JinxConstants.UTF8)); // depends on control dependency: [if], data = [none] } } buffer.write(("Content-Disposition: form-data; name=\"photo\"; filename=\"" + filename + "\";\r\n").getBytes(JinxConstants.UTF8)); buffer.write(("Content-Type: " + fileMimeType + "\r\n\r\n").getBytes(JinxConstants.UTF8)); buffer.write(photoData); buffer.write(("\r\n" + "--" + boundary + "--\r\n").getBytes(JinxConstants.UTF8)); // NOTE: last boundary has -- suffix } catch (Exception e) { throw new JinxException("Unable to build multipart body.", e); } if (this.isVerboseLogging() && this.isMultipartLogging()) { JinxLogger.getLogger().log("Multipart body: " + buffer.toString()); } return buffer.toByteArray(); } }
public class class_name { public Bbox createFittingBox(double ratioWidth, double ratioHeight) { if (ratioWidth > 0 && ratioHeight > 0) { double newRatio = ratioWidth / ratioHeight; double oldRatio = width / height; double newWidth = width; double newHeight = height; if (newRatio > oldRatio) { newHeight = width / newRatio; } else { newWidth = height * newRatio; } Bbox result = new Bbox(0, 0, newWidth, newHeight); result.setCenterPoint(getCenterPoint()); return result; } else { return new Bbox(this); } } }
public class class_name { public Bbox createFittingBox(double ratioWidth, double ratioHeight) { if (ratioWidth > 0 && ratioHeight > 0) { double newRatio = ratioWidth / ratioHeight; double oldRatio = width / height; double newWidth = width; double newHeight = height; if (newRatio > oldRatio) { newHeight = width / newRatio; // depends on control dependency: [if], data = [none] } else { newWidth = height * newRatio; // depends on control dependency: [if], data = [none] } Bbox result = new Bbox(0, 0, newWidth, newHeight); result.setCenterPoint(getCenterPoint()); // depends on control dependency: [if], data = [none] return result; // depends on control dependency: [if], data = [none] } else { return new Bbox(this); // depends on control dependency: [if], data = [none] } } }
public class class_name { public EClass getIfcStructuralLoadSingleForceWarping() { if (ifcStructuralLoadSingleForceWarpingEClass == null) { ifcStructuralLoadSingleForceWarpingEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(552); } return ifcStructuralLoadSingleForceWarpingEClass; } }
public class class_name { public EClass getIfcStructuralLoadSingleForceWarping() { if (ifcStructuralLoadSingleForceWarpingEClass == null) { ifcStructuralLoadSingleForceWarpingEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(552); // depends on control dependency: [if], data = [none] } return ifcStructuralLoadSingleForceWarpingEClass; } }
public class class_name { public static long fromAlpha(String s) { s = s.trim().toUpperCase(); if (s.isEmpty()) throw new IllegalArgumentException( "Empty string not allowed"); long result = 0; for (char c: s.toCharArray()) { if (c < 'A' || c > 'Z') throw new IllegalArgumentException( "Invalid character '" + c + "'"); result = result*26 + (c - 'A' + 1); if (result < 0) throw new IllegalArgumentException( "\"" + s + "\" is too large."); } return result-1; } }
public class class_name { public static long fromAlpha(String s) { s = s.trim().toUpperCase(); if (s.isEmpty()) throw new IllegalArgumentException( "Empty string not allowed"); long result = 0; for (char c: s.toCharArray()) { if (c < 'A' || c > 'Z') throw new IllegalArgumentException( "Invalid character '" + c + "'"); result = result*26 + (c - 'A' + 1); // depends on control dependency: [for], data = [c] if (result < 0) throw new IllegalArgumentException( "\"" + s + "\" is too large."); } return result-1; } }
public class class_name { public void reconcileSnapshots() throws StorageException { checkInitialized(); try { // return all snapshots that _do not_ have a corresponding file on the filesystem List<SnapshotMetadata> snapshotsToDelete = getMatchingOrderedSnapshots(new Predicate<SnapshotMetadata>() { @Override public boolean apply(@Nullable SnapshotMetadata metadata) { checkArgument(metadata != null); return !snapshotExistsOnFilesystem(snapshotsDirectory, metadata.getFilename()); } }); // for each of these broken rows, delete the snapshot entry from the db for (final SnapshotMetadata metadata : snapshotsToDelete) { dbi.withHandle(new HandleCallback<Void>() { @Override public Void withHandle(Handle handle) throws Exception { SnapshotsDAO dao = handle.attach(SnapshotsDAO.class); dao.removeSnapshotWithTimestamp(metadata.getTimestamp()); return null; } }); } } catch (StorageException e) { throw e; } catch (CallbackFailedException e) { throw new StorageException("fail reconcile snapshot", e.getCause()); } catch (Exception e) { throw new StorageException("fail reconcile snapshot", e); } } }
public class class_name { public void reconcileSnapshots() throws StorageException { checkInitialized(); try { // return all snapshots that _do not_ have a corresponding file on the filesystem List<SnapshotMetadata> snapshotsToDelete = getMatchingOrderedSnapshots(new Predicate<SnapshotMetadata>() { @Override public boolean apply(@Nullable SnapshotMetadata metadata) { checkArgument(metadata != null); return !snapshotExistsOnFilesystem(snapshotsDirectory, metadata.getFilename()); } }); // for each of these broken rows, delete the snapshot entry from the db for (final SnapshotMetadata metadata : snapshotsToDelete) { dbi.withHandle(new HandleCallback<Void>() { @Override public Void withHandle(Handle handle) throws Exception { SnapshotsDAO dao = handle.attach(SnapshotsDAO.class); dao.removeSnapshotWithTimestamp(metadata.getTimestamp()); return null; } }); // depends on control dependency: [for], data = [none] } } catch (StorageException e) { throw e; } catch (CallbackFailedException e) { throw new StorageException("fail reconcile snapshot", e.getCause()); } catch (Exception e) { throw new StorageException("fail reconcile snapshot", e); } } }