auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>PageFilePageReader( <START> long readStart, <END> long readLength, FSDataInputStream inputStream, PagesSerde pagesSerde) throws IOException { this.pagesSerde = requireNonNull(pagesSerde, "pagesSerde is null"); this.readLength = readLength; requireNonNull(inputStream, "inputStream is null"); inputStream.seek(readStart); this.input = new InputStreamSliceInput(inputStream); }</code><technical_language>passing positioned limited input stream? (doing inputStream.seek(readStart); ByteStreams#limit outside)? If do need this class</technical_language>

Target:
public PageFilePageReader( long readStart, long readLength, FSDataInputStream inputStream, PagesSerde pagesSerde) throws IOException { this.pagesSerde = requireNonNull(pagesSerde, "pagesSerde is null"); this.readLength = readLength; requireNonNull(inputStream, "inputStream is null"); inputStream.seek(readStart); this.input = new InputStreamSliceInput(inputStream); }
Source:
<code>public void constructorTest() { final double memoryLength = 1e6; final double[] minorAlleleFractions = new double[] {0.1, 0.5, 0.23}; final double[] weights = new double[] {0.2, 0.2, 0.6}; final AllelicBiasParameters params = new AllelicBiasParameters(0.1, 0.01, 0.03); <START> AlleleFractionHiddenMarkovModel model = new AlleleFractionHiddenMarkovModel(minorAlleleFractions, weights, <END> memoryLength, AllelicPanelOfNormals.EMPTY_PON, params); Assert.assertEquals(memoryLength, model.getMemoryLength()); for (int n = 0; n < weights.length; n++) { Assert.assertEquals(weights[n], model.getWeight(n)); Assert.assertEquals(minorAlleleFractions[n], model.getMinorAlleleFraction(n)); } Assert.assertEquals(model.getParameters().getMeanBias(), params.getMeanBias()); Assert.assertEquals(model.getParameters().getBiasVariance(), params.getBiasVariance()); Assert.assertEquals(model.getParameters().getOutlierProbability(), params.getOutlierProbability()); }</code><technical_language>final</technical_language>

Target:
public void constructorTest() { final double memoryLength = 1e6; final double[] minorAlleleFractions = new double[] {0.1, 0.5, 0.23}; final double[] weights = new double[] {0.2, 0.2, 0.6}; final AlleleFractionGlobalParameters params = new AlleleFractionGlobalParameters(0.1, 0.01, 0.03); final AlleleFractionHiddenMarkovModel model = new AlleleFractionHiddenMarkovModel(minorAlleleFractions, weights, memoryLength, AllelicPanelOfNormals.EMPTY_PON, params); Assert.assertEquals(memoryLength, model.getMemoryLength()); for (int n = 0; n < weights.length; n++) { Assert.assertEquals(weights[n], model.getWeight(n)); Assert.assertEquals(minorAlleleFractions[n], model.getMinorAlleleFraction(n)); } Assert.assertEquals(model.getParameters().getMeanBias(), params.getMeanBias()); Assert.assertEquals(model.getParameters().getBiasVariance(), params.getBiasVariance()); Assert.assertEquals(model.getParameters().getOutlierProbability(), params.getOutlierProbability()); }
Source:
<code>public void enable() { if ( !enabled ) { this.enabled = true; <START> Collection<SyncBeanDef<MenuDevCommand>> beanDefs = beanManager.lookupBeans( MenuDevCommand.class ); <END> for ( SyncBeanDef<MenuDevCommand> beanDef : beanDefs ) { MenuDevCommand devCommand = beanDef.getInstance(); devCommands.add( devCommand ); } } }</code><technical_language>In general, a @Inject ManagedInstance<MenuDevCommand> instead is iterable. beans a properly destroyed..</technical_language>

Target:
public void enable() { if ( !enabled ) { this.enabled = true; menuDevCommandManagedInstances.iterator().forEachRemaining( devCommands::add ); } }
Source:
<code>protected List<DatabaseObject> mergeDatabaseObjects(List<DatabaseObject> objects) { int maxIdx = -1; for (DatabaseObject object: objects) { maxIdx = Math.max(maxIdx, object.getOrder()); } final List<DatabaseObject> orderedObjects = createListAndFillNull(maxIdx); final List<DatabaseObject> unorderedObjects = new ArrayList<>(); final List<DatabaseObject> mergedObjects = new ArrayList<>(); for (DatabaseObject object: objects) { if (object.getOrder() > -1) { int objIdx = object.getOrder(); if (objIdx < orderedObjects.size() && orderedObjects.get(objIdx) != null) { throw new TajoInternalError("This catalog configuration contains duplicated order of DatabaseObject"); } orderedObjects.add(objIdx, object); } else { unorderedObjects.add(object); } } orderedObjects.stream().filter(object -> object != null).forEach(mergedObjects::add); <START> unorderedObjects.stream().filter(object -> object != null).forEach(mergedObjects::add); <END> return mergedObjects; }</code><technical_language>merge statements this: java Stream.concat(orderedObjects.stream(), unorderedObjects.stream()) .filter(o -> o != null) .forEach(mergedObjects::add);</technical_language>

Target:
protected List<DatabaseObject> mergeDatabaseObjects(List<DatabaseObject> objects) { int maxIdx = -1; for (DatabaseObject object: objects) { maxIdx = Math.max(maxIdx, object.getOrder()); } final List<DatabaseObject> orderedObjects = createListAndFillNull(maxIdx); final List<DatabaseObject> unorderedObjects = new ArrayList<>(); final List<DatabaseObject> mergedObjects = new ArrayList<>(); for (DatabaseObject object: objects) { if (object.getOrder() > -1) { int objIdx = object.getOrder(); if (objIdx < orderedObjects.size() && orderedObjects.get(objIdx) != null) { throw new TajoInternalError("This catalog configuration contains duplicated order of DatabaseObject"); } orderedObjects.add(objIdx, object); } else { unorderedObjects.add(object); } } Stream.concat(orderedObjects.stream(), unorderedObjects.stream()) .filter(object -> object != null).forEach(mergedObjects::add); return mergedObjects; }
Source:
<code>private long createTable(String name) { <START> return dbi.onDemand(MetadataDao.class).insertTable("test", name, false, true, null, 0, false); <END> }</code><technical_language>do change organized argument false true</technical_language>

Target:
private long createTable(String name) { return dbi.onDemand(MetadataDao.class).insertTable("test", name, false, false, null, 0, false); }
Source:
<code>public static void parseAndReact(@NonNull Activity activity, @NonNull JSONObject paramsJson) throws JSONException { logger.debug("DeepLink received. JSON Details:\n" + paramsJson); final Router router = new Router(); final boolean isLoggedIn = new LoginPrefs(activity).getUsername() != null; if (!isLoggedIn) { activity.startActivity(router.getLogInIntent()); } else { <START> final String screenName = paramsJson.getString(KEY_SCREEN_NAME); <END> switch (screenName) { case Screen.COURSE_DASHBOARD: final String courseId = paramsJson.getString(KEY_COURSE_ID); router.showCourseDashboardTabs(activity, null, courseId, false); break; } } }</code><technical_language>ScreenDef annotation screenName variable</technical_language>

Target:
public static void parseAndReact(@NonNull Activity activity, @NonNull JSONObject paramsJson) throws JSONException { logger.debug("DeepLink received. JSON Details:\n" + paramsJson); final Router router = new Router(); final boolean isLoggedIn = new LoginPrefs(activity).getUsername() != null; if (!isLoggedIn) { activity.startActivity(router.getLogInIntent()); } else { @ScreenDef final String screenName = paramsJson.getString(KEY_SCREEN_NAME); switch (screenName) { case Screen.COURSE_DASHBOARD: final String courseId = paramsJson.getString(KEY_COURSE_ID); router.showCourseDashboardTabs(activity, null, courseId, false); break; } } }
Source:
<code>private void applyService(ObjectEnhancementService service) throws EnhancementException { int backoffAttempts = 1; while (true) { LOG.info("Applying service to object {}", service.getClass().getName(), message.getTargetID()); long retryDelay; try { fedoraManagementClient.waitForRepositoryAvailable(); service.getEnhancement(message).call(); message.getCompletedServices().add(service.getClass().getName()); break; } catch (EnhancementException e) { if (backoffAttempts < MAX_RETRIES && e.getSeverity() == Severity.RECOVERABLE) { <START> LOG.warn("Retrying service for recoverable exception {}, attempt {}: {}: ", <END> new Object[] { service.getClass().getName(), backoffAttempts }, e); retryDelay = recoverableDelay; } else { throw e; } } catch (ServiceException e) { if (backoffAttempts < MAX_RETRIES && e.getCause() instanceof WebServiceIOException) { LOG.warn("Failed to persist changes for service {}, attempt {}", new Object[] { service.getClass().getName(), backoffAttempts }, e); retryDelay = BACKOFF_DELAY * backoffAttempts; } else { throw e; } } backoffAttempts++; message.setFoxml(null); try { Thread.sleep(retryDelay); } catch (InterruptedException e1) { LOG.warn("Thread interrupted while waiting to reattempt job {}", service.getClass().getName()); Thread.currentThread().interrupt(); break; } } }</code><technical_language>i extra {}: in logging string</technical_language>

Target:
private void applyService(ObjectEnhancementService service) throws EnhancementException { int backoffAttempts = 1; while (true) { LOG.info("Applying service to object {}", service.getClass().getName(), message.getTargetID()); long retryDelay; try { fedoraManagementClient.waitForRepositoryAvailable(); service.getEnhancement(message).call(); message.getCompletedServices().add(service.getClass().getName()); break; } catch (EnhancementException e) { if (backoffAttempts < MAX_RETRIES && e.getSeverity() == Severity.RECOVERABLE) { LOG.warn("Retrying service for recoverable exception {}, attempt {}.", new Object[] { service.getClass().getName(), backoffAttempts }, e); retryDelay = recoverableDelay; } else { throw e; } } catch (ServiceException e) { if (backoffAttempts < MAX_RETRIES && e.getCause() instanceof WebServiceIOException) { LOG.warn("Failed to persist changes for service {}, attempt {}", new Object[] { service.getClass().getName(), backoffAttempts }, e); retryDelay = BACKOFF_DELAY * backoffAttempts; } else { throw e; } } backoffAttempts++; message.setFoxml(null); try { Thread.sleep(retryDelay); } catch (InterruptedException e1) { LOG.warn("Thread interrupted while waiting to reattempt job {}", service.getClass().getName()); Thread.currentThread().interrupt(); break; } } }
Source:
<code>public void signalReady() { <START> ((FileSystemDataset<E>)dataset).signalReady(getConstraints()); <END> }</code><technical_language>I cast FileSystemDataset here. prefer pass signal manager views, do partition listener, find some other way, adding getSignalManager AbstractRefinableView, in case return null default, dataset implementation provides a signal manager</technical_language>

Target:
public void signalReady() { if (signalManager != null) { signalManager.signalReady(getConstraints()); } }
Source:
<code>public IngredientRecipe(String name, int attributes, Boolean swapped, List<IngredientRecipe> contents) { this.name = name; this.setAttributes(attributes); this.contents = contents; this.traits = new TreeSet<String>(); this.swapped = swapped; this.necessaryTraits = new HashMap<String, IngredientRecipe>(); this.useCount = 1; <START> this.toolTraits = new TreeSet<String>(); <END> this.toolAttributes = new TreeSet<String>(); }</code><technical_language>Do traits ordered? a hashset instead</technical_language>

Target:
public IngredientRecipe(String name, int attributes, Boolean swapped, List<IngredientRecipe> contents) { this.name = name; this.setAttributes(attributes); this.contents = contents; this.swapped = swapped; this.useCount = 1; this.traits = new HashSet<String>(); this.necessaryTraits = new HashMap<String, IngredientRecipe>(); this.toolTraits = new HashSet<String>(); this.toolAttributes = new HashSet<String>(); this.recipeToolAttributes = new HashSet<String>(); }
Source:
<code>public synchronized void runAll() { String cronExecutingUser = (String) getConfig().get("cronExecutingUser"); if (null == cronExecutingUser) { cronExecutingUser = "anonymous"; <START> } <END> AuthenticationInfo authenticationInfo = new AuthenticationInfo(); authenticationInfo.setUser(cronExecutingUser); runAll(authenticationInfo, true); }</code><technical_language>is matters here, check for empty blank string</technical_language>

Target:
public synchronized void runAll() { String cronExecutingUser = (String) getConfig().get("cronExecutingUser"); String cronExecutingRoles = (String) getConfig().get("cronExecutingRoles"); if (null == cronExecutingUser) { cronExecutingUser = "anonymous"; } AuthenticationInfo authenticationInfo = new AuthenticationInfo( cronExecutingUser, StringUtils.isEmpty(cronExecutingRoles) ? null : cronExecutingRoles, null); runAll(authenticationInfo, true); }
Source:
<code>public Object apply(MemberResource resource, PutMember.Input input) throws AuthException, MethodNotAllowedException, BadRequestException, OrmException { <START> return Response.none(); <END> }</code><technical_language>This return 204 content, return 200 a description of member PUT /groups/{id}/members returns a description of new members</technical_language>

Target:
public Object apply(MemberResource resource, PutMember.Input input) { return get.get().apply(resource); }
Source:
<code>private ObjectNode processTProperties(Properties cProperties, String formName) { ObjectNode schema = JsonNodeFactory.instance.objectNode(); Form form = cProperties.getPreferredForm(formName); if (form != null) { schema.put(JsonSchemaConstants.TAG_TITLE, form.getTitle()); } schema.put(JsonSchemaConstants.TAG_TYPE, JsonSchemaConstants.TYPE_OBJECT); schema.putObject(JsonSchemaConstants.TAG_PROPERTIES); List<Property> propertyList = getSubProperty(cProperties); for (Property property : propertyList) { String name = property.getName(); if (property.isRequired()) { addToRequired(schema, name); } ((ObjectNode) schema.get(JsonSchemaConstants.TAG_PROPERTIES)).set(name, processTProperty(property)); } List<Properties> propertiesList = getSubProperties(cProperties); for (Properties properties : propertiesList) { String name = properties.getName(); if (properties instanceof ReferenceProperties<?>) { ReferenceProperties<?> referenceProperties = (ReferenceProperties<?>) properties; ((ObjectNode) schema.get(JsonSchemaConstants.TAG_PROPERTIES)).set(name, processReferenceProperties(referenceProperties)); } else { <START> ((ObjectNode) schema.get(JsonSchemaConstants.TAG_PROPERTIES)).set(name, processTProperties(properties, formName)); <END> } } return schema; }</code><technical_language>I wondering if for Properties need a title related some form name top</technical_language>

Target:
private ObjectNode processTProperties(Properties cProperties, String formName) { ObjectNode schema = JsonNodeFactory.instance.objectNode(); Form form = null; if (formName != null) { form = cProperties.getPreferredForm(formName); } if (form != null) { schema.put(JsonSchemaConstants.TAG_TITLE, form.getTitle()); } schema.put(JsonSchemaConstants.TAG_TYPE, JsonSchemaConstants.TYPE_OBJECT); schema.putObject(JsonSchemaConstants.TAG_PROPERTIES); List<Property> propertyList = getSubProperty(cProperties); for (Property property : propertyList) { String name = property.getName(); if (property.isRequired()) { addToRequired(schema, name); } ((ObjectNode) schema.get(JsonSchemaConstants.TAG_PROPERTIES)).set(name, processTProperty(property)); } List<Properties> propertiesList = getSubProperties(cProperties); for (Properties properties : propertiesList) { String name = properties.getName(); if (properties instanceof ReferenceProperties<?>) { ReferenceProperties<?> referenceProperties = (ReferenceProperties<?>) properties; ((ObjectNode) schema.get(JsonSchemaConstants.TAG_PROPERTIES)).set(name, processReferenceProperties(referenceProperties)); } else { ((ObjectNode) schema.get(JsonSchemaConstants.TAG_PROPERTIES)).set(name, processTProperties(properties, formName)); } } return schema; }
Source:
<code>private int runMove(final String srcId, final String destId) { final CountDownLatch finishedLatch = new CountDownLatch(1); final int initialSrcNumBlocks = getNumBlocks(srcId); final int initialDestNumBlocks = getNumBlocks(destId); final int numToMove = Math.max(1, RANDOM.nextInt(initialSrcNumBlocks)); LOG.log(Level.INFO, "Move {0} blocks from {1} to {2} (Initial number of blocks: {3} / {4} respectively)", new Object[]{numToMove, srcId, destId, initialSrcNumBlocks, initialDestNumBlocks}); final boolean[] moveSucceeded = {false}; final TraceScope moveTraceScope = <START> Trace.startSpan(String.format("SimpleMove. srcId: %s, dstId: %s", srcId, destId), Sampler.ALWAYS); <END> elasticMemory.move(numToMove, srcId, destId, new EventHandler<AvroElasticMemoryMessage>() { @Override public void onNext(final AvroElasticMemoryMessage emMsg) { moveSucceeded[0] = emMsg.getResultMsg().getResult().equals(Result.SUCCESS); LOG.log(Level.INFO, "Was Move {0} successful? {1}. The result: {2}", new Object[]{emMsg.getOperationId(), moveSucceeded[0], emMsg.getResultMsg() == null ? "" : emMsg.getResultMsg().getResult()}); finishedLatch.countDown(); moveTraceScope.close(); } } ); try { LOG.log(Level.INFO, "Waiting for move to finish"); finishedLatch.await(); checkNumBlocks(srcId, initialSrcNumBlocks - numToMove); checkNumBlocks(destId, initialDestNumBlocks + numToMove); if (moveSucceeded[0]) { LOG.log(Level.INFO, "Move finished successfully"); } else { throw new RuntimeException("Move failed"); } } catch (final InterruptedException e) { throw new RuntimeException("Interrupted while waiting Move", e); } return numToMove; }</code><technical_language>change camel case snake case, Zipkin fails represent</technical_language>

Target:
private int runMove(final String srcId, final String destId) { final CountDownLatch finishedLatch = new CountDownLatch(1); final int initialSrcNumBlocks = getNumBlocks(srcId); final int initialDestNumBlocks = getNumBlocks(destId); final int numToMove = Math.max(1, RANDOM.nextInt(initialSrcNumBlocks)); LOG.log(Level.INFO, "Move {0} blocks from {1} to {2} (Initial number of blocks: {3} / {4} respectively)", new Object[]{numToMove, srcId, destId, initialSrcNumBlocks, initialDestNumBlocks}); final boolean[] moveSucceeded = {false}; elasticMemory.move(numToMove, srcId, destId, new EventHandler<AvroElasticMemoryMessage>() { @Override public void onNext(final AvroElasticMemoryMessage emMsg) { moveSucceeded[0] = emMsg.getResultMsg().getResult().equals(Result.SUCCESS); LOG.log(Level.INFO, "Was Move {0} successful? {1}. The result: {2}", new Object[]{emMsg.getOperationId(), moveSucceeded[0], emMsg.getResultMsg() == null ? "" : emMsg.getResultMsg().getResult()}); finishedLatch.countDown(); } } ); try { LOG.log(Level.INFO, "Waiting for move to finish"); finishedLatch.await(); checkNumBlocks(srcId, initialSrcNumBlocks - numToMove); checkNumBlocks(destId, initialDestNumBlocks + numToMove); if (moveSucceeded[0]) { LOG.log(Level.INFO, "Move finished successfully"); } else { throw new RuntimeException("Move failed"); } } catch (final InterruptedException e) { throw new RuntimeException("Interrupted while waiting Move", e); } return numToMove; }
Source:
<code>public static FixedDoubleHistogram deserialize(SliceInput input) { int bucketCount = input.readInt(); double min = input.readDouble(); double max = input.readDouble(); verifyParameters(bucketCount, min, max); double[] weights = new double[bucketCount]; <START> input.readBytes( <END> Slices.wrappedDoubleArray(weights), bucketCount * SizeOf.SIZE_OF_DOUBLE); return new FixedDoubleHistogram(bucketCount, min, max, weights); }</code><technical_language>put arguments line</technical_language>

Target:
public static FixedDoubleHistogram deserialize(SliceInput input) { int bucketCount = input.readInt(); double min = input.readDouble(); double max = input.readDouble(); validateParameters(bucketCount, min, max); double[] weights = new double[bucketCount]; input.readBytes(Slices.wrappedDoubleArray(weights), bucketCount * SizeOf.SIZE_OF_DOUBLE); return new FixedDoubleHistogram(bucketCount, min, max, weights); }
Source:
<code>protected void doCreateOrUpdate(WorkspaceExpiration expiration) { final EntityManager manager = managerProvider.get(); if (manager.find(WorkspaceExpiration.class, expiration.getWorkspaceId()) == null) { <START> manager.persist(expiration); <END> } else { manager.merge(expiration); manager.flush(); } }</code><technical_language>need flush persist merge operation</technical_language>

Target:
protected void doCreateOrUpdate(WorkspaceExpiration expiration) { final EntityManager manager = managerProvider.get(); if (manager.find(WorkspaceExpiration.class, expiration.getWorkspaceId()) == null) { manager.persist(expiration); } else { manager.merge(expiration); } manager.flush(); }
Source:
<code>public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.convert(TimeUnit.NANOSECONDS)); <START> hash = LangUtils.hashCode(hash, TimeUnit.NANOSECONDS); <END> return hash; }</code><technical_language>@michael-o hash = LangUtils.hashCode(hash, TimeUnit.NANOSECONDS) dropped unnecessary</technical_language>

Target:
public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.convert(TimeUnit.NANOSECONDS)); return hash; }
Source:
<code>public void testPublishPost() { String title = "Title"; String content = "Content"; wpLogin(); MasterbarComponent mb = new MasterbarComponent().goToMySitesTab(); sleep(); mb.clickBlogPosts(); new MySitesPage() .startNewPost(E2E_DEFAULT_USER_SITE_ADDRESS); new EditorPage() .enterTitle(title) .enterContent(content) .publishPost(); <START> sleep(10000); <END> new SnackbarComponent() .verifyPostPublished(); }</code><technical_language>noted this resolved mocking network requests, for this sleep is causing test fail for me. upload faster end time test moves snackbar is screen. hesitant spend time fixing this as-is plan set mocking start tests, though</technical_language>

Target:
public void testPublishPost() { String title = "Title"; String content = "Content"; wpLogin(); MasterbarComponent mb = new MasterbarComponent().goToMySitesTab(); sleep(); mb.clickBlogPosts(); new MySitesPage() .startNewPost(E2E_WP_COM_USER_SITE_ADDRESS); boolean isPublished = new EditorPage() .enterTitle(title) .enterContent(content) .publishPost(); assertTrue(isPublished); }
Source:
<code>private CompletableFuture<PhysicalSlotRequest.Result> allocatePhysicalSlot( final PhysicalSlotRequest physicalSlotRequest) { final SlotRequestId slotRequestId = physicalSlotRequest.getSlotRequestId(); final SlotProfile slotProfile = physicalSlotRequest.getSlotProfile(); final ResourceProfile resourceProfile = slotProfile.getPhysicalSlotResourceProfile(); LOG.debug("Received slot request with resource requirements: {}", slotRequestId, resourceProfile); final Optional<PhysicalSlot> availablePhysicalSlot = tryAllocateFromAvailable(slotRequestId, slotProfile); final CompletableFuture<PhysicalSlot> slotFuture; if (availablePhysicalSlot.isPresent()) { slotFuture = CompletableFuture.completedFuture(availablePhysicalSlot.get()); <START> } else if (physicalSlotRequest.willSlotBeOccupiedIndefinitely()) { slotFuture = slotPool.requestNewAllocatedSlot( slotRequestId, resourceProfile, null); } else { slotFuture = slotPool.requestNewAllocatedBatchSlot( <END> slotRequestId, resourceProfile); } return slotFuture.thenApply(physicalSlot -> new PhysicalSlotRequest.Result(slotRequestId, physicalSlot)); }</code><technical_language>nit: more method slotFuture = requestNewSlot(willSlotBeOccupiedIndefinitely, slotRequestId, resourceProfile)</technical_language>

Target:
private CompletableFuture<PhysicalSlotRequest.Result> allocatePhysicalSlot( final PhysicalSlotRequest physicalSlotRequest) { final SlotRequestId slotRequestId = physicalSlotRequest.getSlotRequestId(); final SlotProfile slotProfile = physicalSlotRequest.getSlotProfile(); final ResourceProfile resourceProfile = slotProfile.getPhysicalSlotResourceProfile(); LOG.debug("Received slot request with resource requirements: {}", slotRequestId, resourceProfile); final Optional<PhysicalSlot> availablePhysicalSlot = tryAllocateFromAvailable(slotRequestId, slotProfile); final CompletableFuture<PhysicalSlot> slotFuture; if (availablePhysicalSlot.isPresent()) { slotFuture = CompletableFuture.completedFuture(availablePhysicalSlot.get()); } else { slotFuture = requestNewSlot( slotRequestId, resourceProfile, physicalSlotRequest.willSlotBeOccupiedIndefinitely()); } return slotFuture.thenApply(physicalSlot -> new PhysicalSlotRequest.Result(slotRequestId, physicalSlot)); }
Source:
<code>public ValueRange range(ChronoField field) { <START> switch (field) { <END> case ALIGNED_WEEK_OF_MONTH: return alignedWeekOfMonthRange; case DAY_OF_MONTH: return dayOfMonthRange; case DAY_OF_YEAR: return DAY_OF_YEAR_RANGE; case MONTH_OF_YEAR: return division.getMonthsInYearRange(); case PROLEPTIC_MONTH: return division == THIRTEEN_EVEN_MONTHS_OF_4_WEEKS ? PROLEPTIC_MONTH_RANGE_13 : PROLEPTIC_MONTH_RANGE_12; default: break; } return field.range(); }</code><technical_language>I thought aligned week of year differ ISO chronology</technical_language>

Target:
public ValueRange range(ChronoField field) { switch (field) { case ALIGNED_WEEK_OF_MONTH: return alignedWeekOfMonthRange; case ALIGNED_WEEK_OF_YEAR: return ALIGNED_WEEK_OF_YEAR_RANGE; case DAY_OF_MONTH: return dayOfMonthRange; case DAY_OF_YEAR: return DAY_OF_YEAR_RANGE; case MONTH_OF_YEAR: return division.getMonthsInYearRange(); case PROLEPTIC_MONTH: return division == THIRTEEN_EVEN_MONTHS_OF_4_WEEKS ? PROLEPTIC_MONTH_RANGE_13 : PROLEPTIC_MONTH_RANGE_12; default: break; } return field.range(); }
Source:
<code>public CompletableFuture<Void> deleteTableSnapshots(Pattern tableNamePattern) { <START> throw new UnsupportedOperationException("please use deleteSnapshot"); <END> }</code><technical_language>Please add a note this implemented right</technical_language>

Target:
public CompletableFuture<Void> deleteTableSnapshots(Pattern tableNamePattern) { throw new UnsupportedOperationException("use deleteSnapshot instead"); }
Source:
<code>private CompositeJobParametersValidator compositeJobParametersValidator() { final List<JobParametersValidator> jobParametersValidators = Arrays.asList( <START> new ConfigRestartabilityAllowValidator(), <END> new DbCollectionsVariantsNameValidator(), new DbNameValidator(), new InputStudyIdValidator(), new InputVcfIdValidator(), new OutputDirAnnotationValidator() ); CompositeJobParametersValidator compositeJobParametersValidator = new CompositeJobParametersValidator(); compositeJobParametersValidator.setValidators(jobParametersValidators); return compositeJobParametersValidator; }</code><technical_language>this argument is mandatory, check wrapped a conditional. I 2 ways do this: * Moving out of composite validator adding "if" condition validate method. This messy for steps multiple optional arguments. * Wrapping ConfigRestartabilityAllowValidator OptionalParameterValidator that, declared "inside" composite validator. This is another indirection level</technical_language>

Target:
private CompositeJobParametersValidator compositeJobParametersValidator() { final List<JobParametersValidator> jobParametersValidators = Arrays.asList( new OptionalValidator(new ConfigRestartabilityAllowValidator(), JobParametersNames.CONFIG_RESTARTABILITY_ALLOW), new DbCollectionsVariantsNameValidator(), new DbNameValidator(), new InputStudyIdValidator(), new InputVcfIdValidator(), new OutputDirAnnotationValidator() ); CompositeJobParametersValidator compositeJobParametersValidator = new CompositeJobParametersValidator(); compositeJobParametersValidator.setValidators(jobParametersValidators); return compositeJobParametersValidator; }
Source:
<code>public void stopServices() throws ConflictException { if (!statusRef.compareAndSet(RUNNING, PREPARING_TO_SHUTDOWN)) { throw new ConflictException("System shutdown has been already called, system status: " + statusRef.get()); } ExecutorService exec = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setDaemon(false) <START> .setNameFormat("ShutdownSystemServicesPool-%s") <END> .setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance()) .build()); exec.execute(ThreadLocalPropagateContext.wrap(this::doStopServices)); exec.shutdown(); }</code><technical_language>FYI avoid %s is single thread executor</technical_language>

Target:
public void stopServices() throws ConflictException { if (!statusRef.compareAndSet(RUNNING, PREPARING_TO_SHUTDOWN)) { throw new ConflictException("System shutdown has been already called, system status: " + statusRef.get()); } ExecutorService exec = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setDaemon(false) .setNameFormat("ShutdownSystemServicesPool") .setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance()) .build()); exec.execute(ThreadLocalPropagateContext.wrap(this::doStopServices)); exec.shutdown(); }
Source:
<code>public HostBricksListModel() { setTitle(ConstantsManager.getInstance().getConstants().hostBricksTitle()); <START> setHashName("host_bricks"); END> setAvailableInModes(ApplicationMode.GlusterOnly); }</code><technical_language>this match place token</technical_language>

Target:
public HostBricksListModel() { setTitle(ConstantsManager.getInstance().getConstants().hostBricksTitle()); setHashName("gluster_bricks"); setAvailableInModes(ApplicationMode.GlusterOnly); }
Source:
<code>public void analyze(Document doc, StreamSource src, Writer xrefOut) throws IOException { StringBuilder fout = new StringBuilder(); try (ZipInputStream zis = new ZipInputStream(src.getStream())) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String ename = entry.getName(); if (xrefOut != null) { xrefOut.append("<br/><b>"); Util.htmlize(ename, xrefOut); xrefOut.append("</b>"); } useExtantValue(fout, doc, QueryBuilder.FULL); fout.append(" fout.append(ename); fout.append("\n"); String fstr = fout.toString(); doc.add(new TextField(QueryBuilder.FULL, fstr, Store.YES)); fout.setLength(0); FileAnalyzerFactory fac = AnalyzerGuru.find(ename); if (fac instanceof JavaClassAnalyzerFactory) { if (xrefOut != null) { xrefOut.append("<br/>"); } JavaClassAnalyzer jca = (JavaClassAnalyzer) fac.getAnalyzer(); <START> jca.analyze(doc, new BufferedInputStream(zis), xrefOut,ename); <END> } } } }</code><technical_language>arg is new</technical_language>

Target:
public void analyze(Document doc, StreamSource src, Writer xrefOut) throws IOException { StringBuilder fout = new StringBuilder(); try (ZipInputStream zis = new ZipInputStream(src.getStream())) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String ename = entry.getName(); if (xrefOut != null) { xrefOut.append("<br/><b>"); Util.htmlize(ename, xrefOut); xrefOut.append("</b>"); } useExtantValue(fout, doc, QueryBuilder.FULL); fout.append(" fout.append(ename); fout.append("\n"); String fstr = fout.toString(); doc.add(new TextField(QueryBuilder.FULL, fstr, Store.YES)); fout.setLength(0); FileAnalyzerFactory fac = AnalyzerGuru.find(ename); if (fac instanceof JavaClassAnalyzerFactory) { if (xrefOut != null) { xrefOut.append("<br/>"); } JavaClassAnalyzer jca = (JavaClassAnalyzer) fac.getAnalyzer(); jca.analyze(doc, new BufferedInputStream(zis), xrefOut); } } } }
Source:
<code>protected void configureTitleAndSidePanel() { if (!ForumController.get().hasForums()) return ; <START> if (selectedForumId != null) <END> selectedForum = ForumController.get().getForumById(selectedForumId); else { selectedForum = ForumController.get().getFirstForum(); selectedForumId = selectedForum.id; TopicController.get().getTopics(selectedForumId); } forumSummarySidePanel.selectItem(selectedForum); if (selectedForum != null) { titleText.setInnerText(selectedForum.title); } forumSummarySidePanel.redraw(); }</code><technical_language>braces in ifs throw exception i.e. add another line of code if</technical_language>

Target:
protected void configureTitleAndSidePanel() { if (ForumController.get().hasForums()) { if (selectedForumId != null) { selectedForum = ForumController.get().getForumById(selectedForumId); } else { selectedForum = ForumController.get().getFirstForum(); selectedForumId = selectedForum.id; TopicController.get().getTopics(selectedForumId); } forumSummarySidePanel.selectItem(selectedForum); if (selectedForum != null) { titleText.setInnerText(selectedForum.title); } forumSummarySidePanel.redraw(); } }
Source:
<code>public void elasticsearchDefaultTest() throws IOException { <START> container = new ElasticsearchContainer(); <END> container.start(); Response response = getClient(container).performRequest(new Request("GET", "/")); assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(EntityUtils.toString(response.getEntity()), containsString("6.4.1")); response = getClient(container).performRequest(new Request("GET", "/_xpack/")); assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(EntityUtils.toString(response.getEntity()), containsString("monitoring")); }</code><technical_language>try-with-resources pattern here, means need stopContainer method (we for other tests). big deal, though</technical_language>

Target:
public void elasticsearchDefaultTest() throws IOException { try (ElasticsearchContainer container = new ElasticsearchContainer()){ container.start(); Response response = getClient(container).performRequest(new Request("GET", "/")); assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(EntityUtils.toString(response.getEntity()), containsString(ELASTICSEARCH_DEFAULT_VERSION)); response = getClient(container).performRequest(new Request("GET", "/_xpack/")); assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(EntityUtils.toString(response.getEntity()), containsString("monitoring")); } }
Source:
<code>public ByteBuffer newByteBuffer(byte[] b, int offset, int length) { <START> return b == null || b.length == 0 || length == 0 ? ByteBufferImpl.EMPTY_INSTANCE : new ByteBufferImpl(b, offset, length); <END> }</code><technical_language>be: java return ByteBufferImpl.create(b, offset, length);</technical_language>

Target:
public ByteBuffer newByteBuffer(byte[] b, int offset, int length) { return ByteBufferImpl.create(b, offset, length); }
Source:
<code>@Test public void getDeletedDateOf_returnsDeletedDate() { FormMapViewModel viewModel = new FormMapViewModel(TEST_FORM_1, testInstancesRepository); <START> assertThat(viewModel.getDeletedDateOf(0L), is(1487782554846L)); <END> }</code><technical_language>Minor nitpick: assertion equal testInstance[0].getDeletedDate() instead. a bit hard track this is coming from</technical_language>

Target:
@Test public void getDeletedDateOf_returnsDeletedDate() { FormMapViewModel viewModel = new FormMapViewModel(TEST_FORM_1, testInstancesRepository); assertThat(viewModel.getDeletedDateOf(0L), is(testInstances[0].getDeletedDate())); }
Source:
<code>public int getViewTypeCount() { <START> return 4; <END> }</code><technical_language>get enumerations array size types shift enumeration</technical_language>

Target:
public int getViewTypeCount() { return SectionRow.NUM_OF_SECTION_ROWS; }
Source:
<code>protected void executeQueryCommand() { List<OvfEntityData> entityList = unregisteredOVFDataDao.getByEntityIdAndStorageDomain(getParameters().getEntityId(), getParameters().getStorageDomainId()); VmTemplate vmTemplate = null; if (!entityList.isEmpty()) { OvfEntityData ovfEntityData = entityList.get(0); try { vmTemplate = ovfHelper.readVmTemplateFromOvf(ovfEntityData.getOvfData()).getVmTemplate(); } catch (OvfReaderException e) { log.debug("Failed to parse a given ovf configuration: \n" + ovfEntityData.getOvfData(), e); getQueryReturnValue().setExceptionString("Failed to parse a given ovf configuration: " + e.getMessage()); } } <START> getQueryReturnValue().setSucceeded(true); <END> getQueryReturnValue().setReturnValue(vmTemplate); }</code><technical_language>remove, default true.</technical_language>

Target:
protected void executeQueryCommand() { List<OvfEntityData> entityList = unregisteredOVFDataDao.getByEntityIdAndStorageDomain(getParameters().getEntityId(), getParameters().getStorageDomainId()); VmTemplate vmTemplate = null; if (!entityList.isEmpty()) { OvfEntityData ovfEntityData = entityList.get(0); try { vmTemplate = ovfHelper.readVmTemplateFromOvf(ovfEntityData.getOvfData()).getVmTemplate(); } catch (OvfReaderException e) { log.debug("Failed to parse a given ovf configuration: \n" + ovfEntityData.getOvfData(), e); getQueryReturnValue().setExceptionString("Failed to parse a given ovf configuration: " + e.getMessage()); } } getQueryReturnValue().setReturnValue(vmTemplate); }
Source:
<code><START> public @Nonnull String getLabel() { <END> try { return Messages.class.getMethod("ManagementLink_Category_" + this.toString()).invoke(null).toString(); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { return Messages.ManagementLink_Category_UNCATEGORIZED(); } }</code><technical_language>inline this in enum? java public enum Category { CONFIGURATION(Messages._ManagementLink_Category_CONFIGURATION()), SECURITY(Messages._ManagementLink_Category_SECURITY()); //..... private Localizable label; Category(Localizable label) { this.label = label); } public Sting getLabel() { return label.toString(); } }</technical_language>

Target:
public @Nonnull String getLabel() { return label.toString(); }
Source:
<code>public Node removeNode(SimpleUri nodeUri) { Preconditions.checkNotNull(nodeUri, "nodeUri cannot be null!"); Node node = findNode(nodeUri); if (!graph.nodes().contains(node)) { <START> throw new RuntimeException("The node you specified is not present in the graph!"); <END> } if (graph.adjacentNodes(node).size() != 0) { throw new RuntimeException("The node you are trying to remove is still connected to other nodes in the graph!"); } nodeMap.remove(nodeUri); return nodeMap.remove(nodeUri); }</code><technical_language>throw new RuntimeException("Node removal failure: is '"+nodeUri+"' in render graph!");</technical_language>

Target:
public Node removeNode(SimpleUri nodeUri) { Preconditions.checkNotNull(nodeUri, "nodeUri cannot be null!"); Node node = findNode(nodeUri); if (node == null) { throw new RuntimeException("Node removal failure: there is no '" + nodeUri + "' in the render graph!"); } if (graph.adjacentNodes(node).size() != 0) { throw new RuntimeException("Node removal failure: node '" + nodeUri + "' is still connected to other nodes in the render graph!"); } nodeMap.remove(nodeUri); return nodeMap.remove(nodeUri); }
Source:
<code>public LifecycleForkJoinPoolProvider getMergeProcessingPoolProvider(DruidProcessingConfig config) { return new LifecycleForkJoinPoolProvider( config.getNumThreadsMergePool(), <START> ForkJoinPool.defaultForkJoinWorkerThreadFactory, END> null, true, config.getMergePoolAwaitShutdownMillis() ); }</code><technical_language>worth more debug friendly for familiar Druid internal</technical_language>

Target:
public LifecycleForkJoinPoolProvider getMergeProcessingPoolProvider(DruidProcessingConfig config) { return new LifecycleForkJoinPoolProvider( config.getMergePoolParallelism(), ForkJoinPool.defaultForkJoinWorkerThreadFactory, (t, e) -> log.error(e, "Unhandled exception in thread [%s]", t), true, config.getMergePoolAwaitShutdownMillis() ); }
Source:
<code>protected HttpCalloutOutcomes doTaskBackground(Object... params) { HttpCalloutOutcomes preHttpOutcome = doSetupTaskBeforeRequest(); if (preHttpOutcome != null) { return preHttpOutcome; } boolean calloutFailed = false; if (shouldMakeHttpCallout()) { HttpCalloutOutcomes outcome; try { Response response = doHttpRequest(); int responseCode = response.code(); if (responseCode >= 200 && responseCode < 300) { outcome = doResponseSuccess(response); } else if (responseCode == 401) { outcome = doResponseAuthFailed(response); } else { outcome = doResponseOther(response); } } catch (UnknownHostException e) { outcome = HttpCalloutOutcomes.NetworkFailure; <START> } catch (SSLPeerUnverifiedException e) { <END> outcome = HttpCalloutOutcomes.BadCertificate; } catch (IOException e) { e.printStackTrace(); outcome = HttpCalloutOutcomes.NetworkFailure; } if (outcome != HttpCalloutOutcomes.Success) { if (calloutSuccessRequired()) { return outcome; } else { calloutFailed = true; } } else { if (!processSuccessfulRequest()) { return HttpCalloutOutcomes.BadResponse; } } } return doPostCalloutTask(calloutFailed); }</code><technical_language>@shubham1g5 Do this is new libraries flag SSL errors us, do need choose new exceptions for processing SSL connection issues</technical_language>

Target:
protected HttpCalloutOutcomes doTaskBackground(Object... params) { HttpCalloutOutcomes preHttpOutcome = doSetupTaskBeforeRequest(); if (preHttpOutcome != null) { return preHttpOutcome; } boolean calloutFailed = false; if (shouldMakeHttpCallout()) { HttpCalloutOutcomes outcome; try { Response response = doHttpRequest(); int responseCode = response.code(); if (responseCode >= 200 && responseCode < 300) { outcome = doResponseSuccess(response); } else if (responseCode == 401) { outcome = doResponseAuthFailed(response); } else { outcome = doResponseOther(response); } } catch (UnknownHostException e) { outcome = HttpCalloutOutcomes.NetworkFailure; } catch (SSLPeerUnverifiedException e) { outcome = HttpCalloutOutcomes.BadCertificate; } catch (AuthenticationInterceptor.PlainTextPasswordException e) { e.printStackTrace(); outcome = HttpCalloutOutcomes.AuthOverHttp; } catch (IOException e) { e.printStackTrace(); outcome = HttpCalloutOutcomes.NetworkFailure; } if (outcome != HttpCalloutOutcomes.Success) { if (calloutSuccessRequired()) { return outcome; } else { calloutFailed = true; } } else { if (!processSuccessfulRequest()) { return HttpCalloutOutcomes.BadResponse; } } } return doPostCalloutTask(calloutFailed); }
Source:
<code>public void weave(WovenClass wovenClass) { String className = wovenClass.getClassName(); if (className.equals("org.openengsb.core.api.model.annotation.Model") || className.contains("javassist") || className.contains("JavassistUtils")) { return; } try { <START> LOGGER.debug("try to enhance {}", className); <END> byte[] result = doActualWeaving(wovenClass.getBytes(), wovenClass.getBundleWiring().getClassLoader()); if (result != null) { wovenClass.getDynamicImports().add("org.openengsb.core.api.model"); wovenClass.setBytes(result); } LOGGER.debug("finished enhancing {}", className); } catch (IOException e) { e.printStackTrace(); } catch (CannotCompileException e) { e.printStackTrace(); } }</code><technical_language>log lvl trace here</technical_language>

Target:
public void weave(WovenClass wovenClass) { String className = wovenClass.getClassName(); if (className.equals("org.openengsb.core.api.model.annotation.Model") || className.contains("javassist") || className.contains("JavassistUtils")) { return; } try { LOGGER.trace("try to enhance {}", className); byte[] result = doActualWeaving(wovenClass.getBytes(), wovenClass.getBundleWiring().getClassLoader()); if (result != null) { wovenClass.getDynamicImports().add("org.openengsb.core.api.model"); wovenClass.setBytes(result); } LOGGER.trace("finished enhancing {}", className); } catch (IOException e) { LOGGER.error("IOException while trying to enhance model {}", className, e); } catch (CannotCompileException e) { LOGGER.error("CannotCompileException while trying to enhance model {}", className, e); } }
Source:
<code>public int generateDataAccessor(final long classid, final String classname, final int probecount, final MethodVisitor mv) { if (instrumented.size() == Companions.FIELDS_PER_CLASS) { throw new UnsupportedOperationException(); } final String fieldName = "p" + Long.toString(classid); if (instrumented.add(classname)) { cw.visitField( Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_TRANSIENT | Opcodes.ACC_FINAL, fieldName, InstrSupport.DATAFIELD_DESC, null, null); generator.generateDataAccessor(classid, classname, probecount, this.mv); this.mv.visitFieldInsn(Opcodes.PUTSTATIC, companionName, fieldName, <START> InstrSupport.DATAFIELD_DESC); <END> } mv.visitFieldInsn(Opcodes.GETSTATIC, companionName, fieldName, InstrSupport.DATAFIELD_DESC); return 1; }</code><technical_language>I guess this overflow maximum instructions method FIELDS_PER_CLASS is reached? Again, I if good generate multiple companion classes</technical_language>

Target:
public int generateDataAccessor(final long classid, final String classname, final int probecount, final MethodVisitor mv) { if (instrumented.size() == Companions.FIELDS_PER_CLASS) { classFileWriter.write(getClassName(), getClassDefinition()); newCompanion(); } final String fieldName = fieldNameFor(classid); if (instrumented.add(classname)) { gen(classid, classname, probecount, fieldName); } mv.visitMethodInsn(Opcodes.INVOKESTATIC, companionName, fieldName, InstrSupport.INITMETHOD_DESC, false); return 1; }
Source:
<code>MultiUserCasesDialog() { super(WindowManager.getDefault().getMainWindow(), REVIEW_MODE_TITLE, Dialog.ModalityType.APPLICATION_MODAL); getRootPane().registerKeyboardAction( e -> { setVisible(false); }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); multiUserCasesPanel = new MultiUserCasesPanel(); add(multiUserCasesPanel); pack(); setResizable(false); <START> } <END></code><technical_language>If hint lightbulbs in IDE, a cluster of of for this constructor, of calling overrideable methods in constructor. This is do - books Java Concurrency in Practice Effective Java for details. short story is for a class this, final, calling methods redefined subclasses properly constructed yet. This is thread safe. solution is part construction, is easily do here: 1) constructor private. This needs done anyway, class is a singleton. Allowing other classes in package construct instance of this class breaks singleton pattern. 2) Move calls overrideable methods a private init method, call like. 3) Call init method in getInstance, object is fully constructed</technical_language>

Target:
private MultiUserCasesDialog() { super(WindowManager.getDefault().getMainWindow(), REVIEW_MODE_TITLE, Dialog.ModalityType.APPLICATION_MODAL); }
Source:
<code>public IExampleService.updateResult fetchNewUpdates(IProgressMonitor monitor) { java.nio.file.Path storageLocation = getStorageLocation(); String remoteBranch = getPreference(ExamplesPreferenceConstants.REMOTE_BRANCH); try { Git git = Git.open(storageLocation.toFile()); <START> if (git.branchList().setListMode(ListMode.REMOTE).call().stream().anyMatch(branch -> branch.getName().contains(remoteBranch))){ <END> CheckoutCommand checkout = git.checkout(); checkout.setName(remoteBranch); if (!git.branchList().call().stream().anyMatch(branch -> branch.getName().contains(remoteBranch)) ) { checkout.setCreateBranch(true); } try { checkout.call(); } catch (RefNotFoundException | InvalidRefNameException e) { return IExampleService.updateResult.INVALID_CONFIGURATION; } } else { return IExampleService.updateResult.INVALID_CONFIGURATION; } FetchCommand fetch = git.fetch(); FetchResult result = fetch.setProgressMonitor(new EclipseGitProgressTransformer(monitor)).setDryRun(true) .call(); Collection<TrackingRefUpdate> trackingRefUpdates = result.getTrackingRefUpdates(); if (trackingRefUpdates.isEmpty()) { return IExampleService.updateResult.UPDATE_AVAILABLE; } else { return IExampleService.updateResult.NO_UPDATES; } } catch (RepositoryNotFoundException ex) { return IExampleService.updateResult.UPDATE_AVAILABLE; } catch (Exception ex) { ex.printStackTrace(); return IExampleService.updateResult.UPDATE_AVAILABLE; } }</code><technical_language>branch.getName().equals(remoteBranch) instead of contains</technical_language>

Target:
public IExampleService.UpdateResult fetchNewUpdates(IProgressMonitor monitor) { java.nio.file.Path storageLocation = getStorageLocation(); String remoteBranch = getPreference(ExamplesPreferenceConstants.REMOTE_BRANCH); try { Git git = Git.open(storageLocation.toFile()); FetchCommand fetch = git.fetch(); FetchResult result = fetch.setProgressMonitor(new EclipseGitProgressTransformer(monitor)).call(); if (doesBranchExist(git, BranchType.REMOTE, remoteBranch)) { CheckoutCommand checkout = git.checkout(); checkout.setName(remoteBranch); checkout.setCreateBranch(!doesBranchExist(git, BranchType.LOCAL, remoteBranch)); try { checkout.call(); } catch (CheckoutConflictException e) { return IExampleService.UpdateResult.REPO_CONTAINS_CONFLICTS; } } else { return IExampleService.UpdateResult.REMOTE_BRANCH_NOT_FOUND; } if (result.getTrackingRefUpdates().isEmpty()) { return IExampleService.UpdateResult.NO_UPDATES; } else { return IExampleService.UpdateResult.UPDATE_AVAILABLE; } } catch (RepositoryNotFoundException ex) { return IExampleService.UpdateResult.NO_UPDATES; } catch (Exception ex) { ex.printStackTrace(); return IExampleService.UpdateResult.NO_UPDATES; } }