auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void updateMetadata(String productName, String metadataName, Metadata metadata) throws APIException { Metadata updatedMetadata; try { updatedMetadata = productManager.loadMetadata(productName, metadataName); } catch (EntityNotFoundException e) { log.warning("The product " + productName + " or metadata: " + metadataName + " does not exist: " + e.getMessage()); throw new APIException(e); } if ((metadata.getKey() != null) && (updatedMetadata.getKey() != null)) { boolean differentKeys = !metadata.getKey().equals(updatedMetadata.getKey()); if (differentKeys) { String message = "Metadata: " + metadataName + " in database has different key to: " + metadata.getKey(); log.warning(message); throw new APIException(new EntityNotFoundException(Metadata.class, "key", metadata.getKey())); } } if (metadata.getDescription() != null) { updatedMetadata.setDescription(metadata.getDescription()); } if (metadata.getValue() != null) { updatedMetadata.setValue(metadata.getValue()); } try { productManager.updateMetadata(updatedMetadata); } catch (Exception e) { throw new APIException(e); } }

Target:
public void updateMetadata(String productName, String metadataName, Metadata metadata) throws APIException { Metadata updatedMetadata; try { updatedMetadata = productManager.loadMetadata(productName, metadataName); } catch (EntityNotFoundException e) { log.warning("The product " + productName + " or metadata: " + metadataName + " does not exist: " + e.getMessage()); throw new APIException(e); } if ((metadata.getKey() != null) && (updatedMetadata.getKey() != null)) { boolean differentKeys = !metadata.getKey().equals(updatedMetadata.getKey()); if (differentKeys) { String message = "Metadata: " + metadataName + " in database has different key to: " + metadata.getKey(); log.warning(message); throw new APIException(new EntityNotFoundException(Metadata.class, "key", metadata.getKey()), 400); } } if (metadata.getDescription() != null) { updatedMetadata.setDescription(metadata.getDescription()); } if (metadata.getValue() != null) { updatedMetadata.setValue(metadata.getValue()); } try { productManager.updateMetadata(updatedMetadata); } catch (Exception e) { throw new APIException(e); } }
Source:
public void before() { PostProcessorDescriptorRegistryImpl<String> registry = new PostProcessorDescriptorRegistryImpl<String>(); registry.put(UMLPostProcessor.class.getName(), new TestPostProcessor.TestPostProcessorDescriptor( Pattern.compile("<LINK_0>\\d\\.0\\.0/UML"), null, new UMLPostProcessor(), 10)); emfCompare = EMFCompare.builder().setPostProcessorRegistry(registry).build(); }

Target:
public void before() { PostProcessorDescriptorRegistryImpl<String> registry = new PostProcessorDescriptorRegistryImpl<String>(); registry.put(UMLPostProcessor.class.getName(), new TestPostProcessor.TestPostProcessorDescriptor( Pattern.compile("<LINK_0>\\d\\.0\\.0/UML"), null, new UMLPostProcessor(), 20)); emfCompare = EMFCompare.builder().setPostProcessorRegistry(registry).build(); }
Source:
public void customizeJdbi(Jdbi jdbi) { if (mapper != null) { jdbi.getConfig(Jackson2Config.class).setMapper(mapper); } jdbi.registerArgument(new JsonArgumentFactory()); jdbi.registerColumnMapper(new JsonColumnMapperFactory()); }

Target:
public void customizeJdbi(Jdbi jdbi) { jdbi.getConfig(JsonConfig.class).setImpl(new JacksonJsonImpl()); super.customizeJdbi(jdbi); }
Source:
private void download(int version) { try { if (metricFile.exists()) metricFile.delete(); info("# Starting download of MetricsModule build: #" + version); AtomicInteger lastPercentPosted = new AtomicInteger(); HttpResponse<File> response = Unirest.get(GH_REPO_RELEASES + "/" + version + "/" + REPO_NAME + ".jar") .downloadMonitor((b, fileName, bytesWritten, totalBytes) -> { int percent = (int) (20 * (Math.round((((double) bytesWritten / totalBytes) * 100) / 20))); if (percent != 0 && percent != lastPercentPosted.get()) { info("# Downloading... " + percent + "% " + "(" + bytesWritten + "/" + totalBytes + " bytes)"); lastPercentPosted.set(percent); } }) .asFile(metricFile.getPath()); if (response.isSuccess()) { info("Successfully downloaded " + REPO_NAME + " build: " + version); metricVersion = String.valueOf(version); } else metricFile.delete(); } catch (UnirestException e) { plugin.getLogger().log(Level.WARNING, "Failed to fetch the latest jar file from the" + " builds page. Perhaps GitHub is down."); } }

Target:
private boolean download(int version) { File f = new File(parentFolder, "Metrics-" + version + ".jar"); try { plugin.getLogger().info("# Starting download of MetricsModule build: #" + version); AtomicInteger lastPercentPosted = new AtomicInteger(); HttpResponse<File> response = Unirest.get(GH_REPO_RELEASES + "/" + version + "/" + REPO_NAME + ".jar") .downloadMonitor((b, fileName, bytesWritten, totalBytes) -> { int percent = (int) (20 * (Math.round((((double) bytesWritten / totalBytes) * 100) / 20))); if (percent != 0 && percent != lastPercentPosted.get()) { plugin.getLogger().info("# Downloading... " + percent + "% " + "(" + bytesWritten + "/" + totalBytes + " bytes)"); lastPercentPosted.set(percent); } }) .asFile(f.getPath()); if (response.isSuccess()) { plugin.getLogger().info("Successfully downloaded " + REPO_NAME + " build: " + version); Files.move(f.toPath(), metricFile.toPath(), StandardCopyOption.REPLACE_EXISTING); metricVersion = String.valueOf(version); newlyDownloaded = true; return true; } } catch (UnirestException e) { plugin.getLogger().log(Level.WARNING, "Failed to fetch the latest jar file from the" + " builds page. Perhaps GitHub is down."); } catch (IOException e) { plugin.getLogger().log(Level.WARNING, "Failed to replace the old metric file with the " + "new one. Please do this manually! Error: {0}", e.getMessage()); } return false; }
Source:
Class getRootType() { return rootType; }

Target:
protected Class getRootType() { return rootType; }
Source:
public SendableResponse<RegisterResponse> register(Identity sender, RegisterRequest registerRequest, InetSocketAddress serverEndpoint) { Registration.Builder builder = new Registration.Builder(RegistrationHandler.createRegistrationId(), registerRequest.getEndpointName(), sender.getPeerAddress().getAddress(), sender.getPeerAddress() .getPort(), serverEndpoint); builder.lwM2mVersion(registerRequest.getLwVersion()).lifeTimeInSec(registerRequest.getLifetime()) .bindingMode(registerRequest.getBindingMode()).objectLinks(registerRequest.getObjectLinks()) .smsNumber(registerRequest.getSmsNumber()).registrationDate(new Date()).lastUpdate(new Date()) .additionalRegistrationAttributes(registerRequest.getAdditionalAttributes()); final Registration registration = builder.build(); if (!authorizer.isAuthorized(registerRequest, registration, sender)) { return new SendableResponse<>(RegisterResponse.forbidden(null)); } final Deregistration deregistration = registrationService.getStore().addRegistration(registration); LOG.debug("New registration: {}", registration); Runnable whenSended = new Runnable (){ public void run() { if (deregistration != null) { registrationService.fireUnregistered(deregistration.getRegistration()); } registrationService.fireRegistred(registration); }; }; return new SendableResponse<>(RegisterResponse.success(registration.getId()), whenSended); }

Target:
public SendableResponse<RegisterResponse> register(Identity sender, RegisterRequest registerRequest, InetSocketAddress serverEndpoint) { Registration.Builder builder = new Registration.Builder(RegistrationHandler.createRegistrationId(), registerRequest.getEndpointName(), sender.getPeerAddress().getAddress(), sender.getPeerAddress() .getPort(), serverEndpoint); builder.lwM2mVersion(registerRequest.getLwVersion()).lifeTimeInSec(registerRequest.getLifetime()) .bindingMode(registerRequest.getBindingMode()).objectLinks(registerRequest.getObjectLinks()) .smsNumber(registerRequest.getSmsNumber()).registrationDate(new Date()).lastUpdate(new Date()) .additionalRegistrationAttributes(registerRequest.getAdditionalAttributes()); final Registration registration = builder.build(); if (!authorizer.isAuthorized(registerRequest, registration, sender)) { return new SendableResponse<>(RegisterResponse.forbidden(null)); } final Deregistration deregistration = registrationService.getStore().addRegistration(registration); LOG.debug("New registration: {}", registration); Runnable whenSent = new Runnable() { @Override public void run() { if (deregistration != null) { registrationService.fireUnregistered(deregistration.getRegistration(), deregistration.getObservations()); } registrationService.fireRegistred(registration); } }; return new SendableResponse<>(RegisterResponse.success(registration.getId()), whenSent); }
Source:
protected final void bindConsumerAndProducers(Module module) { MessageBus bus = findMessageBus(module); Assert.notNull(bus, "MessageBus should be available in the context."); MessageChannel inputChannel = module.getComponent(MODULE_INPUT_CHANNEL, MessageChannel.class); if (inputChannel != null) { bindConsumer(bus, module, inputChannel); } MessageChannel outputChannel = module.getComponent(MODULE_OUTPUT_CHANNEL, MessageChannel.class); if (outputChannel != null) { bindProducer(bus, module, outputChannel); createAndBindTapChannel(bus, module, outputChannel); } }

Target:
protected final void bindConsumerAndProducers(Module module) { MessageChannel inputChannel = module.getComponent(MODULE_INPUT_CHANNEL, MessageChannel.class); if (inputChannel != null) { bindMessageConsumer(inputChannel, getInputChannelName(module), isAliasedInput(module)); } MessageChannel outputChannel = module.getComponent(MODULE_OUTPUT_CHANNEL, MessageChannel.class); if (outputChannel != null) { bindMessageProducer(outputChannel, getOutputChannelName(module), isAliasedOutput(module)); createAndBindTapChannel(module, outputChannel); } }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); sb.append("\t\t Encoded identity value: "); sb.append(ByteArrayUtils.toHex(identityEncoded)); sb.append("\n\t\tDiffie-Hellman public value: "); sb.append(ByteArrayUtils.toHexString(pointEncoded)); sb.append(StringUtil.lineSeparator()); return sb.toString(); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); sb.append("\t\t Encoded identity value: "); sb.append(ByteArrayUtils.toHex(identityEncoded)).append(StringUtil.lineSeparator());; sb.append("\t\tEC Diffie-Hellman public value: "); sb.append(ByteArrayUtils.toHexString(pointEncoded)); sb.append(StringUtil.lineSeparator()); return sb.toString(); }
Source:
public SireOfInsanity(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{4}{B}{R}"); this.subtype.add(SubType.DEMON); this.power = new MageInt(6); this.toughness = new MageInt(4); this.addAbility(new BeginningOfEndStepTriggeredAbility(new SireOfInsanityEffect(), TargetController.YOU, false)); }

Target:
public SireOfInsanity(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{4}{B}{R}"); this.subtype.add(SubType.DEMON); this.power = new MageInt(6); this.toughness = new MageInt(4); this.addAbility(new BeginningOfEndStepTriggeredAbility( new SireOfInsanityEffect(), TargetController.ANY, false )); }
Source:
public AsyncSystemProducer(String systemName, Config config, MetricsRegistry metricsRegistry) { StreamConfig sconfig = new StreamConfig(config); streamIds = config.getList(String.format(CONFIG_STREAM_LIST, systemName)); physicalToStreamIds = streamIds.stream().collect(Collectors.toMap(sconfig::getPhysicalName, Function.identity())); this.metricsRegistry = metricsRegistry; ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder().setNameFormat("SamzaHistogram_%d"); executorService = Executors.newScheduledThreadPool(1, threadFactoryBuilder.build()); }

Target:
public AsyncSystemProducer(String systemName, Config config, MetricsRegistry metricsRegistry) { StreamConfig sconfig = new StreamConfig(config); streamIds = config.getList(String.format(CONFIG_STREAM_LIST, systemName)); physicalToStreamIds = streamIds.stream().collect(Collectors.toMap(sconfig::getPhysicalName, Function.identity())); this.metricsRegistry = metricsRegistry; }
Source:
public long relationshipsGetCount( ) { long base = storeReadLayer.relationshipsGetCount(); return ktx.hasTxStateWithChanges() ? base + ktx.txState().addedAndRemovedRelationships().delta() : base; }

Target:
public long relationshipsGetCount( ) { ktx.assertOpen(); long base = storeReadLayer.relationshipsGetCount(); return ktx.hasTxStateWithChanges() ? base + ktx.txState().addedAndRemovedRelationships().delta() : base; }
Source:
protected static ActivityInstanceIncidentDto[] fromIncidents(Incident[] incidents) { ActivityInstanceIncidentDto[] incidentDtos = new ActivityInstanceIncidentDto[incidents.length]; for (int i = 0; i<incidents.length; i++) { incidentDtos[i] = fromIncident(incidents[0]); } return incidentDtos; }

Target:
protected static ActivityInstanceIncidentDto[] fromIncidents(Incident[] incidents) { ActivityInstanceIncidentDto[] incidentDtos = new ActivityInstanceIncidentDto[incidents.length]; for (int i = 0; i<incidents.length; i++) { incidentDtos[i] = fromIncident(incidents[i]); } return incidentDtos; }
Source:
public boolean pollWhileWaitingForTaskCompletion(FutureVDSCall<?> task, Guid hostId, long timeoutInMillis) { return pollingWithTimeoutAndCustomCondition(hostId, timeoutInMillis, task::isDone); }

Target:
public boolean pollWhileWaitingForTaskCompletion(FutureVDSCall<?> task, Guid hostId, long timeoutInMillis) { return pollingWithTimeoutAndCustomCondition(hostId, timeoutInMillis, e -> task.isDone()); }
Source:
public String getResourceTypeId() { return idIfTypeCorrect(CanonicalPath.this, Resource.class); }

Target:
public String getResourceTypeId() { return idIfTypeCorrect(CanonicalPath.this, ResourceType.class); }
Source:
public void setUp() throws AssumptionViolatedException { assumeTrue(CameraUtil.checkCameraDevice()); mAnalysisResults = new HashSet<>(); mAnalysisResultsSemaphore = new Semaphore( 0); mAnalyzer = new Analyzer() { @Override public void analyze(ImageProxy image, int rotationDegrees) { mAnalysisResults.add(new ImageProperties(image, rotationDegrees)); mAnalysisResultsSemaphore.release(); } }; Context context = ApplicationProvider.getApplicationContext(); AppConfig config = Camera2AppConfig.create(context); CameraFactory cameraFactory = config.getCameraFactory( null); try { mCameraId = cameraFactory.cameraIdForLensFacing(LensFacing.BACK); } catch (Exception e) { throw new IllegalArgumentException( "Unable to attach to camera with LensFacing " + LensFacing.BACK, e); } mCamera = cameraFactory.getCamera(mCameraId); CameraX.init(context, config); mHandlerThread = new HandlerThread("AnalysisThread"); mHandlerThread.start(); mHandler = new Handler(mHandlerThread.getLooper()); }

Target:
public void setUp() { assumeTrue(CameraUtil.deviceHasCamera()); mAnalysisResults = new HashSet<>(); mAnalysisResultsSemaphore = new Semaphore( 0); mAnalyzer = new Analyzer() { @Override public void analyze(ImageProxy image, int rotationDegrees) { mAnalysisResults.add(new ImageProperties(image, rotationDegrees)); mAnalysisResultsSemaphore.release(); } }; Context context = ApplicationProvider.getApplicationContext(); AppConfig config = Camera2AppConfig.create(context); CameraFactory cameraFactory = config.getCameraFactory( null); try { mCameraId = cameraFactory.cameraIdForLensFacing(LensFacing.BACK); } catch (Exception e) { throw new IllegalArgumentException( "Unable to attach to camera with LensFacing " + LensFacing.BACK, e); } mCamera = cameraFactory.getCamera(mCameraId); CameraX.init(context, config); mHandlerThread = new HandlerThread("AnalysisThread"); mHandlerThread.start(); mHandler = new Handler(mHandlerThread.getLooper()); }
Source:
public static PutRequest readFrom(DataInputStream stream, ClusterMap map) throws IOException { int correlationId = stream.readInt(); String clientId = Utils.readIntString(stream); BlobId id = new BlobId(stream, map); BlobProperties properties = BlobPropertiesSerDe.getBlobPropertiesFromStream(stream); ByteBuffer metadata = Utils.readIntBuffer(stream); InputStream data = stream; return new PutRequest(correlationId, clientId, id, properties, metadata, data, properties.getBlobSize(), BlobDataType.DataBlob, Put_Request_Version_V1); }

Target:
static PutRequest readFrom(DataInputStream stream, ClusterMap map) throws IOException { int correlationId = stream.readInt(); String clientId = Utils.readIntString(stream); BlobId id = new BlobId(stream, map); BlobProperties properties = BlobPropertiesSerDe.getBlobPropertiesFromStream(stream); ByteBuffer metadata = Utils.readIntBuffer(stream); return new PutRequest(correlationId, clientId, id, properties, metadata, stream, properties.getBlobSize(), BlobType.DataBlob, Put_Request_Version_V1); }
Source:
public static void testChangeInterestRateForActiveRevolvingCreditLoans() throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println("\nIn " + methodName); LoansService loanService = MambuAPIFactory.getLoanService(); AccountState accountState = loanService.getLoanAccount(NEW_LOAN_ACCOUNT_ID).getAccountState(); LoanProductType loanProductType = demoProduct.getLoanProductType(); if (loanProductType.equals(LoanProductType.REVOLVING_CREDIT) && accountState.equals(AccountState.ACTIVE)) { JSONTransactionRequest jsonTransactionRequest = new JSONTransactionRequest(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 1); jsonTransactionRequest.setDate(calendar.getTime()); jsonTransactionRequest.setRate(new BigDecimal(10)); jsonTransactionRequest .setNotes("Interest rate changet through API to be " + jsonTransactionRequest.getRate() + "%"); LoanTransaction loanTransaction = loanService.postInterestRateChange(NEW_LOAN_ACCOUNT_ID, LoanTransactionType.INTEREST_RATE_CHANGED, jsonTransactionRequest); System.out.println("The interest rate was edited for the loan account " + NEW_LOAN_ACCOUNT_ID + ". Transaction ID = " + loanTransaction); } else { System.out.println( "The loan account does not meet the prerequisites, therefore its interest rate will not be updated."); } }

Target:
public static void testChangeInterestRateForActiveRevolvingCreditLoans() throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println("\nIn " + methodName); LoansService loanService = MambuAPIFactory.getLoanService(); AccountState accountState = loanService.getLoanAccount(NEW_LOAN_ACCOUNT_ID).getAccountState(); LoanProductType loanProductType = demoProduct.getLoanProductType(); if (loanProductType.equals(LoanProductType.REVOLVING_CREDIT) && accountState.equals(AccountState.ACTIVE)) { JSONTransactionRequest jsonTransactionRequest = new JSONTransactionRequest(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 1); jsonTransactionRequest.setDate(calendar.getTime()); jsonTransactionRequest.setRate(new BigDecimal(10)); jsonTransactionRequest .setNotes("Interest rate changed through API to be " + jsonTransactionRequest.getRate() + "%"); LoanTransaction loanTransaction = loanService.postInterestRateChange(NEW_LOAN_ACCOUNT_ID, jsonTransactionRequest); System.out.println("The interest rate was edited for the loan account " + NEW_LOAN_ACCOUNT_ID + ". Transaction ID = " + loanTransaction.getTransactionId()); } else { System.out.println( "The loan account does not meet the prerequisites, therefore its interest rate will not be updated."); } }
Source:
protected boolean buildAndCheckDestStorageDomains() { if (diskInfoDestinationMap.isEmpty() && !fillDestMap()) { return false; } else if (!validateProvidedDestinations()) { return false; } if (getImagesToCheckDestinationStorageDomains().size() != diskInfoDestinationMap.size()) { log.error("Can not find any default active domain for one of the disks of template with id '{}'", vmDisksSource.getId()); return failValidation(EngineMessage.ACTION_TYPE_FAILED_MISSED_STORAGES_FOR_SOME_DISKS); } return validateIsImagesOnDomains(); }

Target:
protected boolean buildAndCheckDestStorageDomains() { if (diskInfoDestinationMap.isEmpty()) { if (!fillDestMap()) { return false; } } else if (!validateProvidedDestinations()) { return false; } if (getImagesToCheckDestinationStorageDomains().size() != diskInfoDestinationMap.size()) { log.error("Can not find any default active domain for one of the disks of template with id '{}'", vmDisksSource.getId()); return failValidation(EngineMessage.ACTION_TYPE_FAILED_MISSED_STORAGES_FOR_SOME_DISKS); } return validateIsImagesOnDomains(); }
Source:
public void testCleanStatefulCheckpoint() throws Exception { prepareClient(SimpleCheckpointManagerClient.RequestType.CLEAN_STATEFUL_CHECKOINTS); runClient(simpleCheckpointManagerClient); Thread.sleep(2 * 1000); verify(backendStorage).dispose(anyString(), anyString(), anyBoolean()); Message response = simpleCheckpointManagerClient.getResponse(); Assert.assertTrue(response instanceof CheckpointManager.CleanStatefulCheckpointResponse); Assert.assertEquals(StatusCode.OK, simpleCheckpointManagerClient.getResponseStatus()); }

Target:
public void testCleanStatefulCheckpoint() throws Exception { prepareClient(SimpleCheckpointManagerClient.RequestType.CLEAN_STATEFUL_CHECKOINTS); runClient(simpleCheckpointManagerClient); finishedSignal.await(2, TimeUnit.SECONDS); verify(backendStorage).dispose(anyString(), anyString(), anyBoolean()); Message response = simpleCheckpointManagerClient.getResponse(); assertTrue(response instanceof CheckpointManager.CleanStatefulCheckpointResponse); assertEquals(StatusCode.OK, simpleCheckpointManagerClient.getResponseStatus()); }
Source:
public void testHuffmanByteHelper() throws IOException { int size = 100; HuffmanParamsCalculator cal = new HuffmanParamsCalculator(); for (byte i = Byte.MIN_VALUE; i < Byte.MAX_VALUE; i++) { cal.add(i, (i + Byte.MIN_VALUE )/3 + 1); } cal.calculate(); HuffmanByteHelper helper = new HuffmanByteHelper(cal.getValuesAsBytes(), cal.getBitLens()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DefaultBitOutputStream bos = new DefaultBitOutputStream(baos); for (int i = 0; i < size; i++) { for (byte b : cal.getValuesAsBytes()) { helper.write(bos, b); } } bos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); DefaultBitInputStream bis = new DefaultBitInputStream(bais); int counter = 0; for (int i = 0; i < size; i++) { for (byte b : cal.getValuesAsBytes()) { byte v = helper.read(bis); if (v != b) { Assert.fail("Mismatch: " + v + " vs " + b + " at " + counter); } counter++; } } }

Target:
public void testHuffmanByteHelper() throws IOException { final int size = 100; final HuffmanParamsCalculator cal = new HuffmanParamsCalculator(); for (byte i = Byte.MIN_VALUE; i < Byte.MAX_VALUE; i++) { cal.add(i, (i + Byte.MIN_VALUE )/3 + 1); } cal.calculate(); final HuffmanByteHelper helper = new HuffmanByteHelper(cal.getValuesAsBytes(), cal.getBitLens()); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DefaultBitOutputStream bos = new DefaultBitOutputStream(baos); for (int i = 0; i < size; i++) { for (final byte b : cal.getValuesAsBytes()) { helper.write(bos, b); } } bos.close(); final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); final DefaultBitInputStream bis = new DefaultBitInputStream(bais); int counter = 0; for (int i = 0; i < size; i++) { for (final byte b : cal.getValuesAsBytes()) { final byte v = helper.read(bis); if (v != b) { Assert.fail("Mismatch: " + v + " vs " + b + " at " + counter); } counter++; } } }
Source:
private void startEnvironment(Environment environment, String workspaceId, boolean recover) throws BadRequestException, ServerException, NotFoundException, ConflictException { final List<? extends MachineConfig> machineConfigs = new ArrayList<>(environment.getMachineConfigs()); final MachineConfig devCfg = findDev(machineConfigs); final MachineImpl devMachine; try { devMachine = createMachine(devCfg, workspaceId, environment.getName(), recover); } catch (MachineException | BadRequestException | NotFoundException | SnapshotException | ConflictException ex) { doRemoveWorkspace(workspaceId); throw ex; } lock.writeLock().lock(); try { addRunningMachine(devMachine); final RuntimeWorkspaceImpl workspace = idToWorkspaces.get(workspaceId); if (workspace != null) { workspace.setStatus(RUNNING); } } finally { lock.writeLock().unlock(); } machineConfigs.remove(devCfg); for (MachineConfig nonDevCfg : machineConfigs) { try { addRunningMachine(createMachine(nonDevCfg, workspaceId, environment.getName(), recover)); } catch (MachineException | BadRequestException | NotFoundException | SnapshotException | ConflictException ex) { LOG.error(format("Error while creating machine '%s' in workspace '%s', environment '%s'", nonDevCfg.getName(), workspaceId, environment.getName()), ex); } } }

Target:
private void startEnvironment(Environment environment, String workspaceId, boolean recover) throws BadRequestException, ServerException, NotFoundException, ConflictException { final List<? extends MachineConfig> machineConfigs = new ArrayList<>(environment.getMachineConfigs()); final MachineConfig devCfg = findDev(machineConfigs); final MachineImpl devMachine; try { devMachine = createMachine(devCfg, workspaceId, environment.getName(), recover); } catch (MachineException | BadRequestException | NotFoundException | SnapshotException | ConflictException ex) { doRemoveWorkspace(workspaceId); throw ex; } lock.writeLock().lock(); try { if (!addRunningMachine(devMachine)) { throw new ServerException("Workspace '" + workspaceId + "' had been stopped before its dev-machine was started"); } idToWorkspaces.get(workspaceId).setStatus(RUNNING); } finally { lock.writeLock().unlock(); } machineConfigs.remove(devCfg); for (MachineConfig nonDevCfg : machineConfigs) { try { final MachineImpl nonDevMachine = createMachine(nonDevCfg, workspaceId, environment.getName(), recover); if (!addRunningMachine(nonDevMachine)) { if (!isStopped) { machineManager.destroy(nonDevMachine.getId(), false); } throw new ServerException("Workspace '" + workspaceId + "' had been stopped before all its machines were started"); } } catch (MachineException | BadRequestException | NotFoundException | SnapshotException | ConflictException ex) { LOG.error(format("Error while creating machine '%s' in workspace '%s', environment '%s'", nonDevCfg.getName(), workspaceId, environment.getName()), ex); } } }
Source:
public static HibernateOrmBootstrapIntrospector create(Metadata metadata, ReflectionManager ormReflectionManager, ConfigurationPropertySource propertySource) { Collection<PersistentClass> persistentClasses = metadata.getEntityBindings() .stream() .filter( PersistentClass::hasPojoRepresentation ) .filter( persistentClass -> !"org.hibernate.envers.DefaultRevisionEntity".equals( persistentClass.getClassName() ) ) .collect( Collectors.toList() ); Map<Class<?>, HibernateOrmBasicTypeMetadata> typeMetadata = new HashMap<>(); collectPersistentTypes( typeMetadata, metadata.getEntityBindings() ); for ( PersistentClass persistentClass : persistentClasses ) { collectEmbeddedTypesRecursively( typeMetadata, persistentClass.getIdentifier() ); collectEmbeddedTypesRecursively( typeMetadata, persistentClass.getPropertyIterator() ); } MethodHandles.Lookup lookup = MethodHandles.publicLookup(); HibernateOrmReflectionStrategyName reflectionStrategyName = REFLECTION_STRATEGY.get( propertySource ); ValueReadHandleFactory valueReadHandleFactory; switch ( reflectionStrategyName ) { case JAVA_LANG_REFLECT: valueReadHandleFactory = ValueReadHandleFactory.usingJavaLangReflect(); break; case METHOD_HANDLE: valueReadHandleFactory = ValueReadHandleFactory.usingMethodHandle( lookup ); break; default: throw new AssertionFailure( "Unexpected reflection strategy name: " + reflectionStrategyName ); } return new HibernateOrmBootstrapIntrospector( typeMetadata, ormReflectionManager, valueReadHandleFactory ); }

Target:
public static HibernateOrmBootstrapIntrospector create(Metadata metadata, ReflectionManager ormReflectionManager, ConfigurationPropertySource propertySource) { Collection<PersistentClass> persistentClasses = metadata.getEntityBindings() .stream() .filter( PersistentClass::hasPojoRepresentation ) .collect( Collectors.toList() ); Map<Class<?>, HibernateOrmBasicTypeMetadata> typeMetadata = new HashMap<>(); collectPersistentTypes( typeMetadata, persistentClasses ); for ( PersistentClass persistentClass : persistentClasses ) { collectEmbeddedTypesRecursively( typeMetadata, persistentClass.getIdentifier() ); collectEmbeddedTypesRecursively( typeMetadata, persistentClass.getPropertyIterator() ); } MethodHandles.Lookup lookup = MethodHandles.publicLookup(); HibernateOrmReflectionStrategyName reflectionStrategyName = REFLECTION_STRATEGY.get( propertySource ); ValueReadHandleFactory valueReadHandleFactory; switch ( reflectionStrategyName ) { case JAVA_LANG_REFLECT: valueReadHandleFactory = ValueReadHandleFactory.usingJavaLangReflect(); break; case METHOD_HANDLE: valueReadHandleFactory = ValueReadHandleFactory.usingMethodHandle( lookup ); break; default: throw new AssertionFailure( "Unexpected reflection strategy name: " + reflectionStrategyName ); } return new HibernateOrmBootstrapIntrospector( typeMetadata, ormReflectionManager, valueReadHandleFactory ); }
Source:
void validateQualifier(String qualifier) throws MojoFailureException { try { Version.parseVersion(Version.emptyVersion + "." + qualifier); } catch (IllegalArgumentException e) { throw new MojoFailureException( "Invalid build qualifier, it does not match the OSGi qualifier constraint ([0..9]|[a..zA..Z]|'_'|'-')"); } }

Target:
void validateQualifier(String qualifier) throws MojoFailureException { try { Version.parseVersion("1.0.0." + qualifier); } catch (IllegalArgumentException e) { throw new MojoFailureException( "Invalid build qualifier, it does not match the OSGi qualifier constraint ([0..9]|[a..zA..Z]|'_'|'-')"); } }
Source:
public List<AddOn> getNewAddOns() { if (this.getPreviousVersionInfo() != null) { return this.getPreviousVersionInfo().getNewAddOns(this.getLatestVersionInfo()); } return getLocalVersionInfo().getNewAddOns(this.getLatestVersionInfo()); }

Target:
protected List<AddOn> getNewAddOns() { if (this.getPreviousVersionInfo() != null) { return this.getPreviousVersionInfo().getNewAddOns(this.getLatestVersionInfo()); } return getLocalVersionInfo().getNewAddOns(this.getLatestVersionInfo()); }
Source:
private byte[] getSerializedEntity(ClientRequest request) { ClientRequest requestCopy = new ClientRequest(request); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); requestCopy.setStreamProvider(new OutboundMessageContext.StreamProvider() { @Override public OutputStream getOutputStream(int contentLength) { return outputStream; } }); try { requestCopy.writeEntity(); } catch (IOException e) { throw new WebApplicationException("Error reading content during signature"); } return outputStream.toByteArray(); }

Target:
private byte[] getSerializedEntity(ClientRequest request) { ClientRequest requestCopy = new ClientRequest(request); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); requestCopy.setStreamProvider(new OutboundMessageContext.StreamProvider() { @Override public OutputStream getOutputStream(int contentLength) { return outputStream; } }); try { requestCopy.writeEntity(); } catch (IOException ioe) { throw new WebApplicationException("Error reading content during signature", ioe); } return outputStream.toByteArray(); }
Source:
protected static ILabel[] getLabels(IASTFunctionDefinition functionDefinition) { FindLabelsAction action = new FindLabelsAction(); functionDefinition.accept(action); ILabel[] result = null; if (action.labels != null) { for (int i = 0; i < action.labels.length && action.labels[i] != null; i++) { IASTLabelStatement labelStatement = action.labels[i]; IBinding binding = labelStatement.getName().resolveBinding(); if (binding != null) result = ArrayUtil.append(ILabel.class, result, (ILabel) binding); } } return ArrayUtil.trim(ILabel.class, result); }

Target:
protected static IBinding[] getLabels(IASTFunctionDefinition functionDefinition) { FindLabelsAction action = new FindLabelsAction(); functionDefinition.accept(action); IBinding[] result = ILabel.EMPTY_LABEL_ARRAY; if (action.labels != null) { for (int i = 0; i < action.labels.length && action.labels[i] != null; i++) { IASTLabelStatement labelStatement = (IASTLabelStatement) action.labels[i]; IBinding binding = labelStatement.getName().resolveBinding(); if (binding != null) result = ArrayUtil.append(result, (ILabel) binding); } } return ArrayUtil.trim(result); }
Source:
public void add(T value) { this.elements.add(new ValueInfo<T>(Instant.now(), value)); this.listGaugeEvictionPolicy.elementAddedCallback(); }

Target:
public void add(T value) { this.elements.add(new TimestampedValue<T>(value, Instant.now().toEpochMilli())); this.evict(); }
Source:
private Properties createJobProps(String topic, Path folder, DateTime folderHour, Path outputDir, FileSystem fs, CamusSweeperMetrics metrics) throws IOException { Properties jobProps = new Properties(props); jobProps.putAll(props); jobProps.put("topic", topic); String topicAndHour = topic + ":" + folderHour.toString(hourFormatter); jobProps.put(CamusHourlySweeper.TOPIC_AND_HOUR, topicAndHour); long dataSize = fs.getContentSummary(folder).getLength(); metrics.dataSizeByTopic.put(topicAndHour, dataSize); metrics.totalDataSize += dataSize; List<Path> sourcePaths = new ArrayList<Path>(); sourcePaths.add(folder); Path destPath = new Path(outputDir, folderHour.toString(hourFormatter)); jobProps.put(CamusHourlySweeper.INPUT_PATHS, pathListToCommaSeperated(sourcePaths)); jobProps.put(CamusHourlySweeper.DEST_PATH, destPath.toString()); if (!fs.exists(destPath)) { LOG.info(topic + " dest dir " + destPath.toString() + " doesn't exist. Processing."); return jobProps; } else if (sourceDirHasOutliers(fs, sourcePaths, destPath)) { LOG.info("found outliers for topic " + topic + ". Will add outliers to " + destPath.toString()); this.outlierProperties.add(jobProps); return null; } else { LOG.info(topic + " dest dir " + destPath.toString() + " already exists. Skipping."); return null; } }

Target:
private Properties createJobProps(String topic, Path folder, DateTime folderHour, Path outputDir, FileSystem fs, CamusSweeperMetrics metrics) throws IOException { Properties jobProps = new Properties(); jobProps.putAll(props); jobProps.put("topic", topic); String topicAndHour = topic + ":" + folderHour.toString(hourFormatter); jobProps.put(CamusHourlySweeper.TOPIC_AND_HOUR, topicAndHour); long dataSize = fs.getContentSummary(folder).getLength(); metrics.recordDataSizeByTopic(topicAndHour, dataSize); metrics.addToTotalDataSize(dataSize); List<Path> sourcePaths = new ArrayList<Path>(); sourcePaths.add(folder); Path destPath = new Path(outputDir, folderHour.toString(hourFormatter)); jobProps.put(CamusHourlySweeper.INPUT_PATHS, pathListToCommaSeperated(sourcePaths)); jobProps.put(CamusHourlySweeper.DEST_PATH, destPath.toString()); if (!fs.exists(destPath)) { LOG.info(topic + " dest dir " + destPath.toString() + " doesn't exist. Processing."); return jobProps; } else if (sourceDirHasOutliers(fs, sourcePaths, destPath)) { LOG.info("found outliers for topic " + topic + ". Will add outliers to " + destPath.toString()); this.outlierProperties.add(jobProps); return null; } else { LOG.info(topic + " dest dir " + destPath.toString() + " already exists. Skipping."); return null; } }
Source:
public void deleteMultipleKeysWithQueryParam() throws Exception { putAll(); assertThat(customerRegion.size()).isEqualTo(60); assertThat(customerRegion.containsKey("2")).isTrue(); assertThat(customerRegion.containsKey("3")).isTrue(); assertThat(customerRegion.containsKey("4")).isTrue(); assertThat(customerRegion.containsKey("5")).isTrue(); mockMvc.perform(delete("/v1/customers?keys=2,3,4,5") .with(POST_PROCESSOR)) .andExpect(status().isOk()); assertThat(customerRegion.size()).isEqualTo(60 - 4); assertThat(customerRegion.containsKey("2")).isFalse(); assertThat(customerRegion.containsKey("3")).isFalse(); assertThat(customerRegion.containsKey("4")).isFalse(); assertThat(customerRegion.containsKey("5")).isFalse(); }

Target:
public void deleteMultipleKeysWithQueryParam() throws Exception { putAll(); mockMvc.perform(delete("/v1/customers?keys=2,3,4,5") .with(POST_PROCESSOR)) .andExpect(status().isOk()); assertThat(customerRegion).hasSize(60 - 4); assertThat(customerRegion.containsKey("2")).isFalse(); assertThat(customerRegion.containsKey("3")).isFalse(); assertThat(customerRegion.containsKey("4")).isFalse(); assertThat(customerRegion.containsKey("5")).isFalse(); }
Source:
public int getHoldingIndexForSymbol(String symbol) { boolean positionContainsHolding = false; Holding hold = null; for (Holding h : this.position){ if (h.getStockSymbol().equals(symbol)) { hold = h; positionContainsHolding = true; break; } } if (!positionContainsHolding) { hold = new Holding(symbol, 0); this.position.add(hold); } return position.indexOf(hold); }

Target:
public int getHoldingIndexForSymbol(String symbol) { boolean positionContainsHolding = false; Holding hold = null; for (Holding holding : this.position){ if (holding.getStockSymbol().equals(symbol)) { hold = holding; positionContainsHolding = true; break; } } if (!positionContainsHolding) { hold = new Holding(symbol, 0); this.position.add(hold); } return position.indexOf(hold); }
Source:
public BoundCurveExtrapolator bind(DoubleArray xValues, DoubleArray yValues, BoundCurveInterpolator interpolator) { ArgChecker.isTrue(interpolator instanceof MathBoundCurveInterpolator, "Interpolator must be ImmutableBoundCurveInterpolator"); Interpolator1D interp = ((MathBoundCurveInterpolator) interpolator).getInterpolator(); Interpolator1DDataBundle data = ((MathBoundCurveInterpolator) interpolator).getDataBundle(); ArgChecker.isTrue(interp instanceof ProductPiecewisePolynomialInterpolator1D, "Interpolator must be ProductPiecewisePolynomialInterpolator1D"); ArgChecker.isTrue(data instanceof Interpolator1DPiecewisePoynomialWithExtraKnotsDataBundle, "Interpolator data must be Interpolator1DPiecewisePoynomialWithExtraKnotsDataBundle"); return new Bound( function, (ProductPiecewisePolynomialInterpolator1D) interp, (Interpolator1DPiecewisePoynomialWithExtraKnotsDataBundle) data); }

Target:
public BoundCurveExtrapolator bind(DoubleArray xValues, DoubleArray yValues, BoundCurveInterpolator interpolator) { ArgChecker.isTrue(interpolator instanceof StandardBoundCurveInterpolator, "Interpolator must be StandardBoundCurveInterpolator"); Interpolator1D interp = ((StandardBoundCurveInterpolator) interpolator).getInterpolator(); Interpolator1DDataBundle data = ((StandardBoundCurveInterpolator) interpolator).getDataBundle(); ArgChecker.isTrue(interp instanceof ProductPiecewisePolynomialInterpolator1D, "Interpolator must be ProductPiecewisePolynomialInterpolator1D"); ArgChecker.isTrue(data instanceof Interpolator1DPiecewisePoynomialWithExtraKnotsDataBundle, "Interpolator data must be Interpolator1DPiecewisePoynomialWithExtraKnotsDataBundle"); return new Bound( function, (ProductPiecewisePolynomialInterpolator1D) interp, (Interpolator1DPiecewisePoynomialWithExtraKnotsDataBundle) data); }
Source:
public Stream<Tuple> getAllMatches(Object[] parameters) { return matchAll(parameters, notNull(parameters)).stream(); }

Target:
public Stream<Tuple> getAllMatches(Object[] parameters) { return matchAll(parameters, notNull(parameters)); }
Source:
private static String createAllLocationsMessage(List<Location> locations) { if (locations == null) { return "\n"; } StringBuilder sb = new StringBuilder(); for (Location invocation : locations) { sb.append(invocation).append("\n"); } return sb.toString(); }

Target:
private static String createAllLocationsMessage(List<Location> locations) { if (locations == null) { return "\n"; } StringBuilder sb = new StringBuilder(); for (Location location : locations) { sb.append(location).append("\n"); } return sb.toString(); }
Source:
protected void executeCommand() { VDSReturnValue vdsReturnaValue = Backend.getInstance().getResourceManager() .RunVdsCommand(VDSCommandType.StopRebalanceGlusterVolume, new GlusterVolumeVDSParameters(upServer.getId(), getGlusterVolumeName())); setSucceeded(vdsReturnaValue.getSucceeded()); if (!getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_REBALANCE_STOP_FAILED, vdsReturnaValue.getVdsError() .getMessage()); return; } endStepJob(); clearVolumeTaskAndReleaseLock(); getReturnValue().setActionReturnValue(vdsReturnaValue); }

Target:
protected void executeCommand() { VDSReturnValue vdsReturnaValue = runVdsCommand(VDSCommandType.StopRebalanceGlusterVolume, new GlusterVolumeVDSParameters(upServer.getId(), getGlusterVolumeName())); setSucceeded(vdsReturnaValue.getSucceeded()); if (!getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_REBALANCE_STOP_FAILED, vdsReturnaValue.getVdsError() .getMessage()); return; } endStepJob(); clearVolumeTaskAndReleaseLock(); getReturnValue().setActionReturnValue(vdsReturnaValue); }
Source:
public void run() { while (true) { try { this.install(); System.exit(0); } catch (InterruptedException e) { logger.warn("Aborting installation"); System.exit(1); } catch (Exception e) { e.printStackTrace(); logger.warn("Schema installer failed, retry again in " + waitRetry + "seconds."); } } }

Target:
public void run() { int retryCounter = 0; while (retryCounter < jobMaxRetries) { try { this.install(); System.exit(0); } catch (InterruptedException e) { logger.warn("Aborting installation"); System.exit(1); } catch (Exception e) { retryCounter++; logger.error("Schema installer failed on retry " + retryCounter + " of " + jobMaxRetries + ", retry again."); if (retryCounter >= jobMaxRetries) { e.printStackTrace(); System.exit(1); } } } }
Source:
private void nullifyInternalProxies() { if (privatemIrsProxy != null) { if (IrsServerWrapper.class.isInstance(privatemIrsProxy)) { XmlRpcUtils.shutDownConnection(((IrsServerWrapper) privatemIrsProxy).getHttpClient()); } else { ((JsonRpcIIrsServer) privatemIrsProxy).close(); } } privatemCurrentIrsHost = null; privatemIrsProxy = null; mCurrentVdsId = null; }

Target:
private void nullifyInternalProxies() { if (irsProxy != null) { if (IrsServerWrapper.class.isInstance(irsProxy)) { XmlRpcUtils.shutDownConnection(((IrsServerWrapper) irsProxy).getHttpClient()); } else { ((JsonRpcIIrsServer) irsProxy).close(); } } privatemCurrentIrsHost = null; irsProxy = null; mCurrentVdsId = null; }
Source:
public void kill(StreamApplication app) { try { ProcessorGraph processorGraph = getExecutionPlan(app); processorGraph.getProcessorNodes().forEach(processor -> { Config processorConfig = processor.generateConfig(); log.info("Killing processor with config {}", processor.getId(), processorConfig); JobRunner runner = new JobRunner(processorConfig); runner.kill(); }); } catch (Throwable t) { throw new SamzaException("Failed to kill application", t); } }

Target:
public void kill(StreamApplication app) { try { ProcessorGraph processorGraph = getExecutionPlan(app); processorGraph.getProcessorNodes().forEach(processor -> { Config processorConfig = processor.generateConfig(); log.info("Killing processor {}", processor.getId()); JobRunner runner = new JobRunner(processorConfig); runner.kill(); }); } catch (Throwable t) { throw new SamzaException("Failed to kill application", t); } }
Source:
public void testJsonRemove() { assertJsonRemove(is("{\"b\":[2]}"), SqlFunctions.dejsonize("{\"a\": 1, \"b\": [2]}"), "$.a"); }

Target:
public void testJsonRemove() { assertJsonRemove( SqlFunctions.jsonValueExpression("{\"a\": 1, \"b\": [2]}"), new Object[]{"$.a"}, is("{\"b\":[2]}")); assertJsonRemove( SqlFunctions.jsonValueExpression("{\"a\": 1, \"b\": [2]}"), new Object[]{"$.a", "$.b"}, is("{}")); }
Source:
static void instantiateMetaspaceMemoryMetrics(final MetricGroup parentMetricGroup) { final List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans() .stream() .filter(bean -> "Metaspace".equals(bean.getName())) .collect(Collectors.toList()); if (memoryPoolMXBeans.isEmpty()) { LOG.warn("No memory pool named 'Metaspace' is present. The '{}' metric group is not going to be instantiated.", METRIC_GROUP_METASPACE_NAME); return; } final MetricGroup metricGroup = parentMetricGroup.addGroup(METRIC_GROUP_METASPACE_NAME); final Iterator<MemoryPoolMXBean> beanIterator = memoryPoolMXBeans.iterator(); final MemoryPoolMXBean firstPool = beanIterator.next(); instantiateMemoryUsageMetrics(metricGroup, firstPool::getUsage); if (beanIterator.hasNext()) { LOG.warn("More than one memory pool named '{}' are present. Only the first pool was used for instantiating the metric.", METRIC_GROUP_METASPACE_NAME); } }

Target:
static void instantiateMetaspaceMemoryMetrics(final MetricGroup parentMetricGroup) { final List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans() .stream() .filter(bean -> "Metaspace".equals(bean.getName())) .collect(Collectors.toList()); if (memoryPoolMXBeans.isEmpty()) { LOG.info("The '{}' metrics will not be exposed because no pool named 'Metaspace' could be found. This might be caused by the used JVM.", METRIC_GROUP_METASPACE_NAME); return; } final MetricGroup metricGroup = parentMetricGroup.addGroup(METRIC_GROUP_METASPACE_NAME); final Iterator<MemoryPoolMXBean> beanIterator = memoryPoolMXBeans.iterator(); final MemoryPoolMXBean firstPool = beanIterator.next(); instantiateMemoryUsageMetrics(metricGroup, firstPool::getUsage); if (beanIterator.hasNext()) { LOG.debug("More than one memory pool named 'Metaspace' is present. Only the first pool was used for instantiating the '{}' metrics.", METRIC_GROUP_METASPACE_NAME); } }
Source:
protected final List<HtmlIssue> verify() { File file = new File(filename); FileReader fileReader; try { fileReader = new FileReader(file); } catch (FileNotFoundException e) { throw Throwables.propagate(e); } HtmlSourceCode result = new HtmlSourceCode( new TestInputFileBuilder("key", file.getPath()) .setLanguage(HtmlConstants.LANGUAGE_KEY) .setType(InputFile.Type.MAIN) .setModuleBaseDir(new File(".").toPath()) .setCharset(StandardCharsets.UTF_8) .build() ); HtlScanner scanner = new HtlScanner(); HtmlCheckVerifier htmlCheckVerifier = new HtmlCheckVerifier(); scanner.addVisitor(new ExpectedIssueCollector(htmlCheckVerifier)); if (check != null) { Class<? extends HtlCheck> htlCheck = check.getClass(); Rule rule = HtlCheckClasses.getRule(htlCheck); RuleKey ruleKey = RuleKey.of(HtlCheckClasses.REPOSITORY_KEY, rule.key()); check.setRuleKey(ruleKey); } scanner.addVisitor(check); scanner.scan(new HtlLexer().parse(fileReader), result); htmlCheckVerifier.checkIssues(result.getIssues()); return result.getIssues(); }

Target:
protected final List<HtmlIssue> verify() { File file = new File(filename); HtmlSourceCode result = createSourceCode(file); HtmlCheckVerifier htmlCheckVerifier = new HtmlCheckVerifier(); HtlScanner scanner = setupScanner(check, htmlCheckVerifier); try (FileReader fileReader = new FileReader(file)) { scanner.scan(new HtlLexer().parse(fileReader), result); } catch (IOException e) { throw Throwables.propagate(e); } htmlCheckVerifier.checkIssues(result.getIssues()); return result.getIssues(); }