auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public synchronized RecommendationResponse recommend(StackAdvisorRequest request) throws StackAdvisorException, AmbariException { requestId = generateRequestId(); String serviceName = "ZOOKEEPER"; ServiceInfo.ServiceAdvisorType serviceAdvisorType = getServiceAdvisorType(request.getStackName(), request.getStackVersion(), serviceName); StackAdvisorCommand<RecommendationResponse> command = createRecommendationCommand(serviceName, request); StackAdvisorRequestType requestType = request.getRequestType(); RecommendationResponse response = null; if (requestType == StackAdvisorRequestType.CONFIGURATIONS) { String hash = getHash(request); <START> LOG.info(String.format("Arrived configuration stack advisor request with hash: %s, service: %s", hash, request.getServiceName())); <END> response = configsRecommendationResponse.computeIfAbsent(hash, h -> { try { LOG.info(String.format("Invoking configuration stack advisor request with hash: %s, service: %s", hash, request.getServiceName())); return command.invoke(request, serviceAdvisorType); } catch (StackAdvisorException e) { return null; } }); } return response == null ? command.invoke(request, serviceAdvisorType) : response; }</code><technical_language>Change log message Calling stack advisor ...</technical_language>

Target:
public synchronized RecommendationResponse recommend(StackAdvisorRequest request) throws StackAdvisorException, AmbariException { requestId = generateRequestId(); String serviceName = "ZOOKEEPER"; ServiceInfo.ServiceAdvisorType serviceAdvisorType = getServiceAdvisorType(request.getStackName(), request.getStackVersion(), serviceName); StackAdvisorCommand<RecommendationResponse> command = createRecommendationCommand(serviceName, request); StackAdvisorRequestType requestType = request.getRequestType(); RecommendationResponse response = null; if (requestType == StackAdvisorRequestType.CONFIGURATIONS) { String hash = getHash(request); LOG.info(String.format("Calling stack advisor with hash: %s, service: %s", hash, request.getServiceName())); response = configsRecommendationResponse.computeIfAbsent(hash, h -> { try { LOG.info(String.format("Invoking configuration stack advisor command with hash: %s, service: %s", hash, request.getServiceName())); return command.invoke(request, serviceAdvisorType); } catch (StackAdvisorException e) { return null; } }); } return response == null ? command.invoke(request, serviceAdvisorType) : response; }
Source:
<code>public void argumentIsReadableXml() throws Exception { <START> final Iterator<String> iter = new FindBugsExcludes( <END> new Environment.Mock() .withExcludes("ClassToExclude,AnotherClass") ).asArguments().iterator(); final ExcludesXml xml = new ExcludesXml( new SAXReader().read(iter.next()) ); xml.assertXpath("count(/FindBugsFilter)=1"); xml.assertXpath("count(/FindBugsFilter/Match)=2"); }</code><technical_language>@ilyakharlamov too, try cactoos classes instead of making this iterator()</technical_language>

Target:
public void argumentIsReadableXml() throws Exception { final List<String> arguments = new FindBugsExcludes( new Environment.Mock().withExcludes("ClassToExclude,AnotherClass") ).asArguments(); MatcherAssert.assertThat( arguments.isEmpty(), new IsEqual<>(false) ); final Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(arguments.get(0)); MatcherAssert.assertThat( doc, Matchers.allOf( new HasXPath( FindBugsExcludesTest.COUNT_FILTER, new IsEqual<>("1") ), new HasXPath( FindBugsExcludesTest.COUNT_MATCH, new IsEqual<>("2") ) ) ); }
Source:
<code>public void modelExec(final Runnable runnable, boolean block) { Display displayThread = Display.getCurrent(); if (displayThread == null) { try { <START> displayThread = Display.getDefault(); <END> } catch (SWTException e) { if (e.getMessage().equals("Invalid thread access")) { throw new OperationCanceledException(); } else { throw e; } } } if (block) { if (Display.getCurrent() != null) { runnable.run(); } else { displayThread.syncExec(runnable); } } else { displayThread.asyncExec(runnable); } }</code><technical_language>recommended ask workbench for display: PlatformUI.getWorkbench().getDisplay()</technical_language>

Target:
public void modelExec(final Runnable runnable, boolean block) { Display displayThread = Display.getCurrent(); if (displayThread == null) { if (!PlatformUI.getWorkbench().isClosing()) { displayThread = Display.getDefault(); } else { throw new OperationCanceledException(); } } if (block) { if (Display.getCurrent() != null) { runnable.run(); } else { displayThread.syncExec(runnable); } } else { displayThread.asyncExec(runnable); } }
Source:
<code>public void runScanTest(boolean populateKeys) throws Exception { logger.info("SCAN TEST -- begin"); final String keyPattern = System.getProperty("dyno.demo.scan.key.pattern", "DynoClientTest_key-*"); final String keyPrefix = System.getProperty("dyno.demo.scan.key.prefix", "DynoClientTest_key-"); if (populateKeys) { logger.info("Writing 500 keys to with prefix {}", this.clusterName, keyPrefix); for (int i = 0; i < 500; i++) { client.set(keyPrefix + i, "value-" + i); } } logger.info("Reading keys from with pattern {}", this.clusterName, keyPattern); CursorBasedResult<String> cbi = null; long start = System.currentTimeMillis(); int count = 0; do { try { cbi = client.dyno_scan(cbi, 5, keyPattern); } catch (PoolOfflineException ex) { logger.info("Caught exception.... retrying scan"); cbi = null; continue; } List<String> results = cbi.getStringResult(); count += results.size(); int i = 0; for (String res : results) { logger.info("{}) {}", i, res); i++; } <START> Thread.sleep(1000); <END> } while ((cbi == null) || !cbi.isComplete()); long end = System.currentTimeMillis(); logger.info("SCAN TEST -- done results in {}ms", count, end - start); }</code><technical_language>calculate fast SCAN performs time sleeping thread in loop</technical_language>

Target:
public void runScanTest(boolean populateKeys) throws Exception { logger.info("SCAN TEST -- begin"); final String keyPattern = System.getProperty("dyno.demo.scan.key.pattern", "DynoClientTest_key-*"); final String keyPrefix = System.getProperty("dyno.demo.scan.key.prefix", "DynoClientTest_key-"); if (populateKeys) { logger.info("Writing 500 keys to with prefix {}", this.clusterName, keyPrefix); for (int i = 0; i < 500; i++) { client.set(keyPrefix + i, "value-" + i); } } logger.info("Reading keys from with pattern {}", this.clusterName, keyPattern); CursorBasedResult<String> cbi = null; long start = System.currentTimeMillis(); int count = 0; do { try { cbi = client.dyno_scan(cbi, 5, keyPattern); } catch (PoolOfflineException ex) { logger.info("Caught exception.... retrying scan"); cbi = null; continue; } List<String> results = cbi.getStringResult(); count += results.size(); int i = 0; for (String res : results) { logger.info("{}) {}", i, res); i++; } } while ((cbi == null) || !cbi.isComplete()); long end = System.currentTimeMillis(); logger.info("SCAN TEST -- done results in {}ms", count, end - start); }
Source:
<code>private void readBlock() throws IOException { mCurrentBlock = nextBlock(mCurrentBlock); if (mCurrentBlock == null) { <START> mCurrentBlock = new CompressionBlock(mStreamOffset, new byte[0], 0); <END> mCurrentBlock.mDecompressedBlock = new byte[0]; } mCurrentOffset = 0; }</code><technical_language>EMPTY_BLOCK line instead of declaring new arrays</technical_language>

Target:
private void readBlock() throws IOException { mCurrentBlock = nextBlock(mCurrentBlock); if (mCurrentBlock == null) { mCurrentBlock = new CompressionBlock(mStreamOffset, EMPTY_BLOCK, 0); mCurrentBlock.mDecompressedBlock = EMPTY_BLOCK; } mCurrentOffset = 0; }
Source:
<code><START> protected void executeCommand() { <END> final DisplayNetworkClusterHelper displayNetworkClusterHelper = new DisplayNetworkClusterHelper( getNetworkClusterDAO(), getVmDAO(), getNetworkCluster(), getNetworkName(), this); if (displayNetworkClusterHelper.isDisplayToBeUpdated()) { displayNetworkClusterHelper.warnOnActiveVm(); } TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { updateNetworkAttachment(getVdsGroupId(), getNetworkCluster(), getNetwork()); return null; } }); if (!getPersistedNetwork().isExternal() && NetworkUtils.isLabeled(getPersistedNetwork()) && NetworkHelper.setupNetworkSupported(getVdsGroup().getcompatibility_version())) { addNetworkToHosts(); } setSucceeded(true); }</code><technical_language>Note this reverted <LINK_0> is merged, - adjust</technical_language>

Target:
protected void executeCommand() { final DisplayNetworkClusterHelper displayNetworkClusterHelper = new DisplayNetworkClusterHelper( getNetworkClusterDAO(), getVmDAO(), getNetworkCluster(), getNetworkName(), AuditLogDirectorDelegator.getInstance()); if (displayNetworkClusterHelper.isDisplayToBeUpdated()) { displayNetworkClusterHelper.warnOnActiveVm(); } TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { attachNetwork(getVdsGroupId(), getNetworkCluster(), getNetwork()); return null; } }); if (!getPersistedNetwork().isExternal() && NetworkUtils.isLabeled(getPersistedNetwork()) && NetworkHelper.setupNetworkSupported(getVdsGroup().getcompatibility_version())) { addNetworkToHosts(); } setSucceeded(true); }
Source:
<code>public synchronized void startScanning(Context ctx) { Log.d(LOG_TAG, "ScanManager::startScanning"); if (this.isScanning()) { return; } mAppContext = ctx.getApplicationContext(); if (mAppContext == null) { Log.w(LOG_TAG, "No app context available."); return; } <START> Prefs prefs = Prefs.getInstance(); <END> if (prefs != null) { Log.d(LOG_TAG, "Simulation is set to: " + prefs.isSimulateStumble()); if (prefs.isSimulateStumble()) { mAppContext = new SimulationContext(mAppContext); Log.d(LOG_TAG, "ScanManager using SimulateStumbleContextWrapper"); } } mGPSScanner = new GPSScanner(mAppContext, this); mWifiScanner = new WifiScanner(mAppContext); mCellScanner = new CellScanner(mAppContext); if (prefs != null) { Log.d(LOG_TAG, "Simulation is set to: " + prefs.isSimulateStumble()); } mGPSScanner.start(mStumblingMode); if (mStumblingMode == ActiveOrPassiveStumbling.ACTIVE_STUMBLING) { mWifiScanner.start(mStumblingMode); mCellScanner.start(mStumblingMode); } mIsScanning = true; }</code><technical_language>love this block wrapping in Build.Debug</technical_language>

Target:
public synchronized void startScanning(Context ctx) { Log.d(LOG_TAG, "ScanManager::startScanning"); if (this.isScanning()) { return; } mAppContext = ctx.getApplicationContext(); if (mAppContext == null) { Log.w(LOG_TAG, "No app context available."); return; } if (AppGlobals.isDebug) { Prefs prefs = Prefs.getInstance(); if (prefs != null) { if (prefs.isSimulateStumble()) { mAppContext = new SimulationContext(mAppContext); Log.d(LOG_TAG, "ScanManager using SimulateStumbleContextWrapper"); } } } mGPSScanner = new GPSScanner(mAppContext, this); mWifiScanner = new WifiScanner(mAppContext); mCellScanner = new CellScanner(mAppContext); mGPSScanner.start(mStumblingMode); if (mStumblingMode == ActiveOrPassiveStumbling.ACTIVE_STUMBLING) { mWifiScanner.start(mStumblingMode); mCellScanner.start(mStumblingMode); } mIsScanning = true; }
Source:
<code>protected List<Class<?>> getStaticImportClasses() { List<Class<?>> result = super.getStaticImportClasses(); result.add(BusEvent.class); result.add(Exec.class); result.add(HTTP.class); result.add(Ping.class); result.add(ScriptExecution.class); result.add(LogAction.class); result.add(Audio.class); result.add(Voice.class); result.add(ThingAction.class); <START> result.add(ImperialUnits.class); <END> result.add(SIUnits.class); result.add(DateTime.class); result.addAll(getActionClasses()); return result; }</code><technical_language>please elaborate a bit ImperialUnits SIUnits classes added, SmartHomeUnits MetricPrefix</technical_language>

Target:
protected List<Class<?>> getStaticImportClasses() { List<Class<?>> result = super.getStaticImportClasses(); result.add(BusEvent.class); result.add(Exec.class); result.add(HTTP.class); result.add(Ping.class); result.add(ScriptExecution.class); result.add(LogAction.class); result.add(Audio.class); result.add(Voice.class); result.add(ThingAction.class); result.add(ImperialUnits.class); result.add(SIUnits.class); result.add(MetricPrefix.class); result.add(DateTime.class); result.addAll(getActionClasses()); return result; }
Source:
<code><START> public int hashCode() { <END> if (upToDateHash) { cachedHashCode = sort.hashCode() + cons.hashCode(); for (Term t : contents) cachedHashCode += t.hashCode(); upToDateHash = true; } return cachedHashCode; }</code><technical_language>pretty this safe. Consider: TermCons tc = something(); List<Term> contents = tc.getContents(); tc.hashCode(); contents.add(somethingElse()); tc.hashCode(); //returns wrong</technical_language>

Target:
public int hashCode() { if (!upToDateHash) { cachedHashCode = cons != null ? cons.hashCode() : 0; cachedHashCode = 31 * cachedHashCode + production.hashCode(); for (Term t : contents) cachedHashCode = 31 * cachedHashCode + t.hashCode(); upToDateHash = true; } return cachedHashCode; }
Source:
<code>public void saveFormData(FormData formData) throws FormDataSaveException { try { formData.setSaveTime(new Date()); formService.saveFormData(formData); <START> System.out.println(formData.getJsonPayload()); <END> } catch (IOException e) { throw new FormDataSaveException(e); } }</code><technical_language>I this log is longer in use</technical_language>

Target:
public void saveFormData(FormData formData) throws FormDataSaveException { try { formData.setSaveTime(new Date()); formService.saveFormData(formData); } catch (IOException e) { throw new FormDataSaveException(e); } }
Source:
<code>public void testCompositeBlobGetBlobInfoSuccess() throws Exception { router = getNonBlockingRouter(); setOperationParams(chunkSize * 6 + 11); String blobId = router.putBlob(putBlobProperties, putUserMetadata, putChannel).get(); BlobInfo blobInfo = router.getBlobInfo(blobId).get(); <START> Assert.assertEquals("Blob properties should match", putBlobProperties, blobInfo.getBlobProperties()); <END> Assert.assertArrayEquals("User metadata should match", putUserMetadata, blobInfo.getUserMetadata()); router.close(); }</code><technical_language>this equality check is equals() for</technical_language>

Target:
public void testCompositeBlobGetBlobInfoSuccess() throws Exception { router = getNonBlockingRouter(); setOperationParams(chunkSize * 6 + 11); String blobId = router.putBlob(putBlobProperties, putUserMetadata, putChannel).get(); BlobInfo blobInfo = router.getBlobInfo(blobId).get(); Assert.assertTrue("Blob properties should match", RouterTestHelpers.haveEquivalentFields(putBlobProperties, blobInfo.getBlobProperties())); Assert.assertArrayEquals("User metadata should match", putUserMetadata, blobInfo.getUserMetadata()); router.close(); }
Source:
<code>public final void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random rand) { randomDisplayTickDefault(state, world, pos, rand); IMicroblockContainerTile tile = getMicroblockTile(world, pos); MicroblockContainer container = tile != null ? tile.getMicroblockContainer() : null; <START> if (container != null) <END> { container.getPartContainer().randomDisplayTick(rand); } }</code><technical_language>this cleaner if didnt intermediate IMicroblockContainerTile caps</technical_language>

Target:
public final void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random rand) { IMicroblockContainerTile tile = getMicroblockTile(world, pos); if (tile != null) { tile.getMicroblockContainer().getPartContainer().randomDisplayTick(rand); } randomDisplayTickDefault(state, world, pos, rand); }
Source:
<code>protected Collection<? extends ITmfTrace> getTraces() { Set<ITmfTrace> traces = new HashSet<>(); for (ITmfTrace trace : fTraces) { <START> traces.addAll(Arrays.asList(TmfTraceManager.getTraceSet(trace))); <END> } return traces; }</code><technical_language>wow, this is hard understand :P I assume sense... want include experiments, want "real" traces, unpack experiments. in case, do this unpacking write fTraces instead? this method remain a simple getter. if exposed publicly, collection synchronized Immutable</technical_language>

Target:
protected Collection<? extends ITmfTrace> getTraces() { return new HashSet<>(fTraces); }
Source:
<code>public void testValueLoaderWithLocking() throws Exception { final SpringRemoteCacheManager springRemoteCacheManager = new SpringRemoteCacheManager(remoteCacheManager); final SpringCache cache = springRemoteCacheManager.getCache(TEST_CACHE_NAME); CountDownLatch waitUntilThread1LocksValueGetter = new CountDownLatch(1); Future<String> thread1 = fork(() -> cache.get("test", () -> { waitUntilThread1LocksValueGetter.countDown(); <START> TimeUnit.MILLISECONDS.sleep(10); <END> return "thread1"; })); Future<String> thread2 = fork(() -> { waitUntilThread1LocksValueGetter.await(); return cache.get("test", () -> "thread2"); }); String valueObtainedByThread1 = thread1.get(); String valueObtainedByThread2 = thread2.get(); Cache.ValueWrapper valueAfterGetterIsDone = cache.get("test"); assertNotNull(valueAfterGetterIsDone); assertEquals("thread1", valueAfterGetterIsDone.get()); assertEquals("thread1", valueObtainedByThread1); assertEquals("thread1", valueObtainedByThread2); }</code><technical_language>other test this delay; is needed here</technical_language>

Target:
public void testValueLoaderWithLocking() throws Exception { final SpringRemoteCacheManager springRemoteCacheManager = new SpringRemoteCacheManager(remoteCacheManager); final SpringCache cache = springRemoteCacheManager.getCache(TEST_CACHE_NAME); CountDownLatch waitUntilThread1LocksValueGetter = new CountDownLatch(1); Future<String> thread1 = fork(() -> cache.get("test", () -> { waitUntilThread1LocksValueGetter.countDown(); return "thread1"; })); Future<String> thread2 = fork(() -> { waitUntilThread1LocksValueGetter.await(); return cache.get("test", () -> "thread2"); }); String valueObtainedByThread1 = thread1.get(); String valueObtainedByThread2 = thread2.get(); Cache.ValueWrapper valueAfterGetterIsDone = cache.get("test"); assertNotNull(valueAfterGetterIsDone); assertEquals("thread1", valueAfterGetterIsDone.get()); assertEquals("thread1", valueObtainedByThread1); assertEquals("thread1", valueObtainedByThread2); }
Source:
<code>public void testIsLocalVariableDefResource() { final DetailAstImpl resourceTwoChildren = getNode(TokenTypes.RESOURCE); final DetailAstImpl modifiers = new DetailAstImpl(); <START> modifiers.setType(TokenTypes.MODIFIERS); <END> resourceTwoChildren.addChild(modifiers); final DetailAstImpl ident = new DetailAstImpl(); ident.setType(TokenTypes.IDENT); resourceTwoChildren.addChild(ident); assertTrue(ScopeUtil.isLocalVariableDef(resourceTwoChildren), "invalid result"); final DetailAstImpl resourceWithIdent = getNode(TokenTypes.RESOURCE); resourceWithIdent.addChild(ident); assertFalse(ScopeUtil.isLocalVariableDef(resourceWithIdent), "invalid result"); assertFalse(ScopeUtil.isLocalVariableDef(getNode(TokenTypes.RESOURCE)), "invalid result"); }</code><technical_language>avoid this type of tests ? do avoid this level of fakes good code</technical_language>

Target:
public void testIsLocalVariableDefResource() { final DetailAstImpl node = getNode(TokenTypes.RESOURCE); final DetailAstImpl modifiers = new DetailAstImpl(); modifiers.setType(TokenTypes.MODIFIERS); node.addChild(modifiers); final DetailAstImpl ident = new DetailAstImpl(); ident.setType(TokenTypes.IDENT); node.addChild(ident); assertTrue(ScopeUtil.isLocalVariableDef(node), "invalid result"); final DetailAstImpl resourceWithIdent = getNode(TokenTypes.RESOURCE); resourceWithIdent.addChild(ident); assertFalse(ScopeUtil.isLocalVariableDef(resourceWithIdent), "invalid result"); assertFalse(ScopeUtil.isLocalVariableDef(getNode(TokenTypes.RESOURCE)), "invalid result"); }
Source:
<code>protected boolean isValidConnection(StorageServerConnections conn) { StorageType storageType = conn.getstorage_type(); if (storageType == StorageType.NFS && !new NfsMountPointConstraint().isValid(conn.getconnection(), null)) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID); } if (storageType == StorageType.POSIXFS && (StringUtils.isEmpty(conn.getVfsType()))) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if ((storageType == StorageType.POSIXFS || storageType == StorageType.NFS) && !validate(validateMountOptions())) { return false; } if (storageType == StorageType.ISCSI) { if (StringUtils.isEmpty(conn.getiqn())) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_IQN); } if (!isValidStorageConnectionPort(conn.getport())) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID_PORT); } } if (storageType == StorageType.GLUSTERFS) { StorageConnectionValidator <START> validatror = <END> new StorageConnectionValidator(conn); ValidationResult validionResult = validatror.isGlusterfsCliPackageInstalled(getVds()); if (!validionResult.isValid()) { return failCanDoAction(validionResult.getMessage(), (String[])validionResult.getVariableReplacements().toArray()); } } if (checkIsConnectionFieldEmpty(conn)) { return false; } return true; }</code><technical_language>s/validatror/validator</technical_language>

Target:
protected boolean isValidConnection(StorageServerConnections conn) { StorageType storageType = conn.getstorage_type(); if (storageType == StorageType.NFS && !new NfsMountPointConstraint().isValid(conn.getconnection(), null)) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID); } if (storageType == StorageType.POSIXFS && (StringUtils.isEmpty(conn.getVfsType()))) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if ((storageType == StorageType.POSIXFS || storageType == StorageType.NFS) && !validate(validateMountOptions())) { return false; } if (storageType == StorageType.ISCSI) { if (StringUtils.isEmpty(conn.getiqn())) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_IQN); } if (!isValidStorageConnectionPort(conn.getport())) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID_PORT); } } if (storageType == StorageType.GLUSTERFS) { StorageConnectionValidator validator = new StorageConnectionValidator(conn); ValidationResult validionResult = validator.isGlusterfsCliPackageInstalled(getVds()); if (!validionResult.isValid()) { return failCanDoAction(validionResult.getMessage(), validionResult.getVariableReplacements().toArray(new String[validionResult.getVariableReplacements().size()])); } } if (checkIsConnectionFieldEmpty(conn)) { return false; } return true; }
Source:
<code>private void setStopTimeAvailable(boolean available) { if (available) { onPropertyChanged(new PropertyChangedEventArgs("STOP_TIME_IS_APPLICABLE")); } else { onPropertyChanged(new PropertyChangedEventArgs("STOP_TIME_NOT_APPLICABLE")); <START> } <END> }</code><technical_language>instead of propertychange events for a single field, a single properychange "STOP_TIME_UPDATED", a boolean field in model. In view, this boolean field decide visibility</technical_language>

Target:
private void setStopTimeAvailable(boolean available) { onPropertyChanged(new PropertyChangedEventArgs("STOP_TIME_UPDATED")); setStopTimeVisible(available); }
Source:
<code>public Response toResponse(InternalServerException e) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setTitle("Error occurred in the server while performing an operation."); errorResponse.setCode(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); errorResponse.setMessage(e.getMessage()); errorResponse.setDescription("Error occurred in the server."); errorResponse.setMoreInfo( <START> "Please contact administrator." + System.lineSeparator() + ExceptionUtils.getFullStackTrace(e)); <END> return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorResponse) .type(MediaType.APPLICATION_JSON).build(); }</code><technical_language>Exposing server stack traces client a security issue. hide information</technical_language>

Target:
public Response toResponse(InternalServerException e) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setTitle("Error occurred in the server while performing an operation."); errorResponse.setCode(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); errorResponse.setMessage(e.getMessage()); errorResponse.setDescription("Error occurred in the server."); errorResponse.setMoreInfo("Please contact administrator."); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorResponse) .type(MediaType.APPLICATION_JSON).build(); }
Source:
<code>public String getSubscriptionStatus(IBaseResource theSubscription) { <START> final IPrimitiveType<?> status = myFhirContext.newTerser().getSingleValueOrNull(theSubscription, SubscriptionConstants.SUBSCRIPTION_STATUS, IPrimitiveType.class); <END> return status.getValueAsString(); }</code><technical_language>Careful of NPE</technical_language>

Target:
public String getSubscriptionStatus(IBaseResource theSubscription) { final IPrimitiveType<?> status = myFhirContext.newTerser().getSingleValueOrNull(theSubscription, SubscriptionConstants.SUBSCRIPTION_STATUS, IPrimitiveType.class); if (status == null) { return null; } return status.getValueAsString(); }
Source:
<code>@Test public void dummyRangeShouldSuccessEvenTheBuildIsRunning() throws Exception { FreeStyleProject project = j.createFreeStyleProject("aProject"); <START> project.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo 1\r\nping -n 10 127.0.01 >nul") : new Shell("echo 1\nsleep 10s")); <END> assertThat("Job wasn't scheduled properly", project.scheduleBuild(0), equalTo(true)); while(!project.isBuilding()) { System.out.println("Waiting for build to start and sleep 1s..."); Thread.sleep(1000); } if(!project.getBuildByNumber(1).getLog().contains("echo 1")) { Thread.sleep(1000); } final CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ, Job.READ) .invokeWithArgs("aProject", "1"); assertThat(result, succeeded()); assertThat(result.stdout(), containsString("Builds: 1" + System.lineSeparator())); }</code><technical_language>IP address me. 127.0.0.1 instead of 127.0.01</technical_language>

Target:
@Test public void dummyRangeShouldSuccessEvenTheBuildIsRunning() throws Exception { FreeStyleProject project = j.createFreeStyleProject("aProject"); project.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo 1\r\nping -n 10 127.0.0.1 >nul") : new Shell("echo 1\nsleep 10s")); assertThat("Job wasn't scheduled properly", project.scheduleBuild(0), equalTo(true)); while(!project.isBuilding()) { System.out.println("Waiting for build to start and sleep 1s..."); Thread.sleep(1000); } if(!project.getBuildByNumber(1).getLog().contains("echo 1")) { Thread.sleep(1000); } final CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ, Job.READ) .invokeWithArgs("aProject", "1"); assertThat(result, succeeded()); assertThat(result.stdout(), containsString("Builds: 1" + System.lineSeparator())); }
Source:
<code>private static Block serializeStruct(Type type, BlockBuilder builder, Object object) { if (object == null) { requireNonNull(builder, "builder is null"); builder.appendNull(); return null; } List<Type> typeParameters = type.getTypeParameters(); BlockBuilder currentBuilder; boolean builderSynthesized = false; if (builder == null) { builderSynthesized = true; builder = type.createBlockBuilder(null, 1); } currentBuilder = builder.beginBlockEntry(); for (int i = 0; i < typeParameters.size(); i++) { Optional<String> fieldName = type.getTypeSignature().getParameters().get(i).getNamedTypeSignature().getName(); String name = ""; if (fieldName.isPresent()) { name = fieldName.get().toLowerCase(ENGLISH); } Object value = ((Map) object).get(name); serializeObject(typeParameters.get(i), currentBuilder, value); } builder.closeEntry(); if (builderSynthesized) { return (Block) type.getObject(builder, 0); } else { <START> return null; <END> } }</code><technical_language>else is redundant</technical_language>

Target:
private static Block serializeStruct(Type type, BlockBuilder builder, Object object) { if (object == null) { requireNonNull(builder, "builder is null"); builder.appendNull(); return null; } List<Type> typeParameters = type.getTypeParameters(); BlockBuilder currentBuilder; boolean builderSynthesized = false; if (builder == null) { builderSynthesized = true; builder = type.createBlockBuilder(null, 1); } currentBuilder = builder.beginBlockEntry(); for (int i = 0; i < typeParameters.size(); i++) { Optional<String> fieldName = type.getTypeSignature().getParameters().get(i).getNamedTypeSignature().getName(); String name = ""; if (fieldName.isPresent()) { name = fieldName.get().toLowerCase(ENGLISH); } Object value = ((Map) object).get(name); serializeObject(typeParameters.get(i), currentBuilder, value); } builder.closeEntry(); if (builderSynthesized) { return (Block) type.getObject(builder, 0); } return null; }
Source:
<code>public ElasticsearchContainer(final DockerImageName dockerImageName) { super(dockerImageName); dockerImageName.assertCompatibleWith(DEFAULT_IMAGE_NAME, DEFAULT_OSS_IMAGE_NAME); <START> if (getDockerImageName().startsWith(DEFAULT_OSS_IMAGE_NAME.getUnversionedPart())) { <END> this.isOss = true; } logger().info("Starting an elasticsearch container using [{}]", dockerImageName); withNetworkAliases("elasticsearch-" + Base58.randomString(6)); withEnv("discovery.type", "single-node"); addExposedPorts(ELASTICSEARCH_DEFAULT_PORT, ELASTICSEARCH_DEFAULT_TCP_PORT); setWaitStrategy(new HttpWaitStrategy() .forPort(ELASTICSEARCH_DEFAULT_PORT) .forStatusCodeMatching(response -> response == HTTP_OK || response == HTTP_UNAUTHORIZED) .withStartupTimeout(Duration.ofMinutes(2))); }</code><technical_language>consider compatibility check instead</technical_language>

Target:
public ElasticsearchContainer(final DockerImageName dockerImageName) { super(dockerImageName); dockerImageName.assertCompatibleWith(DEFAULT_IMAGE_NAME, DEFAULT_OSS_IMAGE_NAME); if (dockerImageName.isCompatibleWith(DEFAULT_OSS_IMAGE_NAME)) { this.isOss = true; } logger().info("Starting an elasticsearch container using [{}]", dockerImageName); withNetworkAliases("elasticsearch-" + Base58.randomString(6)); withEnv("discovery.type", "single-node"); addExposedPorts(ELASTICSEARCH_DEFAULT_PORT, ELASTICSEARCH_DEFAULT_TCP_PORT); setWaitStrategy(new HttpWaitStrategy() .forPort(ELASTICSEARCH_DEFAULT_PORT) .forStatusCodeMatching(response -> response == HTTP_OK || response == HTTP_UNAUTHORIZED) .withStartupTimeout(Duration.ofMinutes(2))); }
Source:
<code>public void testFeatureFinish() throws Exception { testRepository .createInitialCommit("testFeatureFinish\n\nfirst commit\n"); Repository repository = testRepository.getRepository(); new InitOperation(repository).execute(null); GitFlowRepository gfRepo = new GitFlowRepository(repository); new FeatureStartOperation(gfRepo, MY_FEATURE).execute(null); <START> <END> new FeatureFinishOperation(gfRepo).execute(null); assertEquals(gfRepo.getDevelopFull(), repository.getFullBranch()); String branchName = gfRepo.getFeatureBranchName(MY_FEATURE); RevCommit branchCommit = testRepository .createInitialCommit("testFeatureFinish\n\nbranch commit\n"); assertEquals(findBranch(repository, branchName), null); RevCommit developHead = gfRepo.findHead(); assertEquals(branchCommit, developHead); }</code><technical_language>blank lines</technical_language>

Target:
public void testFeatureFinish() throws Exception { Repository repository = testRepository.getRepository(); GitFlowRepository gfRepo = init("testFeatureFinish\n\nfirst commit\n"); new FeatureStartOperation(gfRepo, MY_FEATURE).execute(null); new FeatureFinishOperation(gfRepo).execute(null); assertEquals(gfRepo.getDevelopFull(), repository.getFullBranch()); String branchName = gfRepo.getFeatureBranchName(MY_FEATURE); RevCommit branchCommit = testRepository .createInitialCommit("testFeatureFinish\n\nbranch commit\n"); assertEquals(findBranch(repository, branchName), null); RevCommit developHead = gfRepo.findHead(); assertEquals(branchCommit, developHead); }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CacheQuotaRequirement that = (CacheQuotaRequirement) o; <START> return cacheQuotaScope == that.cacheQuotaScope && Objects.equals(quota, that.quota); <END> }</code><technical_language>Objects.equals for cacheQuotaScope</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CacheQuotaRequirement that = (CacheQuotaRequirement) o; return Objects.equals(cacheQuotaScope, that.cacheQuotaScope) && Objects.equals(quota, that.quota); }
Source:
<code>private Collection<StreamlineEvent> convert(List<Values> result, final StreamlineEvent inputEvent) { Collection<StreamlineEvent> output = Collections.emptyList(); if (result != null) { if (valuesConverter != null) { output = Collections2.transform(result, new Function<Values, StreamlineEvent>() { @Override public StreamlineEvent apply(Values values) { return valuesConverter.convert(values, inputEvent); } }); <START> } else if (result instanceof StreamlineEvent){ <END> output = Collections.singletonList((StreamlineEvent) result); } } LOG.debug("Expression evaluation result converted to [{}]", result, output); return output; }</code><technical_language>nit: space ) {</technical_language>

Target:
private Collection<StreamlineEvent> convert(List<Values> result, final StreamlineEvent inputEvent) { Collection<StreamlineEvent> output = Collections.emptyList(); if (result != null) { if (valuesConverter != null) { output = Collections2.transform(result, new Function<Values, StreamlineEvent>() { @Override public StreamlineEvent apply(Values values) { return valuesConverter.convert(values, inputEvent); } }); } else if (result instanceof StreamlineEvent) { output = Collections.singletonList((StreamlineEvent) result); } else { throw new IllegalArgumentException("valueConverter is null and result is not an instance of StreamlineEvent"); } } LOG.debug("Expression evaluation result converted to [{}]", result, output); return output; }
Source:
<code>public void markForDeletion(AgentPrincipals agent, String... ids) { Collection<PID> removed = new ArrayList<>(); PID pid = null; for (String id : ids) { pid = PIDs.get(id); Runnable job = new MarkForDeletionJob(pid, agent, repositoryObjectLoader, sparqlUpdateService, aclService); job.run(); removed.add(pid); } if (pid != null) { PID destination = repositoryObjectLoader.getRepositoryObject(pid).getParent().getPid(); <START> operationsMessageSender.sendRemoveOperation(agent.getUsername(), destination, removed); <END> } }</code><technical_language>Hmm, Remove event for destroy operations in past, actual removal of object repo marking for deletion. master, existing event for this. I suggest making a new MarkForDeletion operation. Additionally, event impact hierarchy (nothing moves is removed), I suggest event a param for parents, updated objects</technical_language>

Target:
public void markForDeletion(AgentPrincipals agent, String... ids) { Collection<PID> pids = new ArrayList<>(); for (String id : ids) { PID pid = PIDs.get(id); Runnable job = new MarkForDeletionJob(pid, agent, repositoryObjectLoader, sparqlUpdateService, aclService); job.run(); pids.add(pid); } operationsMessageSender.sendMarkForDeletionOperation(agent.getUsername(), pids); }
Source:
<code>public static void main(String[] args) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer() .host("127.0.0.1") .port(ConfigurationProperties.DEFAULT_HOTROD_PORT) .security().authentication() .username("username") .password("password") .realm("default") .saslMechanism("DIGEST-MD5"); builder.remoteCache("my-cache") .templateName("org.infinispan.DIST_SYNC"); builder.remoteCache("another-cache") .configuration("<infinispan><cache-container><distributed-cache name=\"another-cache\"><encoding media-type=\"application/x-protostream\"/></distributed-cache></cache-container></infinispan>"); RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); RemoteCache<String, String> cache = cacheManager.getCache("my-cache"); cache.put("hello", "world"); System.out.printf("key = %s\n", cache.get("key")); <START> cacheManager.stop(); <END> }</code><technical_language>try-with-resources automatically close client finishes. java try (RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build())) { ... }</technical_language>

Target:
public static void main(String[] args) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer() .host("127.0.0.1") .port(ConfigurationProperties.DEFAULT_HOTROD_PORT) .security().authentication() .username("username") .password("password") .realm("default") .saslMechanism("DIGEST-MD5"); builder.remoteCache("my-cache") .templateName("org.infinispan.DIST_SYNC"); builder.remoteCache("another-cache") .configuration("<infinispan><cache-container><distributed-cache name=\"another-cache\"><encoding media-type=\"application/x-protostream\"/></distributed-cache></cache-container></infinispan>"); try (RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build())) { RemoteCache<String, String> cache = cacheManager.getCache("my-cache"); cache.put("hello", "world"); System.out.printf("key = %s\n", cache.get("hello")); } }
Source:
<code>public String getTableToolContent(@ApiParam(value = "workflowId", required = true) @PathParam("workflowId") Long workflowId, @ApiParam(value = "workflowVersionId", required = true) @PathParam("workflowVersionId") Long workflowVersionId) { Workflow workflow = workflowDAO.findById(workflowId); WorkflowVersion workflowVersion = getWorkflowVersion(workflow, workflowVersionId); SourceFile mainDescriptor = getMainDescriptorFile(workflowVersion); if(mainDescriptor != null) { File tmpDir = Files.createTempDir(); File tempMainDescriptor = null; try { tempMainDescriptor = File.createTempFile("main", "descriptor", tmpDir); Files.write(mainDescriptor.getContent(), tempMainDescriptor, StandardCharsets.UTF_8); File secondaryDescriptor; for (SourceFile secondaryFile : workflowVersion.getSourceFiles()) { if (!secondaryFile.getPath().equals(workflowVersion.getWorkflowPath())) { secondaryDescriptor = new File(tmpDir.getAbsolutePath(), secondaryFile.getPath()); Files.write(secondaryFile.getContent(), secondaryDescriptor, StandardCharsets.UTF_8); } } } catch (IOException e) { <START> e.printStackTrace(); <END> } String result; if(workflow.getDescriptorType().equals("wdl")) { result = getContentWDL(tempMainDescriptor, "tools"); } else{ result = getContentCWL(tempMainDescriptor, tmpDir,"tools"); } return result; } return null; }</code><technical_language>here, read content memory writing disk avoid possibility of IOExceptions</technical_language>

Target:
public String getTableToolContent(@ApiParam(value = "workflowId", required = true) @PathParam("workflowId") Long workflowId, @ApiParam(value = "workflowVersionId", required = true) @PathParam("workflowVersionId") Long workflowVersionId) { Workflow workflow = workflowDAO.findById(workflowId); WorkflowVersion workflowVersion = getWorkflowVersion(workflow, workflowVersionId); SourceFile mainDescriptor = getMainDescriptorFile(workflowVersion); if(mainDescriptor != null) { String descFileContent = mainDescriptor.getContent(); Map<String, String> secondaryDescContent = new HashMap<>(); File tmpDir = Files.createTempDir(); File tempMainDescriptor = null; try { tempMainDescriptor = File.createTempFile("main", "descriptor", tmpDir); Files.write(mainDescriptor.getContent(), tempMainDescriptor, StandardCharsets.UTF_8); for (SourceFile secondaryFile : workflowVersion.getSourceFiles()) { if (!secondaryFile.getPath().equals(workflowVersion.getWorkflowPath())) { secondaryDescContent.put(secondaryFile.getPath(),secondaryFile.getContent()); } } } catch (IOException e) { e.printStackTrace(); } String result; if(workflow.getDescriptorType().equals("wdl")) { result = getContentWDL(tempMainDescriptor, Type.TOOLS); } else{ result = getContentCWL(descFileContent, secondaryDescContent, Type.TOOLS); } return result; } return null; }
Source:
<code>public void testReserveFormSuccess() { MockHttpServletRequestBuilder getRequest = MockMvcRequestBuilders.get( "/tours/123/reserve").param("form", ""); <START> when(reserveTourHelper.findTourDetail(any(), eq("123"), any())) <END> .thenReturn(new TourDetailOutput()); try { ResultActions results = mockMvc.perform(getRequest); results.andExpect(status().isOk()); results.andExpect(view().name("reservetour/reserveForm")); results.andExpect(model().attribute("output", notNullValue())); return; } catch (Exception e) { e.printStackTrace(); } fail(); }</code><technical_language>[x] any() is any(ReservationUserDetails.class) any(ReserveTourForm.class)</technical_language>

Target:
public void testReserveFormSuccess() { MockHttpServletRequestBuilder getRequest = MockMvcRequestBuilders.get( "/tours/123/reserve").param("form", "").with(user(userDetails)); when(reserveTourHelper.findTourDetail(any(ReservationUserDetails.class), eq("123"), any(ReserveTourForm.class))).thenReturn( new TourDetailOutput()); try { ResultActions results = mockMvc.perform(getRequest); results.andExpect(status().isOk()); results.andExpect(view().name("reservetour/reserveForm")); results.andExpect(model().attribute("output", notNullValue())); return; } catch (Exception e) { e.printStackTrace(); } fail(); }
Source:
<code>private Event processCustomEvent(ReadContext readContext) { Configuration conf = Configuration.defaultConfiguration(); Event event = new Event(attributesSize); Object[] data = event.getData(); Object childObject = readContext.read(DEFAULT_ENCLOSING_ELEMENT); readContext = JsonPath.using(conf).parse(childObject); for (MappingPositionData mappingPositionData : this.mappingPositions) { int position = mappingPositionData.getPosition(); Object mappedValue; try { mappedValue = readContext.read(mappingPositionData.getMapping()); if (mappedValue == null) { data[position] = null; } else { data[position] = attributeConverter.getPropertyValue(mappedValue.toString(), streamAttributes.get(position).getType()); } } catch (PathNotFoundException e) { <START> if (failOnMissingAttribute) { <END> throw new ExecutionPlanRuntimeException("Json message " + childObject.toString() + " contains missing attributes. Hence dropping the message."); } data[position] = null; } } return event; }</code><technical_language>log</technical_language>

Target:
private Event processCustomEvent(ReadContext readContext) { Configuration conf = Configuration.defaultConfiguration(); Event event = new Event(attributesSize); Object[] data = event.getData(); Object childObject = readContext.read(DEFAULT_ENCLOSING_ELEMENT); readContext = JsonPath.using(conf).parse(childObject); for (MappingPositionData mappingPositionData : this.mappingPositions) { int position = mappingPositionData.getPosition(); Object mappedValue; try { mappedValue = readContext.read(mappingPositionData.getMapping()); if (mappedValue == null) { data[position] = null; } else { data[position] = attributeConverter.getPropertyValue(mappedValue.toString(), streamAttributes.get(position).getType()); } } catch (PathNotFoundException e) { if (failOnMissingAttribute) { log.error("Json message " + childObject.toString() + " contains missing attributes. Hence dropping the message."); return null; } data[position] = null; } } return event; }
Source:
<code>private VelocityContext buildContext(String[] inputStrs) { VelocityContext context = new VelocityContext(); String[][] tokens = new String[inputStrs.length][]; boolean isFloatingPoint = false; for (int i = 0; i < inputStrs.length; i++) { tokens[i] = inputStrs[i].trim().split("\\s+"); for (int j = 0; j < tokens[i].length; j++) { try { Long.valueOf(tokens[i][0]); } catch (NumberFormatException ex) { isFloatingPoint = true; } } } Map<Object, TemplateVertex> vertexMap = new LinkedHashMap<>(inputStrs.length); for (int i = 0; i < inputStrs.length; i++) { Object id = readId(tokens[i][0], isFloatingPoint); TemplateVertex vertex = vertexMap.get(id); if (vertex == null) { vertex = new TemplateVertex(id); vertexMap.put(id, vertex); } if (tokens[i].length > 1) { for (int j = 1; j < tokens[i].length; j++) { Object nbrId = readId(tokens[i][j], isFloatingPoint); if (!vertexMap.containsKey(nbrId)) { vertexMap.put(nbrId, new TemplateVertex(nbrId)); } vertex.addNeighbor(nbrId); } } } <START> if (isFloatingPoint) { <END> context.put("vertexIdClass", DoubleWritable.class.getSimpleName()); } else { context.put("vertexIdClass", LongWritable.class.getSimpleName()); } context.put("vertices", vertexMap); return context; }</code><technical_language>add a blank line if statement? i write this as: context.put("vertexIdClass", isFloatingPoint ? DoubleWritable(...) : LongWritable(...)); nicer I :)</technical_language>

Target:
private VelocityContext buildContext(String[] inputStrs) { VelocityContext context = new VelocityContext(); String[][] tokens = new String[inputStrs.length][]; boolean isFloatingPoint = false; for (int i = 0; i < inputStrs.length; i++) { tokens[i] = inputStrs[i].trim().split("\\s+"); for (int j = 0; j < tokens[i].length; j++) { try { Long.valueOf(tokens[i][0]); } catch (NumberFormatException ex) { isFloatingPoint = true; } } } Map<Object, TemplateVertex> vertexMap = new LinkedHashMap<>(inputStrs.length); for (int i = 0; i < inputStrs.length; i++) { Object id = readId(tokens[i][0], isFloatingPoint); TemplateVertex vertex = vertexMap.get(id); if (vertex == null) { vertex = new TemplateVertex(id); vertexMap.put(id, vertex); } if (tokens[i].length > 1) { for (int j = 1; j < tokens[i].length; j++) { Object nbrId = readId(tokens[i][j], isFloatingPoint); if (!vertexMap.containsKey(nbrId)) { vertexMap.put(nbrId, new TemplateVertex(nbrId)); } vertex.addNeighbor(nbrId); } } } context.put("vertexIdClass", (isFloatingPoint ? DoubleWritable.class.getSimpleName() : LongWritable.class.getSimpleName())); context.put("vertices", vertexMap); return context; }
Source:
<code>private void preprocessParameters(StudentProfileAttributes studentProfile) { studentProfile.shortName = StringHelper.trimIfNotNull(studentProfile.shortName); studentProfile.email = StringHelper.trimIfNotNull(studentProfile.email); <START> studentProfile.gender = Gender.valueOf(StringHelper.trimIfNotNull(studentProfile.gender.name())); <END> studentProfile.nationality = StringHelper.trimIfNotNull(studentProfile.nationality); studentProfile.institute = StringHelper.trimIfNotNull(studentProfile.institute); studentProfile.moreInfo = StringHelper.trimIfNotNull(studentProfile.moreInfo); }</code><technical_language>This is redundant transforming enum string enum again</technical_language>

Target:
private void preprocessParameters(StudentProfileAttributes studentProfile) { studentProfile.shortName = StringHelper.trimIfNotNull(studentProfile.shortName); studentProfile.email = StringHelper.trimIfNotNull(studentProfile.email); studentProfile.nationality = StringHelper.trimIfNotNull(studentProfile.nationality); studentProfile.institute = StringHelper.trimIfNotNull(studentProfile.institute); studentProfile.moreInfo = StringHelper.trimIfNotNull(studentProfile.moreInfo); }
Source:
<code>private void setFlowId(final JSONObject metadata) { <START> if (metadata.optString("flow_id") == null || "".equals(metadata.optString("flow_id"))) { <END> metadata.put("flow_id", FlowIdUtils.peek()); } }</code><technical_language>optString return null, return "null", "" "value" <LINK_0> I sense move metadata.optString("flow_id") var twice</technical_language>

Target:
private void setFlowId(final JSONObject metadata) { if ("".equals(metadata.optString("flow_id"))) { metadata.put("flow_id", FlowIdUtils.peek()); } }