auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Object execute(CommandContext commandContext) { EnsureUtil.ensureNotNull("licenseKey", LicenseKey); AuthorizationManager authorizationManager = commandContext.getAuthorizationManager(); authorizationManager.checkCamundaAdmin(); final ResourceManager resourceManager = commandContext.getResourceManager(); ResourceEntity key = resourceManager.findLicenseKeyResource(); if (key != null) { new DeleteLicenseKeyCmd(false).execute(commandContext); } key = new ResourceEntity(); key.setName(LICENSE_KEY_PROPERTY_NAME); key.setBytes(LicenseKey.getBytes()); resourceManager.insertResource(key); new SetPropertyCmd(LICENSE_KEY_BYTE_ARRAY_ID, key.getId()).execute(commandContext); new DeletePropertyCmd(LICENSE_KEY_PROPERTY_NAME).execute(commandContext); return null; }

Target:
public Object execute(CommandContext commandContext) { EnsureUtil.ensureNotNull("licenseKey", licenseKey); AuthorizationManager authorizationManager = commandContext.getAuthorizationManager(); authorizationManager.checkCamundaAdmin(); final ResourceManager resourceManager = commandContext.getResourceManager(); ResourceEntity key = resourceManager.findLicenseKeyResource(); if (key != null) { new DeleteLicenseKeyCmd(false).execute(commandContext); } key = new ResourceEntity(); key.setName(LICENSE_KEY_PROPERTY_NAME); key.setBytes(licenseKey.getBytes(StandardCharsets.UTF_8)); resourceManager.insertResource(key); new SetPropertyCmd(LICENSE_KEY_BYTE_ARRAY_ID, key.getId()).execute(commandContext); new DeletePropertyCmd(LICENSE_KEY_PROPERTY_NAME).execute(commandContext); return null; }
Source:
public boolean visit(MethodDeclaration node) { if (isMethod(node, "android.widget.TextView", "onDraw", "android.graphics.Canvas")) { final ASTBuilder b = this.ctx.getASTBuilder(); final Refactorings r = this.ctx.getRefactorings(); node.accept(new OnDrawTransformer(this.ctx, node)); } return VISIT_SUBTREE; }

Target:
public boolean visit(MethodDeclaration node) { if (isMethod(node, "android.widget.TextView", "onDraw", "android.graphics.Canvas")) { node.accept(new OnDrawTransformer(this.ctx, node)); } return VISIT_SUBTREE; }
Source:
public void marshallAsXml(final ModelNode model, final OutputStream output) throws ConfigurationPersistenceException { final XMLMapper mapper = XMLMapper.Factory.create(); try { XMLStreamWriter streamWriter = null; try { streamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(output); ModelMarshallingContext extensibleModel = new ModelMarshallingContext() { @Override public ModelNode getModelNode() { return model; } @Override public XMLElementWriter<SubsystemMarshallingContext> getSubsystemWriter(String extensionName) { return subsystemWriters.computeIfAbsent(extensionName, name -> subsystemWriterSuppliers.getOrDefault(name, () -> null).get()); } }; mapper.deparseDocument(rootDeparser, extensibleModel, streamWriter); streamWriter.close(); subsystemWriters.clear(); } finally { safeClose(streamWriter); } } catch (Exception e) { throw ControllerLogger.ROOT_LOGGER.failedToWriteConfiguration(e); } }

Target:
public void marshallAsXml(final ModelNode model, final OutputStream output) throws ConfigurationPersistenceException { final XMLMapper mapper = XMLMapper.Factory.create(); final Map<String, XMLElementWriter<SubsystemMarshallingContext>> subsystemWriters = new ConcurrentHashMap<>(); try { XMLStreamWriter streamWriter = null; try { streamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(output); final ModelMarshallingContext extensibleModel = new ModelMarshallingContext() { @Override public ModelNode getModelNode() { return model; } @Override public XMLElementWriter<SubsystemMarshallingContext> getSubsystemWriter(String extensionName) { return subsystemWriters.computeIfAbsent(extensionName, name -> subsystemWriterSuppliers.getOrDefault(name, () -> null).get()); } }; mapper.deparseDocument(rootDeparser, extensibleModel, streamWriter); streamWriter.close(); } finally { safeClose(streamWriter); } } catch (Exception e) { throw ControllerLogger.ROOT_LOGGER.failedToWriteConfiguration(e); } }
Source:
protected void onInit() throws Exception { super.onInit(); if (this.extractPayload) { Assert.notNull(this.serializer, "'serializer' has to be provided where 'expectMessage == true'."); } if (this.taskExecutor == null) { String beanName = this.getComponentName(); this.taskExecutor = new SimpleAsyncTaskExecutor((beanName == null ? "" : beanName + "-") + this.getComponentType()); } if (!(this.taskExecutor instanceof ErrorHandlingTaskExecutor) && this.getBeanFactory() != null) { MessagePublishingErrorHandler errorHandler = new MessagePublishingErrorHandler(new BeanFactoryChannelResolver(this.getBeanFactory())); errorHandler.setDefaultErrorChannel(this.errorChannel); this.taskExecutor = new ErrorHandlingTaskExecutor(this.taskExecutor, errorHandler); } }

Target:
protected void onInit() throws Exception { super.onInit(); if (this.expectMessage) { Assert.notNull(this.serializer, "'serializer' has to be provided where 'expectMessage == true'."); } if (this.taskExecutor == null) { String beanName = this.getComponentName(); this.taskExecutor = new SimpleAsyncTaskExecutor((beanName == null ? "" : beanName + "-") + this.getComponentType()); } if (!(this.taskExecutor instanceof ErrorHandlingTaskExecutor) && this.getBeanFactory() != null) { MessagePublishingErrorHandler errorHandler = new MessagePublishingErrorHandler(new BeanFactoryChannelResolver(this.getBeanFactory())); errorHandler.setDefaultErrorChannel(this.errorChannel); this.taskExecutor = new ErrorHandlingTaskExecutor(this.taskExecutor, errorHandler); } }
Source:
public void connect() throws DeploymentException { super.connect(); String request = MessageFormat.format(QUERY_FB_TYPES, getNextId()); try { QueryResponseHandler queryResp = sendQUERY("", request); setTypes(queryResp.getQueryResult()); } catch (Exception e) { logger.error(MessageFormat.format(Messages.DTL_QueryFailed, "FB Types")); } }

Target:
public void connect() throws DeploymentException { super.connect(); queryFBTypes(); }
Source:
public void run() { try { while (!stop) { out.write(block); out.hflush(); blocksWritten++; } }catch (IOException e){ e.printStackTrace(); } }

Target:
public void run() { try { while (!stop) { out.write(block); out.hflush(); blocksWritten++; } }catch (IOException e){ LOG.info(e.toString(),e); } }
Source:
protected void executeCommand() { Collection<NetworkCluster> attachments = getParameters().getAttachments(); Collection<NetworkCluster> updates = getParameters().getUpdates(); updates.addAll(updatingDefaultRouteNetwork .whenMovingDefaultRouteRoleCheckIfCurrentNetworkIsAlsoUpdated(updates)); Boolean dbUpdateResult = TransactionSupport.executeInNewTransaction(() -> { final List<NetworkCluster> managementNetworkAttachments = attachments.stream().filter(networkRolePredicates::becomingManagementNetwork).collect(Collectors.toList()); final List<NetworkCluster> nonManagementNetworkAttachments = attachments.stream().filter(becomingManagementNetworkPredicate.negate()).collect(Collectors.toList()); final List<NetworkCluster> managementNetworkUpdates = updates.stream().filter(becomingManagementNetworkPredicate).collect(Collectors.toList()); final List<NetworkCluster> nonManagementNetworkUpdates = updates.stream().filter(becomingManagementNetworkPredicate.negate()).collect(Collectors.toList()); boolean resultStatus = attachNetworks(managementNetworkAttachments); resultStatus = resultStatus && updateNetworkAttachments(managementNetworkUpdates); resultStatus = resultStatus && attachNetworks(nonManagementNetworkAttachments); resultStatus = resultStatus && updateNetworkAttachments(nonManagementNetworkUpdates); resultStatus = resultStatus && detachNetworks(getParameters().getDetachments()); return resultStatus; }); setSucceeded(dbUpdateResult); if (dbUpdateResult) { propagateNetworksChanges(); } }

Target:
protected void executeCommand() { Collection<NetworkCluster> attachments = getParameters().getAttachments(); Collection<NetworkCluster> updates = getParameters().getUpdates(); updates.addAll(updatingDefaultRouteNetwork .whenMovingDefaultRouteRoleCheckIfCurrentNetworkIsAlsoUpdated(updates)); Boolean dbUpdateResult = TransactionSupport.executeInNewTransaction(() -> { List<NetworkCluster> managementNetworkAttachments = becomesManagementNetwork(attachments); List<NetworkCluster> managementNetworkUpdates = becomesManagementNetwork(updates); List<NetworkCluster> nonManagementNetworkAttachments = stopBeingManagementNetwork(attachments); List<NetworkCluster> nonManagementNetworkUpdates = stopBeingManagementNetwork(updates); boolean resultStatus = attachNetworks(managementNetworkAttachments); resultStatus = resultStatus && updateNetworkAttachments(managementNetworkUpdates); resultStatus = resultStatus && attachNetworks(nonManagementNetworkAttachments); resultStatus = resultStatus && updateNetworkAttachments(nonManagementNetworkUpdates); resultStatus = resultStatus && detachNetworks(getParameters().getDetachments()); return resultStatus; }); setSucceeded(dbUpdateResult); if (dbUpdateResult) { propagateNetworksChanges(); } }
Source:
private ApiInfo apiInfo() { Collection<VendorExtension> vendorExtensions = new ArrayList<>(); return new ApiInfo( "Oppijan verkkopalvelukokonaisuus / ePerusteet rajapinta", "", "Spring MVC API based on the swagger 2.0 and 1.2 specification", "<LINK_0>", null, "EUPL 1.1", "<LINK_1>", vendorExtensions); }

Target:
private ApiInfo apiInfo() { return new ApiInfo( "Oppijan verkkopalvelukokonaisuus / ePerusteet rajapinta", "", "Spring MVC API based on the swagger 2.0 and 1.2 specification", "<LINK_0>", null, "EUPL 1.1", "<LINK_1>", new ArrayList<>()); }
Source:
public int TextAlignment() { return 0; }

Target:
public int TextAlignment() { return textAlignment; }
Source:
private static Set<FileFormat> getFileFormatsFromDatabase(FileFormatDAO fileFormatDAO, Set<FileFormat> fileFormats) { Set<FileFormat> fileFormatsFromDB = new HashSet<>(); fileFormats.forEach(fileFormat -> { FileFormat fileFormatFromDB = fileFormatDAO.findByLabelValue(fileFormat.getValue()); if (fileFormatFromDB != null) { fileFormatsFromDB.add((fileFormatFromDB)); } else { fileFormatFromDB = new FileFormat(); fileFormatFromDB.setValue(fileFormat.getValue()); String id = fileFormatDAO.create(fileFormatFromDB); fileFormatsFromDB.add(fileFormatDAO.findByLabelValue(id)); } }); return fileFormatsFromDB; }

Target:
private static Set<FileFormat> getFileFormatsFromDatabase(FileFormatDAO fileFormatDAO, Set<FileFormat> fileFormats) { Set<FileFormat> fileFormatsFromDB = new HashSet<>(); fileFormats.forEach(fileFormat -> { FileFormat fileFormatFromDB = fileFormatDAO.findFileFormatByValue(fileFormat.getValue()); if (fileFormatFromDB != null) { fileFormatsFromDB.add((fileFormatFromDB)); } else { fileFormatFromDB = new FileFormat(); fileFormatFromDB.setValue(fileFormat.getValue()); String id = fileFormatDAO.create(fileFormatFromDB); fileFormatsFromDB.add(fileFormatDAO.findFileFormatByValue(id)); } }); return fileFormatsFromDB; }
Source:
protected Message doReceiveNoWait(final String queueName) { Message message = execute(channel -> { GetResponse response = channel.basicGet(queueName, !isChannelTransacted()); if (response != null) { long deliveryTag = response.getEnvelope().getDeliveryTag(); if (isChannelLocallyTransacted(channel)) { channel.basicAck(deliveryTag, false); channel.txCommit(); } else if (isChannelTransacted()) { ConnectionFactoryUtils.registerDeliveryTag(getConnectionFactory(), channel, deliveryTag); } return RabbitTemplate.this.buildMessageFromResponse(response); } return null; }, obtainTargetConnectionFactory(this.receiveConnectionFactorySelectorExpression, queueName), false); logReceived(message); return message; }

Target:
protected Message doReceiveNoWait(final String queueName) { Message message = execute(channel -> { GetResponse response = channel.basicGet(queueName, !isChannelTransacted()); if (response != null) { long deliveryTag = response.getEnvelope().getDeliveryTag(); if (isChannelLocallyTransacted(channel)) { channel.basicAck(deliveryTag, false); channel.txCommit(); } else if (isChannelTransacted()) { ConnectionFactoryUtils.registerDeliveryTag(getConnectionFactory(), channel, deliveryTag); } return RabbitTemplate.this.buildMessageFromResponse(response); } return null; }, obtainTargetConnectionFactory(this.receiveConnectionFactorySelectorExpression, queueName)); logReceived(message); return message; }
Source:
public void onLongPress(int position) { beginRemoveLanguageMode(); toggleSelectedLanguage(wikipediaLanguages.get(position)); adapter.notifyDataSetChanged(); }

Target:
public void onLongPress(int position) { if (actionMode == null) { beginRemoveLanguageMode(); } toggleSelectedLanguage(wikipediaLanguages.get(position)); adapter.notifyDataSetChanged(); }
Source:
public static String filter(String correlationId) { if (correlationId != null && correlationId.length() > 0) { correlationId = correlationId.replaceAll("[^A-Za-z0-9]", ""); if (correlationId.length() > 0) { return correlationId.substring(0, Math.min(correlationId.length(), 32)); } } return null; }

Target:
private static String filter(String correlationId) { if (StringUtils.isNotEmpty(correlationId)) { correlationId = correlationId.replaceAll("[^A-Za-z0-9]", ""); if (StringUtils.isNotEmpty(correlationId)) { return correlationId.substring(0, Math.min(correlationId.length(), 32)); } } return null; }
Source:
public void theCoupleGMeterRequestIsReceivedForEMeter(final String gasMeter, final String eMeter) throws WebServiceSecurityException { final CoupleMbusDeviceRequest request = CoupleMbusDeviceRequestFactory.forGatewayMbusDeviceAndChannel(eMeter, gasMeter); final CoupleMbusDeviceAsyncResponse asyncResponse = this.smartMeteringInstallationClient .coupleMbusDevice(request); this.checkAndSaveCorrelationId(asyncResponse.getCorrelationUid()); }

Target:
public void theCoupleGMeterRequestIsReceivedForEMeter(final String gasMeter, final String eMeter) throws WebServiceSecurityException { final CoupleMbusDeviceRequest request = CoupleMbusDeviceRequestFactory.forGatewayMbusDevice(eMeter, gasMeter); final CoupleMbusDeviceAsyncResponse asyncResponse = this.smartMeteringInstallationClient .coupleMbusDevice(request); this.checkAndSaveCorrelationId(asyncResponse.getCorrelationUid()); }
Source:
public String sign(String msg) { try { RSAPrivateKey key = getPrivateKey(); Signature sig = Signature.getInstance(SIGNING_ALGORITHM + "with" + key.getAlgorithm()); sig.initSign(key); sig.update(msg.getBytes("UTF8")); return hudson.remoting.Base64.encode(sig.sign()); } catch (GeneralSecurityException e) { throw new SecurityException(e); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } }

Target:
public String sign(String msg) { try { RSAPrivateKey key = getPrivateKey(); Signature sig = Signature.getInstance(SIGNING_ALGORITHM + "with" + key.getAlgorithm()); sig.initSign(key); sig.update(msg.getBytes("UTF-8")); return hudson.remoting.Base64.encode(sig.sign()); } catch (GeneralSecurityException e) { throw new SecurityException(e); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } }
Source:
public void fetchTestInfo(final Collection<TaskDataDto> taskDataDtos, final boolean enableTree) { TestInfoService.Async.getInstance().getTestInfos(taskDataDtos, new AsyncCallback<Map<TaskDataDto, Map<String, TestInfoDto>>>() { @Override public void onFailure(Throwable caught) { caught.printStackTrace(); new ExceptionPanel(place, caught.getMessage()); if (enableTree) enableControl(); } @Override public void onSuccess(Map<TaskDataDto, Map<String, TestInfoDto>> result) { SessionComparisonPanel scp = summaryPanel.getSessionComparisonPanel(); for (TaskDataDto td : result.keySet()) { scp.addTestInfo(td, result.get(td)); } } }); }

Target:
public void fetchTestInfo(final Collection<TaskDataDto> taskDataDtos, final boolean enableTree) { TestInfoService.Async.getInstance().getTestInfos(taskDataDtos, new AsyncCallback<Map<TaskDataDto, Map<String, TestInfoDto>>>() { @Override public void onFailure(Throwable caught) { caught.printStackTrace(); new ExceptionPanel(place, caught.getMessage()); if (enableTree) enableControl(); } @Override public void onSuccess(Map<TaskDataDto, Map<String, TestInfoDto>> result) { SessionComparisonPanel scp = summaryPanel.getSessionComparisonPanel(); for (TaskDataDto td : result.keySet()) { scp.addTestInfo(td, result.get(td)); } if (enableTree) enableControl(); } }); }
Source:
public void unmanage(Entity e) { if (shouldSkipUnmanagement(e)) return; final List<EntityInternal> allEntities = Lists.newArrayList(); final ManagementTransitionInfo info = new ManagementTransitionInfo(managementContext, ManagementTransitionMode.NORMAL); recursively(e, new Predicate<EntityInternal>() { public boolean apply(EntityInternal it) { if (shouldSkipUnmanagement(it)) return false; allEntities.add(it); it.getManagementSupport().onManagementStopping(info); return true; } }); for (EntityInternal it : allEntities) { if (shouldSkipUnmanagement(it)) continue; unmanageNonRecursive(it); it.getManagementSupport().onManagementStopped(info); managementContext.getRebindManager().getChangeListener().onUnmanaged(it); if (managementContext.gc != null) managementContext.gc.onUnmanaged(it); }; }

Target:
public void unmanage(Entity e) { if (shouldSkipUnmanagement(e)) return; final List<EntityInternal> allEntities = Lists.newArrayList(); final ManagementTransitionInfo info = new ManagementTransitionInfo(managementContext, ManagementTransitionMode.NORMAL); recursively(e, new Predicate<EntityInternal>() { public boolean apply(EntityInternal it) { if (shouldSkipUnmanagement(it)) return false; allEntities.add(it); it.getManagementSupport().onManagementStopping(info); return true; } }); for (EntityInternal it : allEntities) { if (shouldSkipUnmanagement(it)) continue; unmanageNonRecursive(it); it.getManagementSupport().onManagementStopped(info); managementContext.getRebindManager().getChangeListener().onUnmanaged(it); if (managementContext.gc != null) managementContext.gc.onUnmanaged(it); } }
Source:
public void testHiddenTables() throws IOException { String[] typenames = dataStore.getTypeNames(); for (String name:typenames) { System.out.println(name); System.out.println(tname(name)); assertFalse("Name should not end with 'MDXT_'",name.startsWith("MDXT_")); assertFalse("Name should not end with '$_BKTS'",name.endsWith("$_BKTS")); assertFalse("Name should not end with '$'",name.endsWith("$")); } }

Target:
public void testHiddenTables() throws IOException { String[] typenames = dataStore.getTypeNames(); for (String name:typenames) { assertFalse("Name should not end with 'MDXT_'",name.startsWith("MDXT_")); assertFalse("Name should not end with '$_BKTS'",name.endsWith("$_BKTS")); assertFalse("Name should not end with '$'",name.endsWith("$")); } }
Source:
public void onFileNodeCreated(FileNodeCreatedEvent event) { if (!isUnderGit()) { return; } final String pathName = normalizePath(event.getCreatedNode().getPath()); final String fileName = pathName.substring(pathName.lastIndexOf("/") + 1); ConfirmCallback confirmCallback = new ConfirmCallback() { @Override public void accepted() { Notification successNotification = new StatusNotification(locale.addSuccess(), locale.newFileAddToIndexNotification(fileName), SUCCESS, false, appContext.getCurrentProject().getRootProject(), null); addToIndex(Collections.singletonList(pathName), successNotification); } }; CancelCallback cancelCallback = new CancelCallback() { @Override public void cancelled() { } }; dialogFactory.createConfirmDialog(locale.newFileAddToIndexDialogTitle(), locale.newFileAddToIndexDialogText(fileName), YES_BUTTON, NO_BUTTON, confirmCallback, cancelCallback).show(); }

Target:
public void onFileNodeCreated(FileNodeCreatedEvent event) { if (!isUnderGit()) { return; } final String pathName = normalizePath(event.getCreatedNode().getPath()); final String fileName = pathName.substring(pathName.lastIndexOf("/") + 1); ConfirmCallback confirmCallback = new ConfirmCallback() { @Override public void accepted() { Notification successNotification = new StatusNotification(locale.addSuccess(), locale.newFileAddToIndexNotification(fileName), SUCCESS, false, appContext.getCurrentProject().getRootProject(), null); addToIndex(Collections.singletonList(pathName), successNotification); } }; CancelCallback cancelCallback = new CancelCallback() { @Override public void cancelled() { } }; dialogFactory.createConfirmDialog(locale.newFileAddToIndexDialogTitle(), locale.newFileAddToIndexDialogText(fileName), locale.buttonYes(), locale.buttonNo(), confirmCallback, cancelCallback).show(); }
Source:
private void deployAsFile(Archive archive) throws CommandFailedException, IOException, OperationException { File testDeploymentFile = new File(tmp.getRoot(), archive.getName()); TEST_DEPLOYMENT.as(ZipExporter.class).exportTo(testDeploymentFile, true); client.apply(new Deploy.DeployCmdBuilder(testDeploymentFile).build()); assertDeploymentExists(archive.getName(), true); }

Target:
private void deployAsFile(Archive archive) throws CommandFailedException, IOException, OperationException { File testDeploymentFile = new File(tmp.getRoot(), archive.getName()); TEST_DEPLOYMENT.as(ZipExporter.class).exportTo(testDeploymentFile, true); client.apply(new Deploy.Builder(testDeploymentFile).build()); assertDeploymentExists(archive.getName(), true); }
Source:
public void commit(final Map<TopicPartition, OffsetAndMetadata> offsets) { if (eosEnabled) { maybeBeginTxn(); try { producer.sendOffsetsToTransaction(offsets, applicationId); producer.commitTransaction(); transactionInFlight = false; } catch (final ProducerFencedException error) { throw new TaskMigratedException(taskId, "Producer get fenced trying to commit a transaction", error); } catch (final TimeoutException error) { throw new StreamsException("Timed out while committing transaction via producer for task " + taskId, error); } catch (final KafkaException error) { throw new StreamsException("Error encountered sending offsets and committing transaction " + "via producer for task " + taskId, error); } } else { try { consumer.commitSync(offsets); } catch (final CommitFailedException error) { throw new TaskMigratedException(taskId, "Consumer committing offsets failed, " + "indicating the corresponding thread is no longer part of the group.", error); } catch (final TimeoutException error) { throw new StreamsException("Timed out while committing offsets via consumer for task " + taskId, error); } catch (final KafkaException error) { throw new StreamsException("Error encountered committing offsets via consumer for task " + taskId, error); } } }

Target:
public void commit(final Map<TopicPartition, OffsetAndMetadata> offsets) { if (eosEnabled) { try { maybeBeginTxn(); producer.sendOffsetsToTransaction(offsets, applicationId); producer.commitTransaction(); transactionInFlight = false; } catch (final ProducerFencedException error) { throw new TaskMigratedException(taskId, "Producer get fenced trying to commit a transaction", error); } catch (final TimeoutException error) { throw new StreamsException("Timed out while committing transaction via producer for task " + taskId, error); } catch (final KafkaException error) { throw new StreamsException("Error encountered sending offsets and committing transaction " + "via producer for task " + taskId, error); } } else { try { consumer.commitSync(offsets); } catch (final CommitFailedException error) { throw new TaskMigratedException(taskId, "Consumer committing offsets failed, " + "indicating the corresponding thread is no longer part of the group.", error); } catch (final TimeoutException error) { throw new StreamsException("Timed out while committing offsets via consumer for task " + taskId, error); } catch (final KafkaException error) { throw new StreamsException("Error encountered committing offsets via consumer for task " + taskId, error); } } }
Source:
private void checkInvocation(Tree tree, MethodMatcher invocationMatcher) { if (tree.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree mit = (MethodInvocationTree) tree; if (invocationMatcher.matches(mit)) { onMethodInvocationFound(mit); } } else if (tree.is(Tree.Kind.NEW_CLASS)) { NewClassTree newClassTree = (NewClassTree) tree; if (invocationMatcher.matches(newClassTree)) { onConstructorFound(newClassTree); } } else if (tree.is(Tree.Kind.METHOD_REFERENCE)) { MethodReferenceTree methodReferenceTree = (MethodReferenceTree) tree; if (invocationMatcher.matches(methodReferenceTree.method().symbol())) { onMethodReferenceFound(methodReferenceTree); } } }

Target:
private void checkInvocation(Tree tree, MethodMatcher invocationMatcher) { if (tree.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree mit = (MethodInvocationTree) tree; if (invocationMatcher.matches(mit)) { onMethodInvocationFound(mit); } } else if (tree.is(Tree.Kind.NEW_CLASS)) { NewClassTree newClassTree = (NewClassTree) tree; if (invocationMatcher.matches(newClassTree)) { onConstructorFound(newClassTree); } } else if (tree.is(Tree.Kind.METHOD_REFERENCE)) { MethodReferenceTree methodReferenceTree = (MethodReferenceTree) tree; if (invocationMatcher.matches(methodReferenceTree)) { onMethodReferenceFound(methodReferenceTree); } } }
Source:
protected String concatenateMinMaxValueIfAvailable(final MeasurementVariable measurementVariable) { if (measurementVariable.getMinRange() != null && measurementVariable.getMaxRange() != null) { return measurementVariable.getMinRange().toString() + " - " + measurementVariable.getMaxRange().toString(); } else if(measurementVariable.getMinRange() == null && measurementVariable.getMaxRange() == null) { return NO_RANGE; } else if(measurementVariable.getMinRange() != null && measurementVariable.getMaxRange() == null) { return measurementVariable.getMinRange().toString() + MIN_ONLY; } else { return measurementVariable.getMaxRange().toString() + MAX_ONLY; } }

Target:
protected String concatenateMinMaxValueIfAvailable(final MeasurementVariable measurementVariable) { if (measurementVariable.getMinRange() == null && measurementVariable.getMaxRange() == null) { return NO_RANGE; } else if (measurementVariable.getMaxRange() == null) { return measurementVariable.getMinRange().toString() + MIN_ONLY; } else if (measurementVariable.getMinRange() == null) { return measurementVariable.getMaxRange().toString() + MAX_ONLY; } else { return measurementVariable.getMinRange().toString() + " - " + measurementVariable.getMaxRange().toString(); } }
Source:
private static boolean hasSelfPermission(Context context, String permission) { try { return checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED; } catch (Throwable t) { return false; } }

Target:
private static boolean hasSelfPermission(Context context, String permission) { try { return checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED; } catch (RuntimeException t) { return false; } }
Source:
public void changeStatus(String migrationId, String state) { KeyValueStore kv = getKeyValueStore(); migrationIds.add(migrationId); kv.put(migrationId + STEP, state); kv.put(migrationId + START_TIME, String.valueOf(System.currentTimeMillis())); kv.put(migrationId + PING_TIME, String.valueOf(System.currentTimeMillis())); kv.put(migrationId + PROGRESS_MESSAGE, "Set from MigrationFearure"); kv.put(migrationId + PROGRESS_NUM, String.valueOf(0)); kv.put(migrationId + PROGRESS_TOTAL, String.valueOf(0)); }

Target:
public void changeStatus(String migrationId, String state) { KeyValueStore kv = getKeyValueStore(); migrationIds.add(migrationId); kv.put(migrationId + STEP, state); kv.put(migrationId + START_TIME, String.valueOf(System.currentTimeMillis())); kv.put(migrationId + PING_TIME, String.valueOf(System.currentTimeMillis())); kv.put(migrationId + PROGRESS_MESSAGE, "Set from MigrationFeature"); kv.put(migrationId + PROGRESS_NUM, String.valueOf(0)); kv.put(migrationId + PROGRESS_TOTAL, String.valueOf(0)); }
Source:
public BufferedReader getInput() throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("GET"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); return reader; }

Target:
public BufferedReader getInput() throws IOException { URL url = new URL(urlString); URLConnection connection = url.openConnection(); connection.setDoInput(true); return new BufferedReader(new InputStreamReader(url.openStream())); }
Source:
public int hashCode() { int result = mSourceFile.hashCode(); result = 31 * result + mBuildToolsRevision.hashCode(); return result; }

Target:
public int hashCode() { return Objects.hashCode(mSourceFile, mBuildToolsRevision); }
Source:
public boolean removedByPlayer(@Nonnull IBlockState state, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull EntityPlayer entityPlayer, boolean willHarvest) { TileEntity te = world.getTileEntity(pos); ITravelAccessable ta = (ITravelAccessable) te; if (ta.getOwner().equals(UserIdent.create(entityPlayer.getGameProfile())) || (ta.getAccessMode() == ITravelAccessable.AccessMode.PUBLIC)) { return super.removedByPlayer(state, world, pos, entityPlayer, willHarvest); } else { ChatUtil.sendNoSpam(entityPlayer, Lang.GUI_HARVEST_ERROR_PRIVATE.toChatServer(TextFormatting.RED + ta.getOwner().getPlayerName() + TextFormatting.WHITE)); return false; } }

Target:
public boolean removedByPlayer(@Nonnull IBlockState state, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull EntityPlayer entityPlayer, boolean willHarvest) { TileEntity te = getTileEntity(world, pos); if (te != null) { ITravelAccessable ta = (ITravelAccessable) te; if (ta.getOwner().equals(UserIdent.create(entityPlayer.getGameProfile())) || (ta.getAccessMode() == ITravelAccessable.AccessMode.PUBLIC)) { return super.removedByPlayer(state, world, pos, entityPlayer, willHarvest); } else { if (!world.isRemote) { entityPlayer.sendStatusMessage(Lang.GUI_AUTH_ERROR_HARVEST.toChat(ta.getOwner().getPlayerName()), false); } } } return false; }
Source:
public void getAllTimestampsThrows() { assertThatThrownBy(() -> OneNodeDownTestSuite.kvs.getAllTimestamps(OneNodeDownTestSuite.TEST_TABLE, ImmutableSet.of(OneNodeDownTestSuite.CELL_1_1), Long.MAX_VALUE)) .isExactlyInstanceOf(InsufficientConsistencyException.class) .hasMessageContaining("requires ALL Cassandra nodes to be up and available."); }

Target:
public void getAllTimestampsThrows() { assertThatThrownBy(() -> OneNodeDownTestSuite.kvs.getAllTimestamps(OneNodeDownTestSuite.TEST_TABLE, ImmutableSet.of(OneNodeDownTestSuite.CELL_1_1), Long.MAX_VALUE)) .isExactlyInstanceOf(InsufficientConsistencyException.class) .hasMessageContaining(REQUIRES_ALL_CASSANDRA_NODES); }
Source:
@Override public int getApi() { return com.android.tools.lint.detector.api.ApiKt.CURRENT_API; }

Target:
@Override public int getApi() { return ApiKt.CURRENT_API; }
Source:
public KontaktExtDialog(Shell shell, Kontakt k, String[] defvalues) { super(shell); this.actKontact = k; logger.info("{} fields are: {}", defvalues.length, defvalues); fieldDefinitions = defvalues; Arrays.sort(fieldDefinitions, new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareTo(o2); } }); for (int i = 0; i < fieldDefinitions.length; i++) { logger.trace("field with id {}: {}", i, fieldDefinitions[i]); } }

Target:
public KontaktExtDialog(Shell shell, Kontakt k, String[] defvalues) { super(shell); this.actKontact = k; fieldDefinitions = defvalues; Arrays.sort(fieldDefinitions, new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareTo(o2); } }); }
Source:
public void dispose() { mSimRecords.unregisterForRecordsLoaded(this); mSimCard.unregisterForAbsent(this); mCmdIf.unSetOnStkSessionEnd(this); mCmdIf.unSetOnStkProactiveCmd(this); mCmdIf.unSetOnStkEvent(this); mCmdIf.unSetOnStkCallSetUp(this); this.removeCallbacksAndMessages(null); mSimRecords = null; mSimCard = null; }

Target:
public void dispose() { mSimRecords.unregisterForRecordsLoaded(this); mSimCard.unregisterForAbsent(this); mCmdIf.unSetOnStkSessionEnd(this); mCmdIf.unSetOnStkProactiveCmd(this); mCmdIf.unSetOnStkEvent(this); mCmdIf.unSetOnStkCallSetUp(this); sInstance = null; }
Source:
public void batchUpdate_localRefIsDeletedInLoopOfNativeBatchUpdateQueries() { final Realm realm = looperThread.realm; final int TEST_COUNT = 512; final AtomicBoolean updatesTriggered = new AtomicBoolean(false); final AtomicInteger firstOnChangeCounter = new AtomicInteger(0); final AtomicInteger secondOnChangeCounter = new AtomicInteger(0); final RealmChangeListener<RealmResults<AllTypes>> listener = new RealmChangeListener<RealmResults<AllTypes>>() { @Override public void onChange(RealmResults<AllTypes> element) { if (updatesTriggered.get()) { int count = secondOnChangeCounter.addAndGet(1); if (count == TEST_COUNT) { realm.removeAllChangeListeners(); looperThread.testComplete(); } } else { int count = firstOnChangeCounter.addAndGet(1); if (count == TEST_COUNT) { updatesTriggered.set(true); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.createObject(AllTypes.class); } }); } else { RealmResults<AllTypes> results = realm.where(AllTypes.class).findAllAsync(); results.addChangeListener(this); looperThread.keepStrongReference.add(results); } } } }; RealmResults<AllTypes> results = realm.where(AllTypes.class).findAllAsync(); results.addChangeListener(listener); looperThread.keepStrongReference.add(results); }

Target:
public void batchUpdate_localRefIsDeletedInLoopOfNativeBatchUpdateQueries() { final Realm realm = looperThread.realm; final int TEST_COUNT = 1024; final AtomicBoolean updatesTriggered = new AtomicBoolean(false); final AtomicInteger firstOnChangeCounter = new AtomicInteger(0); final AtomicInteger secondOnChangeCounter = new AtomicInteger(0); final RealmChangeListener<RealmResults<AllTypes>> listener = new RealmChangeListener<RealmResults<AllTypes>>() { @Override public void onChange(RealmResults<AllTypes> element) { if (updatesTriggered.get()) { int count = secondOnChangeCounter.addAndGet(1); if (count == TEST_COUNT) { realm.removeAllChangeListeners(); looperThread.testComplete(); } } else { int count = firstOnChangeCounter.addAndGet(1); if (count == TEST_COUNT) { updatesTriggered.set(true); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.createObject(AllTypes.class); } }); } else { RealmResults<AllTypes> results = realm.where(AllTypes.class).findAllAsync(); results.addChangeListener(this); looperThread.keepStrongReference.add(results); } } } }; RealmResults<AllTypes> results = realm.where(AllTypes.class).findAllAsync(); results.addChangeListener(listener); looperThread.keepStrongReference.add(results); }
Source:
public float getPitch() { float pitch = super.getPitch(); if (Math.abs(pitch) > Math.abs(lastPitch) + NavX.MAX_DEGREES_PER_TICK) { return lastPitch; } if (pitch < 0) { lastPitch = 360 + pitch; return 360 + pitch; } else { lastPitch = pitch; return pitch; } }

Target:
public float getPitch() { float pitch = super.getPitch(); if (Math.abs(pitch - lastPitch) > NavX.MAX_DEGREES_PER_TICK) { return lastPitch; } if (pitch < 0) { lastPitch = 360 + pitch; return 360 + pitch; } else { lastPitch = pitch; return pitch; } }
Source:
public ApiKey generateApiKey() { URI uri = buildUri(getBaseUri()).path("_api/v2/api_keys").build(); HttpConnection connection = Http.POST(uri, "application/json"); return client.executeRequest(connection, ApiKey.class); }

Target:
public ApiKey generateApiKey() { URI uri = buildUri(getBaseUri()).path("_api/v2/api_keys").build(); InputStream response = client.post(uri, null); return getResponse(response, ApiKey.class, getGson()); }
Source:
public void filter(String URL, byte[] content, DocumentFragment doc, ParseResult parse) { ParseData parseData = parse.get(URL); Metadata metadata = parseData.getMetadata(); if (copyKeyName != null) { String signature = metadata.getFirstValue(key_name); if (signature != null) metadata.setValue(copyKeyName, signature); } byte[] data = null; if (useText) { String text = parseData.getText(); if (StringUtils.isNotBlank(text)) { data = text.getBytes(StandardCharsets.UTF_8); } } else { data = content; } if (data == null) { data = URL.getBytes(StandardCharsets.UTF_8); } String hex = DigestUtils.md5Hex(data); metadata.setValue(key_name, hex); }

Target:
public void filter(String URL, byte[] content, DocumentFragment doc, ParseResult parse) { ParseData parseData = parse.get(URL); Metadata metadata = parseData.getMetadata(); if (copyKeyName != null) { String signature = metadata.getFirstValue(key_name); if (signature != null) { metadata.setValue(copyKeyName, signature); } } byte[] data = null; if (useText) { String text = parseData.getText(); if (StringUtils.isNotBlank(text)) { data = text.getBytes(StandardCharsets.UTF_8); } } else { data = content; } if (data == null) { data = URL.getBytes(StandardCharsets.UTF_8); } String hex = DigestUtils.md5Hex(data); metadata.setValue(key_name, hex); }
Source:
public Builder (List<String> statusClassifications) { statusClassifications.stream() .forEach(classification -> { this.numAnomalies++; if (!classification.equals(NOT_CLASSIFIED)) { this.respondedAnomalies++; switch (classification) { case TRUE_POSITIVE: this.truePos++; break; case FALSE_NEGATIVE: this.falseNeg++; break; case FALSE_POSITIVE: this.falsePos++; break; default: break; } } }); }

Target:
public Builder (List<String> statusClassifications) { statusClassifications.stream() .forEach(classification -> { this.numAnomalies++; if (!NOT_CLASSIFIED.equals(classification)) { this.respondedAnomalies++; switch (classification) { case TRUE_POSITIVE: this.truePos++; break; case FALSE_NEGATIVE: this.falseNeg++; break; case FALSE_POSITIVE: this.falsePos++; break; default: break; } } }); }
Source:
public TextButton (String text, TextButtonStyle style) { super(); setStyle(style); this.style = style; LabelStyle labelStyle; if (style.labelStyle == null) { labelStyle = new LabelStyle(style.font, style.fontColor); } else { labelStyle = style.labelStyle.copy(); if (style.font != null) labelStyle.font = style.font; if (style.fontColor != null) labelStyle.fontColor = style.fontColor; } label = labelStyle.createLabel(text); label.setAlignment(Align.center); add(label).expand().fill(); setSize(getPrefWidth(), getPrefHeight()); }

Target:
public TextButton (String text, TextButtonStyle style) { super(); setStyle(style); this.style = style; LabelStyle labelStyle; if (style.labelStyle == null) { labelStyle = new LabelStyle(style.font, style.fontColor); } else { labelStyle = style.labelStyle; } label = labelStyle.createLabel(text); label.setAlignment(Align.center); add(label).expand().fill(); setSize(getPrefWidth(), getPrefHeight()); }
Source:
private void running() { try { while( getTimerThreadState() == TimerThreadState.RUNNING ) { long timeout = getWaitTimeout(); QueueEntry entry = fQueue.peek(); if ( entry != null ) { long commandTimeout = getTimeoutForCommand( entry.fCommandToken.getCommand() ); if ( GdbDebugOptions.DEBUG_TIMEOUTS ) { String commandText = entry.fCommandToken.getCommand().toString(); if ( commandText.endsWith( "\n" ) ) commandText = commandText.substring( 0, commandText.length() - 1 ); GdbDebugOptions.trace( String.format( "Processing command '%s', command timeout is %d", commandText, Long.valueOf( commandTimeout ) ) ); } long currentTime = System.currentTimeMillis(); long elapsedTime = currentTime - entry.fTimestamp; if ( commandTimeout <= elapsedTime ) { processTimedOutCommand( entry.fCommandToken ); fQueue.remove( entry ); QueueEntry nextEntry = fQueue.peek(); if ( nextEntry != null ) { setTimeStamp( currentTime, nextEntry ); } } else { timeout = Math.min( timeout, commandTimeout - elapsedTime ); if ( GdbDebugOptions.DEBUG_TIMEOUTS ) { String commandText = entry.fCommandToken.getCommand().toString(); if ( commandText.endsWith( "\n" ) ) commandText = commandText.substring( 0, commandText.length() - 1 ); GdbDebugOptions.trace( String.format( "Setting timeout %d for command '%s'", Long.valueOf( timeout ), commandText ) ); } } } synchronized( TimerThread.this ) { wait( timeout ); } } } catch( InterruptedException e ) { } }

Target:
private void running() { try { while( getTimerThreadState() == TimerThreadState.RUNNING ) { long timeout = getWaitTimeout(); QueueEntry entry = fQueue.peek(); if ( entry != null ) { long commandTimeout = getTimeoutForCommand( entry.fCommandToken.getCommand() ); if ( GdbDebugOptions.DEBUG_COMMAND_TIMEOUTS ) { String commandText = entry.fCommandToken.getCommand().toString(); if ( commandText.endsWith( "\n" ) ) commandText = commandText.substring( 0, commandText.length() - 1 ); printDebugMessage( String.format( "Processing command '%s', command timeout is %d", commandText, Long.valueOf( commandTimeout ) ) ); } long currentTime = System.currentTimeMillis(); long elapsedTime = currentTime - entry.fTimestamp; if ( commandTimeout <= elapsedTime ) { processTimedOutCommand( entry.fCommandToken ); fQueue.remove( entry ); QueueEntry nextEntry = fQueue.peek(); if ( nextEntry != null ) { setTimeStamp( currentTime, nextEntry ); } } else { timeout = Math.min( timeout, commandTimeout - elapsedTime ); if ( GdbDebugOptions.DEBUG_COMMAND_TIMEOUTS ) { String commandText = entry.fCommandToken.getCommand().toString(); if ( commandText.endsWith( "\n" ) ) commandText = commandText.substring( 0, commandText.length() - 1 ); printDebugMessage( String.format( "Setting timeout %d for command '%s'", Long.valueOf( timeout ), commandText ) ); } } } synchronized( TimerThread.this ) { wait( timeout ); } } } catch( InterruptedException e ) { } }
Source:
public List<Member> getGroupMembers(PerunSession sess, Group group) throws InternalErrorException { try { return jdbc.query("select " + MembersManagerImpl.memberMappingSelectQuery + ", groups_members.membership_type as membership_type, " + "groups_members.source_group_id as source_group_id from groups_members join members on members.id=groups_members.member_id " + "where groups_members.group_id=?", MembersManagerImpl.MEMBER_MAPPER, group.getId()); } catch (EmptyResultDataAccessException e) { return new ArrayList<Member>(); } catch (RuntimeException e) { throw new InternalErrorException(e); } }

Target:
public List<Member> getGroupMembers(PerunSession sess, Group group) throws InternalErrorException { try { return jdbc.query("select " + MembersManagerImpl.memberMappingSelectQuery + ", groups_members.membership_type as membership_type, " + "groups_members.source_group_id as source_group_id from groups_members join members on members.id=groups_members.member_id " + "where groups_members.group_id=?", MembersManagerImpl.GROUPS_MEMBER_MAPPER, group.getId()); } catch (EmptyResultDataAccessException e) { return new ArrayList<Member>(); } catch (RuntimeException e) { throw new InternalErrorException(e); } }
Source:
private ClassName(String packageName, ClassName enclosingClassName, String simpleName, List<AnnotationSpec> annotations) { super(annotations); this.packageName = (packageName != null) ? packageName : NO_PACKAGE; this.enclosingClassName = enclosingClassName; this.simpleName = simpleName; this.canonicalName = enclosingClassName != null ? (enclosingClassName.canonicalName + '.' + simpleName) : (this.packageName.isEmpty() ? simpleName : packageName + '.' + simpleName); }

Target:
private ClassName(String packageName, ClassName enclosingClassName, String simpleName, List<AnnotationSpec> annotations) { super(annotations); this.packageName = Objects.requireNonNull(packageName, "packageName == null"); this.enclosingClassName = enclosingClassName; this.simpleName = simpleName; this.canonicalName = enclosingClassName != null ? (enclosingClassName.canonicalName + '.' + simpleName) : (this.packageName.isEmpty() ? simpleName : packageName + '.' + simpleName); }
Source:
public void testAppConfigurationInitialisation() { try { setupApplicationRoot(); setupHeadless(); FxToolkit.registerPrimaryStage(); FxToolkit.setupFixture(() -> new AnnotationConfigApplicationContext(AppConfiguration.class)); } catch (TimeoutException | IOException e) { e.printStackTrace(); fail(); } }

Target:
public void testAppConfigurationInitialisation() { try { FxToolkit.registerPrimaryStage(); FxToolkit.setupFixture(() -> new AnnotationConfigApplicationContext(AppConfiguration.class)); } catch (TimeoutException e) { e.printStackTrace(); fail(); } }
Source:
public CheckpointStreamFactory resolveCheckpointStorageLocation(long checkpointId, CheckpointStorageLocationReference reference) { return cache.computeIfAbsent(checkpointId, id -> { try { return delegate.resolveCheckpointStorageLocation(checkpointId, reference); } catch (IOException e) { throw new WrappingRuntimeException(e); } }); }

Target:
public CheckpointStreamFactory resolveCheckpointStorageLocation(long checkpointId, CheckpointStorageLocationReference reference) { return cache.computeIfAbsent(checkpointId, id -> { try { return delegate.resolveCheckpointStorageLocation(checkpointId, reference); } catch (IOException e) { throw new FlinkRuntimeException(e); } }); }
Source:
public <E extends Throwable> E expectError(Class<E> expected, long timeoutMillis) throws Exception { return expectError(expected, timeoutMillis, env.defaultPollTimeoutMillis); }

Target:
public <E extends Throwable> E expectError(Class<E> expected, long timeoutMillis) throws Exception { return expectError(expected, timeoutMillis, env.defaultPollTimeoutMillis()); }
Source:
public void testAuthorityInAliasedList() throws IOException { AuthorityValidationMetadataCache.clearAuthorityValidationCache(); final HttpURLConnection mockedConnection = Mockito.mock(HttpURLConnection.class); HttpUrlConnectionFactory.setMockedHttpUrlConnection(mockedConnection); Util.prepareMockedUrlConnection(mockedConnection); Mockito.when(mockedConnection.getInputStream()).thenReturn(Util.createInputStream(getDiscoveryResponse())); Mockito.when(mockedConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); final String authorityUrl1 = "<LINK_0>"; try { final Discovery discovery = new Discovery(); discovery.validateAuthority(new URL(authorityUrl1)); } catch (AuthenticationException e) { fail(); } final String aliasedAuthorityUrl = "<LINK_1>"; try { final Discovery discovery = new Discovery(); discovery.validateAuthority(new URL(aliasedAuthorityUrl)); } catch (AuthenticationException e) { fail(); } final String aliasedAuthorityUrl2 = "<LINK_2>"; try { final Discovery discovery = new Discovery(); discovery.validateAuthority(new URL(aliasedAuthorityUrl2)); } catch (AuthenticationException e) { fail(); } Mockito.verify(mockedConnection, Mockito.times(1)).getInputStream(); }

Target:
public void testAuthorityInAliasedList() throws IOException { final HttpURLConnection mockedConnection = Mockito.mock(HttpURLConnection.class); HttpUrlConnectionFactory.setMockedHttpUrlConnection(mockedConnection); Util.prepareMockedUrlConnection(mockedConnection); Mockito.when(mockedConnection.getInputStream()).thenReturn(Util.createInputStream(getDiscoveryResponse())); Mockito.when(mockedConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); final String authorityUrl1 = "<LINK_0>"; try { final Discovery discovery = new Discovery(); discovery.validateAuthority(new URL(authorityUrl1)); } catch (AuthenticationException e) { fail(); } final String aliasedAuthorityUrl = "<LINK_1>"; try { final Discovery discovery = new Discovery(); discovery.validateAuthority(new URL(aliasedAuthorityUrl)); } catch (AuthenticationException e) { fail(); } final String aliasedAuthorityUrl2 = "<LINK_2>"; try { final Discovery discovery = new Discovery(); discovery.validateAuthority(new URL(aliasedAuthorityUrl2)); } catch (AuthenticationException e) { fail(); } Mockito.verify(mockedConnection, Mockito.times(1)).getInputStream(); }
Source:
public IndexPreprocessor(final String prefix, final String theNamespace_url, final String draftParameter) { this.prefix = prefix; this.namespace_url = theNamespace_url; this.excludedDraftSection.clear(); this.excludedDraftSection.add(false); includeDraft = draftParameter.equals(ARGS_DRAFT_YES) ? true : false; indexDitaProcessor = new IndexDitaProcessor(); indexGroupProcessor = new IndexGroupProcessor(); }

Target:
public IndexPreprocessor(final String prefix, final String theNamespace_url, final String draftParameter) { this.prefix = prefix; this.namespace_url = theNamespace_url; this.excludedDraftSection.clear(); this.excludedDraftSection.add(false); includeDraft = draftParameter.equals(ARGS_DRAFT_YES); indexDitaProcessor = new IndexDitaProcessor(); indexGroupProcessor = new IndexGroupProcessor(); }