auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static BooleanExpression needsSharedDatabase(StateManager stateManager){ var binding = Bindings.createBooleanBinding(() -> <START> stateManager.activeDatabaseProperty().getValue().filter(context -> context.getLocation() == DatabaseLocation.SHARED).isPresent(), <END> stateManager.activeDatabaseProperty()); return BooleanExpression.booleanExpression(binding); }</code><technical_language>Please Easybind.map(stateManager.activeDatabaseProperty(), ...) instead of createBooleanBinding. a bit more readable shorter</technical_language>

Target:
public static BooleanExpression needsSharedDatabase(StateManager stateManager) { EasyBinding<Boolean> binding = EasyBind.map(stateManager.activeDatabaseProperty(), context -> context.filter(c -> c.getLocation() == DatabaseLocation.SHARED).isPresent()); return BooleanExpression.booleanExpression(binding); }
Source:
<code>private void initializeChangeModeButtons() { ImageButton gridMode = (ImageButton) rootView.findViewById(R.id.av_grid_mode); ImageButton listMode = (ImageButton) rootView.findViewById(R.id.av_list_mode); gridMode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { settingsDataSource.saveMediaListMode(MediaListMode.GRID); mPresenter.onClickChangeMode(MediaListMode.GRID); } }); listMode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { <START> settingsDataSource.saveMediaListMode(MediaListMode.LIST); <END> mPresenter.onClickChangeMode(MediaListMode.LIST); } }); }</code><technical_language>a Fragment settingsDataSource, presenter invoke request save data in data layer of a case, please create SaveSettingsUseCase if exists</technical_language>

Target:
private void initializeChangeModeButtons() { ImageButton gridMode = (ImageButton) rootView.findViewById(R.id.av_grid_mode); ImageButton listMode = (ImageButton) rootView.findViewById(R.id.av_list_mode); gridMode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPresenter.onClickChangeMode(MediaListMode.GRID); } }); listMode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mPresenter.onClickChangeMode(MediaListMode.LIST); } }); }
Source:
<code>public void testDayPeriodFormat() throws Exception { for (Locale locale : new Locale[] { Locale.US, Locale.FRANCE }) { assertDayPeriodFormat("HHb", "08", "08", locale); assertDayPeriodFormat("HHbb", "08", "08", locale); assertDayPeriodFormat("HHbbb", "08", "08", locale); assertDayPeriodFormat("HHbbbb", "08", "08", locale); assertDayPeriodFormat("HHbbbbb", "08", "08", locale); assertDayPeriodFormat("HHB", "08", "08", locale); assertDayPeriodFormat("HHBB", "08", "08", locale); assertDayPeriodFormat("HHBBB", "08", "08", locale); assertDayPeriodFormat("HHBBBB", "08", "08", locale); <START> assertDayPeriodFormat("HHBBBBB", <END> "08", "08", locale); } }</code><technical_language>parsing? Failure silent</technical_language>

Target:
public void testDayPeriodFormat() throws Exception { SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); isoFormat.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = isoFormat.parse("2017-01-01T08:00:00"); for (Locale locale : new Locale[] { Locale.US, Locale.FRANCE }) { assertDayPeriodFormat("HHb", date, "08", locale); assertDayPeriodFormat("HHbb", date, "08", locale); assertDayPeriodFormat("HHbbb", date, "08", locale); assertDayPeriodFormat("HHbbbb", date, "08", locale); assertDayPeriodFormat("HHbbbbb", date, "08", locale); assertDayPeriodFormat("HHB", date, "08", locale); assertDayPeriodFormat("HHBB", date, "08", locale); assertDayPeriodFormat("HHBBB", date, "08", locale); assertDayPeriodFormat("HHBBBB", date, "08", locale); assertDayPeriodFormat("HHBBBBB", date, "08", locale); } }
Source:
<code>public void onStop() { boolean volumeBtnCheckVal = checkVolumeBtn.isChecked(); SharedPreferences sPrefs = getActivity().getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = sPrefs.edit(); editor.putBoolean(getResources().getString(R.string.volumeBtnPrefs),volumeBtnCheckVal); editor.commit(); <START> <END> super.onStop(); }</code><technical_language>Avoid unwanted blank lines</technical_language>

Target:
public void onStop() { boolean volumeBtnCheckVal = checkVolumeBtn.isChecked(); SharedPreferences sPrefs = getActivity().getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = sPrefs.edit(); editor.putBoolean(getResources().getString(R.string.volume_btn_prefs),volumeBtnCheckVal); editor.commit(); super.onStop(); }
Source:
<code>public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { if (!describe && context.getRunningMode() != RunningMode.ADMIN_ONLY) { throw UndertowLogger.ROOT_LOGGER.migrateOperationAllowedOnlyInAdminOnly(); } final ModelNode legacyModelAddOps = new ModelNode(); final Map<PathAddress, ModelNode> migrationOperations = new TreeMap<>(new Comparator<PathAddress>() { @Override public int compare(PathAddress o1, PathAddress o2) { final int compare = Integer.compare(o1.size(), o2.size()); if (compare != 0) { return compare; } return o1.toString().compareTo(o2.toString()); } }); describeLegacyWebResources(context, legacyModelAddOps); addExtension(context, migrationOperations, describe, UNDERTOW_EXTENSION); addExtension(context, migrationOperations, describe, IO_EXTENSION); context.addStep(new OperationStepHandler() { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { addDefaultResources(migrationOperations, legacyModelAddOps); createIoSubsystem(context, migrationOperations); createWelcomeContentHandler(migrationOperations); transformResources(context, legacyModelAddOps, migrationOperations); fixAddressesForDomainMode(pathAddress(operation.get(ADDRESS)), migrationOperations); <START> removeWebSubsystem(migrationOperations); <END> if (describe) { context.getResult().set(migrationOperations.values()); } else { migrateSubsystems(context, migrationOperations); } } }, MODEL); }</code><technical_language>this done fixAddressesForDomainMode</technical_language>

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { if (!describe && context.getRunningMode() != RunningMode.ADMIN_ONLY) { throw UndertowLogger.ROOT_LOGGER.migrateOperationAllowedOnlyInAdminOnly(); } final ModelNode legacyModelAddOps = new ModelNode(); final Map<PathAddress, ModelNode> migrationOperations = new TreeMap<>(new Comparator<PathAddress>() { @Override public int compare(PathAddress o1, PathAddress o2) { final int compare = Integer.compare(o1.size(), o2.size()); if (compare != 0) { return compare; } return o1.toString().compareTo(o2.toString()); } }); describeLegacyWebResources(context, legacyModelAddOps); addExtension(context, migrationOperations, describe, UNDERTOW_EXTENSION); addExtension(context, migrationOperations, describe, IO_EXTENSION); context.addStep(new OperationStepHandler() { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { addDefaultResources(migrationOperations, legacyModelAddOps); createIoSubsystem(context, migrationOperations); createWelcomeContentHandler(migrationOperations); transformResources(context, legacyModelAddOps, migrationOperations); removeWebSubsystem(migrationOperations); fixAddressesForDomainMode(pathAddress(operation.get(ADDRESS)), migrationOperations); if (describe) { context.getResult().set(migrationOperations.values()); } else { migrateSubsystems(context, migrationOperations); } } }, MODEL); }
Source:
<code>public String getRequestorEmail(UserNotification notification) { if(notification == null) return "Unavailable"; if(notification.getRequestor() == null) return "Unavailable"; <START> return notification.getRequestor().getEmail() != null ? notification.getRequestor().getEmail() : "Unavailable"; <END> }</code><technical_language>more lines of English</technical_language>

Target:
public String getRequestorEmail(UserNotification notification) { if(notification == null) return BundleUtil.getStringFromBundle("notification.email.info.unavailable");; if(notification.getRequestor() == null) return BundleUtil.getStringFromBundle("notification.email.info.unavailable");; return notification.getRequestor().getEmail() != null ? notification.getRequestor().getEmail() : BundleUtil.getStringFromBundle("notification.email.info.unavailable"); }
Source:
<code>public void toExecute(JobExecutionContext context) throws JobExecutionException { JobDataMap map = context.getMergedJobDataMap(); String ownerKey = (String) map.get(JobStatus.TARGET_ID); ConflictOverrides overrides = new ConflictOverrides((String[]) map.get(CONFLICT_OVERRIDES)); String storedFileId = (String) map.get(STORED_FILE_ID); String uploadedFileName = (String) map.get(UPLOADED_FILE_NAME); Throwable caught = null; Owner targetOwner = null; try { targetOwner = ownerCurator.lookupByKey(ownerKey); if (targetOwner == null) { <START> context.setResult("Nothing to do. Owner no longer exists."); <END> return; } ImportRecord importRecord = manifestManager.importStoredManifest(targetOwner, storedFileId, overrides, uploadedFileName); context.setResult(importRecord); } catch (SyncDataFormatException e) { caught = new BadRequestException(e.getMessage(), e); } catch (ImporterException e) { caught = new IseException(e.getMessage(), e); } catch (Exception e) { caught = e; } if (caught != null) { log.error("ImportJob encountered a problem.", caught); manifestManager.recordImportFailure(targetOwner, caught, uploadedFileName); context.setResult(caught.getMessage()); manifestManager.deleteStoredManifest(storedFileId); throw new JobExecutionException(caught.getMessage(), caught, false); } }</code><technical_language>While this sense for ConsumerComplianceJob ( point in calculating compliance of a consumer deleted ), is true for import well? I feel if some explicitly requested import, owner longer exists, error out job.. do face problem spec tests owner is cleaned though, im split. thoughts</technical_language>

Target:
public void toExecute(JobExecutionContext context) throws JobExecutionException { JobDataMap map = context.getMergedJobDataMap(); String ownerKey = (String) map.get(JobStatus.TARGET_ID); ConflictOverrides overrides = new ConflictOverrides((String[]) map.get(CONFLICT_OVERRIDES)); String storedFileId = (String) map.get(STORED_FILE_ID); String uploadedFileName = (String) map.get(UPLOADED_FILE_NAME); Throwable caught = null; Owner targetOwner = null; try { targetOwner = ownerCurator.lookupByKey(ownerKey); if (targetOwner == null) { throw new NotFoundException(String.format("Owner %s was not found.", ownerKey)); } ImportRecord importRecord = manifestManager.importStoredManifest(targetOwner, storedFileId, overrides, uploadedFileName); context.setResult(importRecord); } catch (SyncDataFormatException e) { caught = new BadRequestException(e.getMessage(), e); } catch (ImporterException e) { caught = new IseException(e.getMessage(), e); } catch (Exception e) { caught = e; } if (caught != null) { log.error("ImportJob encountered a problem.", caught); manifestManager.recordImportFailure(targetOwner, caught, uploadedFileName); context.setResult(caught.getMessage()); manifestManager.deleteStoredManifest(storedFileId); throw new JobExecutionException(caught.getMessage(), caught, false); } }
Source:
<code>public RestListWrapper<Rule> getRules() { return new RestListWrapper<>( <START> RulesDao.getRules().stream().collect(Collectors.toList()), <END> Rule.class, this, "id", null); }</code><technical_language>RulesDao.getRules() returns a list</technical_language>

Target:
public RestListWrapper<Rule> getRules() { return new RestListWrapper<>(RulesDao.getRules(), Rule.class, this, "id", null); }
Source:
<code>private void sendStatusChangedEvents() { for (String modifiedTagDisplayName : updatedStatusTags) { <START> Case.getCurrentCase().notifyTagStatusChanged(modifiedTagDisplayName); <END> } updatedStatusTags.clear(); }</code><technical_language>is potential for uncaught IllegalStateException call Case.getCurrentCase if is open case</technical_language>

Target:
private void sendStatusChangedEvents() { for (String modifiedTagDisplayName : updatedStatusTags) { if (Case.isCaseOpen()) { Case.getCurrentCase().notifyTagDefinitionChanged(modifiedTagDisplayName); } } updatedStatusTags.clear(); }
Source:
<code>public int execute() { try { if (work.tableDataCopyIteratorsInitialized()) { initiateDataCopyTasks(); } else { Path dumpRoot = getEncodedDumpRootPath(); Path previousValidHiveDumpPath = getPreviousValidDumpMetadataPath(dumpRoot); boolean isBootstrap = (previousValidHiveDumpPath == null); if (shouldDump(previousValidHiveDumpPath)) { Path currentDumpPath = getCurrentDumpPath(dumpRoot, isBootstrap); Path hiveDumpRoot = new Path(currentDumpPath, ReplUtils.REPL_HIVE_BASE_DIR); work.setCurrentDumpPath(currentDumpPath); if (shouldDumpAuthorizationMetadata()) { <START> initiateAuthorizationDumpTask(); <END> } if (shouldDumpAtlasMetadata()) { LOG.info("Added task to dump atlas metadata."); addAtlasDumpTask(isBootstrap, previousValidHiveDumpPath); } DumpMetaData dmd = new DumpMetaData(hiveDumpRoot, conf); ReplChangeManager.getInstance(conf); Path cmRoot = new Path(conf.getVar(HiveConf.ConfVars.REPLCMDIR)); Long lastReplId; if (isBootstrap) { lastReplId = bootStrapDump(hiveDumpRoot, dmd, cmRoot, getHive()); } else { work.setEventFrom(getEventFromPreviousDumpMetadata(previousValidHiveDumpPath)); lastReplId = incrementalDump(hiveDumpRoot, dmd, cmRoot, getHive()); } work.setResultValues(Arrays.asList(currentDumpPath.toUri().toString(), String.valueOf(lastReplId))); initiateDataCopyTasks(); } else { LOG.info("Previous Dump is not yet loaded"); } } } catch (Exception e) { LOG.error("failed", e); setException(e); return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } return 0; }</code><technical_language>this ranger</technical_language>

Target:
public int execute() { try { if (work.tableDataCopyIteratorsInitialized()) { initiateDataCopyTasks(); } else { Path dumpRoot = getEncodedDumpRootPath(); Path previousValidHiveDumpPath = getPreviousValidDumpMetadataPath(dumpRoot); boolean isBootstrap = (previousValidHiveDumpPath == null); if (shouldDump(previousValidHiveDumpPath)) { Path currentDumpPath = getCurrentDumpPath(dumpRoot, isBootstrap); Path hiveDumpRoot = new Path(currentDumpPath, ReplUtils.REPL_HIVE_BASE_DIR); work.setCurrentDumpPath(currentDumpPath); if (shouldDumpAtlasMetadata()) { addAtlasDumpTask(isBootstrap, previousValidHiveDumpPath); LOG.info("Added task to dump atlas metadata."); } if (shouldDumpAuthorizationMetadata()) { initiateAuthorizationDumpTask(); } DumpMetaData dmd = new DumpMetaData(hiveDumpRoot, conf); ReplChangeManager.getInstance(conf); Path cmRoot = new Path(conf.getVar(HiveConf.ConfVars.REPLCMDIR)); Long lastReplId; if (isBootstrap) { lastReplId = bootStrapDump(hiveDumpRoot, dmd, cmRoot, getHive()); } else { work.setEventFrom(getEventFromPreviousDumpMetadata(previousValidHiveDumpPath)); lastReplId = incrementalDump(hiveDumpRoot, dmd, cmRoot, getHive()); } work.setResultValues(Arrays.asList(currentDumpPath.toUri().toString(), String.valueOf(lastReplId))); initiateDataCopyTasks(); } else { LOG.info("Previous Dump is not yet loaded"); } } } catch (Exception e) { LOG.error("failed", e); setException(e); return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } return 0; }
Source:
<code>private BBContainer wrapRetCont(PBDSegment segment, final BBContainer retcont) { return new BBContainer(retcont.b()) { @Override public void discard() { synchronized(PersistentBinaryDeque.this) { checkDoubleFree(); retcont.discard(); assert(m_closed || m_segments.containsKey(segment.segmentId())); if (m_closed) { return; } try { PBDSegmentReader segmentReader = segment.getReader(m_cursorId); if (segment == peekLastSegment() || !segmentReader.allReadAndDiscarded()) { return; } if (canDeleteSegment(segment)) { Iterator<Map.Entry<Long, PBDSegment>> iter = m_segments.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<Long, PBDSegment> entry = iter.next(); if (entry.getKey() > segment.segmentId()) { break; } PBDSegment segmentToDelete = entry.getValue(); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + segmentToDelete.file() + " has been closed and deleted after discarding last buffer"); } closeAndDeleteSegment(segmentToDelete); <START> iter.remove(); <END> } } } catch (IOException e) { LOG.error("Exception closing and deleting PBD segment", e); } } } }; }</code><technical_language>This extracted reused below</technical_language>

Target:
private BBContainer wrapRetCont(PBDSegment segment, final BBContainer retcont) { return new BBContainer(retcont.b()) { @Override public void discard() { synchronized(PersistentBinaryDeque.this) { checkDoubleFree(); retcont.discard(); assert(m_closed || m_segments.containsKey(segment.segmentId())); if (m_closed) { return; } try { PBDSegmentReader segmentReader = segment.getReader(m_cursorId); if (segment == peekLastSegment() || !segmentReader.allReadAndDiscarded()) { return; } if (canDeleteSegment(segment)) { m_segments.remove(segment.segmentId()); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + segment.file() + " has been closed and deleted after discarding last buffer"); } closeAndDeleteSegment(segment); } } catch (IOException e) { LOG.error("Exception closing and deleting PBD segment", e); } } } }; }
Source:
<code>public SpinnerNumberModel (int min, int max, int step, int value) { if (max < min) throw new IllegalArgumentException("The maximum cannot be smaller than the minimum"); if (value < min || value > max) throw new IllegalArgumentException("The current value must be between the minimum and the maximum (inclusive)"); this.min = min; this.max = max; <START> if (step < 0) step *= -1; <END> this.step = step; this.value = value; }</code><technical_language>Nitpick: step = -step clearer? (and is this check necessary?)</technical_language>

Target:
public SpinnerNumberModel (int min, int max, int step, int value) { if (max < min) throw new IllegalArgumentException("The maximum cannot be smaller than the minimum"); if (value < min || value > max) throw new IllegalArgumentException("The current value must be between the minimum and the maximum (inclusive)"); this.min = min; this.max = max; if (step < 0) step = -step; this.step = step; this.value = value; }
Source:
<code>public ExecutorServiceProvider(int corePoolSize, int maxPoolSize, int queueCapacity) { ThreadFactory factory = new ThreadFactoryBuilder() .setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance()) .setNameFormat(this.getClass().getSimpleName() + "-%d") .setDaemon(true) .build(); executor = new ThreadPoolExecutor( corePoolSize, maxPoolSize, 60L, SECONDS, queueCapacity > 0 ? new LinkedBlockingQueue<>(queueCapacity) : new SynchronousQueue<>(), factory); executor.setRejectedExecutionHandler( <START> (r, __) -> LOG.error("Executor rejected to handle the message {}", r)); <END> executor.prestartCoreThread(); }</code><technical_language>If this is a generic executor service provider, I this specific call payload a "message". s/message/payload/</technical_language>

Target:
public ExecutorServiceProvider(int corePoolSize, int maxPoolSize, int queueCapacity) { ThreadFactory factory = new ThreadFactoryBuilder() .setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance()) .setNameFormat(this.getClass().getSimpleName() + "-%d") .setDaemon(true) .build(); executor = new ThreadPoolExecutor( corePoolSize, maxPoolSize, 60L, SECONDS, queueCapacity > 0 ? new LinkedBlockingQueue<>(queueCapacity) : new SynchronousQueue<>(), factory); executor.setRejectedExecutionHandler( (r, __) -> LOG.warn("Executor rejected to handle the payload {}", r)); executor.prestartCoreThread(); }
Source:
<code>private List<String> objectsInDatabase(SQLiteDatabase db, String type) { List<String> tables = new ArrayList<>(); <START> Cursor cursor = db.rawQuery("SELECT sql FROM sqlite_master WHERE type = ? AND sql IS NOT NULL", new String[] { type }); <END> try { if (cursor.moveToFirst()) { while (!cursor.isAfterLast()) { String sql = cursor.getString(cursor.getColumnIndex("sql")); tables.add("table".equals(type) ? sortTableColumns(sql) : sql); cursor.moveToNext(); } } } finally { cursor.close(); } return tables; }</code><technical_language>sql NULL</technical_language>

Target:
private List<String> objectsInDatabase(SQLiteDatabase db, String type) { List<String> databaseObjects = new ArrayList<>(); Cursor cursor = db.rawQuery("SELECT sql FROM sqlite_master WHERE type = ? AND sql IS NOT NULL", new String[] { type }); try { while (cursor.moveToNext()) { String sql = cursor.getString(cursor.getColumnIndex("sql")); String resortedSql = "table".equals(type) ? sortTableColumns(sql) : sql; databaseObjects.add(resortedSql); } } finally { cursor.close(); } return databaseObjects; }
Source:
<code>static Interpolator loadInterpolator(Resources res, Theme theme, int id) throws NotFoundException { XmlResourceParser parser = null; try { parser = res.getAnimation(id); return createInterpolatorFromXml(res, theme, parser); } catch (XmlPullParserException ex) { NotFoundException rnf = new NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id)); <START> rnf.initCause(ex); <END> throw rnf; } catch (IOException ex) { NotFoundException rnf = new NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id)); rnf.initCause(ex); throw rnf; } finally { if (parser != null) { parser.close(); } } }</code><technical_language>nit: pass in constructor</technical_language>

Target:
static Interpolator loadInterpolator(Resources res, Theme theme, int id) throws NotFoundException { XmlResourceParser parser = null; try { parser = res.getAnimation(id); return createInterpolatorFromXml(res, theme, parser); } catch (XmlPullParserException ex) { NotFoundException rnf = new NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id), ex); throw rnf; } catch (IOException ex) { NotFoundException rnf = new NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id), ex); throw rnf; } finally { if (parser != null) { parser.close(); } } }
Source:
<code>private void autoCrop() { new AsyncTask<Void, Void, Void>() { @Override protected void onPreExecute() { IndeterminateProgressDialog.getInstance().show(); } @Override protected Void doInBackground(Void... params) { Rect shapeBounds = cropAlgorithmSnail(LayerListener.getInstance().getBitmapOfAllLayersToSave()); if (shapeBounds != null) { boxWidth = shapeBounds.width() + 1; boxHeight = shapeBounds.height() + 1; toolPosition.x = shapeBounds.left + (shapeBounds.width() + 1) / 2.0f; toolPosition.y = shapeBounds.top + (shapeBounds.height() + 1) / 2.0f; } return null; } @Override protected void onPostExecute(Void result) { PaintroidApplication.drawingSurface.refreshDrawingSurface(); IndeterminateProgressDialog.getInstance().dismiss(); widthEditText.setText(String.format(Locale.getDefault(), "%d", (int) boxWidth)); <START> heightEditText.setText(String.format(Locale.getDefault(), "%d", (int) boxHeight)); <END> } }.execute(); }</code><technical_language>Do this in resetScaleAndTranslation resetInternalState</technical_language>

Target:
private void autoCrop() { new AsyncTask<Void, Void, Void>() { @Override protected void onPreExecute() { IndeterminateProgressDialog.getInstance().show(); } @Override protected Void doInBackground(Void... params) { Rect shapeBounds = cropAlgorithmSnail(LayerListener.getInstance().getBitmapOfAllLayersToSave()); if (shapeBounds != null) { boxWidth = shapeBounds.width() + 1; boxHeight = shapeBounds.height() + 1; toolPosition.x = shapeBounds.left + (shapeBounds.width() + 1) / 2.0f; toolPosition.y = shapeBounds.top + (shapeBounds.height() + 1) / 2.0f; } return null; } @Override protected void onPostExecute(Void result) { PaintroidApplication.drawingSurface.refreshDrawingSurface(); IndeterminateProgressDialog.getInstance().dismiss(); setWidthAndHeightTexts(boxHeight, boxWidth); } }.execute(); }
Source:
<code>public void spoutAckedTuple(String streamId, long latencyMs) { String metricName = METRIC_NAME_ACKED + "-" + streamId; Counter c = this.counters.get(metricName); <START> if (c == null) { <END> c = metricRegistry.counter(metricName, this.topologyId, this.componentId, this.taskId, this.workerPort, streamId); this.counters.put(metricName, c); } c.inc(this.samplingRate); metricName = METRIC_NAME_COMPLETE_LATENCY + "-" + streamId; ResettingAverageGauge gauge = this.gauges.get(metricName); if (gauge == null) { gauge = new ResettingAverageGauge(); metricRegistry.gauge(metricName, gauge, this.topologyId, this.componentId, streamId, this.taskId, this.workerPort); this.gauges.put(metricName, gauge); } gauge.addValue(latencyMs); }</code><technical_language>Do need synchronization here? object created multiple times</technical_language>

Target:
public void spoutAckedTuple(String streamId, long latencyMs) { String metricName = METRIC_NAME_ACKED + "-" + streamId; Counter c = this.getCounter(metricName, streamId); c.inc(this.samplingRate); metricName = METRIC_NAME_COMPLETE_LATENCY + "-" + streamId; RollingAverageGauge gauge = this.getRollingAverageGauge(metricName, streamId); gauge.addValue(latencyMs); }
Source:
<code>synchronized List<ComparisonConfiguration> getComparisonConfigurationsForBaseBranch( String baseBranchName) { List<ComparisonConfiguration> comparisonConfigurationsForBaseBranch = new LinkedList<>(); List<ComparisonConfiguration> comparisonConfigurations = configurationRepository.getConfiguration() .getComparisonConfigurations(); String resolvedBaseBranchName = aliasResolver.resolveBranchAlias(baseBranchName); for (ComparisonConfiguration comparisonConfiguration : comparisonConfigurations) { String resolvedComparisonBranchName = aliasResolver.resolveBranchAlias(comparisonConfiguration.getBaseBranchName()); if (resolvedBaseBranchName.equals(resolvedComparisonBranchName) <START> || resolvedBaseBranchName.matches(resolvedComparisonBranchName)) { <END> comparisonConfigurationsForBaseBranch.add(comparisonConfiguration); } } return comparisonConfigurationsForBaseBranch; }</code><technical_language>Please write a unit test for this. reveal a bug. I wanted write resolvedComparisonBranchName.matches(resolvedBaseBranchName). <LINK_0></technical_language>

Target:
synchronized List<ComparisonConfiguration> getComparisonConfigurationsForBaseBranch(String baseBranchName) { List<ComparisonConfiguration> comparisonConfigurationsForBaseBranch = new LinkedList<>(); List<ComparisonConfiguration> comparisonConfigurations = configurationRepository.getConfiguration() .getComparisonConfigurations(); String resolvedBaseBranchName = aliasResolver.resolveBranchAlias(baseBranchName); for (ComparisonConfiguration comparisonConfiguration : comparisonConfigurations) { String resolvedConfigurationBaseBranchName = aliasResolver.resolveBranchAlias(comparisonConfiguration.getBaseBranchName()); if (resolvedBaseBranchName.equals(resolvedConfigurationBaseBranchName) || resolvedBaseBranchName.matches(resolvedConfigurationBaseBranchName)) { comparisonConfigurationsForBaseBranch.add(new ComparisonConfiguration(comparisonConfiguration, resolvedBaseBranchName)); } } return comparisonConfigurationsForBaseBranch; }
Source:
<code>private void createLatestNode(final int hoursAgo) throws Exception { final DateTime now = new DateTime(DateTimeZone.UTC); <START> final DateTime twoHoursAgo = now.minusHours(hoursAgo); <END> final byte[] data = objectMapper.writeValueAsString(twoHoursAgo).getBytes(Charset.forName("UTF-8")); CURATOR.create().creatingParentsIfNeeded().forPath(latestPath, data); }</code><technical_language>This variable is called twoHoursAgo, in fact number of hours ago</technical_language>

Target:
private void createLatestNode(final int hoursAgo) throws Exception { final DateTime now = new DateTime(DateTimeZone.UTC); final DateTime pastDate = now.minusHours(hoursAgo); final byte[] data = objectMapper.writeValueAsString(pastDate).getBytes(Charsets.UTF_8); CURATOR.create().creatingParentsIfNeeded().forPath(latestPath, data); }
Source:
<code>private S3Object getObject() throws IOException { AmazonS3 s3 = getClientInstance(); final Configuration config = ConfigurationFactory.getInstance(); final Object object = getObjectKey(); final String bucketName; final String objectKey; <START> if (object instanceof RubyHash) { <END> Map<String, Object> map = convertToHashMap((RubyHash)object); if (map.containsKey("bucket") && map.containsKey("key")) { bucketName = map.get("bucket").toString(); objectKey = map.get("key").toString(); } else { logger.error("Hash does not include bucket and key"); throw new IOException(); } } else { bucketName = config.getString(Key.AMAZONS3RESOLVER_BUCKET_NAME); objectKey = (String)object; } try { logger.info("Requesting from bucket {}", objectKey, bucketName); return s3.getObject(new GetObjectRequest(bucketName, objectKey)); } catch (AmazonS3Exception e) { if (e.getErrorCode().equals("NoSuchKey")) { throw new FileNotFoundException(e.getMessage()); } else { throw new IOException(e); } } }</code><technical_language>I do instanceof Map cast object Map, avoid copy. instanceof check safe @SuppressWarnings("unchecked")to suppress compiler warning. But, I a big deal way</technical_language>

Target:
private S3Object getObject() throws IOException { AmazonS3 s3 = getClientInstance(); final Configuration config = ConfigurationFactory.getInstance(); final String objectKey = getObjectKey(); if (bucketName == null) { bucketName = config.getString(Key.AMAZONS3RESOLVER_BUCKET_NAME); } try { logger.info("Requesting from bucket {}", objectKey, bucketName); return s3.getObject(new GetObjectRequest(bucketName, objectKey)); } catch (AmazonS3Exception e) { if (e.getErrorCode().equals("NoSuchKey")) { throw new FileNotFoundException(e.getMessage()); } else { throw new IOException(e); } } }
Source:
<code>private void stopVpn() { final NetworkRequest request = new NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_VPN) .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .build(); mCallback = new NetworkCallback() { public void onLost(Network network) { synchronized (mLockShutdown) { Log.i(TAG, "Got lost callback for" <START> + " <END> network=" + network + ",mNetwork" + " = " + mNetwork); if( mNetwork == network){ mLockShutdown.notify(); } } } }; mCM.registerNetworkCallback(request, mCallback); Intent intent = new Intent(mActivity, MyVpnService.class) .putExtra(mPackageName + ".cmd", "disconnect"); mActivity.startService(intent); synchronized (mLockShutdown) { try { Log.i(TAG, "bf mLockShutdown"); mLockShutdown.wait(TIMEOUT_MS); Log.i(TAG, "af mLockShutdown"); } catch(InterruptedException e) } }</code><technical_language>Style : 8 spaces continuation indent</technical_language>

Target:
private void stopVpn() { final NetworkRequest request = new NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_VPN) .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .build(); mCallback = new NetworkCallback() { public void onLost(Network network) { synchronized (mLockShutdown) { Log.i(TAG, "Got lost callback for network=" + network + ",mNetwork = " + mNetwork); if( mNetwork == network){ mLockShutdown.notify(); } } } }; mCM.registerNetworkCallback(request, mCallback); Intent intent = new Intent(mActivity, MyVpnService.class) .putExtra(mPackageName + ".cmd", "disconnect"); mActivity.startService(intent); synchronized (mLockShutdown) { try { Log.i(TAG, "bf mLockShutdown"); mLockShutdown.wait(TIMEOUT_MS); Log.i(TAG, "af mLockShutdown"); } catch(InterruptedException e) } }
Source:
<code>private int computeNumberOfAvailableThreads() { Preconditions.checkState(getServerFactory() instanceof DefaultServerFactory, "Unexpected serverFactory instance on TimeLockServerConfiguration."); DefaultServerFactory serverFactory = (DefaultServerFactory) getServerFactory(); int maxServerThreads = serverFactory.getMaxThreads(); Preconditions.checkNotNull(serverFactory.getApplicationConnectors(), "applicationConnectors of TimeLockServerConfiguration must not be null."); Preconditions.checkState(serverFactory.getApplicationConnectors().get(0) instanceof HttpConnectorFactory, "applicationConnectors of TimeLockServerConfiguration must have a HttpConnectorFactory instance."); HttpConnectorFactory connectorFactory = (HttpConnectorFactory) serverFactory.getApplicationConnectors().get(0); <START> int selectorThreads = connectorFactory.getSelectorThreads().orElse(0); <END> int acceptorThreads = connectorFactory.getAcceptorThreads().orElse(0); return maxServerThreads - selectorThreads - acceptorThreads - 1; }</code><technical_language>I minimum is 1 for of these, matters here, good consistent</technical_language>

Target:
private int computeNumberOfAvailableThreads() { Preconditions.checkState(getServerFactory() instanceof DefaultServerFactory, "Unexpected serverFactory instance on TimeLockServerConfiguration."); DefaultServerFactory serverFactory = (DefaultServerFactory) getServerFactory(); int maxServerThreads = serverFactory.getMaxThreads(); Preconditions.checkNotNull(serverFactory.getApplicationConnectors(), "applicationConnectors of TimeLockServerConfiguration must not be null."); Preconditions.checkState(serverFactory.getApplicationConnectors().get(0) instanceof HttpConnectorFactory, "applicationConnectors of TimeLockServerConfiguration must have a HttpConnectorFactory instance."); HttpConnectorFactory connectorFactory = (HttpConnectorFactory) serverFactory.getApplicationConnectors().get(0); int selectorThreads = connectorFactory.getSelectorThreads().orElse(1); int acceptorThreads = connectorFactory.getAcceptorThreads().orElse(1); return maxServerThreads - selectorThreads - acceptorThreads - 1; }
Source:
<code>public final void testAddRemoveMember() throws Exception { CommunityService communityService = new CommunityService(); authenticateEndpoint(communityService.getEndpoint(), properties.getProperty("user1"), properties.getProperty("passwordUser1")); CommunityList communities = communityService.getMyCommunities(); Community community = communities.iterator().next(); Member new_member = new Member(communityService, properties.getProperty("email2")); <START> communityService.addMember(community.getCommunityUuid(), new_member ); <END> MemberList members = communityService.getMembers(community.getCommunityUuid()); for (Member member : members) { assertNotNull(member.getUserid()); assertNotNull(member.getName()); } communityService.removeMember(community.getCommunityUuid(), properties.getProperty("email2")); }</code><technical_language>change variable name newMember</technical_language>

Target:
public final void testAddRemoveMember() throws Exception { CommunityService communityService = new CommunityService(); authenticateEndpoint(communityService.getEndpoint(), properties.getProperty("user1"), properties.getProperty("passwordUser1")); CommunityList communities = communityService.getMyCommunities(); Community community = communities.iterator().next(); Member newMember = new Member(communityService, properties.getProperty("email2")); communityService.addMember(community.getCommunityUuid(), newMember ); MemberList members = communityService.getMembers(community.getCommunityUuid()); for (Member member : members) { assertNotNull(member.getUserid()); assertNotNull(member.getName()); } communityService.removeMember(community.getCommunityUuid(), properties.getProperty("email2")); }
Source:
<code>public RewrittenStatement rewrite(String sql, Binding params, StatementContext ctx) { String sqlUpdated = sql <START> .replaceAll( "(?i)BOOLEAN NOT NULL DEFAULT FALSE", "BIT NOT NULL DEFAULT (0)" ) <END> .replaceAll( "(?i)BOOLEAN NOT NULL DEFAULT TRUE", "BIT NOT NULL DEFAULT (1)" ) .replaceAll( "(?i)BOOLEAN DEFAULT FALSE", "BIT NOT NULL DEFAULT (0)" ) .replaceAll( "(?i)BOOLEAN DEFAULT TRUE", "BIT NOT NULL DEFAULT (1)" ) .replaceAll( "(?i)BOOLEAN", "BIT" ) .replaceAll( "(?i)TRUE", "1" ) .replaceAll( "(?i)FALSE", "0" ) ; return ( new ColonPrefixNamedParamStatementRewriter() ).rewrite( sqlUpdated, params, ctx ); }</code><technical_language>file issue this? fact pluggable for varying sql impls is ideal. This a this kind of translation</technical_language>

Target:
public RewrittenStatement rewrite(String sql, Binding params, StatementContext ctx) { String currentSql = sql; currentSql = REWRITE_PATTERN1.matcher(currentSql).replaceAll("BIT NOT NULL DEFAULT (0)"); currentSql = REWRITE_PATTERN2.matcher(currentSql).replaceAll("BIT NOT NULL DEFAULT (1)"); currentSql = REWRITE_PATTERN3.matcher(currentSql).replaceAll("BIT NOT NULL DEFAULT (0)"); currentSql = REWRITE_PATTERN4.matcher(currentSql).replaceAll("BIT NOT NULL DEFAULT (1)"); currentSql = REWRITE_PATTERN5.matcher(currentSql).replaceAll("BIT"); currentSql = REWRITE_PATTERN6.matcher(currentSql).replaceAll("1"); currentSql = REWRITE_PATTERN7.matcher(currentSql).replaceAll("0"); return (colonPrefixNamedParamStatementRewriter).rewrite(currentSql, params, ctx); }
Source:
<code>protected static void createMiniSolrCloudCluster() throws Exception { miniSolrCloud = new MiniSolrCloudCluster( 1, getBaseDirPath(), JettyConfig.builder().setContext("/solr").build()); miniSolrCloud.getSolrClient().connect(); System.setProperty("solr.cloud.shardCount", "1"); System.setProperty("solr.cloud.replicationFactor", "1"); System.setProperty("solr.cloud.maxShardPerNode", "1"); System.setProperty("solr.cloud.zookeeper.chroot", "/solr"); <START> System.setProperty("solr.cloud.zookeeper", miniSolrCloud.getZkServer().getZkHost()); <END> System.setProperty("solr.autoSoftCommit.maxTime", String.valueOf(100)); System.setProperty("solr.autoCommit.maxTime", String.valueOf(100)); }</code><technical_language><LINK_0></technical_language>

Target:
protected static void createMiniSolrCloudCluster() throws Exception { miniSolrCloud = new MiniSolrCloudCluster( 1, getBaseDirPath(), JettyConfig.builder().setContext("/solr").build()); miniSolrCloud.getSolrClient().connect(); System.setProperty("solr.cloud.shardCount", "1"); System.setProperty("solr.cloud.replicationFactor", "1"); System.setProperty("solr.cloud.maxShardPerNode", "1"); System.setProperty("solr.cloud.zookeeper.chroot", "/solr"); System.setProperty(SolrCommands.ZOOKEEPER_HOSTS_PROP, miniSolrCloud.getZkServer().getZkHost()); System.setProperty("solr.autoSoftCommit.maxTime", String.valueOf(100)); System.setProperty("solr.autoCommit.maxTime", String.valueOf(100)); }
Source:
<code>protected void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { Schema inputSchema = getChild().getSchema(); Preconditions.checkState(inputSchema != null, "unable to determine schema in init"); internalAggs = new ArrayList<Aggregator>(); emitEvals = new ArrayList<GenericEvaluator>(); Schema groupingSchema = inputSchema.getSubSchema(gfields); Schema stateSchema = Schema.EMPTY_SCHEMA; <START> for (int i = 0; i < factories.length; ++i) { <END> internalAggs.addAll(factories[i].generateInternalAggs(inputSchema)); List<Expression> emits = factories[i].generateEmitExpressions(inputSchema); Schema newStateSchema = factories[i].generateStateSchema(inputSchema); stateSchema = Schema.merge(stateSchema, newStateSchema); for (Expression exp : emits) { GenericEvaluator evaluator = new GenericEvaluator( exp, new ExpressionOperatorParameter(newStateSchema, newStateSchema)); evaluator.compile(); emitEvals.add(evaluator); } } groupStates = new TupleHashTable( Schema.merge(groupingSchema, stateSchema), MyriaArrayUtils.range(0, gfields.length)); resultBuffer = new TupleBatchBuffer(getSchema()); }</code><technical_language>I this a foreach loop well</technical_language>

Target:
protected void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { Schema inputSchema = getChild().getSchema(); Preconditions.checkState(inputSchema != null, "unable to determine schema in init"); internalAggs = new ArrayList<Aggregator>(); emitEvals = new ArrayList<GenericEvaluator>(); Schema groupingSchema = inputSchema.getSubSchema(gfields); Schema stateSchema = Schema.EMPTY_SCHEMA; PythonFunctionRegistrar pyFuncReg = getPythonFunctionRegistrar(); for (AggregatorFactory factory : factories) { factory.setPyFuncReg(pyFuncReg); internalAggs.addAll(factory.generateInternalAggs(inputSchema)); List<Expression> emits = factory.generateEmitExpressions(inputSchema); Schema newStateSchema = factory.generateStateSchema(inputSchema); stateSchema = Schema.merge(stateSchema, newStateSchema); for (Expression exp : emits) { GenericEvaluator evaluator = null; if (exp.isRegisteredPythonUDF()) { evaluator = new PythonUDFEvaluator( exp, new ExpressionOperatorParameter( inputSchema, stateSchema, getPythonFunctionRegistrar())); } else { evaluator = new GenericEvaluator( exp, new ExpressionOperatorParameter( newStateSchema, newStateSchema, getPythonFunctionRegistrar())); } emitEvals.add(evaluator); } } groupStates = new TupleHashTable( Schema.merge(groupingSchema, stateSchema), MyriaArrayUtils.range(0, gfields.length)); resultBuffer = new TupleBatchBuffer(getSchema()); }
Source:
<code>public void clearRegionCache( String region ) { if ( cacheEnabled ) { Cache cache = regionCache.get( region ); if ( cache != null ) { try { <START> synchronized ( cache ) { <END> cache.clear(); } } catch ( CacheException e ) { CacheManager.logger.error( Messages.getInstance().getString( "CacheManager.ERROR_0006_CACHE_EXCEPTION", e.getLocalizedMessage() ) ); } } else { CacheManager.logger.info( Messages.getInstance().getString( "CacheManager.INFO_0001_CACHE_DOES_NOT_EXIST", region ) ); } } else { CacheManager.logger.warn( Messages.getInstance().getString( "CacheManager.WARN_0001_CACHE_NOT_ENABLED" ) ); } }</code><technical_language>implementations of Cache (such net.sf.ehcache.Cache.java default) highly concurrent. *no* reason synchronize cache object. Please don't</technical_language>

Target:
public void clearRegionCache( String region ) { if ( cacheEnabled ) { Cache cache = regionCache.get( region ); if ( cache != null ) { try { cache.clear(); } catch ( CacheException e ) { CacheManager.logger.error( Messages.getInstance().getString( "CacheManager.ERROR_0006_CACHE_EXCEPTION", e.getLocalizedMessage() ) ); } } else { CacheManager.logger.info( Messages.getInstance().getString( "CacheManager.INFO_0001_CACHE_DOES_NOT_EXIST", region ) ); } } else { CacheManager.logger.warn( Messages.getInstance().getString( "CacheManager.WARN_0001_CACHE_NOT_ENABLED" ) ); } }
Source:
<code>public void doWithMessage(final WebServiceMessage message) throws IOException, TransformerException { final SoapMessage soapMessage = (SoapMessage) message; final SoapHeader header = soapMessage.getSoapHeader(); this.keyValues.entrySet().forEach(k -> { <START> final SoapHeaderElement messagePriorityElement = header.addHeaderElement(new QName(NAMESPACE, k.getKey())); <END> messagePriorityElement.setText(k.getValue()); }); }</code><technical_language>key-value set introduced I header element passing a messagePriorityElement, name changed more general</technical_language>

Target:
public void doWithMessage(final WebServiceMessage message) throws IOException, TransformerException { final SoapMessage soapMessage = (SoapMessage) message; final SoapHeader header = soapMessage.getSoapHeader(); this.keyValues.entrySet().forEach(k -> { final SoapHeaderElement headerElement = header.addHeaderElement(new QName(NAMESPACE, k.getKey())); headerElement.setText(k.getValue()); }); }
Source:
<code>public void switchLanguage(String langCodeCombined) throws IOException { String[] languageCode = langCodeCombined.split("_"); Locale locale; if (languageCode.length == 2) { locale = new Locale(languageCode[0], languageCode[1]); } else { locale = new Locale(languageCode[0]); } try { User user = ServiceManager.getUserService().getById(ServiceManager.getUserService().getAuthenticatedUser().getId()); user.setLanguage(locale.toString()); ServiceManager.getUserService().saveToDatabase(user); } catch (DAOException e) { Helper.setErrorMessage("errorSaving", new Object[] {ObjectType.USER.getTranslationSingular()}, logger, e); } FacesContext context = FacesContext.getCurrentInstance(); context.getViewRoot().setLocale(locale); context.getExternalContext().getSessionMap().put(SESSION_LOCALE_FIELD_ID, locale); context.getExternalContext() <START> .redirect(((HttpServletRequest) context.getExternalContext().getRequest()).getHeader("referer")); <END> }</code><technical_language>This introduce a easy exploit security issue referer information kind of string a valid URI a URI leading application</technical_language>

Target:
public void switchLanguage(String langCodeCombined) throws IOException { String[] languageCode = langCodeCombined.split("_"); Locale locale; if (languageCode.length == 2) { locale = new Locale(languageCode[0], languageCode[1]); } else { locale = new Locale(languageCode[0]); } try { User user = ServiceManager.getUserService().getById(ServiceManager.getUserService().getAuthenticatedUser().getId()); user.setLanguage(locale.toString()); ServiceManager.getUserService().saveToDatabase(user); } catch (DAOException e) { Helper.setErrorMessage("errorSaving", new Object[] {ObjectType.USER.getTranslationSingular()}, logger, e); } FacesContext context = FacesContext.getCurrentInstance(); context.getViewRoot().setLocale(locale); context.getExternalContext().getSessionMap().put(SESSION_LOCALE_FIELD_ID, locale); context.getExternalContext().redirect(null); }
Source:
<code>private void performPromotion() throws IOException { releaseLog.logMessage("Promoting build ..."); PromotionBuilder promotionBuilder = new PromotionBuilder().status(action.getTarget()) .comment(action.getComment()).ciUser(bambooUsername).targetRepo(action.getPromotionRepo()) .dependencies(action.isIncludeDependencies()).copy(action.isUseCopy()) .dryRun(true); releaseLog.logMessage("Performing dry run promotion (no changes are made during dry run) ..."); String buildName = action.getImmutableBuild().getName(); String buildNumber = action.getBuildNumber().toString(); HttpResponse dryResponse = null; HttpResponse wetResponse = null; try { dryResponse = client.stageBuild(buildName, buildNumber, promotionBuilder.build()); if (checkSuccess(dryResponse, true)) { releaseLog.logMessage("Dry run finished successfully. Performing promotion ..."); wetResponse = client.stageBuild(buildName, buildNumber, promotionBuilder.dryRun(false).build()); if (checkSuccess(wetResponse, false)) { releaseLog.logMessage("Promotion completed successfully!"); <START> return; <END> } return; } return; } finally { if (dryResponse != null) { HttpEntity entity = dryResponse.getEntity(); if (entity != null) { EntityUtils.consume(entity); } } if (wetResponse != null) { HttpEntity entity = wetResponse.getEntity(); if (entity != null) { EntityUtils.consume(entity); } } } }</code><technical_language>This return redundant</technical_language>

Target:
private void performPromotion() throws IOException { releaseLog.logMessage("Promoting build ..."); PromotionBuilder promotionBuilder = new PromotionBuilder().status(action.getTarget()) .comment(action.getComment()).ciUser(bambooUsername).targetRepo(action.getPromotionRepo()) .dependencies(action.isIncludeDependencies()).copy(action.isUseCopy()) .dryRun(true); releaseLog.logMessage("Performing dry run promotion (no changes are made during dry run) ..."); String buildName = action.getImmutableBuild().getName(); String buildNumber = action.getBuildNumber().toString(); HttpResponse dryResponse = null; HttpResponse wetResponse = null; try { dryResponse = client.stageBuild(buildName, buildNumber, promotionBuilder.build()); if (checkSuccess(dryResponse, true)) { releaseLog.logMessage("Dry run finished successfully. Performing promotion ..."); wetResponse = client.stageBuild(buildName, buildNumber, promotionBuilder.dryRun(false).build()); if (checkSuccess(wetResponse, false)) { releaseLog.logMessage("Promotion completed successfully!"); } } } finally { if (dryResponse != null) { HttpEntity entity = dryResponse.getEntity(); if (entity != null) { EntityUtils.consume(entity); } } if (wetResponse != null) { HttpEntity entity = wetResponse.getEntity(); if (entity != null) { EntityUtils.consume(entity); } } } }