auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void shouldEnrollBoostVaccinationForSpecificDay() throws IOException { try { fakeNow(newDateTime(2015, 8, 1, 0, 0, 0)); for(int i = 0; i < 7; i++){ Subject subject = createSubjectWithRequireData(Integer.toString(i + 1)); } InputStream inputStream = getClass().getResourceAsStream("/enrollBoostVaccination.csv"); raveImportService.importCsv(new InputStreamReader(inputStream), "/enrollBoostVaccination.csv"); inputStream.close(); int i = 0; for (Subject subject : subjectService.getAll()) { SubjectEnrollments subjectEnrollments = subjectEnrollmentsDataService.findEnrollmentBySubjectId(subject.getSubjectId()); assertEquals(1, subjectEnrollments.getEnrollments().size()); assertEquals(new LocalDate(2015, 9, 21 + i), subjectEnrollments.getEnrollments().iterator().next().getReferenceDate()); i++; } } finally { stopFakingTime(); } }

Target:
public void shouldEnrollBoostVaccinationForSpecificDay() throws IOException { try { fakeNow(newDateTime(2015, 8, 1, 0, 0, 0)); for(int i = 0; i < 7; i++){ Subject subject = createSubjectWithRequireData(Integer.toString(i + 1)); } InputStream inputStream = getClass().getResourceAsStream("/enrollBoostVaccination.csv"); raveImportService.importCsv(new InputStreamReader(inputStream), "/enrollBoostVaccination.csv"); inputStream.close(); int i = 0; for (Subject subject : subjectService.getAll()) { SubjectEnrollments subjectEnrollments = subjectEnrollmentsDataService.findEnrollmentBySubjectId(subject.getSubjectId()); assertEquals(1, subjectEnrollments.getEnrollments().size()); Enrollment enrollment = subjectEnrollments.getEnrollments().iterator().next(); assertEquals(VisitType.BOOST_VACCINATION_DAY.getValue() + " " + EbodacConstants.DAYS_OF_WEEK.get(i), enrollment.getCampaignName()); assertEquals(new LocalDate(2015, 9, 20 + i), subjectEnrollments.getEnrollments().iterator().next().getReferenceDate()); i++; } } finally { stopFakingTime(); } }
Source:
public void scanFile(AstTreeVisitorContext context) { super.scanFile(context); expectedLines = headerFormat.split("(?:\r)?\n|\r"); List<String> lines = Collections.emptyList(); try { lines = Files.readLines(getContext().getFile(), charset); } catch (IOException e) { LOG.error("Unable to execute rule \"TabCharacter\" for file because of error: {}", getContext().getFile().getName(), e); } if (!matches(expectedLines, lines)) { getContext().addFileIssue(this, "Add or update the header of this file."); } }

Target:
public void scanFile(AstTreeVisitorContext context) { expectedLines = headerFormat.split("(?:\r)?\n|\r"); List<String> lines = Collections.emptyList(); try { lines = Files.readLines(context.getFile(), charset); } catch (IOException e) { LOG.error("Unable to execute rule \"TabCharacter\" for file because of error: {}", context.getFile().getName(), e); } if (!matches(expectedLines, lines)) { context.addFileIssue(this, "Add or update the header of this file."); } }
Source:
public Tuple getTuple(EntityKey key, TupleContext tupleContext) { Entity entity = getEntity( key, tupleContext.getOptionsContext() ); if ( entity != null ) { return new Tuple( new RedisTupleSnapshot( entity.getProperties() ) ); } else if ( isInTheQueue( key, tupleContext ) ) { return new Tuple( new RedisTupleSnapshot( entity.getProperties() ) ); } else { return null; } }

Target:
public Tuple getTuple(EntityKey key, TupleContext tupleContext) { Entity entity = getEntity( key ); if ( entity != null ) { return new Tuple( new RedisTupleSnapshot( entity.getProperties() ) ); } else { return null; } }
Source:
public void onOptimizelyExperimentViewed(OptimizelyExperimentData optimizelyExperimentData) { Map<String, OptimizelyExperimentData> visitedExperiments = Optimizely.getVisitedExperiments(); for (String experimentId : visitedExperiments.keySet()) { OptimizelyExperimentData experiment = visitedExperiments.get(experimentId); HashMap<String, String> abTestProperties = new HashMap<>(); abTestProperties.put(ABTEST_NAME, experiment.experimentName); abTestProperties.put(ABTEST_VARIATION, experiment.variationName); AnalyticsTracker.track(AnalyticsTracker.Stat.ABTEST_START); } }

Target:
public void onOptimizelyExperimentViewed(OptimizelyExperimentData optimizelyExperimentData) { Map<String, OptimizelyExperimentData> visitedExperiments = Optimizely.getVisitedExperiments(); for (String experimentId : visitedExperiments.keySet()) { OptimizelyExperimentData experiment = visitedExperiments.get(experimentId); HashMap<String, String> abTestProperties = new HashMap<>(); abTestProperties.put(ABTEST_NAME, experiment.experimentName); abTestProperties.put(ABTEST_VARIATION, experiment.variationName); AnalyticsTracker.track(AnalyticsTracker.Stat.ABTEST_START, abTestProperties); } }
Source:
protected void writeHeader(List<LogEntry> entity, CSVPrinter printer) throws IOException { LogEntryCSVWriter writer = (LogEntryCSVWriter) registry.getWriter(ctx, LogEntry.class, TEXT_CSV_TYPE); writer.writeHeader(printer); }

Target:
protected void writeHeader(List<LogEntry> entity, CSVPrinter printer) throws IOException { LogEntryCSVWriter.writeHeader(printer, ctx); }
Source:
public DiscoveryResult discover(GitInfo gitInfo) throws IOException { GHRepository repository = gitHubHelper.repositoryFor(gitInfo); GHTree tree = gitHubHelper.treeFor(repository, gitInfo); Set<String> staticConfigs = new HashSet<>(); for (GHTreeEntry entry : tree.getTree()) { if (isStaticConfig(entry.getPath())) { staticConfigs.add(entry.getPath()); } } Set<DiscoveredModule> modules = new HashSet<>(); Set<MalformedFile> malformedFiles = new HashSet<>(); for (String config : staticConfigs) { String contents = gitHubHelper.contentsFor(config, repository, gitInfo); StaticConfig configObject = objectMapper.readValue(contents, StaticConfig.class); String moduleDirectory = Paths.get(config).getParent().toString(); String glob = (moduleDirectory.contains("/") ? moduleDirectory.substring(0, moduleDirectory.lastIndexOf('/') + 1) : "") + "**"; modules.add(new DiscoveredModule(configObject.getName(), "hs-static", moduleDirectory, glob, BUILD_CONFIGURATION, makeDeps(configObject))); } return new DiscoveryResult(modules, malformedFiles); }

Target:
public DiscoveryResult discover(GitInfo gitInfo) throws IOException { GHRepository repository = gitHubHelper.repositoryFor(gitInfo); GHTree tree = gitHubHelper.treeFor(repository, gitInfo); Set<String> staticConfigs = new HashSet<>(); for (GHTreeEntry entry : tree.getTree()) { if (isStaticConfig(entry.getPath())) { staticConfigs.add(entry.getPath()); } } Set<DiscoveredModule> modules = new HashSet<>(); Set<MalformedFile> malformedFiles = new HashSet<>(); for (String path : staticConfigs) { String contents = gitHubHelper.contentsFor(path, repository, gitInfo); String moduleDirectory = Paths.get(path).getParent().toString(); String glob = (moduleDirectory.contains("/") ? moduleDirectory.substring(0, moduleDirectory.lastIndexOf('/') + 1) : "") + "**"; Set<String> depends = new HashSet<>(); Set<String> provides = new HashSet<>(); StaticConfig configObject; try { configObject = objectMapper.readValue(contents, StaticConfig.class); } catch (IOException e) { LOG.error("Error parsing static_conf.json at path for repo {}@{}", path, gitInfo.getFullRepositoryName(), gitInfo.getBranch()); malformedFiles.add(new MalformedFile(gitInfo.getId().get(), "hs-static", path, Throwables.getStackTraceAsString(e))); continue; } for (Map.Entry<String, Integer> entry: configObject.getDeps().entrySet()) { depends.add(String.format("%s-%d", entry.getKey(), entry.getValue())); } for (Map.Entry<String, Integer> entry : configObject.getRuntimeDeps().entrySet()) { depends.add(String.format("%s-%d", entry.getKey(), entry.getValue())); } provides.add(String.format("%s-%d", configObject.getName(), configObject.getMajorVersion())); modules.add(new DiscoveredModule(configObject.getName(), "hs-static", moduleDirectory, glob, BUILD_CONFIGURATION, new DependencyInfo(depends, provides))); } return new DiscoveryResult(modules, malformedFiles); }
Source:
public void setFields(StructDefinition fields) { this.fFields = fields; }

Target:
public void setFields(StructDefinition fields) { fFields = fields; }
Source:
public void onError(Throwable e) { if (done) { return; } done = true; try { actual.onError(e); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); RxJavaHooks.onError(e); throw new OnErrorFailedException(new CompositeException(e, ex)); } }

Target:
public void onError(Throwable e) { if (done) { RxJavaHooks.onError(e); return; } done = true; try { actual.onError(e); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); throw new OnErrorFailedException(new CompositeException(e, ex)); } }
Source:
public void handle(ModelRun modelRun) { int diseaseGroupId = modelRun.getDiseaseGroupId(); modelRunWorkflowService.generateDiseaseExtent(diseaseGroupId); }

Target:
public void handle(ModelRun modelRun) { int diseaseGroupId = modelRun.getDiseaseGroupId(); DiseaseGroup diseaseGroup = diseaseService.getDiseaseGroupById(diseaseGroupId); if (diseaseGroup.isAutomaticModelRunsEnabled()) { modelRunWorkflowService.generateDiseaseExtent(diseaseGroup); } }
Source:
private void checkPlan(String sql) { sql = sql.replaceAll(";$", ""); try { if (VoltFastSqlParser.parse(sql).isA(SqlKind.DDL)) { return; } } catch (SqlParseException e) { return; } try { if (!CALCITE_CHECKS.check(sql)) { return; } } catch (SqlParseException e) { return; } CompiledPlan calcitePlan; CompiledPlan voltdbPlan; try { calcitePlan = compileAdHocCalcitePlan(sql, true, true, DeterminismMode.SAFER); } catch (Exception e) { return; } try { voltdbPlan = compileAdHocPlan(sql, true, true); } catch (Exception e) { return; } comparePlanTree(calcitePlan.rootPlanGraph, voltdbPlan.rootPlanGraph, sql); if (calcitePlan.subPlanGraph != null && voltdbPlan.subPlanGraph != null) { comparePlanTree(calcitePlan.subPlanGraph, voltdbPlan.subPlanGraph, sql); } else if (calcitePlan.subPlanGraph != null || voltdbPlan.subPlanGraph != null) { fail(String.format("Two-part MP plans mismatch.\n\nVoltDB plan: %s\n\nCalcite plan:%s\n", voltdbPlan.subPlanGraph.toExplainPlanString(), calcitePlan.subPlanGraph.toExplainPlanString())); } try { compareCompiledPlans(calcitePlan, voltdbPlan); } catch (AssertionError ae) { System.err.println(sql); System.err.println(ae.getMessage()); } }

Target:
private void checkPlan(String sql) { sql = sql.replaceAll(";$", ""); try { if (VoltFastSqlParser.parse(sql).isA(SqlKind.DDL)) { return; } if (!CALCITE_CHECKS.check(sql)) { return; } } catch (SqlParseException e) { return; } CompiledPlan calcitePlan; CompiledPlan voltdbPlan; try { calcitePlan = compileAdHocCalcitePlan(sql, true, true, DeterminismMode.SAFER); voltdbPlan = compileAdHocPlan(sql, true, true); } catch (Exception e) { return; } comparePlanTree(calcitePlan.rootPlanGraph, voltdbPlan.rootPlanGraph, sql); if (calcitePlan.subPlanGraph != null && voltdbPlan.subPlanGraph != null) { comparePlanTree(calcitePlan.subPlanGraph, voltdbPlan.subPlanGraph, sql); } else if (calcitePlan.subPlanGraph != null || voltdbPlan.subPlanGraph != null) { fail(String.format("Two-part MP plans mismatch.\n\nVoltDB plan: %s\n\nCalcite plan:%s\n", voltdbPlan.subPlanGraph.toExplainPlanString(), calcitePlan.subPlanGraph.toExplainPlanString())); } try { compareCompiledPlans(calcitePlan, voltdbPlan); } catch (AssertionError ae) { System.err.println(sql); System.err.println(ae.getMessage()); } }
Source:
public Object combine(Object lhs, Object rhs) { return (((SerializablePair<Long, Long>) lhs).lhs <= ((SerializablePair<Long, Long>) rhs).lhs) ? lhs : rhs; }

Target:
public Object combine(Object lhs, Object rhs) { return DoubleFirstAggregatorFactory.TIME_COMPARATOR.compare(lhs, rhs) <= 0 ? lhs : rhs; }
Source:
public void onSitePluginVersionUpdated(PluginStore.OnSitePluginVersionUpdated event) { if (event.isError()) { AppLog.e(AppLog.T.API, "An error occurred while updating the plugin version with type: " + event.error.type); return; } mPlugin = mPluginStore.getSitePluginByName(mSite, mPlugin.getName()); refreshViews(); }

Target:
public void onSitePluginVersionUpdated(PluginStore.OnSitePluginVersionUpdated event) { if (event.isError()) { AppLog.e(AppLog.T.API, "An error occurred while updating the plugin version with type: " + event.error.type); return; } mPlugin = mPluginStore.getSitePluginByName(mSite, mPlugin.getName()); if (mPlugin == null) { ToastUtils.showToast(this, R.string.plugin_not_found, Duration.SHORT); finish(); return; } refreshViews(); }
Source:
public OmCalendar getCalendarbyId(Long calId){ return em.createNamedQuery("getCalendarbyId", OmCalendar.class) .setParameter("calId", calId) .getSingleResult(); }

Target:
public OmCalendar getCalendarbyId(Long calId) { TypedQuery<OmCalendar> query = em.createNamedQuery("getCalendarbyId", OmCalendar.class) .setParameter("calId", calId); OmCalendar calendar = null; try { calendar = query.getSingleResult(); } catch (NoResultException e) { } return calendar; }
Source:
public Path toPath() { Path result = filePath; if (result == null) { synchronized (this) { result = filePath; if (result == null) { try { Method getDefaultMethod; try { getDefaultMethod = Class.forName("java.nio.file.FileSystems") .getDeclaredMethod("getDefault"); } catch (ClassNotFoundException e) { throw new LibraryNotLinkedError("Get default FileSystem", "jre_file", "java.nio.file.FileSystems"); } Object fileSystem = getDefaultMethod.invoke(null); Method getPathMethod; try { getPathMethod = Class.forName("java.nio.file.FileSystem") .getDeclaredMethod("getPath", String.class); } catch (ClassNotFoundException e) { throw new LibraryNotLinkedError("Get path of FileSystem", "jre_file", "java.nio.file.FileSystem"); } result = (Path) getPathMethod.invoke(fileSystem, path); filePath = result; } catch (Exception e) { throw new AssertionError(e); } } } } return result; }

Target:
public Path toPath() { Path result = filePath; if (result == null) { synchronized (this) { result = filePath; if (result == null) { try { Method getDefaultMethod; try { getDefaultMethod = Class.forName("java.nio.file.FileSystems") .getDeclaredMethod("getDefault"); } catch (ClassNotFoundException e) { throw new LibraryNotLinkedError("java.nio.file support", "jre_file", "JavaNioFileFileSystems"); } Object fileSystem = getDefaultMethod.invoke(null); Method getPathMethod; try { getPathMethod = Class.forName("java.nio.file.FileSystem") .getDeclaredMethod("getPath", String.class); } catch (ClassNotFoundException e) { throw new LibraryNotLinkedError("java.nio.file support", "jre_file", "JavaNioFileFileSystem"); } result = (Path) getPathMethod.invoke(fileSystem, path); filePath = result; } catch (Exception e) { throw new AssertionError(e); } } } } return result; }
Source:
public void locationUnbind() { sContext.unbindService(sConnection); }

Target:
public void locationUnbind() { if (mConnection != null) { sContext.unbindService(mConnection); } }
Source:
public MessageConsumerFactory<KafkaConsumer> messageConsumerFactory() { return new KafkaMessageConsumerFactory(zookeeper, messagingSystem, backOffIntervalMillis, maxBackOffMillis); }

Target:
public MessageConsumerFactory<KafkaConsumer> messageConsumerFactory() { return new KafkaMessageConsumerFactory( zookeeper, messagingSystem, Duration.millis(backOffIntervalMillis), Duration.millis(maxBackOffMillis) ); }
Source:
private StreamStoreDefinitionBuilder hashFirstNRowComponents(int numberOfComponentsHashed) { Preconditions.checkArgument(numberOfComponentsHashed <= 2, "Can't hash more than two row components for StreamStore."); streamTables.forEach((tableName, streamTableBuilder) -> streamTableBuilder.hashFirstNRowComponents(numberOfComponentsHashed)); return this; }

Target:
private StreamStoreDefinitionBuilder hashFirstNRowComponents(int numberOfComponentsHashed) { Preconditions.checkArgument(numberOfComponentsHashed <= 2, "The number of components specified must be less than two as " + "StreamStore internal tables use at most two row components."); streamTables.forEach((tableName, streamTableBuilder) -> streamTableBuilder.hashFirstNRowComponents(numberOfComponentsHashed)); return this; }
Source:
public void stop() { log.debugf("Stopping %s (%s)", this, lock); lock.lock(); try { CompletableFuture[] futures = clientListeners.keySet().stream().map(counterName -> factory.newRemoveListenerOperation(counterName, listenerId, dispatcher.address()).execute()) .toArray(CompletableFuture[]::new); await(CompletableFuture.allOf(futures)); } finally { lock.unlock(); } }

Target:
public void stop() { log.debugf("Stopping %s (%s)", this, lock); lock.lock(); try { CompletableFuture[] futures = clientListeners.keySet().stream().map(counterName -> factory.newRemoveListenerOperation(counterName, listenerId, dispatcher.address()).execute()) .toArray(CompletableFuture[]::new); await(CompletableFuture.allOf(futures)); clientListeners.clear(); } finally { lock.unlock(); } }
Source:
public UploadRequest build() throws BridgeSDKException { if (StringUtils.isBlank(name)) { throw new BridgeSDKException("name cannot be blank"); } if (contentLength < 0) { throw new BridgeSDKException("content length cannot be negative"); } if (StringUtils.isBlank(contentMd5)) { throw new BridgeSDKException("contentMd5 cannot be blank"); } if (StringUtils.isBlank(contentType)) { throw new BridgeSDKException("contentType cannot be blank"); } return new UploadRequest(name, contentLength, contentMd5, contentType); }

Target:
public UploadRequest build() throws InvalidEntityException { if (StringUtils.isBlank(name)) { throw new InvalidEntityException("name cannot be blank"); } if (contentLength < 0) { throw new InvalidEntityException("content length cannot be negative"); } if (StringUtils.isBlank(contentMd5)) { throw new InvalidEntityException("contentMd5 cannot be blank"); } if (StringUtils.isBlank(contentType)) { throw new InvalidEntityException("contentType cannot be blank"); } return new UploadRequest(name, contentLength, contentMd5, contentType); }
Source:
public void start() throws Exception { System.out.println("[Main] Running in " + Thread.currentThread().getName()); getVertx() .deployVerticle("io.vertx.example.core.verticle.worker.WorkerVerticle", new DeploymentOptions().setWorker(true)); getVertx().eventBus().send( "sample.data", "hello vert.x", r -> { System.out.println("[Main] Receiving reply ' " + r.result().body().toString() + "' in " + Thread.currentThread().getName()); } ); }

Target:
public void start() throws Exception { System.out.println("[Main] Running in " + Thread.currentThread().getName()); vertx .deployVerticle("io.vertx.example.core.verticle.worker.WorkerVerticle", new DeploymentOptions().setWorker(true)); vertx.eventBus().send( "sample.data", "hello vert.x", r -> { System.out.println("[Main] Receiving reply ' " + r.result().body().toString() + "' in " + Thread.currentThread().getName()); } ); }
Source:
public void testGfshClearRegionWithOverflow() throws InterruptedException { createPartitionRedundantPersistentOverflowRegion(); populateRegion(); assertRegionSize(NUM_ENTRIES); gfsh.executeAndAssertThat("clear region --name=" + OVERFLOW_REGION_NAME).statusIsSuccess(); assertRegionSize(0); restartServers(); assertRegionSize(0); destroyRegion(); destroyDiskStore(DiskStoreFactory.DEFAULT_DISK_STORE_NAME); }

Target:
public void testGfshClearRegionWithOverflow() throws InterruptedException { createPartitionRedundantPersistentOverflowRegion(); populateRegion(); assertRegionSize(NUM_ENTRIES); gfsh.executeAndAssertThat("clear region --name=" + OVERFLOW_REGION_NAME).statusIsSuccess(); assertRegionSize(0); restartServers(); assertRegionSize(0); }
Source:
static UserPhotoDto createInstance(UserPhoto entity) { return new UserPhotoDto(entity.getId(), entity.getPngBytes()); }

Target:
static UserPhotoDto createInstance(UserPhoto entity) { return new UserPhotoDto(Optional.of(entity.getId()), entity.getPngBytes()); }
Source:
public AttributesRule(String pattern, String attributes) { this.attributes = parseAttributes(attributes); nameOnly = false; dirOnly = false; int endIndex = pattern.length(); if (pattern.endsWith("/")) { endIndex--; dirOnly = true; } String pattern2 = pattern.substring(0, endIndex); boolean hasSlash = pattern2.contains("/"); if (!hasSlash) nameOnly = true; else if (!pattern2.startsWith("/")) { pattern2 = "/" + pattern2; } try { matcher = PathMatcher.createPathMatcher(pattern2, Character.valueOf(FastIgnoreRule.PATH_SEPARATOR), dirOnly); } catch (InvalidPatternException e) { matcher = NO_MATCH; } this.pattern = pattern2; }

Target:
public AttributesRule(String pattern, String attributes) { this.attributes = parseAttributes(attributes); nameOnly = false; dirOnly = false; if (pattern.endsWith("/")) { pattern = pattern.substring(0, pattern.length() - 1); dirOnly = true; } boolean hasSlash = pattern.contains("/"); if (!hasSlash) nameOnly = true; else if (!pattern.startsWith("/")) { pattern = "/" + pattern; } try { matcher = PathMatcher.createPathMatcher(pattern, Character.valueOf(FastIgnoreRule.PATH_SEPARATOR), dirOnly); } catch (InvalidPatternException e) { matcher = NO_MATCH; } this.pattern = pattern; }
Source:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); try { final Bundle bundle = getArguments(); courseData = (EnrolledCoursesResponse) bundle .getSerializable(CourseData); if ( courseData == null ) return; final String headerImageUrl = courseData.getCourse().getCourse_image(environment.getConfig()); final ImageView headerImageView = (ImageView)getView().findViewById(R.id.header_image_view); Glide.with(CourseDashboardFragment.this) .load(headerImageUrl) .skipMemoryCache(true) .transform(new TopAnchorWidthFillTransformation(getActivity())) .into(headerImageView); courseTextName.setText(courseData.getCourse().getName()); CourseEntry course = courseData.getCourse(); courseTextDetails.setText( course.getDescription(this.getActivity())); } catch (Exception ex) { logger.error(ex); } }

Target:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); try { final Bundle bundle = getArguments(); courseData = (EnrolledCoursesResponse) bundle .getSerializable(CourseData); if ( courseData == null ) return; final String headerImageUrl = courseData.getCourse().getCourse_image(environment.getConfig()); Glide.with(CourseDashboardFragment.this) .load(headerImageUrl) .placeholder(R.drawable.edx_map_login) .transform(new TopAnchorFillWidthTransformation(getActivity())) .into(headerImageView); courseTextName.setText(courseData.getCourse().getName()); CourseEntry course = courseData.getCourse(); courseTextDetails.setText(course.getDescription(getActivity())); } catch (Exception ex) { logger.error(ex); } }
Source:
public void nack() { try { amazonSQS.changeMessageVisibility(queueUrl, message.getReceiptHandle(), 0); log.debug("Changed visibility timeout of message: from queue: {}", message.getMessageId(), queueUrl); } catch (ReceiptHandleIsInvalidException e) { log.warn("Error nack-ing message: {}, reason: (receiptHandle: {})", message.getMessageId(), e.getMessage(), message.getReceiptHandle() ); } }

Target:
public void nack() { try { amazonSQS.changeMessageVisibility(queueUrl, message.getReceiptHandle(), 0); log.debug("Changed visibility timeout of message: from queue: {}", message.getMessageId(), queueUrl); registry.counter(getFailedMetricId(subscriptionName)).increment(); } catch (ReceiptHandleIsInvalidException e) { log.warn("Error nack-ing message: {}, queue: {}, reason: (receiptHandle: {})", message.getMessageId(), queueUrl, e.getMessage(), message.getReceiptHandle() ); } }
Source:
private boolean isExtractionFinished() { int count = 0; while (isTempFilePresent() && count < 100) { if (count == 0) { System.out.println( "There is marker file, which means that some other process is already extracting the archive," + " waiting for extraction to finish"); } System.out.print("."); try { Thread.sleep(100); } catch (InterruptedException e) { log.warning("Problem occurred when the thread was sleeping:\n" + e.getMessage()); } count++; } System.out.println(); if (count == 99 && isTempFilePresent()) { try { deleteFileRecursively(destinationDir.toPath()); } catch (IOException e) { throw new RuntimeException("Failed to delete directory:" + destinationDir, e); } } return !isTempFilePresent(); }

Target:
private boolean isExtractionFinished() { int count = 0; while (isTempFilePresent() && count < 100) { if (count == 0) { System.out.println( "There is marker file, which means that some other process is already extracting the archive," + " waiting for extraction to finish"); } System.out.print("."); try { Thread.sleep(100); } catch (InterruptedException e) { log.warning("Problem occurred when the thread was sleeping:\n" + e.getMessage()); } count++; } System.out.println(); if (count == 100 && isTempFilePresent()) { try { deleteFileRecursively(destinationDir.toPath()); return false; } catch (IOException e) { throw new RuntimeException("Failed to delete directory:" + destinationDir, e); } } return true; }
Source:
public static void openEmailClient(final FragmentActivity activityContext, final String to, final String subject, final String email, Config config) { if (NetworkUtil.isConnectedMobile(activityContext) && NetworkUtil.isOnZeroRatedNetwork(activityContext, config)) { IDialogCallback callback = new IDialogCallback() { @Override public void onPositiveClicked() { } @Override public void onNegativeClicked() { return; } }; MediaConsentUtils.showLeavingAppDataDialog(activityContext, callback); } Intent email_intent = new Intent(Intent.ACTION_SEND); email_intent.putExtra(Intent.EXTRA_EMAIL, new String[]{to}); email_intent.putExtra(Intent.EXTRA_SUBJECT, subject); email_intent.putExtra(Intent.EXTRA_TEXT, email); email_intent.setType("plain/text"); try { email_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (activityContext != null) { Intent targetIntent = Intent.createChooser(email_intent, activityContext.getString(R.string.email_chooser_header)); targetIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); activityContext.startActivity(targetIntent); } } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(activityContext, activityContext.getString(R.string.email_client_not_present), Toast.LENGTH_SHORT) .show(); logger.error(ex); } }

Target:
public static void openEmailClient(final FragmentActivity activityContext, final String to, final String subject, final String email, Config config) { if (NetworkUtil.isConnectedMobile(activityContext) && NetworkUtil.isOnZeroRatedNetwork(activityContext, config)) { IDialogCallback callback = new IDialogCallback() { @Override public void onPositiveClicked() { sendEmailIntent(activityContext, to, subject, email); } @Override public void onNegativeClicked() { } }; MediaConsentUtils.showLeavingAppDataDialog(activityContext, callback); } else { sendEmailIntent(activityContext, to, subject, email); } }
Source:
private MethodBehavior createGuavaPreconditionsBehavior(Symbol.MethodSymbol symbol, boolean isCheckNotNull) { MethodBehavior behavior = new MethodBehavior(symbol); HappyPathYield happyPathYield = new HappyPathYield(behavior); happyPathYield.parametersConstraints.add(pmapForConstraint(isCheckNotNull ? ObjectConstraint.NOT_NULL : BooleanConstraint.TRUE)); for (int i = 1; i < symbol.parameterTypes().size(); i++) { happyPathYield.parametersConstraints.add(PCollections.emptyMap()); } PMap<Class<? extends Constraint>, Constraint> constraints = isCheckNotNull ? happyPathYield.parametersConstraints.get(0) : null; happyPathYield.setResult(isCheckNotNull ? 0 : -1, constraints); behavior.addYield(happyPathYield); behavior.completed(); return behavior; }

Target:
private static MethodBehavior createGuavaPreconditionsBehavior(Symbol.MethodSymbol symbol, boolean isCheckNotNull) { MethodBehavior behavior = new MethodBehavior(symbol); HappyPathYield happyPathYield = new HappyPathYield(behavior); happyPathYield.parametersConstraints.add(pmapForConstraint(isCheckNotNull ? ObjectConstraint.NOT_NULL : BooleanConstraint.TRUE)); for (int i = 1; i < symbol.parameterTypes().size(); i++) { happyPathYield.parametersConstraints.add(PCollections.emptyMap()); } PMap<Class<? extends Constraint>, Constraint> constraints = isCheckNotNull ? happyPathYield.parametersConstraints.get(0) : null; happyPathYield.setResult(isCheckNotNull ? 0 : -1, constraints); behavior.addYield(happyPathYield); behavior.completed(); return behavior; }
Source:
public void resetFactory() { factory.setMembersTouse(null); }

Target:
public void resetFactory() { factory.setMembersToUse(null); }
Source:
private boolean skipFilename(Path source) { logger.info("Looking into file: ", source); String skipRegex = "\\.tmcrc|metadata\\.yml|(.*)Hidden(.*)"; if (source.getFileName().toString().matches(skipRegex)) { logger.info("Skipping file: ", source); return true; } return false; }

Target:
private boolean skipFilename(Path source) { String skipRegex = "\\.tmcrc|metadata\\.yml|(.*)Hidden(.*)"; if (source.getFileName().toString().matches(skipRegex)) { logger.info("Skipping file: ", source); return true; } logger.info("Not skipping file: ", source); return false; }
Source:
private boolean isOldStudentExists(StudentAttributes s) { boolean isOldStudentExist = false; for (StudentAttributes studentsInDb : studentsDb.getAllOldStudents()) { if (studentsInDb.getId().equals(s.getId())) { isOldStudentExist = true; } } return isOldStudentExist; }

Target:
private boolean isOldStudentExists(StudentAttributes s) { for (StudentAttributes studentsInDb : studentsDb.getAllOldStudents()) { if (studentsInDb.getId().equals(s.getId())) { return true; } } return false; }
Source:
public static void main(String[] args) throws Exception { Configuration conf = CachedConfiguration.getInstance(); FileSystem fs = FileSystem.get(conf); Opts opts = new Opts(); opts.parseArgs(SplitLarge.class.getName(), args); for (String file : opts.files) { AccumuloConfiguration aconf = DefaultConfiguration.getInstance(); Path path = new Path(file); CachableBlockFile.Reader rdr = new CachableBlockFile.Reader(fs, path, conf, null, null, aconf); try (Reader iter = new RFile.Reader(rdr)) { if (!file.endsWith(".rf")) { throw new IllegalArgumentException("File must end with .rf"); } String smallName = file.substring(0, file.length() - 3) + "_small.rf"; String largeName = file.substring(0, file.length() - 3) + "_large.rf"; int blockSize = (int) aconf.getAsBytes(Property.TABLE_FILE_BLOCK_SIZE); try ( Writer small = new RFile.Writer( new BCFile.Writer(new RateLimitedOutputStream(fs.create(new Path(smallName)), null), "gz", conf, false, aconf), blockSize); Writer large = new RFile.Writer( new BCFile.Writer(new RateLimitedOutputStream(fs.create(new Path(largeName)), null), "gz", conf, false, aconf), blockSize)) { small.startDefaultLocalityGroup(); large.startDefaultLocalityGroup(); iter.seek(new Range(), new ArrayList<>(), false); while (iter.hasTop()) { Key key = iter.getTopKey(); Value value = iter.getTopValue(); if (key.getSize() + value.getSize() < opts.maxSize) { small.append(key, value); } else { large.append(key, value); } iter.next(); } } } } }

Target:
public static void main(String[] args) throws Exception { Configuration conf = CachedConfiguration.getInstance(); FileSystem fs = FileSystem.get(conf); Opts opts = new Opts(); opts.parseArgs(SplitLarge.class.getName(), args); for (String file : opts.files) { AccumuloConfiguration aconf = DefaultConfiguration.getInstance(); Path path = new Path(file); CachableBlockFile.Reader rdr = new CachableBlockFile.Reader(fs, path, conf, null, null, aconf); try (Reader iter = new RFile.Reader(rdr)) { if (!file.endsWith(".rf")) { throw new IllegalArgumentException("File must end with .rf"); } String smallName = file.substring(0, file.length() - 3) + "_small.rf"; String largeName = file.substring(0, file.length() - 3) + "_large.rf"; int blockSize = (int) aconf.getAsBytes(Property.TABLE_FILE_BLOCK_SIZE); try ( Writer small = new RFile.Writer( new BCFile.Writer(fs.create(new Path(smallName)), null, "gz", conf, aconf), blockSize); Writer large = new RFile.Writer( new BCFile.Writer(fs.create(new Path(largeName)), null, "gz", conf, aconf), blockSize)) { small.startDefaultLocalityGroup(); large.startDefaultLocalityGroup(); iter.seek(new Range(), new ArrayList<>(), false); while (iter.hasTop()) { Key key = iter.getTopKey(); Value value = iter.getTopValue(); if (key.getSize() + value.getSize() < opts.maxSize) { small.append(key, value); } else { large.append(key, value); } iter.next(); } } } } }
Source:
public void verify_with_default_test_jar() throws IOException { File file = new File("target/test-jars"); if (file.mkdir()) { JavaCheckVerifier.verifyNoIssue(FILENAME_NO_ISSUE, NO_EFFECT_VISITOR); file.delete(); } }

Target:
public void verify_with_default_test_jar() throws IOException { File file = new File("target/test-jars"); if (file.exists()) { file.delete(); } if (file.mkdir()) { JavaCheckVerifier.verifyNoIssue(FILENAME_NO_ISSUE, NO_EFFECT_VISITOR); file.delete(); } else { Fail.fail(); } }
Source:
public static boolean isLeadingADigit(String identifier) { Pattern p = Pattern.compile("\\d.*"); Matcher m = p.matcher(identifier); return m.matches(); }

Target:
public static boolean isLeadingADigit(String identifier) { return identifier.length() > 0 && Character.isDigit(identifier.charAt(0)); }
Source:
public ScheduledReporter build(MetricRegistry registry) { GraphiteReporter.Builder builder = builder(registry); if ("udp".equalsIgnoreCase(this.transport)) { return builder.build(new GraphiteUDP(host, port)); } else { return builder.build(new Graphite(host, port)); } }

Target:
public ScheduledReporter build(MetricRegistry registry) { GraphiteReporter.Builder builder = builder(registry); if ("udp".equalsIgnoreCase(transport)) { return builder.build(new GraphiteUDP(host, port)); } else { return builder.build(new Graphite(host, port)); } }
Source:
@Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); U.writeString(out, login()); U.writeString(out, password()); U.writeMap(out, userAttrs); out.writeObject(cred); }

Target:
@Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeObject(cred); U.writeMap(out, userAttrs); }
Source:
public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta delta : containers) { IRepositoryElement reviewRepoElement = delta.getElement(); if (!(reviewRepoElement instanceof ITask)) { return; } ITask review = (ITask) reviewRepoElement; AbstractRepositoryConnector connector = repositoryManager.getRepositoryConnector(review.getConnectorKind()); if (review != null && connector instanceof ReviewsConnector) { try { String reviewUrl = review.getUrl(); switch (delta.getKind()) { case DELETED: deleteMappingsTo(reviewUrl); break; case ADDED: case CONTENT: TaskData taskData = taskDataManager.getTaskData(review); if (taskData == null) { return; } String reviewDescription = taskData.getRoot() .getMappedAttribute(TaskAttribute.DESCRIPTION) .getValue(); updateMapping(reviewUrl, reviewDescription); break; case REMOVED: default: StatusHandler.log(new Status(IStatus.ERROR, ReviewsCoreConstants.PLUGIN_ID, "Unknown change")); } } catch (CoreException e) { StatusHandler.log( new Status(IStatus.ERROR, ReviewsCoreConstants.PLUGIN_ID, "Error getting taskData.", e)); } } } }

Target:
public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta delta : containers) { IRepositoryElement reviewRepoElement = delta.getElement(); if (!(reviewRepoElement instanceof ITask)) { return; } ITask review = (ITask) reviewRepoElement; AbstractRepositoryConnector connector = repositoryManager.getRepositoryConnector(review.getConnectorKind()); if (review != null && connector instanceof ReviewsConnector) { try { String reviewUrl = review.getUrl(); switch (delta.getKind()) { case REMOVED: break; case DELETED: deleteMappingsTo(reviewUrl); break; case ADDED: case CONTENT: TaskData taskData = taskDataManager.getTaskData(review); if (taskData == null) { continue; } TaskAttribute attr = taskData.getRoot().getMappedAttribute(TaskAttribute.DESCRIPTION); if (attr == null) { continue; } String reviewDescription = attr.getValue(); updateMapping(reviewUrl, reviewDescription); break; default: StatusHandler.log(new Status(IStatus.ERROR, ReviewsCoreConstants.PLUGIN_ID, "Unknown change")); } } catch (CoreException e) { StatusHandler.log( new Status(IStatus.ERROR, ReviewsCoreConstants.PLUGIN_ID, "Error getting taskData.", e)); } } } }
Source:
public void setup() { for (int i = 0; i < POSITIONS_PER_PAGE; i++) { longValues[i] = random.nextLong(); ids[i] = random.nextInt(POSITIONS_PER_PAGE / 10); positions[i] = i; if (i % 7 == 0) { nulls[i] = true; } } }

Target:
public void setup() { for (int i = 0; i < POSITIONS_PER_PAGE; i++) { longValues[i] = random.nextLong(); ids[i] = random.nextInt(POSITIONS_PER_PAGE / 10); positions[i] = i; nulls[i] = i % 7 == 0; } }
Source:
private int encodeStringToBufferAt(int pos, String s) { prepareEncoder(); ByteBuffer bb = buffer.sliceAsByteBuffer(pos, buffer.size() - pos); int startPosition = bb.position(); CharBuffer in = CharBuffer.wrap(s); encoder.reset(); CoderResult cr = encoder.encode(in, bb, true); if (cr.isError()) { try { cr.throwException(); } catch (CharacterCodingException e) { throw new MessageStringCodingException(e); } } if (!cr.isUnderflow() || cr.isOverflow()) { return -1; } cr = encoder.flush(bb); if (!cr.isUnderflow()) { return -1; } return bb.position() - startPosition; }

Target:
private int encodeStringToBufferAt(int pos, String s) { prepareEncoder(); ByteBuffer bb = buffer.sliceAsByteBuffer(pos, buffer.size() - pos); int startPosition = bb.position(); CharBuffer in = CharBuffer.wrap(s); CoderResult cr = encoder.encode(in, bb, true); if (cr.isError()) { try { cr.throwException(); } catch (CharacterCodingException e) { throw new MessageStringCodingException(e); } } if (!cr.isUnderflow() || cr.isOverflow()) { return -1; } cr = encoder.flush(bb); if (!cr.isUnderflow()) { return -1; } return bb.position() - startPosition; }
Source:
public void fetchAll() throws Exception { VenueService service = new VenueService(venueFinder); final VenueItem item = newVenueItemBuilder().group("test").types(new VenueType("typeOne"), new VenueType("typeTwo")).build(); context.checking(new Expectations() {{ oneOf(venueFinder).findAll(); will(returnValue(Lists.newArrayList(item))); }}); Reply<?> reply = service.fetchAll(); List<VenueItemDTO> dtos = Lists.newArrayList(new VenueItemDTO("test", Lists.newArrayList("typeOne", "typeTwo"))); assertThat(reply, containsValue(dtos)); assertThat(reply, isOk()); }

Target:
public void fetchAll() throws Exception { VenueGroup group = new VenueGroup("test"); VenueTypeList types = new VenueTypeList(new VenueType("typeOne"), new VenueType("typeTwo")); final VenueItem item = new VenueItem(group, types); context.checking(new Expectations() {{ oneOf(venueFinder).findAll(); will(returnValue(Lists.newArrayList(item))); }}); Reply<?> reply = service.fetchAll(); List<VenueItemDTO> dtos = Lists.newArrayList(new VenueItemDTO("test", Lists.newArrayList("typeOne", "typeTwo"))); assertThat(reply, containsValue(dtos)); assertThat(reply, isOk()); }
Source:
private static void deploy(Promise<String> startCallback) { log.debug("Deeplearning4j UI server is starting."); Promise<String> promise = Promise.promise(); promise.future().compose( success -> Future.future(prom -> startCallback.complete(success)), failure -> Future.future(prom -> startCallback.fail(new RuntimeException(failure))) ); Vertx vertx = Vertx.vertx(); vertx.deployVerticle(VertxUIServer.class.getName(), promise); VertxUIServer.shutdownHook = new Thread(() -> { if (VertxUIServer.instance != null && !VertxUIServer.instance.isStopped()) { log.info("Deeplearning4j UI server is auto-stopping in shutdown hook."); try { instance.stop(); } catch (InterruptedException e) { e.printStackTrace(); } } }); Runtime.getRuntime().addShutdownHook(shutdownHook); }

Target:
private static void deploy(Promise<String> startCallback) { log.debug("Deeplearning4j UI server is starting."); Promise<String> promise = Promise.promise(); promise.future().compose( success -> Future.future(prom -> startCallback.complete(success)), failure -> Future.future(prom -> startCallback.fail(new RuntimeException(failure))) ); Vertx vertx = Vertx.vertx(); vertx.deployVerticle(VertxUIServer.class.getName(), promise); VertxUIServer.shutdownHook = new Thread(() -> { if (VertxUIServer.instance != null && !VertxUIServer.instance.isStopped()) { log.info("Deeplearning4j UI server is auto-stopping in shutdown hook."); try { instance.stop(); } catch (InterruptedException e) { log.error("Interrupted stopping of Deeplearning4j UI server in shutdown hook.", e); } } }); Runtime.getRuntime().addShutdownHook(shutdownHook); }
Source:
private void verifySCN() throws SQLException { if (!HbaseCompatCapabilities.isMaxLookbackTimeSupported()) { return; } PhoenixConnection conn = statement.getConnection(); Long scn = conn.getSCN(); if (scn == null) { return; } ColumnResolver resolver = FromCompiler.getResolverForQuery(select, conn); int maxLookBackAge = conn.getQueryServices(). getConfiguration().getInt(CompatBaseScannerRegionObserver.PHOENIX_MAX_LOOKBACK_AGE_CONF_KEY, CompatBaseScannerRegionObserver.DEFAULT_PHOENIX_MAX_LOOKBACK_AGE); long now = EnvironmentEdgeManager.currentTimeMillis(); if (maxLookBackAge > 0 && now - maxLookBackAge * 1000L > scn){ throw new SQLExceptionInfo.Builder( SQLExceptionCode.CANNOT_QUERY_TABLE_WITH_SCN_OLDER_THAN_MAX_LOOKBACK_AGE) .build().buildException(); } }

Target:
private void verifySCN() throws SQLException { if (!HbaseCompatCapabilities.isMaxLookbackTimeSupported()) { return; } PhoenixConnection conn = statement.getConnection(); Long scn = conn.getSCN(); if (scn == null) { return; } ColumnResolver resolver = FromCompiler.getResolverForQuery(select, conn); long maxLookBackAgeInMillis = CompatBaseScannerRegionObserver.getMaxLookbackInMillis(conn.getQueryServices(). getConfiguration()); long now = EnvironmentEdgeManager.currentTimeMillis(); if (maxLookBackAgeInMillis > 0 && now - maxLookBackAgeInMillis > scn){ throw new SQLExceptionInfo.Builder( SQLExceptionCode.CANNOT_QUERY_TABLE_WITH_SCN_OLDER_THAN_MAX_LOOKBACK_AGE) .build().buildException(); } }
Source:
public SolenoidExtend(SolenoidSubsystem system) { super("Extending " + system.getName(), system, SolenoidState.EXTEND); }

Target:
public SolenoidExtend(SolenoidSubsystem system) { this("Extending " + system.getName(), system); }
Source:
private void updateMarkerPosition(Location location) { Marker marker = mMapFragment.getMap().addMarker(new MarkerOptions(). position(MapHelpV2.makeLatLng(location.getLatitude(), location.getLongitude()))); issueLocationHelper.handleMarkerUpdate(marker); }

Target:
private void updateMarkerPosition(Location location) { int markerId = mMapFragment.addMarker(location); issueLocationHelper.handleMarkerUpdate(markerId); }
Source:
public MIValue getMIValue(String name) { for (MIResult r : results) { if (r.getVariable().equals(name)) { return r.getMIValue(); } } return null; }

Target:
public MIValue getMIValue(String name) { if (name2value == null) { name2value = new HashMap<String, MIValue>(); for (MIResult r : results) name2value.put(r.getVariable(), r.getMIValue()); } return name2value.get(name); }
Source:
public void toggleMilestone_hasMilestone_milestoneReplaced() { MilestonePickerState state = prepareAssignedState(); state.toggleExactMatchMilestone("milestone1"); assertEquals(true, state.getCurrentMilestonesList().get(0).isSelected()); assertEquals(false, state.getCurrentMilestonesList().get(1).isSelected()); }

Target:
public void toggleMilestone_hasMilestone_milestoneReplaced() { MilestonePickerState state = prepareAssignedState(); state.toggleExactMatchMilestone("milestone1"); assertTrue(state.getCurrentMilestonesList().get(0).isSelected()); assertFalse(state.getCurrentMilestonesList().get(1).isSelected()); }
Source:
public ADBInfo(HashMap<String,String> env) throws URISyntaxException { this.env = env; String dockerHost = env.get("DOCKER_HOST"); URI url = new URI(dockerHost); String h = url.getHost(); openshiftHost = "https://" + h; }

Target:
public ADBInfo(HashMap<String,String> env) throws URISyntaxException { this.env = env; String dockerHost = env.get("DOCKER_HOST"); if( dockerHost != null ) { URI url = new URI(dockerHost); String h = url.getHost(); openshiftHost = "https://" + h; } }
Source:
public ValidationResult.Result calculateValidationStatus() { ValidationResult.Result status = ValidationResult.Result.OK; if (!getErrors().isEmpty()) { status = ValidationResult.Result.ERROR; } else if (!getWarnings().isEmpty()) { status = ValidationResult.Result.WARNING; } return status; }

Target:
public ValidationResult.Result calculateValidationStatus() { if (!getErrors().isEmpty()) { return ValidationResult.Result.ERROR; } else if (!getWarnings().isEmpty()) { return ValidationResult.Result.WARNING; } return ValidationResult.Result.OK; }
Source:
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { IControllableServerBehavior serverBehavior = getServerBehavior(configuration); if( !(serverBehavior instanceof ControllableServerBehavior )) { throw toCoreException("Unable to find a IControllableServerBehavior instance"); } ControllableServerBehavior beh = (ControllableServerBehavior) serverBehavior; beh.setServerStarting(); IServer server = beh.getServer(); IDeploymentConfig dc = OpenShiftServerUtils.getDeploymentConfig(server); DebuggingContext debugContext = OpenShiftDebugUtils.get().getDebuggingContext(dc); if( "debug".equals(mode)) { startDebugging(server, dc, debugContext, monitor); } else { stopDebugging(dc, debugContext, monitor); } int state = pollState(); if( state == IServer.STATE_STARTED) { beh.setServerStarted(); beh.setRunMode(mode); } else { beh.setServerStopped(); ((ControllableServerBehavior)getControllableBehavior()).setRunMode(null); } }

Target:
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { IControllableServerBehavior serverBehavior = getServerBehavior(configuration); if( !(serverBehavior instanceof ControllableServerBehavior )) { throw toCoreException("Unable to find a IControllableServerBehavior instance"); } ControllableServerBehavior beh = (ControllableServerBehavior) serverBehavior; beh.setServerStarting(); IServer server = beh.getServer(); IDeploymentConfig dc = OpenShiftServerUtils.getDeploymentConfig(server); if (dc == null) { throw toCoreException("No deployment config was found for "+server.getName()); } DebuggingContext debugContext = OpenShiftDebugUtils.get().getDebuggingContext(dc); if( DEBUG_MODE.equals(mode)) { startDebugging(server, dc, debugContext, monitor); } else { stopDebugging(dc, debugContext, monitor); } int state = pollState(); if( state == IServer.STATE_STARTED) { beh.setServerStarted(); beh.setRunMode(mode); } else { beh.setServerStopped(); ((ControllableServerBehavior)getControllableBehavior()).setRunMode(null); } }
Source:
public static void setup() { Project project = mock(Project.class); ProjectFileSystem pfs = mock(ProjectFileSystem.class); JavaClasspath javaClasspath = mock(JavaClasspath.class); SuppressWarningsFilter suppressWarningsFilter = mock(SuppressWarningsFilter.class); when(javaClasspath.getBinaryDirs()).thenReturn(Lists.newArrayList(new File("target/test-classes"))); when(javaClasspath.getElements()).thenReturn(Lists.newArrayList(new File("target/test-classes"))); File baseDir = new File("src/test/java"); when(project.getFileSystem()).thenReturn(pfs); when(pfs.getBasedir()).thenReturn(baseDir); DefaultJavaResourceLocator jrl = new DefaultJavaResourceLocator(project, javaClasspath, suppressWarningsFilter); JavaAstScanner.scanSingleFile(new File("src/test/java/org/sonar/java/DefaultJavaResourceLocatorTest.java"), new VisitorsBridge(jrl)); javaResourceLocator = jrl; }

Target:
public static void setup() { Project project = mock(Project.class); ProjectFileSystem pfs = mock(ProjectFileSystem.class); JavaClasspath javaClasspath = mock(JavaClasspath.class); when(javaClasspath.getBinaryDirs()).thenReturn(Lists.newArrayList(new File("target/test-classes"))); when(javaClasspath.getElements()).thenReturn(Lists.newArrayList(new File("target/test-classes"))); File baseDir = new File("src/test/java"); when(project.getFileSystem()).thenReturn(pfs); when(pfs.getBasedir()).thenReturn(baseDir); SensorContext sensorContext = mock(SensorContext.class); DefaultJavaResourceLocator jrl = new DefaultJavaResourceLocator(project, javaClasspath, new SuppressWarningsFilter()); jrl.setSensorContext(sensorContext); JavaAstScanner.scanSingleFile(new File("src/test/java/org/sonar/java/DefaultJavaResourceLocatorTest.java"), new VisitorsBridge(jrl)); javaResourceLocator = jrl; }