auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void canTriggerOpenCircuit() throws InterruptedException, TimeoutException { EventForwarder eventForwarder = mock(EventForwarder.class); NettyDnsResolver dnsResolver = new NettyDnsResolver(eventForwarder, new MetricRegistry()); dnsResolver.setNameservers(InetAddressUtils.str(InetAddressUtils.UNPINGABLE_ADDRESS)); dnsResolver.setBreakerFailureRateThreshold(80); dnsResolver.setBreakerWaitDurationInOpenState(15); dnsResolver.setBreakerRingBufferSizeInHalfOpenState(10); dnsResolver.setBreakerRingBufferSizeInClosedState(100); dnsResolver.init(); final int N = 2 * dnsResolver.getCircuitBreaker().getCircuitBreakerConfig().getRingBufferSizeInClosedState(); final CompletableFuture futures[] = new CompletableFuture[N]; for (int i = 0; i < N; i++) { futures[i] = dnsResolver.reverseLookup(InetAddressUtils.addr("fe80::")); } try { CompletableFuture.allOf(futures) .get(2 * dnsResolver.getQueryTimeoutMillis(), TimeUnit.MILLISECONDS); fail("Expected an ExecutionException to be thrown"); } catch (ExecutionException e) { } try { dnsResolver.reverseLookup(InetAddressUtils.addr("fe80::")).get(); fail("Expected an CallNotPermittedException to be thrown"); } catch (ExecutionException e) { assertThat(e.getCause(), is(instanceOf(CallNotPermittedException.class))); } }

Target:
public void canTriggerOpenCircuit() throws InterruptedException, TimeoutException { EventForwarder eventForwarder = mock(EventForwarder.class); NettyDnsResolver dnsResolver = new NettyDnsResolver(eventForwarder, new MetricRegistry()); dnsResolver.setNameservers(InetAddressUtils.str(InetAddressUtils.UNPINGABLE_ADDRESS)); dnsResolver.init(); final int N = 2 * dnsResolver.getCircuitBreaker().getCircuitBreakerConfig().getRingBufferSizeInClosedState(); final CompletableFuture futures[] = new CompletableFuture[N]; for (int i = 0; i < N; i++) { futures[i] = dnsResolver.reverseLookup(InetAddressUtils.addr("fe80::")); } try { CompletableFuture.allOf(futures) .get(2 * dnsResolver.getQueryTimeoutMillis(), TimeUnit.MILLISECONDS); fail("Expected an ExecutionException to be thrown"); } catch (ExecutionException e) { } try { dnsResolver.reverseLookup(InetAddressUtils.addr("fe80::")).get(); fail("Expected an CallNotPermittedException to be thrown"); } catch (ExecutionException e) { assertThat(e.getCause(), is(instanceOf(CallNotPermittedException.class))); } }
Source:
public URI getBaseUri() { if (baseURI == null) { baseURI = delegate.getBaseUriBuilder().scheme(scheme).host(hostname).port(port).replacePath(contextPath).build(); } return baseURI; }

Target:
public URI getBaseUri() { if (baseURI == null) { baseURI = initUriBuilder(delegate.getBaseUriBuilder()).build(); } return baseURI; }
Source:
KafkaConsumer<byte[], byte[]> newConsumer() { ClassLoader currCtxCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); final Map<String, Object> consumerConfigs = KafkaConsumerConfigs.getConsumerProperties(); final Properties props = new Properties(); props.putAll(consumerConfigs); KafkaRecordSupplier.addConsumerPropertiesFromConfig( props, configMapper, ioConfig.getConsumerProperties() ); return new KafkaConsumer<>(props); } finally { Thread.currentThread().setContextClassLoader(currCtxCl); } }

Target:
KafkaConsumer<byte[], byte[]> newConsumer() { ClassLoader currCtxCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); final Map<String, Object> consumerConfigs = KafkaConsumerConfigs.getConsumerProperties(); final Properties props = new Properties(); KafkaRecordSupplier.addConsumerPropertiesFromConfig( props, configMapper, ioConfig.getConsumerProperties() ); props.putAll(consumerConfigs); return new KafkaConsumer<>(props); } finally { Thread.currentThread().setContextClassLoader(currCtxCl); } }
Source:
private static Document toDocument(Node node, Map<String, String> namespaces) { Namespaces abbr = namespaces instanceof Namespaces ? (Namespaces) namespaces : new Namespaces(namespaces); DocumentBuilder builder; try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { String message = e.getMessage(); throw new RuntimeException(message != null ? message : e.getClass().getSimpleName(), e); } String qualifiedName = abbr.abbreviateElement(getTypeOrDefault(node)); Document document = builder.getDOMImplementation() .createDocument(Namespaces.namespaceOfForXMLFile(getTypeOrDefault(node)), qualifiedName, null); Element root = document.getDocumentElement(); if ((node instanceof Node) && (node instanceof IdentifiableNode)) { root.setAttribute(abbr.abbreviateAttribute(getTypeOrDefault(node), RDF.ABOUT), ((IdentifiableNode) node).getIdentifier()); } nodeToElement(node, document, abbr, root); for (Entry<String, String> nsAttr : abbr.namespaceSetForXMLFile()) { root.setAttribute(nsAttr.getKey(), nsAttr.getValue()); } return document; }

Target:
private static Document toDocument(Node node, Map<String, String> namespaces) { try { Namespaces abbr = namespaces instanceof Namespaces ? (Namespaces) namespaces : new Namespaces(namespaces); String qualifiedName = abbr.abbreviateElement(getTypeOrDefault(node)); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation() .createDocument(Namespaces.namespaceOfForXMLFile(getTypeOrDefault(node)), qualifiedName, null); Element root = document.getDocumentElement(); if (node instanceof IdentifiableNode) { root.setAttribute(abbr.abbreviateAttribute(getTypeOrDefault(node), RDF.ABOUT), ((IdentifiableNode) node).getIdentifier()); } nodeToElement(node, document, abbr, root); abbr.namespaceSetForXMLFile().forEach(nsAttr -> root.setAttribute(nsAttr.getKey(), nsAttr.getValue())); return document; } catch (ParserConfigurationException e) { throw new IllegalStateException(e.getMessage(), e); } }
Source:
public static String toPortableString(Path path) { Objects.requireNonNull(path, "The given path must not be null"); if (path.isAbsolute()) { throw new IllegalArgumentException("The given path must not be absolute"); } String localPathString = path.toString(); if (File.separator.equals(PORTABLE_SEPARATOR)) { if (localPathString.contains(WINDOWS_SEPARATOR)) { log.warn( "The given local path contains occurrences of the Windows separator character '" + WINDOWS_SEPARATOR + "'. As this character is not seen as a separator by the local filesystem, this " + "will most likely lead to issues when the path is transferred to a Saros " + "instance running on a Windows system."); } return localPathString; } return localPathString.replace(File.separator, PORTABLE_SEPARATOR); }

Target:
public static String toPortableString(Path path) { Objects.requireNonNull(path, "The given path must not be null"); Path normalizedPath = normalize(path); String normalizedLocalPathString = normalizedPath.toString(); if (File.separator.equals(PORTABLE_SEPARATOR)) { if (normalizedLocalPathString.contains(WINDOWS_SEPARATOR)) { log.warn( "The given local path contains occurrences of the Windows separator character '" + WINDOWS_SEPARATOR + "'. This character is not seen as a separator by the local filesystem, meaning " + " resolving the path on a Windows system will lead to a different path. path: " + normalizedLocalPathString); } return normalizedLocalPathString; } return normalizedLocalPathString.replace(File.separator, PORTABLE_SEPARATOR); }
Source:
private static void merge(String key, BiFunction<Long,Long,Long> mergeFunc, Map<String, Long> stats1, Map<String,Long> stats2) { if (stats2.containsKey(key) && (stats1.containsKey(key) == false)) { stats1.put(key, stats2.get(key)); } else if (stats2.containsKey(key) && stats1.containsKey(key)){ stats1.merge(key, stats2.get(key), mergeFunc); } }

Target:
private static void merge(String key, BiFunction<Long,Long,Long> mergeFunc, Map<String, Long> stats1, Map<String,Long> stats2) { Long mergeVal = stats2.get(key); if(mergeVal != null) { stats1.merge(key, mergeVal, mergeFunc); } }
Source:
private CacheStoreHolder getHolder(int grpId) throws IgniteCheckedException { try { return cleanupAsyncExecutor.afterAsyncCompletion( () -> idxCacheStores.computeIfAbsent(grpId, (key) -> { CacheGroupDescriptor gDesc = cctx.cache().cacheGroupDescriptors().get(grpId); CacheStoreHolder holder0 = null; if (gDesc != null) { if (CU.isPersistentCache(gDesc.config(), cctx.gridConfig().getDataStorageConfiguration())) { try { holder0 = initForCache(gDesc, gDesc.config()); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } } return holder0; }) ); } catch (IgniteException ex) { if (X.hasCause(ex, IgniteCheckedException.class)) throw ex.getCause(IgniteCheckedException.class); else throw ex; } }

Target:
private CacheStoreHolder getHolder(int grpId) throws IgniteCheckedException { try { return idxCacheStores.computeIfAbsent(grpId, (key) -> { CacheGroupDescriptor gDesc = cctx.cache().cacheGroupDescriptors().get(grpId); CacheStoreHolder holder0 = null; if (gDesc != null && CU.isPersistentCache(gDesc.config(), cctx.gridConfig().getDataStorageConfiguration())) { try { holder0 = initForCache(gDesc, gDesc.config()); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } return holder0; }); } catch (IgniteException ex) { if (X.hasCause(ex, IgniteCheckedException.class)) throw ex.getCause(IgniteCheckedException.class); else throw ex; } }
Source:
protected void run() throws Exception { final AmazonS3 s3 = new AmazonS3(properties()); if (null == op) { throw die(MessageFormat.format(CLIText.get().unsupportedOperation, op)); } else switch (op) { case "get": final URLConnection c = s3.get(bucket, key); int len = c.getContentLength(); try (InputStream in = c.getInputStream()) { outw.flush(); final byte[] tmp = new byte[2048]; while (len > 0) { final int n = in.read(tmp); if (n < 0) throw new EOFException(MessageFormat.format( CLIText.get().expectedNumberOfbytes, valueOf(len))); outs.write(tmp, 0, n); len -= n; } outs.flush(); } break; case "ls"://$NON-NLS-1$ case "list"://$NON-NLS-1$ for (String k : s3.list(bucket, key)) outw.println(k); break; case "rm"://$NON-NLS-1$ case "delete"://$NON-NLS-1$ s3.delete(bucket, key); break; case "put"://$NON-NLS-1$ try (OutputStream os = s3.beginPut(bucket, key, null, null)) { final byte[] tmp = new byte[2048]; int n; while ((n = ins.read(tmp)) > 0) os.write(tmp, 0, n); } break; default: throw die(MessageFormat.format(CLIText.get().unsupportedOperation, op)); } }

Target:
protected void run() throws Exception { final AmazonS3 s3 = new AmazonS3(properties()); if (op == null) { throw die(MessageFormat.format(CLIText.get().unsupportedOperation, op)); } switch (op) { case "get": final URLConnection c = s3.get(bucket, key); int len = c.getContentLength(); try (InputStream in = c.getInputStream()) { outw.flush(); final byte[] tmp = new byte[2048]; while (len > 0) { final int n = in.read(tmp); if (n < 0) throw new EOFException(MessageFormat.format( CLIText.get().expectedNumberOfbytes, valueOf(len))); outs.write(tmp, 0, n); len -= n; } outs.flush(); } break; case "ls": case "list": for (String k : s3.list(bucket, key)) outw.println(k); break; case "rm": case "delete": s3.delete(bucket, key); break; case "put": try (OutputStream os = s3.beginPut(bucket, key, null, null)) { final byte[] tmp = new byte[2048]; int n; while ((n = ins.read(tmp)) > 0) os.write(tmp, 0, n); } break; default: throw die(MessageFormat.format(CLIText.get().unsupportedOperation, op)); } }
Source:
static boolean isSupportedOnVersion(ListChangesOption listChangesOption, String gerritVersion) { ListChangesOption maxOption = maxChangeOptionByVersion.get(gerritVersion); if(maxOption == null) { return true; } return listChangesOption.getValue() <= maxOption.getValue(); }

Target:
static boolean isSupportedOnVersion(ListChangesOption listChangesOption, String gerritVersion) { Matcher versionMatcher = VERSION_PATTERN.matcher(gerritVersion); if (!versionMatcher.matches()) { return true; } ListChangesOption maxOption = MAX_CHANGE_OPTION_BY_VERSION.get(versionMatcher.group(1) + "." + versionMatcher.group(2)); if (maxOption == null) { return true; } return listChangesOption.getValue() <= maxOption.getValue(); }
Source:
protected Route(BlackboardArtifact artifact) throws TskCoreException { points = new ArrayList<>(); Waypoint point = getRouteStartPoint(artifact); if (point != null) { points.add(point); } point = getRouteEndPoint(artifact); if (point != null) { points.add(point); } altitude = getRouteAltitude(artifact); timestamp = getRouteTimestamp(artifact); otherAttributesMap = initalizeOtherAttributes(artifact); }

Target:
Route(BlackboardArtifact artifact) throws GeoLocationDataException { points = new ArrayList<>(); Map<BlackboardAttribute.ATTRIBUTE_TYPE, BlackboardAttribute> attributeMap = ArtifactWaypoint.getAttributesFromArtifactAsMap(artifact); points.add(getRouteStartPoint(attributeMap)); points.add(getRouteEndPoint(attributeMap)); BlackboardAttribute attribute = attributeMap.get(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_ALTITUDE); altitude = attribute != null ? attribute.getValueDouble() : null; attribute = attributeMap.get(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME); timestamp = attribute != null ? attribute.getValueLong() : null; immutablePropertiesList = Collections.unmodifiableList(Waypoint.createGeolocationProperties(attributeMap)); }
Source:
public VdcActionParametersBase getParameters(Template incoming, VmTemplate entity) { VmTemplate updated = getMapper(modelType, VmTemplate.class).map(incoming, entity); updated.setUsbPolicy(VmMapper.getUsbPolicyOnUpdate(incoming.getUsb(), entity.getUsbPolicy(), lookupCluster(updated.getVdsGroupId()))); UpdateVmTemplateParameters params = new UpdateVmTemplateParameters(updated); if (incoming.isSetConsoleDeviceEnabled()) { params.setConsoleEnabled(incoming.isConsoleDeviceEnabled()); } return params; }

Target:
public VdcActionParametersBase getParameters(Template incoming, VmTemplate entity) { VmTemplate updated = getMapper(modelType, VmTemplate.class).map(incoming, entity); updated.setUsbPolicy(VmMapper.getUsbPolicyOnUpdate(incoming.getUsb(), entity.getUsbPolicy(), lookupCluster(updated.getVdsGroupId()))); return getMapper(modelType, UpdateVmTemplateParameters.class).map(incoming, new UpdateVmTemplateParameters(updated)); }
Source:
private ArrayList<CramCompressionRecord> getRecords(final Slice slice, final CompressionHeader header, final ValidationStringency validationStringency) { String seqName = SAMRecord.NO_ALIGNMENT_REFERENCE_NAME; switch (slice.sequenceId) { case SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX: case -2: break; default: final SAMSequenceRecord sequence = samFileHeader .getSequence(slice.sequenceId); seqName = sequence.getSequenceName(); break; } final CramRecordReader reader = slice.createCramRecordReader(header, validationStringency); final ArrayList<CramCompressionRecord> records = new ArrayList<>(slice.nofRecords); int prevAlignmentStart = slice.alignmentStart; for (int i = 0; i < slice.nofRecords; i++) { final CramCompressionRecord record = new CramCompressionRecord(); record.sliceIndex = slice.index; record.index = i; reader.read(record, prevAlignmentStart); prevAlignmentStart = record.alignmentStart; if (record.sequenceId == slice.sequenceId) { record.sequenceName = seqName; record.sequenceId = slice.sequenceId; } else { if (record.sequenceId == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX) { record.sequenceName = SAMRecord.NO_ALIGNMENT_REFERENCE_NAME; } else { record.sequenceName = samFileHeader.getSequence(record.sequenceId) .getSequenceName(); } } records.add(record); } return records; }

Target:
private ArrayList<CramCompressionRecord> getRecords(final Slice slice, final CompressionHeader header, final ValidationStringency validationStringency) { String seqName = SAMRecord.NO_ALIGNMENT_REFERENCE_NAME; switch (slice.sequenceId) { case SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX: case -2: break; default: final SAMSequenceRecord sequence = samFileHeader .getSequence(slice.sequenceId); seqName = sequence.getSequenceName(); break; } final CramRecordReader reader = slice.createCramRecordReader(header, validationStringency); final ArrayList<CramCompressionRecord> records = new ArrayList<>(slice.nofRecords); int prevAlignmentStart = slice.alignmentStart; for (int i = 0; i < slice.nofRecords; i++) { final CramCompressionRecord record = new CramCompressionRecord(); record.sliceIndex = slice.index; record.index = i; prevAlignmentStart = reader.read(record, prevAlignmentStart); if (record.sequenceId == slice.sequenceId) { record.sequenceName = seqName; record.sequenceId = slice.sequenceId; } else { if (record.sequenceId == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX) { record.sequenceName = SAMRecord.NO_ALIGNMENT_REFERENCE_NAME; } else { record.sequenceName = samFileHeader.getSequence(record.sequenceId) .getSequenceName(); } } records.add(record); } return records; }
Source:
public void selectionChanged(final SelectionChangedEvent event) { final ISelection selection = event.getSelection(); depopulateMenus(); Collection<?> newChildDescriptors = null; if (selection instanceof IStructuredSelection && ((IStructuredSelection) selection).size() == 1) { final Object object = ((IStructuredSelection) selection).getFirstElement(); final EditingDomain domain = ((IEditingDomainProvider) activeEditorPart).getEditingDomain(); newChildDescriptors = domain.getNewChildDescriptors(object, null); } else if (((IStructuredSelection) selection).size() > 1) { newChildDescriptors = Lists.newArrayList(); } if (newChildDescriptors != null) { updateChildDescriptorMenus(selection, newChildDescriptors); } populateMenus(); }

Target:
public void selectionChanged(final SelectionChangedEvent event) { final ISelection selection = event.getSelection(); depopulateMenus(); Collection<?> newChildDescriptors = null; if (selection instanceof IStructuredSelection) { IStructuredSelection stsel = (IStructuredSelection) selection; if (stsel.size() == 1) { final Object object = ((IStructuredSelection) selection).getFirstElement(); final EditingDomain domain = ((IEditingDomainProvider) activeEditorPart).getEditingDomain(); newChildDescriptors = domain.getNewChildDescriptors(object, null); } else if (stsel.size() > 1) { newChildDescriptors = Lists.newArrayList(); } } if (newChildDescriptors != null) { updateChildDescriptorMenus(selection, newChildDescriptors); } populateMenus(); }
Source:
public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); Permanent sourcePermanent = game.getPermanentOrLKIBattlefield(source.getSourceId()); Spell spell = (Spell) game.getStack().getStackObject(targetPointer.getFirst(game, source)); if(sourcePermanent != null && spell != null) { Cost cost = new ManaCostsImpl(spell.getSpellAbility().getManaCosts().getText()); for (UUID playerId : game.getState().getPlayerList(source.getControllerId())) { Player player = game.getPlayer(playerId); if(player.getId() != spell.getControllerId()) { cost.clearPaid(); if (cost.canPay(source, source.getSourceId(), player.getId(), game) && player.chooseUse(outcome, "Pay " + cost.getText() + " to counter " + spell.getIdName() + '?', source, game)) { if (cost.pay(source, game, source.getSourceId(), playerId, false, null)) { game.informPlayers(player.getLogName() + " pays" + cost.getText() + " to counter " + spell.getIdName() + '.'); game.getStack().counter(spell.getId(), source.getSourceId(), game); } } } } } return true; }

Target:
public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); Permanent sourcePermanent = game.getPermanentOrLKIBattlefield(source.getSourceId()); Spell spell = (Spell) game.getStack().getStackObject(targetPointer.getFirst(game, source)); if(sourcePermanent != null && spell != null && controller != null) { Player spellController = game.getPlayer(spell.getControllerId()); Cost cost = new ManaCostsImpl(spell.getSpellAbility().getManaCosts().getText()); if(spellController != null) { for (UUID playerId : game.getState().getPlayersInRange(source.getControllerId(), game)) { Player player = game.getPlayer(playerId); if(player != null && player != spellController) { cost.clearPaid(); if(cost.canPay(source, source.getSourceId(), player.getId(), game) && player.chooseUse(outcome, "Pay " + cost.getText() + " to counter " + spell.getIdName() + '?', source, game)) { if(cost.pay(source, game, source.getSourceId(), playerId, false, null)) { game.informPlayers(player.getLogName() + " pays" + cost.getText() + " to counter " + spell.getIdName() + '.'); game.getStack().counter(spell.getId(), source.getSourceId(), game); return true; } } } } } } return true; }
Source:
public void clickOnWorkspaceStopStartButton(String workspaceName) { String buttonXpath = String.format(WORKSPACE_ITEM_STOP_START_WORKSPACE_BUTTON, workspaceName); waitProgressBarInvisibility(); moveCursorToWorkspaceRamSection(workspaceName); waitWorkspaceActionTooltipDisappearance(); seleniumWebDriverHelper.waitAndClick(By.xpath(buttonXpath)); waitProgressBarInvisibility(); }

Target:
public void clickOnWorkspaceStopStartButton(String workspaceName) { String buttonXpath = String.format(WORKSPACE_ITEM_STOP_START_WORKSPACE_BUTTON, workspaceName); moveCursorToWorkspaceRamSection(workspaceName); waitWorkspaceActionTooltipDisappearance(); seleniumWebDriverHelper.waitAndClick(By.xpath(buttonXpath)); waitProgressBarInvisibility(); }
Source:
public void handle(final I input) { final S state = (S)ssm.read(queryId, operatorId).getState(); final S intermediateState = updateState(input, state); ssm.update(queryId, operatorId, new OperatorState<>(intermediateState)); final O output = generateOutput(intermediateState); LOG.log(Level.FINE, "{0} updates the state {1} with input {2} to {3}, and generates {4}", new Object[]{getOperatorClassName(), state, input, intermediateState, output}); if (output != null) { outputEmitter.emit(output); } }

Target:
public void handle(final I input) { final S state = (S)ssm.read(queryId, operatorId).getState(); final S intermediateState = updateState(input, state); ssm.update(queryId, operatorId, new OperatorState<>(intermediateState)); final O output = generateOutput(intermediateState); LOG.log(Level.FINE, "{0} updates the state {1} with input {2} to {3}, and generates {4}", new Object[]{getOperatorIdentifier(), state, input, intermediateState, output}); if (output != null) { outputEmitter.emit(output); } }
Source:
public void visitArrayAccess(ArrayAccessTree tree) { if (tree.object().is(Tree.Kind.VARIABLE_IDENTIFIER) && tree.offset() != null && tree.offset().is(Tree.Kind.REGULAR_STRING_LITERAL)) { String variable = ((VariableIdentifierTree) tree.object()).text(); String indexValue = trimQuotes((LiteralTree) tree.offset()); if ("argv".equals(indexValue) && SUSPICIOUS_ARRAY_ACCESSES.contains(variable)) { context().newIssue(this, tree, MESSAGE); } } super.visitArrayAccess(tree); }

Target:
public void visitArrayAccess(ArrayAccessTree tree) { ExpressionTree offset = tree.offset(); if (tree.object().is(Tree.Kind.VARIABLE_IDENTIFIER) && offset != null && offset.is(Tree.Kind.REGULAR_STRING_LITERAL)) { String variable = ((VariableIdentifierTree) tree.object()).text(); String indexValue = trimQuotes((LiteralTree) offset); if ("argv".equals(indexValue) && SUSPICIOUS_ARRAY_ACCESSES.contains(variable)) { context().newIssue(this, tree, MESSAGE); } } super.visitArrayAccess(tree); }
Source:
public PartitionClientResponse[] callAllPartitionProcedure(String procedureName, Object... params) throws IOException, NoConnectionsException, ProcCallException { Object[] args = new Object[params.length + 1]; System.arraycopy(params, 0, args, 1, params.length); setPartitions(); int partitionCount = m_partitionKeys.size(); PartitionClientResponse[] responses = new PartitionClientResponse[partitionCount]; for (int key : m_partitionKeys) { args[0] = key; partitionCount--; ClientResponse response = callProcedure(procedureName, args); responses[partitionCount] = new PartitionClientResponse(key, response); } return responses; }

Target:
public ClientResponseWithPartitionKey[] callAllPartitionProcedure(String procedureName, Object... params) throws IOException, NoConnectionsException, ProcCallException { SyncAllPartitionProcedureCallback callBack = new SyncAllPartitionProcedureCallback(); callAllPartitionProcedure(callBack, procedureName, params); return callBack.getResponse(); }
Source:
protected void setLoadedHostsEntries(Collection<HostEntryPair> keys) { keysSupplier = () -> keys; }

Target:
protected void setLoadedHostsEntries(Collection<HostEntryPair> keys) { keysSupplier.set(() -> keys); }
Source:
public void copyPixelsFromBuffer (Buffer dst) { if (isRecycled()) { throw new IllegalStateException("Can't call copyPixelsFromBuffer() on a recycled bitmap"); } if (getBytesPerPixel(config) != 4) { throw new RuntimeException( "Not implemented: only Bitmaps with 4 bytes per pixel are supported"); } if (!(dst instanceof ByteBuffer)) { throw new RuntimeException("Not implemented: unsupported Buffer subclass"); } ByteBuffer byteBuffer = (ByteBuffer) dst; if (byteBuffer.remaining() < colors.length * 4) { throw new RuntimeException("Buffer not large enough for pixels"); } for (int i = 0; i < colors.length; i++) { colors[i] = byteBuffer.getInt(); } }

Target:
public void copyPixelsFromBuffer(Buffer dst) { if (isRecycled()) { throw new IllegalStateException("Can't call copyPixelsFromBuffer() on a recycled bitmap"); } if (getBytesPerPixel(config) != INTERNAL_BYTES_PER_PIXEL) { throw new RuntimeException("Not implemented: only Bitmaps with " + INTERNAL_BYTES_PER_PIXEL + " bytes per pixel are supported"); } if (!(dst instanceof ByteBuffer)) { throw new RuntimeException("Not implemented: unsupported Buffer subclass"); } ByteBuffer byteBuffer = (ByteBuffer) dst; if (byteBuffer.remaining() < colors.length * INTERNAL_BYTES_PER_PIXEL) { throw new RuntimeException("Buffer not large enough for pixels"); } for (int i = 0; i < colors.length; i++) { colors[i] = byteBuffer.getInt(); } }
Source:
public ResponseEntity<?> charge(@RequestBody @Valid ChargeDTO chargeDTO) { LOG.info(" Charge controller new chargeDTO: " + chargeDTO.getDescription()); ChargeDTO resultDTO; try { resultDTO = paymentService.charge(chargeDTO, PaymentType.USER_LICENSE); } catch (ServiceException e) { LOG.log(Level.SEVERE, e.getMessage()); throw new BadRequestException(e.getMessage()); } return new ResponseEntity<>(resultDTO, HttpStatus.OK); }

Target:
public ResponseEntity<ChargeDTO> charge(@RequestBody @Valid ChargeDTO chargeDTO) { LOG.info(" Charge controller new chargeDTO: " + chargeDTO.getDescription()); ChargeDTO resultDTO; try { resultDTO = paymentService.charge(chargeDTO, PaymentType.USER_LICENSE); } catch (ServiceException e) { LOG.log(Level.SEVERE, e.getMessage()); throw new BadRequestException(e.getMessage()); } return new ResponseEntity<>(resultDTO, HttpStatus.OK); }
Source:
public void schedule(Work work, Scheduling scheduling, boolean afterCommit) { String workId = work.getId(); String queueId = getCategoryQueueId(work.getCategory()); if (!isQueuingEnabled(queueId)) { return; } if (afterCommit && scheduleAfterCommit(work, scheduling)) { return; } work.setWorkInstanceState(State.SCHEDULED); WorkSchedulePath.newInstance(work); switch (scheduling) { case ENQUEUE: break; case CANCEL_SCHEDULED: getExecutor(queueId).removeScheduled(workId); WorkStateHelper.setCanceled(work.getId()); break; case IF_NOT_SCHEDULED: case IF_NOT_RUNNING_OR_SCHEDULED: boolean disabled = Boolean.TRUE.booleanValue(); if (!disabled && hasWorkInState(workId, scheduling.state)) { log.debug("Canceling schedule because found: {}", scheduling); return; } break; } if (work.isGroupJoin()) { WorkStateHelper.addGroupJoinWork(work.getPartitionKey()); } queuing.workSchedule(queueId, work); }

Target:
public void schedule(Work work, Scheduling scheduling, boolean afterCommit) { String workId = work.getId(); String queueId = getCategoryQueueId(work.getCategory()); if (!isQueuingEnabled(queueId)) { return; } if (afterCommit && scheduleAfterCommit(work, scheduling)) { return; } work.setWorkInstanceState(State.SCHEDULED); WorkSchedulePath.newInstance(work); switch (scheduling) { case ENQUEUE: break; case CANCEL_SCHEDULED: getExecutor(queueId).removeScheduled(workId); WorkStateHelper.setCanceled(work.getId()); break; case IF_NOT_SCHEDULED: case IF_NOT_RUNNING_OR_SCHEDULED: boolean disabled = Boolean.TRUE.booleanValue(); if (!disabled && hasWorkInState(workId, scheduling.state)) { log.debug("Canceling schedule because found: {}", scheduling); return; } break; } if (work.isGroupJoin()) { log.debug("Submit Work: to GroupJoin: {}", work::getId, work::getPartitionKey); WorkStateHelper.addGroupJoinWork(work.getPartitionKey()); } queuing.workSchedule(queueId, work); }
Source:
public void testAckBeforeSync() throws Exception { File journalDir = tempDir.newFolder(); Bookie.checkDirectoryStructure(Bookie.getCurrentDirectory(journalDir)); ServerConfiguration conf = TestBKConfiguration.newServerConfiguration(); conf.setJournalDirName(journalDir.getPath()) .setZkServers(null); LedgerDirsManager ledgerDirsManager = mock(LedgerDirsManager.class); Journal journal = new Journal(journalDir, conf, ledgerDirsManager); journal.start(); CountDownLatch latch = new CountDownLatch(1); AtomicInteger countForceWriteCallsBeforeAck = new AtomicInteger(); replace(method(JournalChannel.class, "forceWrite")).with(new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { log.info("{} called with arguments ", method.getName(), Arrays.toString(args)); if (latch.getCount() == 1) { countForceWriteCallsBeforeAck.incrementAndGet(); } try { method.invoke(proxy, args); } catch (InvocationTargetException err) { throw err.getCause(); } return null; } }); while (countForceWriteCallsBeforeAck.get() == 0) { Thread.sleep(100); } long ledgerId = 1; long entryId = 0; journal.logAddEntry(ledgerId, entryId, DATA, true , new WriteCallback() { @Override public void writeComplete(int rc, long ledgerId, long entryId, BookieSocketAddress addr, Object ctx) { latch.countDown(); } }, null); assertTrue(latch.await(20, TimeUnit.SECONDS)); assertEquals(1, countForceWriteCallsBeforeAck.get()); journal.shutdown(); }

Target:
public void testAckBeforeSync() throws Exception { File journalDir = tempDir.newFolder(); Bookie.checkDirectoryStructure(Bookie.getCurrentDirectory(journalDir)); ServerConfiguration conf = TestBKConfiguration.newServerConfiguration(); conf.setJournalDirName(journalDir.getPath()) .setZkServers(null); JournalChannel jc = spy(new JournalChannel(journalDir, 1)); whenNew(JournalChannel.class).withAnyArguments().thenReturn(jc); LedgerDirsManager ledgerDirsManager = mock(LedgerDirsManager.class); Journal journal = new Journal(journalDir, conf, ledgerDirsManager); CountDownLatch forceWriteThreadSuspendedLatch = new CountDownLatch(1); enableForceWriteThreadSuspension(forceWriteThreadSuspendedLatch, journal); journal.start(); LogMark lastLogMarkBeforeWrite = journal.getLastLogMark().markLog().getCurMark(); CountDownLatch latch = new CountDownLatch(1); long ledgerId = 1; long entryId = 0; journal.logAddEntry(ledgerId, entryId, DATA, true , new WriteCallback() { @Override public void writeComplete(int rc, long ledgerId, long entryId, BookieSocketAddress addr, Object ctx) { latch.countDown(); } }, null); latch.await(20, TimeUnit.SECONDS); verify(jc, times(0)).forceWrite(true); verify(jc, times(0)).forceWrite(false); LastLogMark lastLogMarkAfterForceWrite = journal.getLastLogMark(); assertEquals(0, lastLogMarkAfterForceWrite.getCurMark().compare(lastLogMarkBeforeWrite)); forceWriteThreadSuspendedLatch.countDown(); journal.shutdown(); }
Source:
public LeaderPingResult pingLeaderWithUuid(UUID uuid) { Optional<LeaderPingerContext<PingableLeader>> suspectedLeader = getSuspectedLeader(uuid); if (!suspectedLeader.isPresent()) { return LeaderPingResults.pingReturnedFalse(); } LeaderPingerContext<PingableLeader> leader = suspectedLeader.get(); MultiplexingCompletionService<LeaderPingerContext<PingableLeader>, Boolean> multiplexingCompletionService = MultiplexingCompletionService.create(leaderPingExecutors); try { multiplexingCompletionService.submit(leader, () -> leader.pinger().ping()); Future<Map.Entry<LeaderPingerContext<PingableLeader>, Boolean>> pingFuture = multiplexingCompletionService .poll(leaderPingResponseWait.toMillis(), TimeUnit.MILLISECONDS); return getLeaderPingResult(uuid, pingFuture); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); return LeaderPingResults.pingCallFailure(ex); } catch (RejectedExecutionException ex) { log.warn("Could not ping the leader, because the executor used to talk to that node is overloaded", ex); return LeaderPingResults.pingCallFailure(ex); } }

Target:
public LeaderPingResult pingLeaderWithUuid(UUID uuid) { Optional<LeaderPingerContext<PingableLeader>> suspectedLeader = getSuspectedLeader(uuid); if (!suspectedLeader.isPresent()) { return LeaderPingResults.pingReturnedFalse(); } LeaderPingerContext<PingableLeader> leader = suspectedLeader.get(); MultiplexingCompletionService<LeaderPingerContext<PingableLeader>, Boolean> multiplexingCompletionService = MultiplexingCompletionService.create(leaderPingExecutors); try { multiplexingCompletionService.submit(leader, () -> leader.pinger().ping()); Future<Map.Entry<LeaderPingerContext<PingableLeader>, Boolean>> pingFuture = multiplexingCompletionService .poll(leaderPingResponseWait.toMillis(), TimeUnit.MILLISECONDS); return getLeaderPingResult(uuid, pingFuture); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return LeaderPingResults.pingCallFailure(e); } catch (RejectedExecutionException e) { log.warn("Could not ping the leader, because the executor used to talk to that node is overloaded", e); return LeaderPingResults.pingCallFailure(e); } }
Source:
private void shareShortAppInviteLink(String longUrl) { FirebaseDynamicLinksHub firebaseDynamicLinksHub = App.from(activity).getFirebaseDynamicLinksHub(); String requestString = "{\"longDynamicLink\": \"" + longUrl + "\",\"suffix\": {\"option\": \"SHORT\"}}"; RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), requestString); firebaseDynamicLinksHub.getShortenedUrl(BuildConfig.FIREBASE_WEB_API_KEY, body).enqueue(new Callback<FirebaseDynamicLinksResponse>() { @Override public void onSuccess(FirebaseDynamicLinksResponse response) { createChooser(HttpUrl.parse(response.getShortLink())); shareProgressDialog.dismiss(); } @Override public void onError() { createChooser(NON_SIGNED_IN_INVITE_URL); shareProgressDialog.dismiss(); } }); }

Target:
private void shareShortAppInviteLink(String longUrl) { FirebaseDynamicLinks firebaseDynamicLinks = App.from(activity).getFirebaseDynamicLinks(); FirebaseDynamicLinksRequest firebaseDynamicLinksRequest = new FirebaseDynamicLinksRequest(longUrl, new Suffix()); firebaseDynamicLinks.shortenUrl(BuildConfig.IP_SIMPLE_API_ACCESS_KEY, firebaseDynamicLinksRequest) .enqueue(new Callback<FirebaseDynamicLinksResponse>() { @Override public void onSuccess(FirebaseDynamicLinksResponse response) { createChooser(HttpUrl.parse(response.getShortLink())); shareProgressDialog.dismiss(); } @Override public void onError() { createChooser(NON_SIGNED_IN_INVITE_URL); shareProgressDialog.dismiss(); } }); }
Source:
protected String getNonNullRequestParamValue(String paramName) { String value = getRequestParamValue(paramName); Assumption.assertPostParamNotNull(paramName, value); return value; }

Target:
protected String getNonNullRequestParamValue(String paramName) { return getNonNullRequestParamValues(paramName)[0]; }
Source:
protected void analyzeBFB(BasicFBType basicFBType) { ECC ecc = basicFBType.getECC(); int nrstates = ecc.getECState().size(); int nrtransitions = ecc.getECTransition().size(); double ccfb = (nrtransitions - nrstates + 2); for (ECState state : ecc.getECState()) { for (ECAction action : state.getECAction()) { if (null != action.getAlgorithm()) { ccfb += analyzeAlgorithm(action.getAlgorithm()); } } } ccapp += ccfb; metrics.add(new MetricData("Cyclomatic Number " + basicFBType.getName(), ccfb)); }

Target:
protected void analyzeBFB(BasicFBType basicFBType) { ECC ecc = basicFBType.getECC(); double ccfb = (ecc.getECTransition().size() - ecc.getECState().size() + 2); for (ECState state : ecc.getECState()) { for (ECAction action : state.getECAction()) { if (null != action.getAlgorithm()) { ccfb += analyzeAlgorithm(action.getAlgorithm()); } } } ccapp += ccfb; metrics.add(new MetricData("Cyclomatic Number " + basicFBType.getName(), ccfb)); }
Source:
private KafkaIndexTask createTask( final String taskId, final DataSchema dataSchema, final KafkaIOConfig ioConfig ) { final KafkaTuningConfig tuningConfig = new KafkaTuningConfig( 1000, null, maxRowsPerSegment, new Period("P1Y"), null, null, null, true, reportParseExceptions, handoffConditionTimeout, resetOffsetAutomatically, null, intermediateHandoffPeriod ); final Map<String, Object> context = isIncrementalHandoffSupported ? ImmutableMap.of(KafkaSupervisor.IS_INCREMENTAL_HANDOFF_SUPPORTED, true) : null; final KafkaIndexTask task = new KafkaIndexTask( taskId, null, cloneDataSchema(dataSchema), tuningConfig, ioConfig, context, null, null ); task.setPollRetryMs(POLL_RETRY_MS); return task; }

Target:
private KafkaIndexTask createTask( final String taskId, final DataSchema dataSchema, final KafkaIOConfig ioConfig ) { final KafkaTuningConfig tuningConfig = new KafkaTuningConfig( 1000, null, maxRowsPerSegment, new Period("P1Y"), null, null, null, true, reportParseExceptions, handoffConditionTimeout, resetOffsetAutomatically, null, intermediateHandoffPeriod, logParseExceptions, maxParseExceptions, maxSavedParseExceptions ); final Map<String, Object> context = isIncrementalHandoffSupported ? ImmutableMap.of(KafkaSupervisor.IS_INCREMENTAL_HANDOFF_SUPPORTED, true) : null; final KafkaIndexTask task = new KafkaIndexTask( taskId, null, cloneDataSchema(dataSchema), tuningConfig, ioConfig, context, null, null ); task.setPollRetryMs(POLL_RETRY_MS); return task; }
Source:
public String toString() { return prow + " " + pcol + " " + (isWrite ? "WRITE" : "NOT_WRITE") + " " + (isDelete ? "DELETE" : "NOT_DELETE") + " " + (isTrigger ? "TRIGGER" : "NOT_TRIGGER") + " " + transactor; }

Target:
public String toString() { return prow + " " + pcol + " " + (isWrite ? "WRITE" : "NOT_WRITE") + " " + (isDelete ? "DELETE" : "NOT_DELETE") + " " + (isTrigger ? "TRIGGER" : "NOT_TRIGGER") + " " + TransactorID.longToString(transactor); }
Source:
public void setUp(boolean enableRemote) throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.client.refresh.interval", CLIENT_REFRESH_RATE); ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "false"); if (enableRemote) { ConfigurationManager.getConfigInstance().setProperty("eureka.fetchRemoteRegionsRegistry", REMOTE_REGION); } ConfigurationManager.getConfigInstance().setProperty("eureka.myregion.availabilityZones", REMOTE_ZONE); ConfigurationManager.getConfigInstance().setProperty("eureka.backupregistry", MockBackupRegistry.class.getName()); ConfigurationManager.getConfigInstance().setProperty("eureka.serviceUrl.default", "http://localhost:" + NOT_AVAILABLE_EUREKA_PORT + MockRemoteEurekaServer.EUREKA_API_BASE_PATH); InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(); builder.setIPAddr("10.10.101.00"); builder.setHostName("Hosttt"); builder.setAppName("EurekaTestApp-" + UUID.randomUUID()); builder.setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }); ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig(), builder.build()); backupRegistry = new MockBackupRegistry(); setupBackupMock(); client = new DiscoveryClient(applicationInfoManager, new DefaultEurekaClientConfig(), null, new Provider<BackupRegistry>() { @Override public BackupRegistry get() { return backupRegistry; } }); }

Target:
public void setUp(boolean enableRemote) throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.client.refresh.interval", CLIENT_REFRESH_RATE); ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "false"); if (enableRemote) { ConfigurationManager.getConfigInstance().setProperty("eureka.fetchRemoteRegionsRegistry", REMOTE_REGION); } ConfigurationManager.getConfigInstance().setProperty("eureka.myregion.availabilityZones", REMOTE_ZONE); ConfigurationManager.getConfigInstance().setProperty("eureka.backupregistry", MockBackupRegistry.class.getName()); ConfigurationManager.getConfigInstance().setProperty("eureka.serviceUrl.default", "http://localhost:" + NOT_AVAILABLE_EUREKA_PORT + MockRemoteEurekaServer.EUREKA_API_BASE_PATH); InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(); builder.setIPAddr("10.10.101.00"); builder.setHostName("Hosttt"); builder.setAppName("EurekaTestApp-" + UUID.randomUUID()); builder.setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }); ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig(), builder.build()); backupRegistry = new MockBackupRegistry(); setupBackupMock(); client = new DiscoveryClient( applicationInfoManager, new DefaultEurekaClientConfig(), null, Providers.of((BackupRegistry)backupRegistry) ); }
Source:
void fixStateIfRequired() throws IOException, StoreException { if (CompactionLog.isCompactionInProgress(dataDir.getAbsolutePath(), storeId)) { compactionLog = new CompactionLog(dataDir.getAbsolutePath(), storeId, storeKeyFactory, time); CompactionLog.Phase phase = compactionLog.getCompactionPhase(); switch (phase) { case COMMIT: commit(true); compactionLog.markCleanupStart(); case CLEANUP: cleanup(true); compactionLog.markCycleComplete(); break; case COPY: recoveryStartToken = compactionLog.getSafeToken(); case PREPARE: case DONE: break; default: throw new IllegalStateException("Unrecognized compaction phase: " + phase); } if (compactionLog.getCompactionPhase().equals(CompactionLog.Phase.DONE)) { endCompaction(); } } }

Target:
private void fixStateIfRequired() throws IOException, StoreException { if (CompactionLog.isCompactionInProgress(dataDir.getAbsolutePath(), storeId)) { compactionLog = new CompactionLog(dataDir.getAbsolutePath(), storeId, storeKeyFactory, time); CompactionLog.Phase phase = compactionLog.getCompactionPhase(); switch (phase) { case COMMIT: commit(true); compactionLog.markCleanupStart(); case CLEANUP: cleanup(true); compactionLog.markCycleComplete(); break; case COPY: recoveryStartToken = compactionLog.getSafeToken(); case PREPARE: case DONE: break; default: throw new IllegalStateException("Unrecognized compaction phase: " + phase); } if (compactionLog.getCompactionPhase().equals(CompactionLog.Phase.DONE)) { endCompaction(); } } }
Source:
public Object[] factory() { List<Object> tests = new ArrayList<>(3 * 2); for (org.infinispan.configuration.cache.TransactionMode txMode : org.infinispan.configuration.cache.TransactionMode.values()) { if (txMode == org.infinispan.configuration.cache.TransactionMode.NONE) { continue; } for (LockingMode lockingMode : LockingMode.values()) { tests.add(new TopologyChangeFunctionalTest().transactionMode(txMode).lockingMode(lockingMode)); } } return tests.toArray(); }

Target:
public Object[] factory() { return Arrays.stream(org.infinispan.configuration.cache.TransactionMode.values()) .filter(tMode -> tMode != org.infinispan.configuration.cache.TransactionMode.NONE) .flatMap(txMode -> Arrays.stream(LockingMode.values()) .map(lockingMode -> new TopologyChangeFunctionalTest() .transactionMode(txMode) .lockingMode(lockingMode))) .toArray(); }
Source:
protected MapSqlParameterSource createFullParametersMapper(VmDevice entity) { return createIdParameterMapper(entity.getId()) .addValue("device", entity.getDevice()) .addValue("type", entity.getType().getValue()) .addValue("address", entity.getAddress()) .addValue("boot_order", entity.getBootOrder()) .addValue("spec_params", entity.getSpecParams() == null ? null : SerializationFactory .getSerializer() .serialize(entity.getSpecParams())) .addValue("is_managed", entity.getIsManaged()) .addValue("is_plugged", entity.getIsPlugged()) .addValue("is_readonly", entity.getIsReadOnly()) .addValue("alias", entity.getAlias()) .addValue("custom_properties", entity.getCustomProperties()); }

Target:
protected MapSqlParameterSource createFullParametersMapper(VmDevice entity) { return createIdParameterMapper(entity.getId()) .addValue("device", entity.getDevice()) .addValue("type", entity.getType().getValue()) .addValue("address", entity.getAddress()) .addValue("boot_order", entity.getBootOrder()) .addValue("spec_params", entity.getSpecParams() == null ? null : SerializationFactory .getSerializer() .serialize(entity.getSpecParams())) .addValue("is_managed", entity.getIsManaged()) .addValue("is_plugged", entity.getIsPlugged()) .addValue("is_readonly", entity.getIsReadOnly()) .addValue("alias", entity.getAlias()) .addValue("custom_properties", entity.getCustomProperties() == null ? null : SerializationFactory .getSerializer() .serialize(entity.getCustomProperties())); }
Source:
private static MethodTree findEnclosingMethod(Tree tree) { while (!tree.is(Tree.Kind.CLASS, Tree.Kind.METHOD)) { tree = tree.parent(); } if (tree.is(Tree.Kind.CLASS)) { return null; } return (MethodTree) tree; }

Target:
public static MethodTree findEnclosingMethod(Tree tree) { while (!tree.is(Tree.Kind.CLASS, Tree.Kind.METHOD)) { tree = tree.parent(); } if (tree.is(Tree.Kind.CLASS)) { return null; } return (MethodTree) tree; }
Source:
void setUlimit(Instance instance, Map<String, Object> fromInspect) { Object ulimits = CollectionUtils.getNestedValue(fromInspect, HOST_CONFIG, "Ulimits"); if (ulimits == null) { return; } List<Ulimit> ret = new ArrayList<>(); if (ulimits instanceof List) { for (Object ulimit : (List<Object>) ulimits) { if (ulimit instanceof Map) { Ulimit l = new Ulimit(); Map<String, Object> temp = (Map<String, Object>) ulimit; if (temp.get("Name") instanceof String) { l.setName(temp.get("Name").toString()); } if (temp.get("Hard") instanceof Integer) { l.setHard((Integer) temp.get("Hard")); } if (temp.get("Soft") instanceof Integer) { l.setSoft((Integer) temp.get("Soft")); } if (!l.getName().isEmpty()) { ret.add(l); } } } } setField(instance, FIELD_ULIMITS, ret); }

Target:
void setUlimit(Instance instance, Map<String, Object> fromInspect) { Object ulimits = CollectionUtils.getNestedValue(fromInspect, HOST_CONFIG, "Ulimits"); if (ulimits == null) { return; } List<Ulimit> ret = new ArrayList<>(); if (ulimits instanceof List) { for (Object ulimit : (List<Object>) ulimits) { if (ulimit instanceof Map) { Ulimit l = new Ulimit(); Map<String, Object> temp = (Map<String, Object>) ulimit; if (temp.get("Name") instanceof String) { l.setName(temp.get("Name").toString()); } if (temp.get("Hard") instanceof Number) { l.setHard(((Number) temp.get("Hard")).intValue()); } if (temp.get("Soft") instanceof Integer) { l.setSoft(((Number) temp.get("Soft")).intValue()); } if (!l.getName().isEmpty()) { ret.add(l); } } } } if (!ret.isEmpty()) { setField(instance, FIELD_ULIMITS, ret); } }
Source:
private Map getViews(){ Map allViews = new HashMap<>(); allViews.put( ViewType.CLI, getCliViews() ); allViews.put( ViewType.JSON, getJsonViews() ); return allViews; }

Target:
private Map getViews(){ final Map allViews = new HashMap<>(); allViews.put( ViewType.CLI, getCliViews() ); allViews.put( ViewType.JSON, getJsonViews() ); return allViews; }