code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public void endPermanent(AddOnModel addOnModel) { if (!isUsing.get() || (permanentAddOn != null && !permanentAddOn.equals(addOnModel))) return; synchronized (permanentUserReadWriteLock) { permanentAddOn = null; Identification tempID = this.knownIdentification; this.knownIdentification = null; if (permanentLines != null) { permanentLines.forEach(weakReferenceLine -> { if (weakReferenceLine.get() != null) weakReferenceLine.get().setToNonPermanent(); }); nonPermanent.put(addOnModel, permanentLines); permanentLines = null; } stopAddon(tempID); endWaitingForUsage(); isUsing.set(false); } } }
public class class_name { public void endPermanent(AddOnModel addOnModel) { if (!isUsing.get() || (permanentAddOn != null && !permanentAddOn.equals(addOnModel))) return; synchronized (permanentUserReadWriteLock) { permanentAddOn = null; Identification tempID = this.knownIdentification; this.knownIdentification = null; if (permanentLines != null) { permanentLines.forEach(weakReferenceLine -> { if (weakReferenceLine.get() != null) weakReferenceLine.get().setToNonPermanent(); // depends on control dependency: [if], data = [none] }); nonPermanent.put(addOnModel, permanentLines); permanentLines = null; } stopAddon(tempID); endWaitingForUsage(); isUsing.set(false); } } }
public class class_name { @POST @Path("{taskName}") public Response processTask(@PathParam("taskName") String taskName) { checkNotNull(requestParamsProvider.get()); checkNotNull(taskName); LOGGER.info("Processing task for {}...", taskName); for (AdminTask adminTask : adminTasks) { final Object body = adminTask.processTask(taskName, requestParamsProvider.get()); LOGGER.info("Processed tasks for {}: {}", taskName, body); } return Response.ok().build(); } }
public class class_name { @POST @Path("{taskName}") public Response processTask(@PathParam("taskName") String taskName) { checkNotNull(requestParamsProvider.get()); checkNotNull(taskName); LOGGER.info("Processing task for {}...", taskName); for (AdminTask adminTask : adminTasks) { final Object body = adminTask.processTask(taskName, requestParamsProvider.get()); LOGGER.info("Processed tasks for {}: {}", taskName, body); // depends on control dependency: [for], data = [none] } return Response.ok().build(); } }
public class class_name { static String getGlobalName(Binding binding) { if (binding.isModuleNamespace()) { return getGlobalName(binding.metadata(), binding.closureNamespace()); } return getGlobalName(binding.originatingExport()); } }
public class class_name { static String getGlobalName(Binding binding) { if (binding.isModuleNamespace()) { return getGlobalName(binding.metadata(), binding.closureNamespace()); // depends on control dependency: [if], data = [none] } return getGlobalName(binding.originatingExport()); } }
public class class_name { File findRepoPath(final String repoAlias) { if ("user".equals(repoAlias)) { return new File(System.getProperty("user.home") + CeylonUtil.PATH_SEPARATOR + ".ceylon/repo"); } else if ("cache".equals(repoAlias)) { return new File(System.getProperty("user.home") + CeylonUtil.PATH_SEPARATOR + ".ceylon/cache"); } else if ("system".equals(repoAlias)) { throw new IllegalArgumentException("Ceylon Repository 'system' should not be written to"); } else if ("remote".equals(repoAlias)) { throw new IllegalArgumentException("Ceylon Repository 'remote' should use the ceylon:deploy Maven goal"); } else if ("local".equals(repoAlias)) { return new File(project.getBasedir(), "modules"); } else { throw new IllegalArgumentException( "Property ceylonRepository must one of 'user', 'cache' or 'local'. Defaults to 'user'"); } } }
public class class_name { File findRepoPath(final String repoAlias) { if ("user".equals(repoAlias)) { return new File(System.getProperty("user.home") + CeylonUtil.PATH_SEPARATOR + ".ceylon/repo"); // depends on control dependency: [if], data = [none] } else if ("cache".equals(repoAlias)) { return new File(System.getProperty("user.home") + CeylonUtil.PATH_SEPARATOR + ".ceylon/cache"); // depends on control dependency: [if], data = [none] } else if ("system".equals(repoAlias)) { throw new IllegalArgumentException("Ceylon Repository 'system' should not be written to"); } else if ("remote".equals(repoAlias)) { throw new IllegalArgumentException("Ceylon Repository 'remote' should use the ceylon:deploy Maven goal"); } else if ("local".equals(repoAlias)) { return new File(project.getBasedir(), "modules"); // depends on control dependency: [if], data = [none] } else { throw new IllegalArgumentException( "Property ceylonRepository must one of 'user', 'cache' or 'local'. Defaults to 'user'"); } } }
public class class_name { protected void makeDatasets(CancelTask cancelTask) throws IOException { // heres where the results will go datasets = new ArrayList<>(); for (MFile cd : datasetManager.getFilesSorted()) { datasets.add( makeDataset(cd)); } // sort using Aggregation.Dataset as Comparator. // Sort by date if it exists, else filename. Collections.sort(datasets); /* optionally extract the date String dateCoordS = null; if (null != dateFormatMark) { String filename = myf.getName(); // LOOK operates on name, not path Date dateCoord = DateFromString.getDateUsingDemarkatedCount(filename, dateFormatMark, '#'); dateCoordS = formatter.toDateTimeStringISO(dateCoord); if (debugDateParse) System.out.println(" adding " + myf.getPath() + " date= " + dateCoordS); } else { if (debugDateParse) System.out.println(" adding " + myf.getPath()); } String location = myf.getPath(); Aggregation.Dataset ds = makeDataset(location, location, null, null, dateCoordS, null, enhance, null); datasets.add(ds); } // Sort by date if it exists, else filename. Collections.sort(datasets, new Comparator<Aggregation.Dataset>() { public int compare(Aggregation.Dataset ds1, Aggregation.Dataset ds2) { if(ds1.cd == null) return ds1.getLocation().compareTo(ds2.getLocation()) ; if (ds1.cd.dateCoord != null) // LOOK can we generalize return ds1.cd.dateCoord.compareTo(ds2.cd.dateCoord); else return ds1.cd.file.getName().compareTo(ds2.cd.file.getName()); } }); */ // add the explicit datasets - these need to be kept in order // LOOK - should they be before or after scanned? Does it make sense to mix scan and explicit? // AggFmrcSingle sets explicit datasets - the scan is empty for (Aggregation.Dataset dataset : explicitDatasets) { datasets.add(dataset); } // Remove unreadable files (i.e. due to permissions) from the aggregation. // LOOK: Is this logic we should install "upstream", perhaps in MFileCollectionManager? // It would affect other collections than just NcML aggregation in that case. for (Iterator<Dataset> datasetsIter = datasets.iterator(); datasetsIter.hasNext(); ) { Dataset dataset = datasetsIter.next(); Path datasetPath; if (dataset.getMFile() instanceof MFileOS) { datasetPath = ((MFileOS) dataset.getMFile()).getFile().toPath(); } else if (dataset.getMFile() instanceof MFileOS7) { datasetPath = ((MFileOS7) dataset.getMFile()).getNioPath(); } else { continue; } if (!Files.isReadable(datasetPath)) { // File.canRead() is broken on Windows, but the JDK7 methods work. logger.warn("Aggregation member isn't readable (permissions issue?). Skipping: " + datasetPath); datasetsIter.remove(); } } // check for duplicate location Set<String> dset = new HashSet<>( 2 * datasets.size()); for (Aggregation.Dataset dataset : datasets) { if (dset.contains(dataset.cacheLocation)) logger.warn("Duplicate dataset in aggregation = "+dataset.cacheLocation); dset.add(dataset.cacheLocation); } if (datasets.size() == 0) { throw new IllegalStateException("There are no datasets in the aggregation " + datasetManager); } } }
public class class_name { protected void makeDatasets(CancelTask cancelTask) throws IOException { // heres where the results will go datasets = new ArrayList<>(); for (MFile cd : datasetManager.getFilesSorted()) { datasets.add( makeDataset(cd)); } // sort using Aggregation.Dataset as Comparator. // Sort by date if it exists, else filename. Collections.sort(datasets); /* optionally extract the date String dateCoordS = null; if (null != dateFormatMark) { String filename = myf.getName(); // LOOK operates on name, not path Date dateCoord = DateFromString.getDateUsingDemarkatedCount(filename, dateFormatMark, '#'); dateCoordS = formatter.toDateTimeStringISO(dateCoord); if (debugDateParse) System.out.println(" adding " + myf.getPath() + " date= " + dateCoordS); } else { if (debugDateParse) System.out.println(" adding " + myf.getPath()); } String location = myf.getPath(); Aggregation.Dataset ds = makeDataset(location, location, null, null, dateCoordS, null, enhance, null); datasets.add(ds); } // Sort by date if it exists, else filename. Collections.sort(datasets, new Comparator<Aggregation.Dataset>() { public int compare(Aggregation.Dataset ds1, Aggregation.Dataset ds2) { if(ds1.cd == null) return ds1.getLocation().compareTo(ds2.getLocation()) ; if (ds1.cd.dateCoord != null) // LOOK can we generalize return ds1.cd.dateCoord.compareTo(ds2.cd.dateCoord); else return ds1.cd.file.getName().compareTo(ds2.cd.file.getName()); } }); */ // add the explicit datasets - these need to be kept in order // LOOK - should they be before or after scanned? Does it make sense to mix scan and explicit? // AggFmrcSingle sets explicit datasets - the scan is empty for (Aggregation.Dataset dataset : explicitDatasets) { datasets.add(dataset); } // Remove unreadable files (i.e. due to permissions) from the aggregation. // LOOK: Is this logic we should install "upstream", perhaps in MFileCollectionManager? // It would affect other collections than just NcML aggregation in that case. for (Iterator<Dataset> datasetsIter = datasets.iterator(); datasetsIter.hasNext(); ) { Dataset dataset = datasetsIter.next(); Path datasetPath; if (dataset.getMFile() instanceof MFileOS) { datasetPath = ((MFileOS) dataset.getMFile()).getFile().toPath(); // depends on control dependency: [if], data = [none] } else if (dataset.getMFile() instanceof MFileOS7) { datasetPath = ((MFileOS7) dataset.getMFile()).getNioPath(); // depends on control dependency: [if], data = [none] } else { continue; } if (!Files.isReadable(datasetPath)) { // File.canRead() is broken on Windows, but the JDK7 methods work. logger.warn("Aggregation member isn't readable (permissions issue?). Skipping: " + datasetPath); // depends on control dependency: [if], data = [none] datasetsIter.remove(); // depends on control dependency: [if], data = [none] } } // check for duplicate location Set<String> dset = new HashSet<>( 2 * datasets.size()); for (Aggregation.Dataset dataset : datasets) { if (dset.contains(dataset.cacheLocation)) logger.warn("Duplicate dataset in aggregation = "+dataset.cacheLocation); dset.add(dataset.cacheLocation); } if (datasets.size() == 0) { throw new IllegalStateException("There are no datasets in the aggregation " + datasetManager); } } }
public class class_name { public void setSecurityGroupArns(java.util.Collection<String> securityGroupArns) { if (securityGroupArns == null) { this.securityGroupArns = null; return; } this.securityGroupArns = new java.util.ArrayList<String>(securityGroupArns); } }
public class class_name { public void setSecurityGroupArns(java.util.Collection<String> securityGroupArns) { if (securityGroupArns == null) { this.securityGroupArns = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.securityGroupArns = new java.util.ArrayList<String>(securityGroupArns); } }
public class class_name { public void setOr(java.util.Collection<Expression> or) { if (or == null) { this.or = null; return; } this.or = new java.util.ArrayList<Expression>(or); } }
public class class_name { public void setOr(java.util.Collection<Expression> or) { if (or == null) { this.or = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.or = new java.util.ArrayList<Expression>(or); } }
public class class_name { public void marshall(AddTagsToCertificateRequest addTagsToCertificateRequest, ProtocolMarshaller protocolMarshaller) { if (addTagsToCertificateRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(addTagsToCertificateRequest.getCertificateArn(), CERTIFICATEARN_BINDING); protocolMarshaller.marshall(addTagsToCertificateRequest.getTags(), TAGS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(AddTagsToCertificateRequest addTagsToCertificateRequest, ProtocolMarshaller protocolMarshaller) { if (addTagsToCertificateRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(addTagsToCertificateRequest.getCertificateArn(), CERTIFICATEARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(addTagsToCertificateRequest.getTags(), TAGS_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static long getSizeOfPhysicalMemory() { // first try if the JVM can directly tell us what the system memory is // this works only on Oracle JVMs try { Class<?> clazz = Class.forName("com.sun.management.OperatingSystemMXBean"); Method method = clazz.getMethod("getTotalPhysicalMemorySize"); OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); // someone may install different beans, so we need to check whether the bean // is in fact the sun management bean if (clazz.isInstance(operatingSystemMXBean)) { return (Long) method.invoke(operatingSystemMXBean); } } catch (ClassNotFoundException e) { // this happens on non-Oracle JVMs, do nothing and use the alternative code paths } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { LOG.warn("Access to physical memory size: " + "com.sun.management.OperatingSystemMXBean incompatibly changed.", e); } // we now try the OS specific access paths switch (OperatingSystem.getCurrentOperatingSystem()) { case LINUX: return getSizeOfPhysicalMemoryForLinux(); case WINDOWS: return getSizeOfPhysicalMemoryForWindows(); case MAC_OS: return getSizeOfPhysicalMemoryForMac(); case FREE_BSD: return getSizeOfPhysicalMemoryForFreeBSD(); case UNKNOWN: LOG.error("Cannot determine size of physical memory for unknown operating system"); return -1; default: LOG.error("Unrecognized OS: " + OperatingSystem.getCurrentOperatingSystem()); return -1; } } }
public class class_name { public static long getSizeOfPhysicalMemory() { // first try if the JVM can directly tell us what the system memory is // this works only on Oracle JVMs try { Class<?> clazz = Class.forName("com.sun.management.OperatingSystemMXBean"); Method method = clazz.getMethod("getTotalPhysicalMemorySize"); OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); // someone may install different beans, so we need to check whether the bean // is in fact the sun management bean if (clazz.isInstance(operatingSystemMXBean)) { return (Long) method.invoke(operatingSystemMXBean); // depends on control dependency: [if], data = [none] } } catch (ClassNotFoundException e) { // this happens on non-Oracle JVMs, do nothing and use the alternative code paths } // depends on control dependency: [catch], data = [none] catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { LOG.warn("Access to physical memory size: " + "com.sun.management.OperatingSystemMXBean incompatibly changed.", e); } // depends on control dependency: [catch], data = [none] // we now try the OS specific access paths switch (OperatingSystem.getCurrentOperatingSystem()) { case LINUX: return getSizeOfPhysicalMemoryForLinux(); case WINDOWS: return getSizeOfPhysicalMemoryForWindows(); case MAC_OS: return getSizeOfPhysicalMemoryForMac(); case FREE_BSD: return getSizeOfPhysicalMemoryForFreeBSD(); case UNKNOWN: LOG.error("Cannot determine size of physical memory for unknown operating system"); return -1; default: LOG.error("Unrecognized OS: " + OperatingSystem.getCurrentOperatingSystem()); return -1; } } }
public class class_name { public int compareTo(final Vertex<T> o) { int orderInd; if (m_order < o.m_order) { orderInd = -1; } else if (m_order > o.m_order) { orderInd = 1; } else { orderInd = 0; } return orderInd; } }
public class class_name { public int compareTo(final Vertex<T> o) { int orderInd; if (m_order < o.m_order) { orderInd = -1; // depends on control dependency: [if], data = [none] } else if (m_order > o.m_order) { orderInd = 1; // depends on control dependency: [if], data = [none] } else { orderInd = 0; // depends on control dependency: [if], data = [none] } return orderInd; } }
public class class_name { private static Optional<Fix> rewriteCompoundAssignment( CompoundAssignmentTree tree, VisitorState state) { CharSequence var = state.getSourceForNode(tree.getVariable()); CharSequence expr = state.getSourceForNode(tree.getExpression()); if (var == null || expr == null) { return Optional.absent(); } switch (tree.getKind()) { case RIGHT_SHIFT_ASSIGNMENT: // narrowing the result of a signed right shift does not lose information return Optional.absent(); default: break; } Kind regularAssignmentKind = regularAssignmentFromCompound(tree.getKind()); String op = assignmentToString(regularAssignmentKind); // Add parens to the rhs if necessary to preserve the current precedence // e.g. 's -= 1 - 2' -> 's = s - (1 - 2)' OperatorPrecedence rhsPrecedence = tree.getExpression() instanceof JCBinary ? OperatorPrecedence.from(tree.getExpression().getKind()) : tree.getExpression() instanceof ConditionalExpressionTree ? OperatorPrecedence.TERNARY : null; if (rhsPrecedence != null) { if (!rhsPrecedence.isHigher(OperatorPrecedence.from(regularAssignmentKind))) { expr = String.format("(%s)", expr); } } // e.g. 's *= 42' -> 's = (short) (s * 42)' String castType = getType(tree.getVariable()).toString(); String replacement = String.format("%s = (%s) (%s %s %s)", var, castType, var, op, expr); return Optional.of(SuggestedFix.replace(tree, replacement)); } }
public class class_name { private static Optional<Fix> rewriteCompoundAssignment( CompoundAssignmentTree tree, VisitorState state) { CharSequence var = state.getSourceForNode(tree.getVariable()); CharSequence expr = state.getSourceForNode(tree.getExpression()); if (var == null || expr == null) { return Optional.absent(); // depends on control dependency: [if], data = [none] } switch (tree.getKind()) { case RIGHT_SHIFT_ASSIGNMENT: // narrowing the result of a signed right shift does not lose information return Optional.absent(); default: break; } Kind regularAssignmentKind = regularAssignmentFromCompound(tree.getKind()); String op = assignmentToString(regularAssignmentKind); // Add parens to the rhs if necessary to preserve the current precedence // e.g. 's -= 1 - 2' -> 's = s - (1 - 2)' OperatorPrecedence rhsPrecedence = tree.getExpression() instanceof JCBinary ? OperatorPrecedence.from(tree.getExpression().getKind()) : tree.getExpression() instanceof ConditionalExpressionTree ? OperatorPrecedence.TERNARY : null; if (rhsPrecedence != null) { if (!rhsPrecedence.isHigher(OperatorPrecedence.from(regularAssignmentKind))) { expr = String.format("(%s)", expr); } } // e.g. 's *= 42' -> 's = (short) (s * 42)' String castType = getType(tree.getVariable()).toString(); String replacement = String.format("%s = (%s) (%s %s %s)", var, castType, var, op, expr); return Optional.of(SuggestedFix.replace(tree, replacement)); } }
public class class_name { @SuppressWarnings("unchecked") public static <T> boolean hasClass(Class<T> type, ClassLoader classloader) { try { loadClass(type.getName(), classloader); return true; } catch (RuntimeException e) { if(e.getCause() instanceof ClassNotFoundException) { return false; } throw e; } } }
public class class_name { @SuppressWarnings("unchecked") public static <T> boolean hasClass(Class<T> type, ClassLoader classloader) { try { loadClass(type.getName(), classloader); // depends on control dependency: [try], data = [none] return true; // depends on control dependency: [try], data = [none] } catch (RuntimeException e) { if(e.getCause() instanceof ClassNotFoundException) { return false; // depends on control dependency: [if], data = [none] } throw e; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static WsByteBuffer[] allocateByteBuffers(int requestedBufferSize, long totalDataSize, boolean allocateDirect, boolean enforceRequestedSize) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.entry(tc, "allocateByteBuffers"); } // Allocate the first buffer. WsByteBuffer firstBuffer = allocateByteBuffer(requestedBufferSize, allocateDirect); // Check if we are obligated to stick to the requested size. if (enforceRequestedSize) { firstBuffer.limit(requestedBufferSize); } // Note, allocation can result in a buffer larger than requested. Determine the // number of buffers to allocated based on the resulting actual size. int actualBufferSize = firstBuffer.limit(); // if the actual size is the same as the requested size, then no need to force it boolean enforce = enforceRequestedSize; if (enforce && actualBufferSize == requestedBufferSize) { enforce = false; } int numBuffersToAllocate = (int) (totalDataSize / actualBufferSize); // Still need to account for a remainder. if ((totalDataSize % actualBufferSize) > 0) { numBuffersToAllocate++; } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "allocate: requestSize=" + requestedBufferSize + ", actualSize=" + actualBufferSize + ", totSize=" + totalDataSize + ", numBufs=" + numBuffersToAllocate); } // Create the array of the determined size. WsByteBuffer newBuffers[] = new WsByteBuffer[numBuffersToAllocate]; newBuffers[0] = firstBuffer; for (int i = 1; i < newBuffers.length; i++) { newBuffers[i] = allocateByteBuffer(requestedBufferSize, allocateDirect); // Check if we are obligated to stick to the requested size. if (enforce) { newBuffers[i].limit(requestedBufferSize); } } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.exit(tc, "allocateByteBuffers"); } return newBuffers; } }
public class class_name { public static WsByteBuffer[] allocateByteBuffers(int requestedBufferSize, long totalDataSize, boolean allocateDirect, boolean enforceRequestedSize) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.entry(tc, "allocateByteBuffers"); // depends on control dependency: [if], data = [none] } // Allocate the first buffer. WsByteBuffer firstBuffer = allocateByteBuffer(requestedBufferSize, allocateDirect); // Check if we are obligated to stick to the requested size. if (enforceRequestedSize) { firstBuffer.limit(requestedBufferSize); // depends on control dependency: [if], data = [none] } // Note, allocation can result in a buffer larger than requested. Determine the // number of buffers to allocated based on the resulting actual size. int actualBufferSize = firstBuffer.limit(); // if the actual size is the same as the requested size, then no need to force it boolean enforce = enforceRequestedSize; if (enforce && actualBufferSize == requestedBufferSize) { enforce = false; // depends on control dependency: [if], data = [none] } int numBuffersToAllocate = (int) (totalDataSize / actualBufferSize); // Still need to account for a remainder. if ((totalDataSize % actualBufferSize) > 0) { numBuffersToAllocate++; // depends on control dependency: [if], data = [none] } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "allocate: requestSize=" + requestedBufferSize + ", actualSize=" + actualBufferSize + ", totSize=" + totalDataSize + ", numBufs=" + numBuffersToAllocate); // depends on control dependency: [if], data = [none] } // Create the array of the determined size. WsByteBuffer newBuffers[] = new WsByteBuffer[numBuffersToAllocate]; newBuffers[0] = firstBuffer; for (int i = 1; i < newBuffers.length; i++) { newBuffers[i] = allocateByteBuffer(requestedBufferSize, allocateDirect); // depends on control dependency: [for], data = [i] // Check if we are obligated to stick to the requested size. if (enforce) { newBuffers[i].limit(requestedBufferSize); // depends on control dependency: [if], data = [none] } } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.exit(tc, "allocateByteBuffers"); // depends on control dependency: [if], data = [none] } return newBuffers; } }
public class class_name { public AudioChannelMapping withInputChannelLevels(InputChannelLevel... inputChannelLevels) { if (this.inputChannelLevels == null) { setInputChannelLevels(new java.util.ArrayList<InputChannelLevel>(inputChannelLevels.length)); } for (InputChannelLevel ele : inputChannelLevels) { this.inputChannelLevels.add(ele); } return this; } }
public class class_name { public AudioChannelMapping withInputChannelLevels(InputChannelLevel... inputChannelLevels) { if (this.inputChannelLevels == null) { setInputChannelLevels(new java.util.ArrayList<InputChannelLevel>(inputChannelLevels.length)); // depends on control dependency: [if], data = [none] } for (InputChannelLevel ele : inputChannelLevels) { this.inputChannelLevels.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public void configure(long newCheckInterval) { long newInterval = newCheckInterval / 10 * 10; if (checkInterval.getAndSet(newInterval) != newInterval) { if (newInterval <= 0) { stop(); // No more active monitoring lastTime.set(milliSecondFromNano()); } else { // Start if necessary start(); } } } }
public class class_name { public void configure(long newCheckInterval) { long newInterval = newCheckInterval / 10 * 10; if (checkInterval.getAndSet(newInterval) != newInterval) { if (newInterval <= 0) { stop(); // depends on control dependency: [if], data = [none] // No more active monitoring lastTime.set(milliSecondFromNano()); // depends on control dependency: [if], data = [none] } else { // Start if necessary start(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public java.util.List<UpdateTarget> getUpdateTargets() { if (updateTargets == null) { updateTargets = new com.amazonaws.internal.SdkInternalList<UpdateTarget>(); } return updateTargets; } }
public class class_name { public java.util.List<UpdateTarget> getUpdateTargets() { if (updateTargets == null) { updateTargets = new com.amazonaws.internal.SdkInternalList<UpdateTarget>(); // depends on control dependency: [if], data = [none] } return updateTargets; } }
public class class_name { @Override public final void setName(String name) { log.debug("Set name: {}", name); if (this.name == null && StringUtils.isNotBlank(name)) { // reset of the name is no longer allowed this.name = name; // unregister from jmx if (oName != null) { unregisterJMX(); } // register registerJMX(); } else { log.info("Scope {} name reset to: {} disallowed", this.name, name); } } }
public class class_name { @Override public final void setName(String name) { log.debug("Set name: {}", name); if (this.name == null && StringUtils.isNotBlank(name)) { // reset of the name is no longer allowed this.name = name; // depends on control dependency: [if], data = [none] // unregister from jmx if (oName != null) { unregisterJMX(); // depends on control dependency: [if], data = [none] } // register registerJMX(); // depends on control dependency: [if], data = [none] } else { log.info("Scope {} name reset to: {} disallowed", this.name, name); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static List<List<CDKRMap>> search(IAtomContainer sourceGraph, IAtomContainer targetGraph, BitSet sourceBitSet, BitSet targetBitSet, boolean findAllStructure, boolean findAllMap, boolean shouldMatchBonds) throws CDKException { // handle single query atom case separately if (targetGraph.getAtomCount() == 1) { List<List<CDKRMap>> matches = new ArrayList<List<CDKRMap>>(); IAtom queryAtom = targetGraph.getAtom(0); // we can have a IQueryAtomContainer *or* an IAtomContainer if (queryAtom instanceof IQueryAtom) { IQueryAtom qAtom = (IQueryAtom) queryAtom; for (IAtom atom : sourceGraph.atoms()) { if (qAtom.matches(atom)) { List<CDKRMap> lmap = new ArrayList<CDKRMap>(); lmap.add(new CDKRMap(sourceGraph.indexOf(atom), 0)); matches.add(lmap); } } } else { for (IAtom atom : sourceGraph.atoms()) { if (queryAtom.getSymbol().equals(atom.getSymbol())) { List<CDKRMap> lmap = new ArrayList<CDKRMap>(); lmap.add(new CDKRMap(sourceGraph.indexOf(atom), 0)); matches.add(lmap); } } } return matches; } // reset result List<List<CDKRMap>> rMapsList = new ArrayList<List<CDKRMap>>(); // build the CDKRGraph corresponding to this problem CDKRGraph rGraph = buildRGraph(sourceGraph, targetGraph, shouldMatchBonds); setTimeManager(new TimeManager()); // parse the CDKRGraph with the given constrains and options rGraph.parse(sourceBitSet, targetBitSet, findAllStructure, findAllMap, getTimeManager()); List<BitSet> solutionList = rGraph.getSolutions(); // conversions of CDKRGraph's internal solutions to G1/G2 mappings for (BitSet set : solutionList) { rMapsList.add(rGraph.bitSetToRMap(set)); } return rMapsList; } }
public class class_name { public static List<List<CDKRMap>> search(IAtomContainer sourceGraph, IAtomContainer targetGraph, BitSet sourceBitSet, BitSet targetBitSet, boolean findAllStructure, boolean findAllMap, boolean shouldMatchBonds) throws CDKException { // handle single query atom case separately if (targetGraph.getAtomCount() == 1) { List<List<CDKRMap>> matches = new ArrayList<List<CDKRMap>>(); IAtom queryAtom = targetGraph.getAtom(0); // we can have a IQueryAtomContainer *or* an IAtomContainer if (queryAtom instanceof IQueryAtom) { IQueryAtom qAtom = (IQueryAtom) queryAtom; for (IAtom atom : sourceGraph.atoms()) { if (qAtom.matches(atom)) { List<CDKRMap> lmap = new ArrayList<CDKRMap>(); lmap.add(new CDKRMap(sourceGraph.indexOf(atom), 0)); // depends on control dependency: [if], data = [none] matches.add(lmap); // depends on control dependency: [if], data = [none] } } } else { for (IAtom atom : sourceGraph.atoms()) { if (queryAtom.getSymbol().equals(atom.getSymbol())) { List<CDKRMap> lmap = new ArrayList<CDKRMap>(); lmap.add(new CDKRMap(sourceGraph.indexOf(atom), 0)); // depends on control dependency: [if], data = [none] matches.add(lmap); // depends on control dependency: [if], data = [none] } } } return matches; } // reset result List<List<CDKRMap>> rMapsList = new ArrayList<List<CDKRMap>>(); // build the CDKRGraph corresponding to this problem CDKRGraph rGraph = buildRGraph(sourceGraph, targetGraph, shouldMatchBonds); setTimeManager(new TimeManager()); // parse the CDKRGraph with the given constrains and options rGraph.parse(sourceBitSet, targetBitSet, findAllStructure, findAllMap, getTimeManager()); List<BitSet> solutionList = rGraph.getSolutions(); // conversions of CDKRGraph's internal solutions to G1/G2 mappings for (BitSet set : solutionList) { rMapsList.add(rGraph.bitSetToRMap(set)); } return rMapsList; } }
public class class_name { public static Set<String> getForeignKeys(DriverTypeEnum.ConnectionProperties theConnectionProperties, String theTableName, String theForeignTable) throws SQLException { DataSource dataSource = Objects.requireNonNull(theConnectionProperties.getDataSource()); try (Connection connection = dataSource.getConnection()) { return theConnectionProperties.getTxTemplate().execute(t -> { DatabaseMetaData metadata; try { metadata = connection.getMetaData(); ResultSet indexes = metadata.getCrossReference(connection.getCatalog(), connection.getSchema(), massageIdentifier(metadata, theTableName), connection.getCatalog(), connection.getSchema(), massageIdentifier(metadata, theForeignTable)); Set<String> columnNames = new HashSet<>(); while (indexes.next()) { String tableName = toUpperCase(indexes.getString("PKTABLE_NAME"), Locale.US); if (!theTableName.equalsIgnoreCase(tableName)) { continue; } tableName = toUpperCase(indexes.getString("FKTABLE_NAME"), Locale.US); if (!theForeignTable.equalsIgnoreCase(tableName)) { continue; } String fkName = indexes.getString("FK_NAME"); fkName = toUpperCase(fkName, Locale.US); columnNames.add(fkName); } return columnNames; } catch (SQLException e) { throw new InternalErrorException(e); } }); } } }
public class class_name { public static Set<String> getForeignKeys(DriverTypeEnum.ConnectionProperties theConnectionProperties, String theTableName, String theForeignTable) throws SQLException { DataSource dataSource = Objects.requireNonNull(theConnectionProperties.getDataSource()); try (Connection connection = dataSource.getConnection()) { return theConnectionProperties.getTxTemplate().execute(t -> { DatabaseMetaData metadata; try { metadata = connection.getMetaData(); // depends on control dependency: [try], data = [none] ResultSet indexes = metadata.getCrossReference(connection.getCatalog(), connection.getSchema(), massageIdentifier(metadata, theTableName), connection.getCatalog(), connection.getSchema(), massageIdentifier(metadata, theForeignTable)); Set<String> columnNames = new HashSet<>(); while (indexes.next()) { String tableName = toUpperCase(indexes.getString("PKTABLE_NAME"), Locale.US); if (!theTableName.equalsIgnoreCase(tableName)) { continue; } tableName = toUpperCase(indexes.getString("FKTABLE_NAME"), Locale.US); // depends on control dependency: [while], data = [none] if (!theForeignTable.equalsIgnoreCase(tableName)) { continue; } String fkName = indexes.getString("FK_NAME"); fkName = toUpperCase(fkName, Locale.US); // depends on control dependency: [while], data = [none] columnNames.add(fkName); // depends on control dependency: [while], data = [none] } return columnNames; // depends on control dependency: [try], data = [none] } catch (SQLException e) { throw new InternalErrorException(e); } // depends on control dependency: [catch], data = [none] }); } } }
public class class_name { public Duration getWork(Date startDate, Date endDate, TimeUnit format) { DateRange range = new DateRange(startDate, endDate); Long cachedResult = m_workingDateCache.get(range); long totalTime = 0; if (cachedResult == null) { // // We want the start date to be the earliest date, and the end date // to be the latest date. Set a flag here to indicate if we have swapped // the order of the supplied date. // boolean invert = false; if (startDate.getTime() > endDate.getTime()) { invert = true; Date temp = startDate; startDate = endDate; endDate = temp; } Date canonicalStartDate = DateHelper.getDayStartDate(startDate); Date canonicalEndDate = DateHelper.getDayStartDate(endDate); if (canonicalStartDate.getTime() == canonicalEndDate.getTime()) { ProjectCalendarDateRanges ranges = getRanges(startDate, null, null); if (ranges.getRangeCount() != 0) { totalTime = getTotalTime(ranges, startDate, endDate); } } else { // // Find the first working day in the range // Date currentDate = startDate; Calendar cal = Calendar.getInstance(); cal.setTime(startDate); Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK)); while (isWorkingDate(currentDate, day) == false && currentDate.getTime() < canonicalEndDate.getTime()) { cal.add(Calendar.DAY_OF_YEAR, 1); currentDate = cal.getTime(); day = day.getNextDay(); } if (currentDate.getTime() < canonicalEndDate.getTime()) { // // Calculate the amount of working time for this day // totalTime += getTotalTime(getRanges(currentDate, null, day), currentDate, true); // // Process each working day until we reach the last day // while (true) { cal.add(Calendar.DAY_OF_YEAR, 1); currentDate = cal.getTime(); day = day.getNextDay(); // // We have reached the last day // if (currentDate.getTime() >= canonicalEndDate.getTime()) { break; } // // Skip this day if it has no working time // ProjectCalendarDateRanges ranges = getRanges(currentDate, null, day); if (ranges.getRangeCount() == 0) { continue; } // // Add the working time for the whole day // totalTime += getTotalTime(ranges); } } // // We are now at the last day // ProjectCalendarDateRanges ranges = getRanges(endDate, null, day); if (ranges.getRangeCount() != 0) { totalTime += getTotalTime(ranges, DateHelper.getDayStartDate(endDate), endDate); } } if (invert) { totalTime = -totalTime; } m_workingDateCache.put(range, Long.valueOf(totalTime)); } else { totalTime = cachedResult.longValue(); } return convertFormat(totalTime, format); } }
public class class_name { public Duration getWork(Date startDate, Date endDate, TimeUnit format) { DateRange range = new DateRange(startDate, endDate); Long cachedResult = m_workingDateCache.get(range); long totalTime = 0; if (cachedResult == null) { // // We want the start date to be the earliest date, and the end date // to be the latest date. Set a flag here to indicate if we have swapped // the order of the supplied date. // boolean invert = false; if (startDate.getTime() > endDate.getTime()) { invert = true; // depends on control dependency: [if], data = [none] Date temp = startDate; startDate = endDate; // depends on control dependency: [if], data = [none] endDate = temp; // depends on control dependency: [if], data = [none] } Date canonicalStartDate = DateHelper.getDayStartDate(startDate); Date canonicalEndDate = DateHelper.getDayStartDate(endDate); if (canonicalStartDate.getTime() == canonicalEndDate.getTime()) { ProjectCalendarDateRanges ranges = getRanges(startDate, null, null); if (ranges.getRangeCount() != 0) { totalTime = getTotalTime(ranges, startDate, endDate); // depends on control dependency: [if], data = [none] } } else { // // Find the first working day in the range // Date currentDate = startDate; Calendar cal = Calendar.getInstance(); cal.setTime(startDate); // depends on control dependency: [if], data = [none] Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK)); while (isWorkingDate(currentDate, day) == false && currentDate.getTime() < canonicalEndDate.getTime()) { cal.add(Calendar.DAY_OF_YEAR, 1); // depends on control dependency: [while], data = [none] currentDate = cal.getTime(); // depends on control dependency: [while], data = [none] day = day.getNextDay(); // depends on control dependency: [while], data = [none] } if (currentDate.getTime() < canonicalEndDate.getTime()) { // // Calculate the amount of working time for this day // totalTime += getTotalTime(getRanges(currentDate, null, day), currentDate, true); // depends on control dependency: [if], data = [none] // // Process each working day until we reach the last day // while (true) { cal.add(Calendar.DAY_OF_YEAR, 1); // depends on control dependency: [while], data = [none] currentDate = cal.getTime(); // depends on control dependency: [while], data = [none] day = day.getNextDay(); // depends on control dependency: [while], data = [none] // // We have reached the last day // if (currentDate.getTime() >= canonicalEndDate.getTime()) { break; } // // Skip this day if it has no working time // ProjectCalendarDateRanges ranges = getRanges(currentDate, null, day); if (ranges.getRangeCount() == 0) { continue; } // // Add the working time for the whole day // totalTime += getTotalTime(ranges); // depends on control dependency: [while], data = [none] } } // // We are now at the last day // ProjectCalendarDateRanges ranges = getRanges(endDate, null, day); if (ranges.getRangeCount() != 0) { totalTime += getTotalTime(ranges, DateHelper.getDayStartDate(endDate), endDate); // depends on control dependency: [if], data = [none] } } if (invert) { totalTime = -totalTime; // depends on control dependency: [if], data = [none] } m_workingDateCache.put(range, Long.valueOf(totalTime)); // depends on control dependency: [if], data = [none] } else { totalTime = cachedResult.longValue(); // depends on control dependency: [if], data = [none] } return convertFormat(totalTime, format); } }
public class class_name { private void runPrimary() throws Exception { try { // start the server socket on the right interface doBind(); while (true) { try { final int selectedKeyCount = m_selector.select(); if (selectedKeyCount == 0) { continue; } Set<SelectionKey> selectedKeys = m_selector.selectedKeys(); try { for (SelectionKey key : selectedKeys) { processSSC((ServerSocketChannel)key.channel()); } } finally { selectedKeys.clear(); } } catch (ClosedByInterruptException | ClosedSelectorException e) { throw new InterruptedException(); } catch (Exception e) { LOG.error("Exception occurred in the connection accept loop", e); } } } finally { for (ServerSocketChannel ssc : m_listenerSockets) { try { ssc.close(); } catch (IOException e) { } } m_listenerSockets.clear(); try { m_selector.close(); } catch (IOException e) { } m_selector = null; } } }
public class class_name { private void runPrimary() throws Exception { try { // start the server socket on the right interface doBind(); while (true) { try { final int selectedKeyCount = m_selector.select(); if (selectedKeyCount == 0) { continue; } Set<SelectionKey> selectedKeys = m_selector.selectedKeys(); try { for (SelectionKey key : selectedKeys) { processSSC((ServerSocketChannel)key.channel()); // depends on control dependency: [for], data = [key] } } finally { selectedKeys.clear(); } } catch (ClosedByInterruptException | ClosedSelectorException e) { throw new InterruptedException(); } catch (Exception e) { // depends on control dependency: [catch], data = [none] LOG.error("Exception occurred in the connection accept loop", e); } // depends on control dependency: [catch], data = [none] } } finally { for (ServerSocketChannel ssc : m_listenerSockets) { try { ssc.close(); } catch (IOException e) { } } m_listenerSockets.clear(); try { m_selector.close(); } catch (IOException e) { } m_selector = null; } } }
public class class_name { public void load(BufferedReader input) throws IOException { String line; while( (line=input.readLine()) != null ) { if( StringUtils.matches(line, "\\s*(%.*)?") ) { // comment or blank line System.err.println("Skipping: " + line); continue; } char [] linechars = line.toCharArray(); int [] pattern = new int[linechars.length]; char [] chars = new char[linechars.length]; int c = 0; for( int i = 0; i < linechars.length; ++i) { if( Character.isDigit(linechars[i]) ) { pattern[c] = Character.digit(linechars[i], 10); } else { chars[c++] = linechars[i]; } } char[] shortchars = new char[c]; int [] shortpattern = new int[c+1]; System.arraycopy(chars, 0, shortchars, 0, c); System.arraycopy(pattern, 0, shortpattern, 0, c+1); insertHyphPattern(shortchars, shortpattern); } } }
public class class_name { public void load(BufferedReader input) throws IOException { String line; while( (line=input.readLine()) != null ) { if( StringUtils.matches(line, "\\s*(%.*)?") ) { // comment or blank line System.err.println("Skipping: " + line); // depends on control dependency: [if], data = [none] continue; } char [] linechars = line.toCharArray(); int [] pattern = new int[linechars.length]; char [] chars = new char[linechars.length]; int c = 0; for( int i = 0; i < linechars.length; ++i) { if( Character.isDigit(linechars[i]) ) { pattern[c] = Character.digit(linechars[i], 10); // depends on control dependency: [if], data = [none] } else { chars[c++] = linechars[i]; // depends on control dependency: [if], data = [none] } } char[] shortchars = new char[c]; int [] shortpattern = new int[c+1]; System.arraycopy(chars, 0, shortchars, 0, c); System.arraycopy(pattern, 0, shortpattern, 0, c+1); insertHyphPattern(shortchars, shortpattern); } } }
public class class_name { public List<String> getOwnedClustersByServer(Collection<String> iClusterNames, final String iNode) { if (iClusterNames == null || iClusterNames.isEmpty()) iClusterNames = DEFAULT_CLUSTER_NAME; final List<String> notDefinedClusters = new ArrayList<String>(5); final List<String> candidates = new ArrayList<String>(5); for (String p : iClusterNames) { if (p == null) continue; final String ownerServer = getClusterOwner(p); if (ownerServer == null) notDefinedClusters.add(p); else if (iNode.equals(ownerServer)) { // COLLECT AS CANDIDATE candidates.add(p); } } if (!candidates.isEmpty()) // RETURN THE FIRST ONE return candidates; final String owner = getClusterOwner(ALL_WILDCARD); if (iNode.equals(owner)) // CURRENT SERVER IS MASTER OF DEFAULT: RETURN ALL THE NON CONFIGURED CLUSTERS return notDefinedClusters; // NO MASTER FOUND, RETURN EMPTY LIST return candidates; } }
public class class_name { public List<String> getOwnedClustersByServer(Collection<String> iClusterNames, final String iNode) { if (iClusterNames == null || iClusterNames.isEmpty()) iClusterNames = DEFAULT_CLUSTER_NAME; final List<String> notDefinedClusters = new ArrayList<String>(5); final List<String> candidates = new ArrayList<String>(5); for (String p : iClusterNames) { if (p == null) continue; final String ownerServer = getClusterOwner(p); if (ownerServer == null) notDefinedClusters.add(p); else if (iNode.equals(ownerServer)) { // COLLECT AS CANDIDATE candidates.add(p); // depends on control dependency: [if], data = [none] } } if (!candidates.isEmpty()) // RETURN THE FIRST ONE return candidates; final String owner = getClusterOwner(ALL_WILDCARD); if (iNode.equals(owner)) // CURRENT SERVER IS MASTER OF DEFAULT: RETURN ALL THE NON CONFIGURED CLUSTERS return notDefinedClusters; // NO MASTER FOUND, RETURN EMPTY LIST return candidates; } }
public class class_name { public void marshall(InvokeRequest invokeRequest, ProtocolMarshaller protocolMarshaller) { if (invokeRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(invokeRequest.getFunctionName(), FUNCTIONNAME_BINDING); protocolMarshaller.marshall(invokeRequest.getInvocationType(), INVOCATIONTYPE_BINDING); protocolMarshaller.marshall(invokeRequest.getLogType(), LOGTYPE_BINDING); protocolMarshaller.marshall(invokeRequest.getClientContext(), CLIENTCONTEXT_BINDING); protocolMarshaller.marshall(invokeRequest.getPayload(), PAYLOAD_BINDING); protocolMarshaller.marshall(invokeRequest.getQualifier(), QUALIFIER_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(InvokeRequest invokeRequest, ProtocolMarshaller protocolMarshaller) { if (invokeRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(invokeRequest.getFunctionName(), FUNCTIONNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(invokeRequest.getInvocationType(), INVOCATIONTYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(invokeRequest.getLogType(), LOGTYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(invokeRequest.getClientContext(), CLIENTCONTEXT_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(invokeRequest.getPayload(), PAYLOAD_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(invokeRequest.getQualifier(), QUALIFIER_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void ensureMinMax() { double t; if (this.maxx < this.minx) { t = this.minx; this.minx = this.maxx; this.maxx = t; } if (this.maxy < this.miny) { t = this.miny; this.miny = this.maxy; this.maxy = t; } if (this.maxz < this.minz) { t = this.minz; this.minz = this.maxz; this.maxz = t; } if (this.maxm < this.minm) { t = this.minm; this.minm = this.maxm; this.maxm = t; } } }
public class class_name { public void ensureMinMax() { double t; if (this.maxx < this.minx) { t = this.minx; // depends on control dependency: [if], data = [none] this.minx = this.maxx; // depends on control dependency: [if], data = [none] this.maxx = t; // depends on control dependency: [if], data = [none] } if (this.maxy < this.miny) { t = this.miny; // depends on control dependency: [if], data = [none] this.miny = this.maxy; // depends on control dependency: [if], data = [none] this.maxy = t; // depends on control dependency: [if], data = [none] } if (this.maxz < this.minz) { t = this.minz; // depends on control dependency: [if], data = [none] this.minz = this.maxz; // depends on control dependency: [if], data = [none] this.maxz = t; // depends on control dependency: [if], data = [none] } if (this.maxm < this.minm) { t = this.minm; // depends on control dependency: [if], data = [none] this.minm = this.maxm; // depends on control dependency: [if], data = [none] this.maxm = t; // depends on control dependency: [if], data = [none] } } }
public class class_name { public RuleDescr query(PackageDescrBuilder pkg) throws RecognitionException { QueryDescrBuilder query = null; try { query = helper.start(pkg, QueryDescrBuilder.class, null); setAnnotationsOn(query); // 'query' match(input, DRL6Lexer.ID, DroolsSoftKeywords.QUERY, null, DroolsEditorType.KEYWORD); if (state.failed) return null; if (helper.validateIdentifierKey(DroolsSoftKeywords.WHEN) || helper.validateIdentifierKey(DroolsSoftKeywords.THEN) || helper.validateIdentifierKey(DroolsSoftKeywords.END)) { failMissingTokenException(); return null; // in case it is backtracking } String name = stringId(); if (state.backtracking == 0) query.name(name); if (state.failed) return null; if (state.backtracking == 0) { helper.emit(Location.LOCATION_RULE_HEADER); } if (speculateParameters(true)) { // parameters parameters(query, true); if (state.failed) return null; if (state.backtracking == 0) { helper.emit(Location.LOCATION_LHS_BEGIN_OF_CONDITION); } } else if (speculateParameters(false)) { // parameters parameters(query, false); if (state.failed) return null; if (state.backtracking == 0) { helper.emit(Location.LOCATION_LHS_BEGIN_OF_CONDITION); } } if (state.backtracking == 0 && input.LA(1) != DRL6Lexer.EOF) { helper.emit(Location.LOCATION_LHS_BEGIN_OF_CONDITION); } if (input.LA(1) != DRL6Lexer.EOF) { lhsExpression(query != null ? query.lhs() : null); } match(input, DRL6Lexer.ID, DroolsSoftKeywords.END, null, DroolsEditorType.KEYWORD); if (state.failed) return null; helper.emit(Location.LOCATION_RHS); } catch (RecognitionException re) { reportError(re); } finally { helper.end(QueryDescrBuilder.class, query); } return (query != null) ? query.getDescr() : null; } }
public class class_name { public RuleDescr query(PackageDescrBuilder pkg) throws RecognitionException { QueryDescrBuilder query = null; try { query = helper.start(pkg, QueryDescrBuilder.class, null); setAnnotationsOn(query); // 'query' match(input, DRL6Lexer.ID, DroolsSoftKeywords.QUERY, null, DroolsEditorType.KEYWORD); if (state.failed) return null; if (helper.validateIdentifierKey(DroolsSoftKeywords.WHEN) || helper.validateIdentifierKey(DroolsSoftKeywords.THEN) || helper.validateIdentifierKey(DroolsSoftKeywords.END)) { failMissingTokenException(); // depends on control dependency: [if], data = [none] return null; // in case it is backtracking // depends on control dependency: [if], data = [none] } String name = stringId(); if (state.backtracking == 0) query.name(name); if (state.failed) return null; if (state.backtracking == 0) { helper.emit(Location.LOCATION_RULE_HEADER); // depends on control dependency: [if], data = [none] } if (speculateParameters(true)) { // parameters parameters(query, true); // depends on control dependency: [if], data = [none] if (state.failed) return null; if (state.backtracking == 0) { helper.emit(Location.LOCATION_LHS_BEGIN_OF_CONDITION); // depends on control dependency: [if], data = [none] } } else if (speculateParameters(false)) { // parameters parameters(query, false); // depends on control dependency: [if], data = [none] if (state.failed) return null; if (state.backtracking == 0) { helper.emit(Location.LOCATION_LHS_BEGIN_OF_CONDITION); // depends on control dependency: [if], data = [none] } } if (state.backtracking == 0 && input.LA(1) != DRL6Lexer.EOF) { helper.emit(Location.LOCATION_LHS_BEGIN_OF_CONDITION); // depends on control dependency: [if], data = [none] } if (input.LA(1) != DRL6Lexer.EOF) { lhsExpression(query != null ? query.lhs() : null); // depends on control dependency: [if], data = [none] } match(input, DRL6Lexer.ID, DroolsSoftKeywords.END, null, DroolsEditorType.KEYWORD); if (state.failed) return null; helper.emit(Location.LOCATION_RHS); } catch (RecognitionException re) { reportError(re); } finally { helper.end(QueryDescrBuilder.class, query); } return (query != null) ? query.getDescr() : null; } }
public class class_name { public static ByteBuffer[] split(ByteBuffer byteBuffer, AbstractType<?> type) { if (type instanceof CompositeType) { return ((CompositeType) type).split(byteBuffer); } else { return new ByteBuffer[]{byteBuffer}; } } }
public class class_name { public static ByteBuffer[] split(ByteBuffer byteBuffer, AbstractType<?> type) { if (type instanceof CompositeType) { return ((CompositeType) type).split(byteBuffer); // depends on control dependency: [if], data = [none] } else { return new ByteBuffer[]{byteBuffer}; // depends on control dependency: [if], data = [none] } } }
public class class_name { private static MavenProject toBuild(MavenProject project, BomConfig config) { File outputDir = new File(project.getBuild().getOutputDirectory()); File bomDir = new File(outputDir, config.getArtifactId()); File generatedBom = new File(bomDir, BOM_NAME); MavenProject toBuild = project.clone(); //we want to avoid recursive "generate-bom". toBuild.setExecutionRoot(false); toBuild.setFile(generatedBom); toBuild.getModel().setPomFile(generatedBom); toBuild.setModelVersion(project.getModelVersion()); toBuild.setArtifact(new DefaultArtifact(project.getGroupId(), config.getArtifactId(), project.getVersion(), project.getArtifact().getScope(), project.getArtifact().getType(), project.getArtifact().getClassifier(), project.getArtifact().getArtifactHandler())); toBuild.setParent(project.getParent()); toBuild.getModel().setParent(project.getModel().getParent()); toBuild.setGroupId(project.getGroupId()); toBuild.setArtifactId(config.getArtifactId()); toBuild.setVersion(project.getVersion()); toBuild.setPackaging("pom"); toBuild.setName(config.getName()); toBuild.setDescription(config.getDescription()); toBuild.setUrl(project.getUrl()); toBuild.setLicenses(project.getLicenses()); toBuild.setScm(project.getScm()); toBuild.setDevelopers(project.getDevelopers()); toBuild.setDistributionManagement(project.getDistributionManagement()); toBuild.getModel().setProfiles(project.getModel().getProfiles()); //We want to avoid having the generated stuff wiped. toBuild.getProperties().put("clean.skip", "true"); toBuild.getModel().getBuild().setDirectory(bomDir.getAbsolutePath()); toBuild.getModel().getBuild().setOutputDirectory(new File(bomDir, "target").getAbsolutePath()); for (String key : config.getProperties().stringPropertyNames()) { toBuild.getProperties().put(key, config.getProperties().getProperty(key)); } return toBuild; } }
public class class_name { private static MavenProject toBuild(MavenProject project, BomConfig config) { File outputDir = new File(project.getBuild().getOutputDirectory()); File bomDir = new File(outputDir, config.getArtifactId()); File generatedBom = new File(bomDir, BOM_NAME); MavenProject toBuild = project.clone(); //we want to avoid recursive "generate-bom". toBuild.setExecutionRoot(false); toBuild.setFile(generatedBom); toBuild.getModel().setPomFile(generatedBom); toBuild.setModelVersion(project.getModelVersion()); toBuild.setArtifact(new DefaultArtifact(project.getGroupId(), config.getArtifactId(), project.getVersion(), project.getArtifact().getScope(), project.getArtifact().getType(), project.getArtifact().getClassifier(), project.getArtifact().getArtifactHandler())); toBuild.setParent(project.getParent()); toBuild.getModel().setParent(project.getModel().getParent()); toBuild.setGroupId(project.getGroupId()); toBuild.setArtifactId(config.getArtifactId()); toBuild.setVersion(project.getVersion()); toBuild.setPackaging("pom"); toBuild.setName(config.getName()); toBuild.setDescription(config.getDescription()); toBuild.setUrl(project.getUrl()); toBuild.setLicenses(project.getLicenses()); toBuild.setScm(project.getScm()); toBuild.setDevelopers(project.getDevelopers()); toBuild.setDistributionManagement(project.getDistributionManagement()); toBuild.getModel().setProfiles(project.getModel().getProfiles()); //We want to avoid having the generated stuff wiped. toBuild.getProperties().put("clean.skip", "true"); toBuild.getModel().getBuild().setDirectory(bomDir.getAbsolutePath()); toBuild.getModel().getBuild().setOutputDirectory(new File(bomDir, "target").getAbsolutePath()); for (String key : config.getProperties().stringPropertyNames()) { toBuild.getProperties().put(key, config.getProperties().getProperty(key)); // depends on control dependency: [for], data = [key] } return toBuild; } }
public class class_name { @Provides @Singleton Map<String, HealthDependency> provideHealthDependencyMap( Set<HealthDependency> healthDependencySet) { Map<String, HealthDependency> result = Maps.newHashMap(); for (HealthDependency dependency : healthDependencySet) { if (result.containsKey(dependency.getName())) { throw new IllegalStateException( "Dependency name " + dependency.getName() + " is used by both " + dependency.getName() + " and " + result.get(dependency.getName())); } result.put(dependency.getName(), dependency); } return ImmutableMap.copyOf(result); } }
public class class_name { @Provides @Singleton Map<String, HealthDependency> provideHealthDependencyMap( Set<HealthDependency> healthDependencySet) { Map<String, HealthDependency> result = Maps.newHashMap(); for (HealthDependency dependency : healthDependencySet) { if (result.containsKey(dependency.getName())) { throw new IllegalStateException( "Dependency name " + dependency.getName() + " is used by both " + dependency.getName() + " and " + result.get(dependency.getName())); } result.put(dependency.getName(), dependency); // depends on control dependency: [for], data = [dependency] } return ImmutableMap.copyOf(result); } }
public class class_name { @Override public List<CounterSample> getCounterSamples(String namePattern) { List<CounterSample> counterSamples = new ArrayList<>(); for (Simon simon : manager.getSimons(SimonPattern.createForCounter(namePattern))) { counterSamples.add(sampleCounter(simon)); } return counterSamples; } }
public class class_name { @Override public List<CounterSample> getCounterSamples(String namePattern) { List<CounterSample> counterSamples = new ArrayList<>(); for (Simon simon : manager.getSimons(SimonPattern.createForCounter(namePattern))) { counterSamples.add(sampleCounter(simon)); // depends on control dependency: [for], data = [simon] } return counterSamples; } }
public class class_name { public MatchResult doWork(List<Observation> gpxList) { // filter the entries: List<Observation> filteredGPXEntries = filterGPXEntries(gpxList); // now find each of the entries in the graph: List<Collection<QueryResult>> queriesPerEntry = lookupGPXEntries(filteredGPXEntries, DefaultEdgeFilter.allEdges(weighting.getFlagEncoder())); // Add virtual nodes and edges to the graph so that candidates on edges can be represented // by virtual nodes. QueryGraph queryGraph = new QueryGraph(routingGraph).setUseEdgeExplorerCache(true); List<QueryResult> allQueryResults = new ArrayList<>(); for (Collection<QueryResult> qrs : queriesPerEntry) { allQueryResults.addAll(qrs); } queryGraph.lookup(allQueryResults); // Different QueryResults can have the same tower node as their closest node. // Hence, we now dedupe the query results of each GPX entry by their closest node (#91). // This must be done after calling queryGraph.lookup() since this replaces some of the // QueryResult nodes with virtual nodes. Virtual nodes are not deduped since there is at // most one QueryResult per edge and virtual nodes are inserted into the middle of an edge. // Reducing the number of QueryResults improves performance since less shortest/fastest // routes need to be computed. queriesPerEntry = deduplicateQueryResultsByClosestNode(queriesPerEntry); logger.debug("================= Query results ================="); int i = 1; for (Collection<QueryResult> entries : queriesPerEntry) { logger.debug("Query results for GPX entry {}", i++); for (QueryResult qr : entries) { logger.debug("Node id: {}, virtual: {}, snapped on: {}, pos: {},{}, " + "query distance: {}", qr.getClosestNode(), isVirtualNode(qr.getClosestNode()), qr.getSnappedPosition(), qr.getSnappedPoint().getLat(), qr.getSnappedPoint().getLon(), qr.getQueryDistance()); } } // Creates candidates from the QueryResults of all GPX entries (a candidate is basically a // QueryResult + direction). List<TimeStep<State, Observation, Path>> timeSteps = createTimeSteps(filteredGPXEntries, queriesPerEntry, queryGraph); logger.debug("=============== Time steps ==============="); i = 1; for (TimeStep<State, Observation, Path> ts : timeSteps) { logger.debug("Candidates for time step {}", i++); for (State candidate : ts.candidates) { logger.debug(candidate.toString()); } } // Compute the most likely sequence of map matching candidates: List<SequenceState<State, Observation, Path>> seq = computeViterbiSequence(timeSteps, gpxList.size(), queryGraph); logger.debug("=============== Viterbi results =============== "); i = 1; for (SequenceState<State, Observation, Path> ss : seq) { logger.debug("{}: {}, path: {}", i, ss.state, ss.transitionDescriptor != null ? ss.transitionDescriptor.calcEdges() : null); i++; } final EdgeExplorer explorer = queryGraph.createEdgeExplorer(DefaultEdgeFilter.allEdges(weighting.getFlagEncoder())); final Map<String, EdgeIteratorState> virtualEdgesMap = createVirtualEdgesMap(queriesPerEntry, explorer); MatchResult matchResult = computeMatchResult(seq, virtualEdgesMap, gpxList, queryGraph); logger.debug("=============== Matched real edges =============== "); i = 1; for (EdgeMatch em : matchResult.getEdgeMatches()) { logger.debug("{}: {}", i, em.getEdgeState()); i++; } return matchResult; } }
public class class_name { public MatchResult doWork(List<Observation> gpxList) { // filter the entries: List<Observation> filteredGPXEntries = filterGPXEntries(gpxList); // now find each of the entries in the graph: List<Collection<QueryResult>> queriesPerEntry = lookupGPXEntries(filteredGPXEntries, DefaultEdgeFilter.allEdges(weighting.getFlagEncoder())); // Add virtual nodes and edges to the graph so that candidates on edges can be represented // by virtual nodes. QueryGraph queryGraph = new QueryGraph(routingGraph).setUseEdgeExplorerCache(true); List<QueryResult> allQueryResults = new ArrayList<>(); for (Collection<QueryResult> qrs : queriesPerEntry) { allQueryResults.addAll(qrs); // depends on control dependency: [for], data = [qrs] } queryGraph.lookup(allQueryResults); // Different QueryResults can have the same tower node as their closest node. // Hence, we now dedupe the query results of each GPX entry by their closest node (#91). // This must be done after calling queryGraph.lookup() since this replaces some of the // QueryResult nodes with virtual nodes. Virtual nodes are not deduped since there is at // most one QueryResult per edge and virtual nodes are inserted into the middle of an edge. // Reducing the number of QueryResults improves performance since less shortest/fastest // routes need to be computed. queriesPerEntry = deduplicateQueryResultsByClosestNode(queriesPerEntry); logger.debug("================= Query results ================="); int i = 1; for (Collection<QueryResult> entries : queriesPerEntry) { logger.debug("Query results for GPX entry {}", i++); // depends on control dependency: [for], data = [none] for (QueryResult qr : entries) { logger.debug("Node id: {}, virtual: {}, snapped on: {}, pos: {},{}, " + "query distance: {}", qr.getClosestNode(), isVirtualNode(qr.getClosestNode()), qr.getSnappedPosition(), qr.getSnappedPoint().getLat(), qr.getSnappedPoint().getLon(), qr.getQueryDistance()); // depends on control dependency: [for], data = [none] } } // Creates candidates from the QueryResults of all GPX entries (a candidate is basically a // QueryResult + direction). List<TimeStep<State, Observation, Path>> timeSteps = createTimeSteps(filteredGPXEntries, queriesPerEntry, queryGraph); logger.debug("=============== Time steps ==============="); i = 1; for (TimeStep<State, Observation, Path> ts : timeSteps) { logger.debug("Candidates for time step {}", i++); for (State candidate : ts.candidates) { logger.debug(candidate.toString()); } } // Compute the most likely sequence of map matching candidates: List<SequenceState<State, Observation, Path>> seq = computeViterbiSequence(timeSteps, gpxList.size(), queryGraph); logger.debug("=============== Viterbi results =============== "); i = 1; for (SequenceState<State, Observation, Path> ss : seq) { logger.debug("{}: {}, path: {}", i, ss.state, ss.transitionDescriptor != null ? ss.transitionDescriptor.calcEdges() : null); i++; } final EdgeExplorer explorer = queryGraph.createEdgeExplorer(DefaultEdgeFilter.allEdges(weighting.getFlagEncoder())); final Map<String, EdgeIteratorState> virtualEdgesMap = createVirtualEdgesMap(queriesPerEntry, explorer); MatchResult matchResult = computeMatchResult(seq, virtualEdgesMap, gpxList, queryGraph); logger.debug("=============== Matched real edges =============== "); i = 1; for (EdgeMatch em : matchResult.getEdgeMatches()) { logger.debug("{}: {}", i, em.getEdgeState()); i++; } return matchResult; } }
public class class_name { public void add(TimeSeries other) { TreeMap<Long, Integer> otherSeries = other.getSeries(); for (Map.Entry<Long, Integer> event : otherSeries.entrySet()) { record(event.getKey() + other.getWidthNano() / 2, event.getValue()); } } }
public class class_name { public void add(TimeSeries other) { TreeMap<Long, Integer> otherSeries = other.getSeries(); for (Map.Entry<Long, Integer> event : otherSeries.entrySet()) { record(event.getKey() + other.getWidthNano() / 2, event.getValue()); // depends on control dependency: [for], data = [event] } } }
public class class_name { public Object get(final Object key) { if (key == null) return null; if (!cacheLineTable.containsKey(key)) return null; CacheLine line = (CacheLine) cacheLineTable.get(key); if (hasExpired(line)) { removeObject(key); line = null; } if (line == null) { missCount++; return null; } hitCount++; // double hitPercent = 100*(double)hitCount/(hitCount + missCount); // Debug.logVerbose("[JdonFramework]cache hit percent: " + // percentFormat.format(hitPercent)+"%", module); if (maxSize > 0) { keyLRUList.moveFirst(key); } return line.getValue(); } }
public class class_name { public Object get(final Object key) { if (key == null) return null; if (!cacheLineTable.containsKey(key)) return null; CacheLine line = (CacheLine) cacheLineTable.get(key); if (hasExpired(line)) { removeObject(key); // depends on control dependency: [if], data = [none] line = null; // depends on control dependency: [if], data = [none] } if (line == null) { missCount++; // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } hitCount++; // double hitPercent = 100*(double)hitCount/(hitCount + missCount); // Debug.logVerbose("[JdonFramework]cache hit percent: " + // percentFormat.format(hitPercent)+"%", module); if (maxSize > 0) { keyLRUList.moveFirst(key); // depends on control dependency: [if], data = [none] } return line.getValue(); } }
public class class_name { public TaskTable add(String id, CronPattern pattern, Task task) { final Lock writeLock = lock.writeLock(); try { writeLock.lock(); if (ids.contains(id)) { throw new CronException("Id [{}] has been existed!", id); } ids.add(id); patterns.add(pattern); tasks.add(task); size++; } finally { writeLock.unlock(); } return this; } }
public class class_name { public TaskTable add(String id, CronPattern pattern, Task task) { final Lock writeLock = lock.writeLock(); try { writeLock.lock(); // depends on control dependency: [try], data = [none] if (ids.contains(id)) { throw new CronException("Id [{}] has been existed!", id); } ids.add(id); // depends on control dependency: [try], data = [none] patterns.add(pattern); // depends on control dependency: [try], data = [none] tasks.add(task); // depends on control dependency: [try], data = [none] size++; // depends on control dependency: [try], data = [none] } finally { writeLock.unlock(); } return this; } }
public class class_name { @Override public int getPositionForSection(int sectionIndex) { if (mSectionList.size() == 0) { for (Integer key : mSections.keySet()) { mSectionList.add(key); } } return sectionIndex < mSectionList.size() ? mSectionList.get(sectionIndex) : getCount(); } }
public class class_name { @Override public int getPositionForSection(int sectionIndex) { if (mSectionList.size() == 0) { for (Integer key : mSections.keySet()) { mSectionList.add(key); // depends on control dependency: [for], data = [key] } } return sectionIndex < mSectionList.size() ? mSectionList.get(sectionIndex) : getCount(); } }
public class class_name { public static Execution newInstance(Specification specification, SystemUnderTest systemUnderTest, XmlReport xmlReport) { if(xmlReport.getGlobalException() != null) { return error(specification, systemUnderTest, null, xmlReport.getGlobalException()); } Execution execution = new Execution(); execution.setExecutionDate(new Timestamp(System.currentTimeMillis())); execution.setSpecification(specification); execution.setSystemUnderTest(systemUnderTest); execution.setFailures( xmlReport.getFailure(0) ); execution.setErrors( xmlReport.getError(0) ); execution.setSuccess( xmlReport.getSuccess(0) ); execution.setIgnored( xmlReport.getIgnored(0) ); String results = xmlReport.getResults(0); if(results != null) { execution.setResults(results); } if (xmlReport.getSections(0) != null) { StringBuilder sections = new StringBuilder(); int index = 0; while (xmlReport.getSections(index) != null) { if (index > 0) sections.append(','); sections.append(xmlReport.getSections(index)); index++; } execution.setSections(sections.toString()); } return execution; } }
public class class_name { public static Execution newInstance(Specification specification, SystemUnderTest systemUnderTest, XmlReport xmlReport) { if(xmlReport.getGlobalException() != null) { return error(specification, systemUnderTest, null, xmlReport.getGlobalException()); // depends on control dependency: [if], data = [none] } Execution execution = new Execution(); execution.setExecutionDate(new Timestamp(System.currentTimeMillis())); execution.setSpecification(specification); execution.setSystemUnderTest(systemUnderTest); execution.setFailures( xmlReport.getFailure(0) ); execution.setErrors( xmlReport.getError(0) ); execution.setSuccess( xmlReport.getSuccess(0) ); execution.setIgnored( xmlReport.getIgnored(0) ); String results = xmlReport.getResults(0); if(results != null) { execution.setResults(results); // depends on control dependency: [if], data = [(results] } if (xmlReport.getSections(0) != null) { StringBuilder sections = new StringBuilder(); int index = 0; while (xmlReport.getSections(index) != null) { if (index > 0) sections.append(','); sections.append(xmlReport.getSections(index)); // depends on control dependency: [while], data = [(xmlReport.getSections(index)] index++; // depends on control dependency: [while], data = [none] } execution.setSections(sections.toString()); // depends on control dependency: [if], data = [none] } return execution; } }
public class class_name { public static JSONObject getRepositoryDef(final String repositoryName) { if (StringUtils.isBlank(repositoryName)) { return null; } if (null == repositoriesDescription) { return null; } final JSONArray repositories = repositoriesDescription.optJSONArray("repositories"); for (int i = 0; i < repositories.length(); i++) { final JSONObject repository = repositories.optJSONObject(i); if (repositoryName.equals(repository.optString("name"))) { return repository; } } throw new RuntimeException("Not found the repository [name=" + repositoryName + "] definition, please define it in repositories.json"); } }
public class class_name { public static JSONObject getRepositoryDef(final String repositoryName) { if (StringUtils.isBlank(repositoryName)) { return null; // depends on control dependency: [if], data = [none] } if (null == repositoriesDescription) { return null; // depends on control dependency: [if], data = [none] } final JSONArray repositories = repositoriesDescription.optJSONArray("repositories"); for (int i = 0; i < repositories.length(); i++) { final JSONObject repository = repositories.optJSONObject(i); if (repositoryName.equals(repository.optString("name"))) { return repository; // depends on control dependency: [if], data = [none] } } throw new RuntimeException("Not found the repository [name=" + repositoryName + "] definition, please define it in repositories.json"); } }
public class class_name { public void selectParentFrame() { String action = "Switching to parent frame"; String expected = "Parent frame is selected"; try { driver.switchTo().parentFrame(); } catch (Exception e) { reporter.fail(action, expected, "Parent frame was not selected. " + e.getMessage()); log.warn(e); return; } reporter.pass(action, expected, expected); } }
public class class_name { public void selectParentFrame() { String action = "Switching to parent frame"; String expected = "Parent frame is selected"; try { driver.switchTo().parentFrame(); // depends on control dependency: [try], data = [none] } catch (Exception e) { reporter.fail(action, expected, "Parent frame was not selected. " + e.getMessage()); log.warn(e); return; } // depends on control dependency: [catch], data = [none] reporter.pass(action, expected, expected); } }
public class class_name { @SuppressWarnings("deprecation") private void addRunningTaskToTIPUnprotected( TaskInProgress tip, TaskAttemptID id, String taskTracker, String hostName, boolean isScheduled) { // Make an entry in the tip if the attempt is not scheduled i.e externally // added if (!isScheduled) { tip.addRunningTask(id, taskTracker); } // keeping the earlier ordering intact String name; String splits = ""; Enum<Counter> counter = null; if (tip.isJobSetupTask()) { launchedSetup = true; name = Values.SETUP.name(); } else if (tip.isJobCleanupTask()) { launchedCleanup = true; name = Values.CLEANUP.name(); } else if (tip.isMapTask()) { ++runningMapTasks; name = Values.MAP.name(); counter = Counter.TOTAL_LAUNCHED_MAPS; splits = tip.getSplitNodes(); if (tip.getActiveTasks().size() > 1) { speculativeMapTasks++; jobStats.incNumSpeculativeMaps(); } jobStats.incNumMapTasksLaunched(); } else { ++runningReduceTasks; name = Values.REDUCE.name(); counter = Counter.TOTAL_LAUNCHED_REDUCES; if (tip.getActiveTasks().size() > 1) { speculativeReduceTasks++; jobStats.incNumSpeculativeReduces(); } jobStats.incNumReduceTasksLaunched(); } // Note that the logs are for the scheduled tasks only. Tasks that join on // restart has already their logs in place. if (tip.isFirstAttempt(id)) { jobHistory.logTaskStarted(tip.getTIPId(), name, tip.getExecStartTime(), splits); } if (!tip.isJobSetupTask() && !tip.isJobCleanupTask()) { jobCounters.incrCounter(counter, 1); } if (tip.isMapTask() && !tip.isJobSetupTask() && !tip.isJobCleanupTask()) { localityStats.record(tip, hostName, -1); } } }
public class class_name { @SuppressWarnings("deprecation") private void addRunningTaskToTIPUnprotected( TaskInProgress tip, TaskAttemptID id, String taskTracker, String hostName, boolean isScheduled) { // Make an entry in the tip if the attempt is not scheduled i.e externally // added if (!isScheduled) { tip.addRunningTask(id, taskTracker); // depends on control dependency: [if], data = [none] } // keeping the earlier ordering intact String name; String splits = ""; Enum<Counter> counter = null; if (tip.isJobSetupTask()) { launchedSetup = true; // depends on control dependency: [if], data = [none] name = Values.SETUP.name(); // depends on control dependency: [if], data = [none] } else if (tip.isJobCleanupTask()) { launchedCleanup = true; // depends on control dependency: [if], data = [none] name = Values.CLEANUP.name(); // depends on control dependency: [if], data = [none] } else if (tip.isMapTask()) { ++runningMapTasks; // depends on control dependency: [if], data = [none] name = Values.MAP.name(); // depends on control dependency: [if], data = [none] counter = Counter.TOTAL_LAUNCHED_MAPS; // depends on control dependency: [if], data = [none] splits = tip.getSplitNodes(); // depends on control dependency: [if], data = [none] if (tip.getActiveTasks().size() > 1) { speculativeMapTasks++; // depends on control dependency: [if], data = [none] jobStats.incNumSpeculativeMaps(); // depends on control dependency: [if], data = [none] } jobStats.incNumMapTasksLaunched(); // depends on control dependency: [if], data = [none] } else { ++runningReduceTasks; // depends on control dependency: [if], data = [none] name = Values.REDUCE.name(); // depends on control dependency: [if], data = [none] counter = Counter.TOTAL_LAUNCHED_REDUCES; // depends on control dependency: [if], data = [none] if (tip.getActiveTasks().size() > 1) { speculativeReduceTasks++; // depends on control dependency: [if], data = [none] jobStats.incNumSpeculativeReduces(); // depends on control dependency: [if], data = [none] } jobStats.incNumReduceTasksLaunched(); // depends on control dependency: [if], data = [none] } // Note that the logs are for the scheduled tasks only. Tasks that join on // restart has already their logs in place. if (tip.isFirstAttempt(id)) { jobHistory.logTaskStarted(tip.getTIPId(), name, tip.getExecStartTime(), splits); // depends on control dependency: [if], data = [none] } if (!tip.isJobSetupTask() && !tip.isJobCleanupTask()) { jobCounters.incrCounter(counter, 1); // depends on control dependency: [if], data = [none] } if (tip.isMapTask() && !tip.isJobSetupTask() && !tip.isJobCleanupTask()) { localityStats.record(tip, hostName, -1); // depends on control dependency: [if], data = [none] } } }
public class class_name { public boolean goTo(MonthAdapter.CalendarDay day, boolean animate, boolean setSelected, boolean forceScroll) { // Set the selected day if (setSelected) { mSelectedDay.set(day); } mTempDay.set(day); int minMonth = mController.getStartDate().get(Calendar.MONTH); final int position = (day.year - mController.getMinYear()) * MonthAdapter.MONTHS_IN_YEAR + day.month - minMonth; View child; int i = 0; int top = 0; // Find a child that's completely in the view do { child = getChildAt(i++); if (child == null) { break; } top = child.getTop(); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "child at " + (i - 1) + " has top " + top); } } while (top < 0); // Compute the first and last position visible int selectedPosition = child != null ? getChildAdapterPosition(child) : 0; if (setSelected) { mAdapter.setSelectedDay(mSelectedDay); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "GoTo position " + position); } // Check if the selected day is now outside of our visible range // and if so scroll to the month that contains it if (position != selectedPosition || forceScroll) { setMonthDisplayed(mTempDay); mPreviousScrollState = RecyclerView.SCROLL_STATE_DRAGGING; if (animate) { smoothScrollToPosition(position); if (pageListener != null) pageListener.onPageChanged(position); return true; } else { postSetSelection(position); } } else if (setSelected) { setMonthDisplayed(mSelectedDay); } return false; } }
public class class_name { public boolean goTo(MonthAdapter.CalendarDay day, boolean animate, boolean setSelected, boolean forceScroll) { // Set the selected day if (setSelected) { mSelectedDay.set(day); // depends on control dependency: [if], data = [none] } mTempDay.set(day); int minMonth = mController.getStartDate().get(Calendar.MONTH); final int position = (day.year - mController.getMinYear()) * MonthAdapter.MONTHS_IN_YEAR + day.month - minMonth; View child; int i = 0; int top = 0; // Find a child that's completely in the view do { child = getChildAt(i++); if (child == null) { break; } top = child.getTop(); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "child at " + (i - 1) + " has top " + top); // depends on control dependency: [if], data = [none] } } while (top < 0); // Compute the first and last position visible int selectedPosition = child != null ? getChildAdapterPosition(child) : 0; if (setSelected) { mAdapter.setSelectedDay(mSelectedDay); // depends on control dependency: [if], data = [none] } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "GoTo position " + position); // depends on control dependency: [if], data = [none] } // Check if the selected day is now outside of our visible range // and if so scroll to the month that contains it if (position != selectedPosition || forceScroll) { setMonthDisplayed(mTempDay); // depends on control dependency: [if], data = [none] mPreviousScrollState = RecyclerView.SCROLL_STATE_DRAGGING; // depends on control dependency: [if], data = [none] if (animate) { smoothScrollToPosition(position); // depends on control dependency: [if], data = [none] if (pageListener != null) pageListener.onPageChanged(position); return true; // depends on control dependency: [if], data = [none] } else { postSetSelection(position); // depends on control dependency: [if], data = [none] } } else if (setSelected) { setMonthDisplayed(mSelectedDay); // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { public static String getCookieValue(Cookie[] cookies, String name) { for (int i = 0; (cookies != null) && (i < cookies.length); i++) { if (name.equalsIgnoreCase(cookies[i].getName())) { return cookies[i].getValue(); } } return null; } }
public class class_name { public static String getCookieValue(Cookie[] cookies, String name) { for (int i = 0; (cookies != null) && (i < cookies.length); i++) { if (name.equalsIgnoreCase(cookies[i].getName())) { return cookies[i].getValue(); // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { public static File newFile (File root, String... parts) { File path = root; for (String part : parts) { path = new File(path, part); } return path; } }
public class class_name { public static File newFile (File root, String... parts) { File path = root; for (String part : parts) { path = new File(path, part); // depends on control dependency: [for], data = [part] } return path; } }
public class class_name { private void setIsStepEnabled(int step, boolean isEnabled) { try { Object oRoadmapItem = m_xRMIndexCont.getByIndex(step - 1); XPropertySet xRMItemPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oRoadmapItem); xRMItemPSet.setPropertyValue("Enabled", new Boolean(isEnabled)); } catch (com.sun.star.uno.Exception e) { LOGGER.log(Level.SEVERE, "Error in setIsStepEnabled", e); throw new CogrooRuntimeException(e); } } }
public class class_name { private void setIsStepEnabled(int step, boolean isEnabled) { try { Object oRoadmapItem = m_xRMIndexCont.getByIndex(step - 1); XPropertySet xRMItemPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oRoadmapItem); xRMItemPSet.setPropertyValue("Enabled", new Boolean(isEnabled)); // depends on control dependency: [try], data = [none] } catch (com.sun.star.uno.Exception e) { LOGGER.log(Level.SEVERE, "Error in setIsStepEnabled", e); throw new CogrooRuntimeException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override protected void executeSQL(String sql, boolean trigger) { if (trigger) { connection.execSQL(sql); } else { database.execSQL(sql); } } }
public class class_name { @Override protected void executeSQL(String sql, boolean trigger) { if (trigger) { connection.execSQL(sql); // depends on control dependency: [if], data = [none] } else { database.execSQL(sql); // depends on control dependency: [if], data = [none] } } }
public class class_name { List<? extends E> list() { List<E> result = new ArrayList<E>(); while (hasNext()) { result.add(next()); } return result; } }
public class class_name { List<? extends E> list() { List<E> result = new ArrayList<E>(); while (hasNext()) { result.add(next()); // depends on control dependency: [while], data = [none] } return result; } }
public class class_name { protected static String formatApiVersion(String version) { if (StringUtils.isBlank(version)) { return VERSION; } else { final Matcher matcher = VERSION_PATTERN.matcher(version); if (matcher.matches()) { return String.format("%s.%s", matcher.group(1), matcher.group(2)); } else { return VERSION; } } } }
public class class_name { protected static String formatApiVersion(String version) { if (StringUtils.isBlank(version)) { return VERSION; // depends on control dependency: [if], data = [none] } else { final Matcher matcher = VERSION_PATTERN.matcher(version); if (matcher.matches()) { return String.format("%s.%s", matcher.group(1), matcher.group(2)); // depends on control dependency: [if], data = [none] } else { return VERSION; // depends on control dependency: [if], data = [none] } } } }
public class class_name { void handleStorageException(final TSDB tsdb, final IncomingDataPoint dp, final Exception e) { final StorageExceptionHandler handler = tsdb.getStorageExceptionHandler(); if (handler != null) { handler.handleError(dp, e); } } }
public class class_name { void handleStorageException(final TSDB tsdb, final IncomingDataPoint dp, final Exception e) { final StorageExceptionHandler handler = tsdb.getStorageExceptionHandler(); if (handler != null) { handler.handleError(dp, e); // depends on control dependency: [if], data = [none] } } }
public class class_name { public <T extends CSSProperty> T genericPropertyRaw(Class<T> type, Set<T> intersection, TermIdent term) { try { String name = term.getValue().replace("-", "_").toUpperCase(); T property = CSSProperty.Translator.valueOf(type, name); if (intersection != null && intersection.contains(property)) return property; return property; } catch (Exception e) { return null; } } }
public class class_name { public <T extends CSSProperty> T genericPropertyRaw(Class<T> type, Set<T> intersection, TermIdent term) { try { String name = term.getValue().replace("-", "_").toUpperCase(); T property = CSSProperty.Translator.valueOf(type, name); if (intersection != null && intersection.contains(property)) return property; return property; // depends on control dependency: [try], data = [none] } catch (Exception e) { return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public void removeByCPTaxCategoryId(long CPTaxCategoryId) { for (CommerceTaxFixedRate commerceTaxFixedRate : findByCPTaxCategoryId( CPTaxCategoryId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceTaxFixedRate); } } }
public class class_name { @Override public void removeByCPTaxCategoryId(long CPTaxCategoryId) { for (CommerceTaxFixedRate commerceTaxFixedRate : findByCPTaxCategoryId( CPTaxCategoryId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceTaxFixedRate); // depends on control dependency: [for], data = [commerceTaxFixedRate] } } }
public class class_name { private String registerTransactionListenerProcessor() throws InvalidArgumentException { logger.debug(format("Channel %s registerTransactionListenerProcessor starting", name)); // Transaction listener is internal Block listener for transactions return registerBlockListener(blockEvent -> { HFClient lclient = client; if (null == lclient || shutdown) { //can happen if were not quite shutdown return; } final String source = blockEvent.getPeer() != null ? blockEvent.getPeer().toString() : "not peer!"; logger.debug(format("is peer %b, is filtered: %b", blockEvent.getPeer() != null, blockEvent.isFiltered())); final Iterable<TransactionEvent> transactionEvents = blockEvent.getTransactionEvents(); if (transactionEvents == null || !transactionEvents.iterator().hasNext()) { // no transactions today we can assume it was a config or update block. if (isLaterBlock(blockEvent.getBlockNumber())) { ServiceDiscovery lserviceDiscovery = serviceDiscovery; if (null != lserviceDiscovery) { client.getExecutorService().execute(() -> lserviceDiscovery.fullNetworkDiscovery(true)); } } else { lclient.getExecutorService().execute(() -> { try { if (!shutdown) { loadCACertificates(true); } } catch (Exception e) { logger.warn(format("Channel %s failed to load certificates for an update", name), e); } }); } return; } if (txListeners.isEmpty() || shutdown) { return; } for (TransactionEvent transactionEvent : blockEvent.getTransactionEvents()) { logger.debug(format("Channel %s got event from %s for transaction %s in block number: %d", name, source, transactionEvent.getTransactionID(), blockEvent.getBlockNumber())); List<TL> txL = new ArrayList<>(txListeners.size() + 2); synchronized (txListeners) { LinkedList<TL> list = txListeners.get(transactionEvent.getTransactionID()); if (null != list) { txL.addAll(list); } } for (TL l : txL) { try { // only if we get events from each eventhub on the channel fire the transactions event. // if (getEventHubs().containsAll(l.eventReceived(transactionEvent.getEventHub()))) { if (shutdown) { break; } if (l.eventReceived(transactionEvent)) { l.fire(transactionEvent); } } catch (Throwable e) { logger.error(e); // Don't let one register stop rest. } } } }); } }
public class class_name { private String registerTransactionListenerProcessor() throws InvalidArgumentException { logger.debug(format("Channel %s registerTransactionListenerProcessor starting", name)); // Transaction listener is internal Block listener for transactions return registerBlockListener(blockEvent -> { HFClient lclient = client; if (null == lclient || shutdown) { //can happen if were not quite shutdown return; } final String source = blockEvent.getPeer() != null ? blockEvent.getPeer().toString() : "not peer!"; logger.debug(format("is peer %b, is filtered: %b", blockEvent.getPeer() != null, blockEvent.isFiltered())); final Iterable<TransactionEvent> transactionEvents = blockEvent.getTransactionEvents(); if (transactionEvents == null || !transactionEvents.iterator().hasNext()) { // no transactions today we can assume it was a config or update block. if (isLaterBlock(blockEvent.getBlockNumber())) { ServiceDiscovery lserviceDiscovery = serviceDiscovery; if (null != lserviceDiscovery) { client.getExecutorService().execute(() -> lserviceDiscovery.fullNetworkDiscovery(true)); // depends on control dependency: [if], data = [none] } } else { lclient.getExecutorService().execute(() -> { try { if (!shutdown) { loadCACertificates(true); // depends on control dependency: [if], data = [none] } } catch (Exception e) { logger.warn(format("Channel %s failed to load certificates for an update", name), e); } // depends on control dependency: [catch], data = [none] }); } return; } if (txListeners.isEmpty() || shutdown) { return; } for (TransactionEvent transactionEvent : blockEvent.getTransactionEvents()) { logger.debug(format("Channel %s got event from %s for transaction %s in block number: %d", name, source, transactionEvent.getTransactionID(), blockEvent.getBlockNumber())); List<TL> txL = new ArrayList<>(txListeners.size() + 2); synchronized (txListeners) { LinkedList<TL> list = txListeners.get(transactionEvent.getTransactionID()); if (null != list) { txL.addAll(list); } } for (TL l : txL) { try { // only if we get events from each eventhub on the channel fire the transactions event. // if (getEventHubs().containsAll(l.eventReceived(transactionEvent.getEventHub()))) { if (shutdown) { break; } if (l.eventReceived(transactionEvent)) { l.fire(transactionEvent); } } catch (Throwable e) { logger.error(e); // Don't let one register stop rest. } } } }); } }
public class class_name { public void propertyChange(PropertyChangeEvent event) { if (contains(event.getSource()) && "beanContext".equals(event.getPropertyName()) && event.getOldValue() == getBeanContextPeer()) { remove(event.getSource(), false); } } }
public class class_name { public void propertyChange(PropertyChangeEvent event) { if (contains(event.getSource()) && "beanContext".equals(event.getPropertyName()) && event.getOldValue() == getBeanContextPeer()) { remove(event.getSource(), false); // depends on control dependency: [if], data = [none] } } }
public class class_name { private boolean validateAppSignatureForPackage(Context context, String packageName) { PackageInfo packageInfo; try { packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES); } catch (NameNotFoundException e) { return false; } for (Signature signature : packageInfo.signatures) { if (signature.toCharsString().equals(FB_APP_SIGNATURE)) { return true; } } return false; } }
public class class_name { private boolean validateAppSignatureForPackage(Context context, String packageName) { PackageInfo packageInfo; try { packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES); // depends on control dependency: [try], data = [none] } catch (NameNotFoundException e) { return false; } // depends on control dependency: [catch], data = [none] for (Signature signature : packageInfo.signatures) { if (signature.toCharsString().equals(FB_APP_SIGNATURE)) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { public <K, V, T> ViewResult<K, V, T> queryView(Class<K> classOfK, Class<V> classOfV, Class<T> classOfT) { InputStream instream = null; try { Reader reader = new InputStreamReader(instream = queryForStream(), Charsets.UTF_8); JsonObject json = new JsonParser().parse(reader).getAsJsonObject(); ViewResult<K, V, T> vr = new ViewResult<K, V, T>(); vr.setTotalRows(getAsLong(json, "total_rows")); vr.setOffset(getAsInt(json, "offset")); vr.setUpdateSeq(getAsString(json, "update_seq")); JsonArray jsonArray = json.getAsJsonArray("rows"); for (JsonElement e : jsonArray) { ViewResult<K, V, T>.Rows row = vr.new Rows(); row.setId(JsonToObject(gson, e, "id", String.class)); if (classOfK != null) { row.setKey(JsonToObject(gson, e, "key", classOfK)); } if (classOfV != null) { row.setValue(JsonToObject(gson, e, "value", classOfV)); } if(Boolean.TRUE.equals(this.includeDocs)) { row.setDoc(JsonToObject(gson, e, "doc", classOfT)); } vr.getRows().add(row); } return vr; } finally { close(instream); } } }
public class class_name { public <K, V, T> ViewResult<K, V, T> queryView(Class<K> classOfK, Class<V> classOfV, Class<T> classOfT) { InputStream instream = null; try { Reader reader = new InputStreamReader(instream = queryForStream(), Charsets.UTF_8); JsonObject json = new JsonParser().parse(reader).getAsJsonObject(); ViewResult<K, V, T> vr = new ViewResult<K, V, T>(); vr.setTotalRows(getAsLong(json, "total_rows")); // depends on control dependency: [try], data = [none] vr.setOffset(getAsInt(json, "offset")); // depends on control dependency: [try], data = [none] vr.setUpdateSeq(getAsString(json, "update_seq")); // depends on control dependency: [try], data = [none] JsonArray jsonArray = json.getAsJsonArray("rows"); for (JsonElement e : jsonArray) { ViewResult<K, V, T>.Rows row = vr.new Rows(); row.setId(JsonToObject(gson, e, "id", String.class)); // depends on control dependency: [for], data = [e] if (classOfK != null) { row.setKey(JsonToObject(gson, e, "key", classOfK)); // depends on control dependency: [if], data = [none] } if (classOfV != null) { row.setValue(JsonToObject(gson, e, "value", classOfV)); // depends on control dependency: [if], data = [none] } if(Boolean.TRUE.equals(this.includeDocs)) { row.setDoc(JsonToObject(gson, e, "doc", classOfT)); // depends on control dependency: [if], data = [none] } vr.getRows().add(row); // depends on control dependency: [for], data = [e] } return vr; // depends on control dependency: [try], data = [none] } finally { close(instream); } } }
public class class_name { @SuppressWarnings("unchecked") @Deprecated protected static <T> Mono<T> onLastAssembly(Mono<T> source) { Function<Publisher, Publisher> hook = Hooks.onLastOperatorHook; if(hook == null) { return source; } return (Mono<T>)Objects.requireNonNull(hook.apply(source), "LastOperator hook returned null"); } }
public class class_name { @SuppressWarnings("unchecked") @Deprecated protected static <T> Mono<T> onLastAssembly(Mono<T> source) { Function<Publisher, Publisher> hook = Hooks.onLastOperatorHook; if(hook == null) { return source; // depends on control dependency: [if], data = [none] } return (Mono<T>)Objects.requireNonNull(hook.apply(source), "LastOperator hook returned null"); } }
public class class_name { public static <X,Y> Map<X,Y> zip(List<X> keys, List<Y> values) { if (keys.size() != values.size()) { throw new IllegalArgumentException("Lengths are not equal"); } Map<X,Y> map = new HashMap<>(keys.size()); for (int i=0; i<keys.size(); i++) { map.put(keys.get(i), values.get(i)); } return map; } }
public class class_name { public static <X,Y> Map<X,Y> zip(List<X> keys, List<Y> values) { if (keys.size() != values.size()) { throw new IllegalArgumentException("Lengths are not equal"); } Map<X,Y> map = new HashMap<>(keys.size()); for (int i=0; i<keys.size(); i++) { map.put(keys.get(i), values.get(i)); // depends on control dependency: [for], data = [i] } return map; } }
public class class_name { public InventoryDeletionSummary withSummaryItems(InventoryDeletionSummaryItem... summaryItems) { if (this.summaryItems == null) { setSummaryItems(new com.amazonaws.internal.SdkInternalList<InventoryDeletionSummaryItem>(summaryItems.length)); } for (InventoryDeletionSummaryItem ele : summaryItems) { this.summaryItems.add(ele); } return this; } }
public class class_name { public InventoryDeletionSummary withSummaryItems(InventoryDeletionSummaryItem... summaryItems) { if (this.summaryItems == null) { setSummaryItems(new com.amazonaws.internal.SdkInternalList<InventoryDeletionSummaryItem>(summaryItems.length)); // depends on control dependency: [if], data = [none] } for (InventoryDeletionSummaryItem ele : summaryItems) { this.summaryItems.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public static void removeInvocationStat(InvocationStatDimension statDimension) { InvocationStat invocationStat = ALL_STATS.remove(statDimension); if (invocationStat != null) { for (InvocationStatListener listener : LISTENERS) { listener.onRemoveInvocationStat(invocationStat); } } } }
public class class_name { public static void removeInvocationStat(InvocationStatDimension statDimension) { InvocationStat invocationStat = ALL_STATS.remove(statDimension); if (invocationStat != null) { for (InvocationStatListener listener : LISTENERS) { listener.onRemoveInvocationStat(invocationStat); // depends on control dependency: [for], data = [listener] } } } }
public class class_name { protected <T> T getConnection(ConnectionFuture<T> connectionFuture) { try { return connectionFuture.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw RedisConnectionException.create(connectionFuture.getRemoteAddress(), e); } catch (Exception e) { if (e instanceof ExecutionException) { throw RedisConnectionException.create(connectionFuture.getRemoteAddress(), e.getCause()); } throw RedisConnectionException.create(connectionFuture.getRemoteAddress(), e); } } }
public class class_name { protected <T> T getConnection(ConnectionFuture<T> connectionFuture) { try { return connectionFuture.get(); // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw RedisConnectionException.create(connectionFuture.getRemoteAddress(), e); } catch (Exception e) { // depends on control dependency: [catch], data = [none] if (e instanceof ExecutionException) { throw RedisConnectionException.create(connectionFuture.getRemoteAddress(), e.getCause()); } throw RedisConnectionException.create(connectionFuture.getRemoteAddress(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public TPredict[] classify(InstanceSet instances,LabelParser.Type type, int n) { TPredict[] res= new Predict[instances.size()]; for(int i=0;i<instances.size();i++){ res[i]= classify(instances.getInstance(i),type,n); } return res; } }
public class class_name { public TPredict[] classify(InstanceSet instances,LabelParser.Type type, int n) { TPredict[] res= new Predict[instances.size()]; for(int i=0;i<instances.size();i++){ res[i]= classify(instances.getInstance(i),type,n); // depends on control dependency: [for], data = [i] } return res; } }
public class class_name { public void marshall(AudioSelector audioSelector, ProtocolMarshaller protocolMarshaller) { if (audioSelector == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(audioSelector.getCustomLanguageCode(), CUSTOMLANGUAGECODE_BINDING); protocolMarshaller.marshall(audioSelector.getDefaultSelection(), DEFAULTSELECTION_BINDING); protocolMarshaller.marshall(audioSelector.getExternalAudioFileInput(), EXTERNALAUDIOFILEINPUT_BINDING); protocolMarshaller.marshall(audioSelector.getLanguageCode(), LANGUAGECODE_BINDING); protocolMarshaller.marshall(audioSelector.getOffset(), OFFSET_BINDING); protocolMarshaller.marshall(audioSelector.getPids(), PIDS_BINDING); protocolMarshaller.marshall(audioSelector.getProgramSelection(), PROGRAMSELECTION_BINDING); protocolMarshaller.marshall(audioSelector.getRemixSettings(), REMIXSETTINGS_BINDING); protocolMarshaller.marshall(audioSelector.getSelectorType(), SELECTORTYPE_BINDING); protocolMarshaller.marshall(audioSelector.getTracks(), TRACKS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(AudioSelector audioSelector, ProtocolMarshaller protocolMarshaller) { if (audioSelector == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(audioSelector.getCustomLanguageCode(), CUSTOMLANGUAGECODE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(audioSelector.getDefaultSelection(), DEFAULTSELECTION_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(audioSelector.getExternalAudioFileInput(), EXTERNALAUDIOFILEINPUT_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(audioSelector.getLanguageCode(), LANGUAGECODE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(audioSelector.getOffset(), OFFSET_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(audioSelector.getPids(), PIDS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(audioSelector.getProgramSelection(), PROGRAMSELECTION_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(audioSelector.getRemixSettings(), REMIXSETTINGS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(audioSelector.getSelectorType(), SELECTORTYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(audioSelector.getTracks(), TRACKS_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private static String[] appendEmbeddedNodes(String path, StringBuilder queryBuilder) { String[] columns = split( path ); for ( int i = 0; i < columns.length - 1; i++ ) { queryBuilder.append( " - [:" ); appendRelationshipType( queryBuilder, columns[i] ); queryBuilder.append( "] ->" ); if ( i < columns.length - 2 ) { queryBuilder.append( " (e" ); queryBuilder.append( i ); queryBuilder.append( ":" ); queryBuilder.append( EMBEDDED ); queryBuilder.append( ") MERGE (e" ); queryBuilder.append( i ); queryBuilder.append( ")" ); } } queryBuilder.append( " (e:" ); queryBuilder.append( EMBEDDED ); queryBuilder.append( ")" ); return columns; } }
public class class_name { private static String[] appendEmbeddedNodes(String path, StringBuilder queryBuilder) { String[] columns = split( path ); for ( int i = 0; i < columns.length - 1; i++ ) { queryBuilder.append( " - [:" ); // depends on control dependency: [for], data = [none] appendRelationshipType( queryBuilder, columns[i] ); // depends on control dependency: [for], data = [i] queryBuilder.append( "] ->" ); // depends on control dependency: [for], data = [none] if ( i < columns.length - 2 ) { queryBuilder.append( " (e" ); queryBuilder.append( i ); queryBuilder.append( ":" ); queryBuilder.append( EMBEDDED ); queryBuilder.append( ") MERGE (e" ); queryBuilder.append( i ); queryBuilder.append( ")" ); // depends on control dependency: [if], data = [none] } } queryBuilder.append( " (e:" ); queryBuilder.append( EMBEDDED ); queryBuilder.append( ")" ); return columns; } }
public class class_name { private StackTraceElement tryToCreateStackTraceElementInstanceIntern() { StackTraceElement lvStackTraceElement = null; try { Constructor<StackTraceElement> lvConstructor = StackTraceElement.class.getDeclaredConstructor(); AccessController.doPrivileged(new AccessiblePrivilegedAction(lvConstructor)); lvStackTraceElement = (StackTraceElement) lvConstructor.newInstance(); } catch (Exception e) { try { Constructor<?> lvConstructor = StackTraceElement.class.getDeclaredConstructors()[0]; AccessController.doPrivileged(new AccessiblePrivilegedAction(lvConstructor)); lvStackTraceElement = (StackTraceElement) lvConstructor.newInstance(new Object[] { getClassName(), getMethodName(), getFileName(), new Integer(getLineNumber()) }); } catch (Exception ex) { ex.printStackTrace(); } } return lvStackTraceElement; } }
public class class_name { private StackTraceElement tryToCreateStackTraceElementInstanceIntern() { StackTraceElement lvStackTraceElement = null; try { Constructor<StackTraceElement> lvConstructor = StackTraceElement.class.getDeclaredConstructor(); AccessController.doPrivileged(new AccessiblePrivilegedAction(lvConstructor)); // depends on control dependency: [try], data = [none] lvStackTraceElement = (StackTraceElement) lvConstructor.newInstance(); // depends on control dependency: [try], data = [none] } catch (Exception e) { try { Constructor<?> lvConstructor = StackTraceElement.class.getDeclaredConstructors()[0]; AccessController.doPrivileged(new AccessiblePrivilegedAction(lvConstructor)); // depends on control dependency: [try], data = [none] lvStackTraceElement = (StackTraceElement) lvConstructor.newInstance(new Object[] { getClassName(), getMethodName(), getFileName(), new Integer(getLineNumber()) }); // depends on control dependency: [try], data = [none] } catch (Exception ex) { ex.printStackTrace(); } // depends on control dependency: [catch], data = [none] } // depends on control dependency: [catch], data = [none] return lvStackTraceElement; } }
public class class_name { @CheckReturnValue public ChannelAction addPermissionOverride(IPermissionHolder target, long allow, long deny) { Checks.notNull(target, "Override Role"); Checks.notNegative(allow, "Granted permissions value"); Checks.notNegative(deny, "Denied permissions value"); Checks.check(allow <= Permission.ALL_PERMISSIONS, "Specified allow value may not be greater than a full permission set"); Checks.check(deny <= Permission.ALL_PERMISSIONS, "Specified deny value may not be greater than a full permission set"); Checks.check(target.getGuild().equals(guild), "Specified Role is not in the same Guild!"); if (target instanceof Role) { Role r = (Role) target; long id = r.getIdLong(); overrides.add(new PermOverrideData(PermOverrideData.ROLE_TYPE, id, allow, deny)); } else { Member m = (Member) target; long id = m.getUser().getIdLong(); overrides.add(new PermOverrideData(PermOverrideData.MEMBER_TYPE, id, allow, deny)); } return this; } }
public class class_name { @CheckReturnValue public ChannelAction addPermissionOverride(IPermissionHolder target, long allow, long deny) { Checks.notNull(target, "Override Role"); Checks.notNegative(allow, "Granted permissions value"); Checks.notNegative(deny, "Denied permissions value"); Checks.check(allow <= Permission.ALL_PERMISSIONS, "Specified allow value may not be greater than a full permission set"); Checks.check(deny <= Permission.ALL_PERMISSIONS, "Specified deny value may not be greater than a full permission set"); Checks.check(target.getGuild().equals(guild), "Specified Role is not in the same Guild!"); if (target instanceof Role) { Role r = (Role) target; long id = r.getIdLong(); overrides.add(new PermOverrideData(PermOverrideData.ROLE_TYPE, id, allow, deny)); // depends on control dependency: [if], data = [none] } else { Member m = (Member) target; long id = m.getUser().getIdLong(); overrides.add(new PermOverrideData(PermOverrideData.MEMBER_TYPE, id, allow, deny)); // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { public double calculateInitialTotalCost(final List<ServerHolder> serverHolders) { double cost = 0; for (ServerHolder server : serverHolders) { Iterable<DataSegment> segments = server.getServer().getLazyAllSegments(); for (DataSegment s : segments) { cost += computeJointSegmentsCost(s, segments); } } return cost; } }
public class class_name { public double calculateInitialTotalCost(final List<ServerHolder> serverHolders) { double cost = 0; for (ServerHolder server : serverHolders) { Iterable<DataSegment> segments = server.getServer().getLazyAllSegments(); for (DataSegment s : segments) { cost += computeJointSegmentsCost(s, segments); // depends on control dependency: [for], data = [s] } } return cost; } }
public class class_name { private List<CmsGalleryFolderEntry> getGalleriesForType( String entryPointUri, CmsGalleryType galleryType, List<String> subSitePaths) throws CmsException { List<CmsGalleryFolderEntry> galleries = new ArrayList<CmsGalleryFolderEntry>(); @SuppressWarnings("deprecation") List<CmsResource> galleryFolders = getCmsObject().readResources( entryPointUri, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED.addRequireType(galleryType.getTypeId())); for (CmsResource folder : galleryFolders) { try { if (!isInSubsite(subSitePaths, folder.getRootPath())) { galleries.add(readGalleryFolderEntry(folder, galleryType.getResourceType())); } } catch (CmsException ex) { log(ex.getLocalizedMessage(), ex); } } // create a tree structure Collections.sort(galleries, new Comparator<CmsGalleryFolderEntry>() { public int compare(CmsGalleryFolderEntry o1, CmsGalleryFolderEntry o2) { return o1.getSitePath().compareTo(o2.getSitePath()); } }); List<CmsGalleryFolderEntry> galleryTree = new ArrayList<CmsGalleryFolderEntry>(); for (int i = 0; i < galleries.size(); i++) { boolean isSubGallery = false; if (i > 0) { for (int j = i - 1; j >= 0; j--) { if (galleries.get(i).getSitePath().startsWith(galleries.get(j).getSitePath())) { galleries.get(j).addSubGallery(galleries.get(i)); isSubGallery = true; break; } } } if (!isSubGallery) { galleryTree.add(galleries.get(i)); } } return galleryTree; } }
public class class_name { private List<CmsGalleryFolderEntry> getGalleriesForType( String entryPointUri, CmsGalleryType galleryType, List<String> subSitePaths) throws CmsException { List<CmsGalleryFolderEntry> galleries = new ArrayList<CmsGalleryFolderEntry>(); @SuppressWarnings("deprecation") List<CmsResource> galleryFolders = getCmsObject().readResources( entryPointUri, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED.addRequireType(galleryType.getTypeId())); for (CmsResource folder : galleryFolders) { try { if (!isInSubsite(subSitePaths, folder.getRootPath())) { galleries.add(readGalleryFolderEntry(folder, galleryType.getResourceType())); // depends on control dependency: [if], data = [none] } } catch (CmsException ex) { log(ex.getLocalizedMessage(), ex); } // depends on control dependency: [catch], data = [none] } // create a tree structure Collections.sort(galleries, new Comparator<CmsGalleryFolderEntry>() { public int compare(CmsGalleryFolderEntry o1, CmsGalleryFolderEntry o2) { return o1.getSitePath().compareTo(o2.getSitePath()); } }); List<CmsGalleryFolderEntry> galleryTree = new ArrayList<CmsGalleryFolderEntry>(); for (int i = 0; i < galleries.size(); i++) { boolean isSubGallery = false; if (i > 0) { for (int j = i - 1; j >= 0; j--) { if (galleries.get(i).getSitePath().startsWith(galleries.get(j).getSitePath())) { galleries.get(j).addSubGallery(galleries.get(i)); isSubGallery = true; break; } } } if (!isSubGallery) { galleryTree.add(galleries.get(i)); } } return galleryTree; } }
public class class_name { public static String getServiceName(UUID uuid) { String result = null; String uuid16bit = getStandardizedUUIDComponent(uuid); if (uuid16bit != null) { result = SERVICE_UUIDS.get(uuid16bit); } return result; } }
public class class_name { public static String getServiceName(UUID uuid) { String result = null; String uuid16bit = getStandardizedUUIDComponent(uuid); if (uuid16bit != null) { result = SERVICE_UUIDS.get(uuid16bit); // depends on control dependency: [if], data = [(uuid16bit] } return result; } }
public class class_name { public List<KeyPath> resolveKeyPath(KeyPath keyPath) { if (compositionLayer == null) { Log.w(L.TAG, "Cannot resolve KeyPath. Composition is not set yet."); return Collections.emptyList(); } List<KeyPath> keyPaths = new ArrayList<>(); compositionLayer.resolveKeyPath(keyPath, 0, keyPaths, new KeyPath()); return keyPaths; } }
public class class_name { public List<KeyPath> resolveKeyPath(KeyPath keyPath) { if (compositionLayer == null) { Log.w(L.TAG, "Cannot resolve KeyPath. Composition is not set yet."); // depends on control dependency: [if], data = [none] return Collections.emptyList(); // depends on control dependency: [if], data = [none] } List<KeyPath> keyPaths = new ArrayList<>(); compositionLayer.resolveKeyPath(keyPath, 0, keyPaths, new KeyPath()); return keyPaths; } }
public class class_name { public long count(GeometryEnvelope envelope) { long count = 0; QueryBuilder<GeometryIndex, GeometryIndexKey> qb = queryBuilder(envelope); try { count = qb.countOf(); } catch (SQLException e) { throw new GeoPackageException( "Failed to query for Geometry Index count. GeoPackage: " + geoPackage.getName() + ", Table Name: " + tableName + ", Column Name: " + columnName, e); } return count; } }
public class class_name { public long count(GeometryEnvelope envelope) { long count = 0; QueryBuilder<GeometryIndex, GeometryIndexKey> qb = queryBuilder(envelope); try { count = qb.countOf(); // depends on control dependency: [try], data = [none] } catch (SQLException e) { throw new GeoPackageException( "Failed to query for Geometry Index count. GeoPackage: " + geoPackage.getName() + ", Table Name: " + tableName + ", Column Name: " + columnName, e); } // depends on control dependency: [catch], data = [none] return count; } }
public class class_name { public static byte[] decode(String string) { if (string.length() % 5 != 0) { return null; } ByteBuffer buf = ByteBuffer.allocate(string.length() * 4 / 5); int byteNbr = 0; int charNbr = 0; int stringLen = string.length(); long value = 0; while (charNbr < stringLen) { // Accumulate value in base 85 value = value * 85 + (decoder[string.charAt(charNbr++) - 32] & 0xff); if (charNbr % 5 == 0) { // Output value in base 256 int divisor = 256 * 256 * 256; while (divisor != 0) { buf.put(byteNbr++, (byte) ((value / divisor) % 256)); divisor /= 256; } value = 0; } } assert (byteNbr == string.length() * 4 / 5); return buf.array(); } }
public class class_name { public static byte[] decode(String string) { if (string.length() % 5 != 0) { return null; // depends on control dependency: [if], data = [none] } ByteBuffer buf = ByteBuffer.allocate(string.length() * 4 / 5); int byteNbr = 0; int charNbr = 0; int stringLen = string.length(); long value = 0; while (charNbr < stringLen) { // Accumulate value in base 85 value = value * 85 + (decoder[string.charAt(charNbr++) - 32] & 0xff); // depends on control dependency: [while], data = [(charNbr] if (charNbr % 5 == 0) { // Output value in base 256 int divisor = 256 * 256 * 256; while (divisor != 0) { buf.put(byteNbr++, (byte) ((value / divisor) % 256)); // depends on control dependency: [while], data = [none] divisor /= 256; // depends on control dependency: [while], data = [none] } value = 0; // depends on control dependency: [if], data = [none] } } assert (byteNbr == string.length() * 4 / 5); return buf.array(); } }
public class class_name { static String getRelativeNameFrom(String itemFullName, String groupFullName) { String[] itemFullNameA = itemFullName.isEmpty() ? MemoryReductionUtil.EMPTY_STRING_ARRAY : itemFullName.split("/"); String[] groupFullNameA = groupFullName.isEmpty() ? MemoryReductionUtil.EMPTY_STRING_ARRAY : groupFullName.split("/"); for (int i = 0; ; i++) { if (i == itemFullNameA.length) { if (i == groupFullNameA.length) { // itemFullName and groupFullName are identical return "."; } else { // itemFullName is an ancestor of groupFullName; insert ../ for rest of groupFullName StringBuilder b = new StringBuilder(); for (int j = 0; j < groupFullNameA.length - itemFullNameA.length; j++) { if (j > 0) { b.append('/'); } b.append(".."); } return b.toString(); } } else if (i == groupFullNameA.length) { // groupFullName is an ancestor of itemFullName; insert rest of itemFullName StringBuilder b = new StringBuilder(); for (int j = i; j < itemFullNameA.length; j++) { if (j > i) { b.append('/'); } b.append(itemFullNameA[j]); } return b.toString(); } else if (itemFullNameA[i].equals(groupFullNameA[i])) { // identical up to this point continue; } else { // first mismatch; insert ../ for rest of groupFullName, then rest of itemFullName StringBuilder b = new StringBuilder(); for (int j = i; j < groupFullNameA.length; j++) { if (j > i) { b.append('/'); } b.append(".."); } for (int j = i; j < itemFullNameA.length; j++) { b.append('/').append(itemFullNameA[j]); } return b.toString(); } } } }
public class class_name { static String getRelativeNameFrom(String itemFullName, String groupFullName) { String[] itemFullNameA = itemFullName.isEmpty() ? MemoryReductionUtil.EMPTY_STRING_ARRAY : itemFullName.split("/"); String[] groupFullNameA = groupFullName.isEmpty() ? MemoryReductionUtil.EMPTY_STRING_ARRAY : groupFullName.split("/"); for (int i = 0; ; i++) { if (i == itemFullNameA.length) { if (i == groupFullNameA.length) { // itemFullName and groupFullName are identical return "."; // depends on control dependency: [if], data = [none] } else { // itemFullName is an ancestor of groupFullName; insert ../ for rest of groupFullName StringBuilder b = new StringBuilder(); for (int j = 0; j < groupFullNameA.length - itemFullNameA.length; j++) { if (j > 0) { b.append('/'); // depends on control dependency: [if], data = [none] } b.append(".."); // depends on control dependency: [for], data = [none] } return b.toString(); // depends on control dependency: [if], data = [none] } } else if (i == groupFullNameA.length) { // groupFullName is an ancestor of itemFullName; insert rest of itemFullName StringBuilder b = new StringBuilder(); for (int j = i; j < itemFullNameA.length; j++) { if (j > i) { b.append('/'); // depends on control dependency: [if], data = [none] } b.append(itemFullNameA[j]); // depends on control dependency: [for], data = [j] } return b.toString(); // depends on control dependency: [if], data = [none] } else if (itemFullNameA[i].equals(groupFullNameA[i])) { // identical up to this point continue; } else { // first mismatch; insert ../ for rest of groupFullName, then rest of itemFullName StringBuilder b = new StringBuilder(); for (int j = i; j < groupFullNameA.length; j++) { if (j > i) { b.append('/'); // depends on control dependency: [if], data = [none] } b.append(".."); // depends on control dependency: [for], data = [none] } for (int j = i; j < itemFullNameA.length; j++) { b.append('/').append(itemFullNameA[j]); // depends on control dependency: [for], data = [j] } return b.toString(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { @Override // Check is broken [LOG.info()]: PMD reports issues although log stmt is guarded. @todo revisit when upgrading PMD. @SuppressWarnings("PMD.GuardLogStatementJavaUtil") public final boolean login() throws LoginException { LOG.debug("Attempting login"); if (pCallbackHandler == null) { final String error = "No CallbackHandler available to garner authentication information from the user"; LOG.error(error); throw new LoginException(error); } Callback[] callbacks = new Callback[3]; callbacks[0] = new TextInputCallback("j_domain"); callbacks[1] = new NameCallback("j_username"); callbacks[2] = new PasswordCallback("j_password", false); try { pCallbackHandler.handle(callbacks); // store the domain domain = ((TextInputCallback) callbacks[0]).getText(); // store the username username = ((NameCallback) callbacks[1]).getName(); // store the password (i.e. a copy of the password) final char[] tempPassword = ((PasswordCallback) callbacks[2]).getPassword(); password = tempPassword.clone(); // clear the password in the callback ((PasswordCallback) callbacks[2]).clearPassword(); } catch (java.io.IOException e) { cleanState(); final String error = "Encountered an I/O exception during login"; LOG.warn(error, e); throw Util.newLoginException(error, e); } catch (UnsupportedCallbackException e) { cleanState(); final String error = e.getCallback().toString() + " not available to garner authentication information from the user"; LOG.warn(error, e); throw Util.newLoginException(error, e); } LOG.debug("Attempting login - discovered user '" + username + "@" + domain + "'"); // Using a try/catch construct for managing control flows is really a bad idea. // Unfortunately, this is how JAAS works :-( try { // authenticate, and update state and pending subject if successful pendingSubject = pwAuthenticator.authenticate(domain, username, password, pwValidator); // then clear the password Cleanser.wipe(password); final String baseError = new StringBuilder(). append("Login successful for '"). append(username). append("@"). append(domain). toString(); AuditHelper.auditEvent(audit, domain, username, Events.AUTHN_ATTEMPT, baseError + "', but cannot audit login attempt, and hence fail the operation"); MessageHelper.postMessage(messageQ, domain, username, Events.AUTHN_ATTEMPT, baseError + "', but cannot post MQ login attempt event, and hence fail the operation"); // string concatenation is only executed if log level is actually enabled if (LOG.isInfoEnabled()) { LOG.info("Login complete for '" + username + "@" + domain + "'"); } return true; } catch (LoginException e) { // the login failed // cache the username and domain, for they will be purged by "cleanState()" final String tempUsername = username; final String tempDomain = domain; cleanState(); final String baseError = new StringBuilder(). append("Login failed for '"). append(tempUsername). append("@"). append(tempDomain). toString(); AuditHelper.auditEvent(audit, tempDomain, tempUsername, Events.AUTHN_FAILURE, baseError + "', but cannot audit login attempt"); MessageHelper.postMessage(messageQ, tempDomain, tempUsername, Events.AUTHN_FAILURE, baseError + "', but cannot post MQ login attempt event"); final String error = "Login failed for '" + tempUsername + "@" + tempDomain + "'"; LOG.info(error, e); throw e; } } }
public class class_name { @Override // Check is broken [LOG.info()]: PMD reports issues although log stmt is guarded. @todo revisit when upgrading PMD. @SuppressWarnings("PMD.GuardLogStatementJavaUtil") public final boolean login() throws LoginException { LOG.debug("Attempting login"); if (pCallbackHandler == null) { final String error = "No CallbackHandler available to garner authentication information from the user"; LOG.error(error); throw new LoginException(error); } Callback[] callbacks = new Callback[3]; callbacks[0] = new TextInputCallback("j_domain"); callbacks[1] = new NameCallback("j_username"); callbacks[2] = new PasswordCallback("j_password", false); try { pCallbackHandler.handle(callbacks); // store the domain domain = ((TextInputCallback) callbacks[0]).getText(); // store the username username = ((NameCallback) callbacks[1]).getName(); // store the password (i.e. a copy of the password) final char[] tempPassword = ((PasswordCallback) callbacks[2]).getPassword(); password = tempPassword.clone(); // clear the password in the callback ((PasswordCallback) callbacks[2]).clearPassword(); } catch (java.io.IOException e) { cleanState(); final String error = "Encountered an I/O exception during login"; LOG.warn(error, e); throw Util.newLoginException(error, e); } catch (UnsupportedCallbackException e) { cleanState(); final String error = e.getCallback().toString() + " not available to garner authentication information from the user"; LOG.warn(error, e); throw Util.newLoginException(error, e); } LOG.debug("Attempting login - discovered user '" + username + "@" + domain + "'"); // Using a try/catch construct for managing control flows is really a bad idea. // Unfortunately, this is how JAAS works :-( try { // authenticate, and update state and pending subject if successful pendingSubject = pwAuthenticator.authenticate(domain, username, password, pwValidator); // then clear the password Cleanser.wipe(password); final String baseError = new StringBuilder(). append("Login successful for '"). append(username). append("@"). append(domain). toString(); AuditHelper.auditEvent(audit, domain, username, Events.AUTHN_ATTEMPT, baseError + "', but cannot audit login attempt, and hence fail the operation"); MessageHelper.postMessage(messageQ, domain, username, Events.AUTHN_ATTEMPT, baseError + "', but cannot post MQ login attempt event, and hence fail the operation"); // string concatenation is only executed if log level is actually enabled if (LOG.isInfoEnabled()) { LOG.info("Login complete for '" + username + "@" + domain + "'"); // depends on control dependency: [if], data = [none] } return true; } catch (LoginException e) { // the login failed // cache the username and domain, for they will be purged by "cleanState()" final String tempUsername = username; final String tempDomain = domain; cleanState(); final String baseError = new StringBuilder(). append("Login failed for '"). append(tempUsername). append("@"). append(tempDomain). toString(); AuditHelper.auditEvent(audit, tempDomain, tempUsername, Events.AUTHN_FAILURE, baseError + "', but cannot audit login attempt"); MessageHelper.postMessage(messageQ, tempDomain, tempUsername, Events.AUTHN_FAILURE, baseError + "', but cannot post MQ login attempt event"); final String error = "Login failed for '" + tempUsername + "@" + tempDomain + "'"; LOG.info(error, e); throw e; } } }
public class class_name { @Override public void setDefaultPrefix(final String prefixString) { lock.writeLock().lock(); try { if (prefixString == null || StringUtils.isBlank(prefixString)) { defaultPrefix = null; } else { if (prefixes != null) { if (!prefixes.contains(prefixString)) { throw new IllegalArgumentException("The given prefix is not part of the prefixes."); } } defaultPrefix = prefixString; } } finally { lock.writeLock().unlock(); } } }
public class class_name { @Override public void setDefaultPrefix(final String prefixString) { lock.writeLock().lock(); try { if (prefixString == null || StringUtils.isBlank(prefixString)) { defaultPrefix = null; // depends on control dependency: [if], data = [none] } else { if (prefixes != null) { if (!prefixes.contains(prefixString)) { throw new IllegalArgumentException("The given prefix is not part of the prefixes."); } } defaultPrefix = prefixString; // depends on control dependency: [if], data = [none] } } finally { lock.writeLock().unlock(); } } }
public class class_name { @Override public void doExecute() { if (!getEditor().isReadOnly()) { deleted = getEditor().delete().charAt(0); getEditor().put(replace); getEditor().moveLeft(replace.length()); } } }
public class class_name { @Override public void doExecute() { if (!getEditor().isReadOnly()) { deleted = getEditor().delete().charAt(0); // depends on control dependency: [if], data = [none] getEditor().put(replace); // depends on control dependency: [if], data = [none] getEditor().moveLeft(replace.length()); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static boolean endsWithIgnoreCase(final String source, final String target) { if (source.endsWith(target)) { return true; } if (source.length() < target.length()) { return false; } return source.substring(source.length() - target.length()).equalsIgnoreCase(target); } }
public class class_name { public static boolean endsWithIgnoreCase(final String source, final String target) { if (source.endsWith(target)) { return true; // depends on control dependency: [if], data = [none] } if (source.length() < target.length()) { return false; // depends on control dependency: [if], data = [none] } return source.substring(source.length() - target.length()).equalsIgnoreCase(target); } }
public class class_name { public void setHandshakes(java.util.Collection<Handshake> handshakes) { if (handshakes == null) { this.handshakes = null; return; } this.handshakes = new java.util.ArrayList<Handshake>(handshakes); } }
public class class_name { public void setHandshakes(java.util.Collection<Handshake> handshakes) { if (handshakes == null) { this.handshakes = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.handshakes = new java.util.ArrayList<Handshake>(handshakes); } }
public class class_name { public static void setInternalComments(Node node, ParserRuleContext parserRuleContext, AdapterParameters adapterParameters) { BufferedTokenStream tokens = adapterParameters.getTokens(); if (node == null || parserRuleContext == null || tokens == null) { throw new IllegalArgumentException("Parameters must not be null"); } Token startToken = parserRuleContext.getStart(); Token stopToken = parserRuleContext.getStop(); List<Token> commentTokens; List<Comment> internalCommentList = new LinkedList<Comment>(); // Checking to the right of the start token will check inside the statement commentTokens = tokens.getHiddenTokensToRight(startToken.getTokenIndex(), Java7Lexer.COMMENTS); if (commentTokens != null) { for (Token commentToken : commentTokens) { // Skip already claimed comments (prevents comment repeats) if (adapterParameters.isCommentTokenClaimed(commentToken.getTokenIndex())) { continue; } else { // Claim it adapterParameters.claimCommentToken(commentToken.getTokenIndex()); } if (commentToken.getText().startsWith("/**")) { JavadocComment javadocComment = new JavadocComment(commentToken.getText()); internalCommentList.add(javadocComment); } else if (commentToken.getText().startsWith("/*")) { BlockComment blockComment = new BlockComment(commentToken.getText()); internalCommentList.add(blockComment); } else if (commentToken.getText().startsWith("//")) { LineComment lineComment = new LineComment(commentToken.getText()); internalCommentList.add(lineComment); } } } if (internalCommentList.size() > 0) { if (node.getInternalComments() != null) { node.getInternalComments().addAll(internalCommentList); } else { node.setInternalComments(internalCommentList); } } } }
public class class_name { public static void setInternalComments(Node node, ParserRuleContext parserRuleContext, AdapterParameters adapterParameters) { BufferedTokenStream tokens = adapterParameters.getTokens(); if (node == null || parserRuleContext == null || tokens == null) { throw new IllegalArgumentException("Parameters must not be null"); } Token startToken = parserRuleContext.getStart(); Token stopToken = parserRuleContext.getStop(); List<Token> commentTokens; List<Comment> internalCommentList = new LinkedList<Comment>(); // Checking to the right of the start token will check inside the statement commentTokens = tokens.getHiddenTokensToRight(startToken.getTokenIndex(), Java7Lexer.COMMENTS); if (commentTokens != null) { for (Token commentToken : commentTokens) { // Skip already claimed comments (prevents comment repeats) if (adapterParameters.isCommentTokenClaimed(commentToken.getTokenIndex())) { continue; } else { // Claim it adapterParameters.claimCommentToken(commentToken.getTokenIndex()); // depends on control dependency: [if], data = [none] } if (commentToken.getText().startsWith("/**")) { JavadocComment javadocComment = new JavadocComment(commentToken.getText()); internalCommentList.add(javadocComment); } else if (commentToken.getText().startsWith("/*")) { BlockComment blockComment = new BlockComment(commentToken.getText()); internalCommentList.add(blockComment); } else if (commentToken.getText().startsWith("//")) { LineComment lineComment = new LineComment(commentToken.getText()); internalCommentList.add(lineComment); } } } if (internalCommentList.size() > 0) { if (node.getInternalComments() != null) { node.getInternalComments().addAll(internalCommentList); } else { node.setInternalComments(internalCommentList); } } } }
public class class_name { public T getValue() { // Check if the attribute class has been finalized yet. if (attributeClass.finalized) { // Fetch the object value from the attribute class. return attributeClass.lookupValue[value].label; } else { return attributeClass.lookupValueList.get(value).label; } } }
public class class_name { public T getValue() { // Check if the attribute class has been finalized yet. if (attributeClass.finalized) { // Fetch the object value from the attribute class. return attributeClass.lookupValue[value].label; // depends on control dependency: [if], data = [none] } else { return attributeClass.lookupValueList.get(value).label; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static List<String> readListResource(Class<?> clazz, String path) { File targetFile = resolve(clazz, path); if (targetFile == null) { return null; } List<String> result; try { result = FileUtils.readLines(targetFile, "UTF-8"); } catch (IOException ex) { return null; } return result; } }
public class class_name { public static List<String> readListResource(Class<?> clazz, String path) { File targetFile = resolve(clazz, path); if (targetFile == null) { return null; // depends on control dependency: [if], data = [none] } List<String> result; try { result = FileUtils.readLines(targetFile, "UTF-8"); // depends on control dependency: [try], data = [none] } catch (IOException ex) { return null; } // depends on control dependency: [catch], data = [none] return result; } }
public class class_name { private void map() { if (storageLevel == StorageLevel.MAPPED) { MappedByteBuffer buffer = writer.map(); readers.forEach(reader -> reader.map(buffer)); } } }
public class class_name { private void map() { if (storageLevel == StorageLevel.MAPPED) { MappedByteBuffer buffer = writer.map(); readers.forEach(reader -> reader.map(buffer)); // depends on control dependency: [if], data = [none] } } }
public class class_name { void onDataSetSelected() { String selectedUUID = view.getSelectedDataSetId(); for (DataSetDef dataSetDef : _dataSetDefList) { if (dataSetDef.getUUID().equals(selectedUUID)) { fetchMetadata(selectedUUID, new RemoteCallback<DataSetMetadata>() { public void callback(DataSetMetadata metadata) { dataSetLookup = lookupConstraints.newDataSetLookup(metadata); updateDataSetLookup(); changeEvent.fire(new DataSetLookupChangedEvent(dataSetLookup)); } }); } } } }
public class class_name { void onDataSetSelected() { String selectedUUID = view.getSelectedDataSetId(); for (DataSetDef dataSetDef : _dataSetDefList) { if (dataSetDef.getUUID().equals(selectedUUID)) { fetchMetadata(selectedUUID, new RemoteCallback<DataSetMetadata>() { public void callback(DataSetMetadata metadata) { dataSetLookup = lookupConstraints.newDataSetLookup(metadata); updateDataSetLookup(); changeEvent.fire(new DataSetLookupChangedEvent(dataSetLookup)); } }); // depends on control dependency: [if], data = [none] } } } }
public class class_name { @Override public PortletWindowIdImpl getPortletWindowId( HttpServletRequest request, String portletWindowId) { Validate.notNull(portletWindowId, "portletWindowId can not be null"); final String entityIdStr = PortletWindowIdStringUtils.parsePortletEntityId(portletWindowId); final String instanceId; if (!PortletEntityIdStringUtils.hasCorrectNumberOfParts(entityIdStr) || !PortletWindowIdStringUtils.hasCorrectNumberOfParts(portletWindowId)) { throw new IllegalArgumentException( "Provided portlet window ID '" + portletWindowId + "' is not valid"); } if (PortletWindowIdStringUtils.hasPortletWindowInstanceId(portletWindowId)) { instanceId = PortletWindowIdStringUtils.parsePortletWindowInstanceId(portletWindowId); } else { instanceId = null; } final IPortletEntity portletEntity = this.portletEntityRegistry.getPortletEntity(request, entityIdStr); if (portletEntity == null) { throw new IllegalArgumentException( "No parent IPortletEntity found for id '" + entityIdStr + "' from portlet window id: " + portletWindowId); } return createPortletWindowId(instanceId, portletEntity.getPortletEntityId()); } }
public class class_name { @Override public PortletWindowIdImpl getPortletWindowId( HttpServletRequest request, String portletWindowId) { Validate.notNull(portletWindowId, "portletWindowId can not be null"); final String entityIdStr = PortletWindowIdStringUtils.parsePortletEntityId(portletWindowId); final String instanceId; if (!PortletEntityIdStringUtils.hasCorrectNumberOfParts(entityIdStr) || !PortletWindowIdStringUtils.hasCorrectNumberOfParts(portletWindowId)) { throw new IllegalArgumentException( "Provided portlet window ID '" + portletWindowId + "' is not valid"); } if (PortletWindowIdStringUtils.hasPortletWindowInstanceId(portletWindowId)) { instanceId = PortletWindowIdStringUtils.parsePortletWindowInstanceId(portletWindowId); // depends on control dependency: [if], data = [none] } else { instanceId = null; // depends on control dependency: [if], data = [none] } final IPortletEntity portletEntity = this.portletEntityRegistry.getPortletEntity(request, entityIdStr); if (portletEntity == null) { throw new IllegalArgumentException( "No parent IPortletEntity found for id '" + entityIdStr + "' from portlet window id: " + portletWindowId); } return createPortletWindowId(instanceId, portletEntity.getPortletEntityId()); } }
public class class_name { public long getMaximumTimeInStore() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getMaximumTimeInStore"); long originalExpiryTime = super.getMaximumTimeInStore(); long rejectTime = aih.getRCD().getRejectTimeout(); if (originalExpiryTime == NEVER_EXPIRES) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getMaximumTimeInStore", Long.valueOf(rejectTime)); return rejectTime; } else if (rejectTime == NEVER_EXPIRES) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getMaximumTimeInStore", Long.valueOf(originalExpiryTime)); return originalExpiryTime; } else { // neither is NEVER_EXPIRES, so return the minimum of the two long min = originalExpiryTime < rejectTime?originalExpiryTime:rejectTime; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getMaximumTimeInStore", Long.valueOf(min)); return min; } } }
public class class_name { public long getMaximumTimeInStore() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getMaximumTimeInStore"); long originalExpiryTime = super.getMaximumTimeInStore(); long rejectTime = aih.getRCD().getRejectTimeout(); if (originalExpiryTime == NEVER_EXPIRES) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getMaximumTimeInStore", Long.valueOf(rejectTime)); return rejectTime; // depends on control dependency: [if], data = [none] } else if (rejectTime == NEVER_EXPIRES) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getMaximumTimeInStore", Long.valueOf(originalExpiryTime)); return originalExpiryTime; // depends on control dependency: [if], data = [none] } else { // neither is NEVER_EXPIRES, so return the minimum of the two long min = originalExpiryTime < rejectTime?originalExpiryTime:rejectTime; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getMaximumTimeInStore", Long.valueOf(min)); return min; // depends on control dependency: [if], data = [none] } } }
public class class_name { public void marshall(ActionExecutionOutput actionExecutionOutput, ProtocolMarshaller protocolMarshaller) { if (actionExecutionOutput == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(actionExecutionOutput.getOutputArtifacts(), OUTPUTARTIFACTS_BINDING); protocolMarshaller.marshall(actionExecutionOutput.getExecutionResult(), EXECUTIONRESULT_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ActionExecutionOutput actionExecutionOutput, ProtocolMarshaller protocolMarshaller) { if (actionExecutionOutput == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(actionExecutionOutput.getOutputArtifacts(), OUTPUTARTIFACTS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(actionExecutionOutput.getExecutionResult(), EXECUTIONRESULT_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public EClass getIfcDuctSilencerType() { if (ifcDuctSilencerTypeEClass == null) { ifcDuctSilencerTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(181); } return ifcDuctSilencerTypeEClass; } }
public class class_name { public EClass getIfcDuctSilencerType() { if (ifcDuctSilencerTypeEClass == null) { ifcDuctSilencerTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(181); // depends on control dependency: [if], data = [none] } return ifcDuctSilencerTypeEClass; } }
public class class_name { public void xmlWriteOn(FormattedWriter writer) throws IOException { writer.newLine(); writer.startTag(XML_ITEM_MAP); writer.indent(); for (int i = 0; null != _entry && i < _entry.length; i++) // 666212 { AbstractItemLink ail = _entry[i]; while (null != ail) { writer.newLine(); ail.xmlShortWriteOn(writer); ail = ail.getNextMappedLink(); } } writer.outdent(); writer.newLine(); writer.endTag(XML_ITEM_MAP); } }
public class class_name { public void xmlWriteOn(FormattedWriter writer) throws IOException { writer.newLine(); writer.startTag(XML_ITEM_MAP); writer.indent(); for (int i = 0; null != _entry && i < _entry.length; i++) // 666212 { AbstractItemLink ail = _entry[i]; while (null != ail) { writer.newLine(); // depends on control dependency: [while], data = [none] ail.xmlShortWriteOn(writer); // depends on control dependency: [while], data = [none] ail = ail.getNextMappedLink(); // depends on control dependency: [while], data = [none] } } writer.outdent(); writer.newLine(); writer.endTag(XML_ITEM_MAP); } }
public class class_name { public String getDependency() { String dependency = ""; CmsRole role = m_role; while (role.getParentRole() != null) { dependency = dependency + role.getParentRole().getName(getCms().getRequestContext().getLocale()); role = role.getParentRole(); if (role.getParentRole() != null) { dependency = dependency + ", "; } } return dependency; } }
public class class_name { public String getDependency() { String dependency = ""; CmsRole role = m_role; while (role.getParentRole() != null) { dependency = dependency + role.getParentRole().getName(getCms().getRequestContext().getLocale()); // depends on control dependency: [while], data = [none] role = role.getParentRole(); // depends on control dependency: [while], data = [none] if (role.getParentRole() != null) { dependency = dependency + ", "; // depends on control dependency: [if], data = [none] } } return dependency; } }
public class class_name { public MockResponse handleDelete(String path) { MockResponse response = new MockResponse(); List<AttributeSet> items = new ArrayList<>(); AttributeSet query = attributeExtractor.extract(path); for (Map.Entry<AttributeSet, String> entry : map.entrySet()) { if (entry.getKey().matches(query)) { items.add(entry.getKey()); } } if (!items.isEmpty()) { for (AttributeSet item : items) { map.remove(item); } response.setResponseCode(200); } else { response.setResponseCode(404); } return response; } }
public class class_name { public MockResponse handleDelete(String path) { MockResponse response = new MockResponse(); List<AttributeSet> items = new ArrayList<>(); AttributeSet query = attributeExtractor.extract(path); for (Map.Entry<AttributeSet, String> entry : map.entrySet()) { if (entry.getKey().matches(query)) { items.add(entry.getKey()); // depends on control dependency: [if], data = [none] } } if (!items.isEmpty()) { for (AttributeSet item : items) { map.remove(item); // depends on control dependency: [for], data = [item] } response.setResponseCode(200); // depends on control dependency: [if], data = [none] } else { response.setResponseCode(404); // depends on control dependency: [if], data = [none] } return response; } }
public class class_name { public void setParameterType(String type) { String typeName; if (Strings.isEmpty(type)) { typeName = Object.class.getName(); } else { typeName = type; } this.parameter.setParameterType(newTypeRef(this.context, typeName)); } }
public class class_name { public void setParameterType(String type) { String typeName; if (Strings.isEmpty(type)) { typeName = Object.class.getName(); // depends on control dependency: [if], data = [none] } else { typeName = type; // depends on control dependency: [if], data = [none] } this.parameter.setParameterType(newTypeRef(this.context, typeName)); } }
public class class_name { private <T> BindingAmp<T> findBinding(Key<T> key) { BindingSet<T> set = (BindingSet) _bindingSetMap.get(key.rawClass()); if (set != null) { BindingAmp<T> binding = set.find(key); if (binding != null) { return binding; } } return null; } }
public class class_name { private <T> BindingAmp<T> findBinding(Key<T> key) { BindingSet<T> set = (BindingSet) _bindingSetMap.get(key.rawClass()); if (set != null) { BindingAmp<T> binding = set.find(key); if (binding != null) { return binding; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { public EClass getIfcAnnotationFillAreaOccurrence() { if (ifcAnnotationFillAreaOccurrenceEClass == null) { ifcAnnotationFillAreaOccurrenceEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(15); } return ifcAnnotationFillAreaOccurrenceEClass; } }
public class class_name { public EClass getIfcAnnotationFillAreaOccurrence() { if (ifcAnnotationFillAreaOccurrenceEClass == null) { ifcAnnotationFillAreaOccurrenceEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(15); // depends on control dependency: [if], data = [none] } return ifcAnnotationFillAreaOccurrenceEClass; } }
public class class_name { public void setNotificationARNs(java.util.Collection<String> notificationARNs) { if (notificationARNs == null) { this.notificationARNs = null; return; } this.notificationARNs = new com.amazonaws.internal.SdkInternalList<String>(notificationARNs); } }
public class class_name { public void setNotificationARNs(java.util.Collection<String> notificationARNs) { if (notificationARNs == null) { this.notificationARNs = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.notificationARNs = new com.amazonaws.internal.SdkInternalList<String>(notificationARNs); } }
public class class_name { public static void invalidateReferrerURLCookie(HttpServletRequest req, HttpServletResponse res, String cookieName) { // 240540 getReferrerURLCookieHandler().invalidateReferrerURLCookie(req, res, cookieName); // need to have domain here too if (cookieName == null || req == null || res == null) { if (tc.isDebugEnabled()) { Tr.debug(tc, "invalidateReferrerURLCookie param is null, return"); } return; } Cookie c = createCookie(cookieName, "", req); String domainName = getSsoDomain(req); if (domainName != null && !domainName.isEmpty()) { c.setDomain(domainName); } c.setMaxAge(0); res.addCookie(c); } }
public class class_name { public static void invalidateReferrerURLCookie(HttpServletRequest req, HttpServletResponse res, String cookieName) { // 240540 getReferrerURLCookieHandler().invalidateReferrerURLCookie(req, res, cookieName); // need to have domain here too if (cookieName == null || req == null || res == null) { if (tc.isDebugEnabled()) { Tr.debug(tc, "invalidateReferrerURLCookie param is null, return"); // depends on control dependency: [if], data = [none] } return; // depends on control dependency: [if], data = [none] } Cookie c = createCookie(cookieName, "", req); String domainName = getSsoDomain(req); if (domainName != null && !domainName.isEmpty()) { c.setDomain(domainName); // depends on control dependency: [if], data = [(domainName] } c.setMaxAge(0); res.addCookie(c); } }
public class class_name { @GwtIncompatible // concurrency @SuppressWarnings("GoodTime") // should accept a java.time.Duration public static boolean tryAcquireUninterruptibly( Semaphore semaphore, int permits, long timeout, TimeUnit unit) { boolean interrupted = false; try { long remainingNanos = unit.toNanos(timeout); long end = System.nanoTime() + remainingNanos; while (true) { try { // Semaphore treats negative timeouts just like zero. return semaphore.tryAcquire(permits, remainingNanos, NANOSECONDS); } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } }
public class class_name { @GwtIncompatible // concurrency @SuppressWarnings("GoodTime") // should accept a java.time.Duration public static boolean tryAcquireUninterruptibly( Semaphore semaphore, int permits, long timeout, TimeUnit unit) { boolean interrupted = false; try { long remainingNanos = unit.toNanos(timeout); long end = System.nanoTime() + remainingNanos; while (true) { try { // Semaphore treats negative timeouts just like zero. return semaphore.tryAcquire(permits, remainingNanos, NANOSECONDS); // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } // depends on control dependency: [catch], data = [none] } } finally { if (interrupted) { Thread.currentThread().interrupt(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static WebElement loopFindOrRefresh(int maxRefreshes, By locator, WebDriver driver) { for (int i = 0; i < maxRefreshes; i++) { WebElement element; try { // implicitly wait element = driver.findElement(locator); // if no exception is thrown, then we can exit the loop return element; } catch(NoSuchElementException e) { // if implicit wait times out, then refresh page and continue the loop logger.info("after implicit wait, element " + locator + " is still not present: refreshing page and trying again"); Navigation.refreshPage(driver); } } return null; } }
public class class_name { public static WebElement loopFindOrRefresh(int maxRefreshes, By locator, WebDriver driver) { for (int i = 0; i < maxRefreshes; i++) { WebElement element; try { // implicitly wait element = driver.findElement(locator); // depends on control dependency: [try], data = [none] // if no exception is thrown, then we can exit the loop return element; // depends on control dependency: [try], data = [none] } catch(NoSuchElementException e) { // if implicit wait times out, then refresh page and continue the loop logger.info("after implicit wait, element " + locator + " is still not present: refreshing page and trying again"); Navigation.refreshPage(driver); } // depends on control dependency: [catch], data = [none] } return null; } }
public class class_name { private void processScanResponse(ClientResponse response) { setState(State.WAITING); if (response.getStatus() != ClientResponse.SUCCESS) { logFailureResponse("Initial snapshot scan failed", response); return; } final VoltTable results[] = response.getResults(); if (results.length == 1) { final VoltTable result = results[0]; boolean advanced = result.advanceRow(); assert(advanced); assert(result.getColumnCount() == 1); assert(result.getColumnType(0) == VoltType.STRING); SNAP_LOG.warn("Initial snapshot scan failed with failure response: " + result.getString("ERR_MSG")); return; } assert(results.length == 3); final VoltTable snapshots = results[0]; assert(snapshots.getColumnCount() == 10); final File myPath = new File(m_path); while (snapshots.advanceRow()) { final String path = snapshots.getString("PATH"); final File pathFile = new File(path); if (pathFile.equals(myPath)) { final String nonce = snapshots.getString("NONCE"); if (nonce.startsWith(m_prefixAndSeparator)) { final Long txnId = snapshots.getLong("TXNID"); m_snapshots.add(new Snapshot(path, SnapshotPathType.SNAP_AUTO, nonce, txnId)); } } } java.util.Collections.sort(m_snapshots); deleteExtraSnapshots(); } }
public class class_name { private void processScanResponse(ClientResponse response) { setState(State.WAITING); if (response.getStatus() != ClientResponse.SUCCESS) { logFailureResponse("Initial snapshot scan failed", response); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } final VoltTable results[] = response.getResults(); if (results.length == 1) { final VoltTable result = results[0]; boolean advanced = result.advanceRow(); assert(advanced); assert(result.getColumnCount() == 1); assert(result.getColumnType(0) == VoltType.STRING); SNAP_LOG.warn("Initial snapshot scan failed with failure response: " + result.getString("ERR_MSG")); return; } assert(results.length == 3); final VoltTable snapshots = results[0]; assert(snapshots.getColumnCount() == 10); final File myPath = new File(m_path); while (snapshots.advanceRow()) { final String path = snapshots.getString("PATH"); final File pathFile = new File(path); if (pathFile.equals(myPath)) { final String nonce = snapshots.getString("NONCE"); if (nonce.startsWith(m_prefixAndSeparator)) { final Long txnId = snapshots.getLong("TXNID"); m_snapshots.add(new Snapshot(path, SnapshotPathType.SNAP_AUTO, nonce, txnId)); } } } java.util.Collections.sort(m_snapshots); deleteExtraSnapshots(); } }
public class class_name { private boolean areChildrenComputableAsJsExprs(ParentSoyNode<?> node) { for (SoyNode child : node.getChildren()) { if (canSkipChild(child)) { continue; } if (!visit(child)) { return false; } } return true; } }
public class class_name { private boolean areChildrenComputableAsJsExprs(ParentSoyNode<?> node) { for (SoyNode child : node.getChildren()) { if (canSkipChild(child)) { continue; } if (!visit(child)) { return false; // depends on control dependency: [if], data = [none] } } return true; } }
public class class_name { public List<BaseDownloadTask> shutdown() { synchronized (finishCallback) { if (workingTask != null) { pause(); } final List<BaseDownloadTask> unDealTaskList = new ArrayList<>(pausedList); pausedList.clear(); mHandler.removeMessages(WHAT_NEXT); mHandlerThread.interrupt(); mHandlerThread.quit(); return unDealTaskList; } } }
public class class_name { public List<BaseDownloadTask> shutdown() { synchronized (finishCallback) { if (workingTask != null) { pause(); // depends on control dependency: [if], data = [none] } final List<BaseDownloadTask> unDealTaskList = new ArrayList<>(pausedList); pausedList.clear(); mHandler.removeMessages(WHAT_NEXT); mHandlerThread.interrupt(); mHandlerThread.quit(); return unDealTaskList; } } }
public class class_name { protected final void validateAssertionConditions(final Conditions conditions, final SAML2MessageContext context) { if (conditions == null) { return; } if (conditions.getNotBefore() != null && conditions.getNotBefore().minusSeconds(acceptedSkew).isAfterNow()) { throw new SAMLAssertionConditionException("Assertion condition notBefore is not valid"); } if (conditions.getNotOnOrAfter() != null && conditions.getNotOnOrAfter().plusSeconds(acceptedSkew).isBeforeNow()) { throw new SAMLAssertionConditionException("Assertion condition notOnOrAfter is not valid"); } final String entityId = context.getSAMLSelfEntityContext().getEntityId(); validateAudienceRestrictions(conditions.getAudienceRestrictions(), entityId); } }
public class class_name { protected final void validateAssertionConditions(final Conditions conditions, final SAML2MessageContext context) { if (conditions == null) { return; // depends on control dependency: [if], data = [none] } if (conditions.getNotBefore() != null && conditions.getNotBefore().minusSeconds(acceptedSkew).isAfterNow()) { throw new SAMLAssertionConditionException("Assertion condition notBefore is not valid"); } if (conditions.getNotOnOrAfter() != null && conditions.getNotOnOrAfter().plusSeconds(acceptedSkew).isBeforeNow()) { throw new SAMLAssertionConditionException("Assertion condition notOnOrAfter is not valid"); } final String entityId = context.getSAMLSelfEntityContext().getEntityId(); validateAudienceRestrictions(conditions.getAudienceRestrictions(), entityId); } }
public class class_name { public synchronized @CheckForNull HashedToken revokeToken(@Nonnull String tokenUuid) { for (Iterator<HashedToken> iterator = tokenList.iterator(); iterator.hasNext(); ) { HashedToken token = iterator.next(); if (token.uuid.equals(tokenUuid)) { iterator.remove(); return token; } } return null; } }
public class class_name { public synchronized @CheckForNull HashedToken revokeToken(@Nonnull String tokenUuid) { for (Iterator<HashedToken> iterator = tokenList.iterator(); iterator.hasNext(); ) { HashedToken token = iterator.next(); if (token.uuid.equals(tokenUuid)) { iterator.remove(); // depends on control dependency: [if], data = [none] return token; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { public void queueAnimation(final GQAnimation anim, final int duration) { if (isOff()) { anim.onStart(); anim.onComplete(); } else { queue(anim.e, DEFAULT_NAME, new Function() { public void cancel(Element e) { Animation anim = (Animation) data(e, GQAnimation.ACTUAL_ANIMATION, null); if (anim != null) { anim.cancel(); } } public void f(Element e) { anim.run(duration); } }); } } }
public class class_name { public void queueAnimation(final GQAnimation anim, final int duration) { if (isOff()) { anim.onStart(); // depends on control dependency: [if], data = [none] anim.onComplete(); // depends on control dependency: [if], data = [none] } else { queue(anim.e, DEFAULT_NAME, new Function() { public void cancel(Element e) { Animation anim = (Animation) data(e, GQAnimation.ACTUAL_ANIMATION, null); if (anim != null) { anim.cancel(); // depends on control dependency: [if], data = [none] } } public void f(Element e) { anim.run(duration); } }); // depends on control dependency: [if], data = [none] } } }