auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ClusterFeature get() { Cluster cluster = parent.getClusterEntity(); SupportedAdditionalClusterFeature feature = cluster.getAddtionalFeaturesSupported() .stream() .filter(f -> f.getFeature().getId().equals(asGuid(id))) .findFirst() <START> .orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND)); <END> return ClusterFeaturesMapper.map(feature.getFeature(), null); }</code><technical_language>This code get feature is in remove method. suggest create a new BackendClusterFeatureHelper class put this code there. call methos. BackendDataCenterHelper for example</technical_language>

Target:
public ClusterFeature get() { SupportedAdditionalClusterFeature feature = BackendClusterFeatureHelper.getEnabledFeature(this, asGuid(clusterId), asGuid(id)); return ClusterFeaturesMapper.map(feature.getFeature(), null); }
Source:
<code><START> public Iterator getLocations() <END> { return ORDERING.sortedCopy(this.storageLocations).iterator(); }</code><technical_language>Please type properly Iterator<StorageLocation></technical_language>

Target:
public Iterator<StorageLocation> getLocations() { return ORDERING.sortedCopy(this.storageLocations).iterator(); }
Source:
<code>public CoprocessorRpcChannel coprocessorService(ServerName serverName) { <START> return null; <END> }</code><technical_language>throw UnsupportedExceptions</technical_language>

Target:
public CoprocessorRpcChannel coprocessorService(ServerName serverName) { throw new UnsupportedOperationException("coprocessorService"); }
Source:
<code>public static String getGatewayAliasDefaultTo(String overrideAlias) { if (StringUtils.isNotBlank(overrideAlias)) { return overrideAlias; } <START> String alias = System.getProperty(NhincConstants.CLIENT_KEY_ALIAS); <END> return StringUtils.isBlank(alias) ? NhincConstants.DEFAULT_CLIENT_KEY_ALIAS : alias; }</code><technical_language>duplicate logic in getPrivateKeyAlias method()</technical_language>

Target:
public static String getGatewayAliasDefaultTo(String overrideAlias) { if (StringUtils.isNotBlank(overrideAlias)) { return overrideAlias; } return getPrivateKeyAlias(); }
Source:
<code>public String toString() { return "exceededCount=" + m_exceededCount + <START> "\nm_armed=" + m_armed; <END> }</code><technical_language>suggestion "\narmed=" + m_armed;</technical_language>

Target:
public String toString() { return "exceededCount=" + m_exceededCount + "\narmed=" + m_armed; }
Source:
<code>private void updateFileCacheSizeLimit() { boolean isAvailableSpaceLowerThanHighLimit; if(mDiskCacheIsExternal){ <START> isAvailableSpaceLowerThanHighLimit = <END> mStatFsHelper.testLowDiskSpace( StatFsHelper.StorageType.EXTERNAL, mDefaultCacheSizeLimit - mCacheStats.getSize()); } else{ isAvailableSpaceLowerThanHighLimit = mStatFsHelper.testLowDiskSpace( StatFsHelper.StorageType.INTERNAL, mDefaultCacheSizeLimit - mCacheStats.getSize()); } if (isAvailableSpaceLowerThanHighLimit) { mCacheSizeLimit = mLowDiskSpaceCacheSizeLimit; } else { mCacheSizeLimit = mDefaultCacheSizeLimit; } }</code><technical_language>need for code duplication. do like: StorageType storageType = mStorage.isExternal() ? StatFsHelper.StorageType.EXTERNAL : StatFsHelper.StorageType.INTERNAL;</technical_language>

Target:
private void updateFileCacheSizeLimit() { boolean isAvailableSpaceLowerThanHighLimit; StatFsHelper.StorageType storageType = mStorage.isExternal() ? StatFsHelper.StorageType.EXTERNAL : StatFsHelper.StorageType.INTERNAL; isAvailableSpaceLowerThanHighLimit = mStatFsHelper.testLowDiskSpace( storageType, mDefaultCacheSizeLimit - mCacheStats.getSize()); if (isAvailableSpaceLowerThanHighLimit) { mCacheSizeLimit = mLowDiskSpaceCacheSizeLimit; } else { mCacheSizeLimit = mDefaultCacheSizeLimit; } }
Source:
<code>BufferAndBacklog pollBuffer() { synchronized (buffers) { if (isBlocked) { return null; } Buffer buffer = null; if (buffers.isEmpty()) { flushRequested = false; } while (!buffers.isEmpty()) { BufferConsumer bufferConsumer = buffers.peek().getBufferConsumer(); buffer = bufferConsumer.build(); checkState(bufferConsumer.isFinished() || buffers.size() == 1 || (buffers.size() == 2 && buffers.peekLast().getBufferConsumer().getDataType() == Buffer.DataType.RECOVERY_COMPLETION), "When there are multiple buffers, an unfinished bufferConsumer can not be at the head of the buffers queue."); <START> <END> if (buffers.size() == 1) { flushRequested = false; } if (bufferConsumer.isFinished()) { buffers.poll().getBufferConsumer().close(); decreaseBuffersInBacklogUnsafe(bufferConsumer.isBuffer()); } if (buffer.readableBytes() > 0) { break; } buffer.recycleBuffer(); buffer = null; if (!bufferConsumer.isFinished()) { break; } } if (buffer == null) { return null; } if (buffer.getDataType().isBlockingUpstream()) { isBlocked = true; } updateStatistics(buffer); return new BufferAndBacklog( buffer, getBuffersInBacklog(), isDataAvailableUnsafe() ? getNextBufferTypeUnsafe() : Buffer.DataType.NONE, sequenceNumber++); } }</code><technical_language>do need change for aligned barriers</technical_language>

Target:
BufferAndBacklog pollBuffer() { synchronized (buffers) { if (isBlocked) { return null; } Buffer buffer = null; if (buffers.isEmpty()) { flushRequested = false; } while (!buffers.isEmpty()) { BufferConsumerWithPartialRecordLength bufferConsumerWithPartialRecordLength = buffers.peek(); BufferConsumer bufferConsumer = bufferConsumerWithPartialRecordLength.getBufferConsumer(); buffer = buildSliceBuffer(bufferConsumerWithPartialRecordLength); checkState(bufferConsumer.isFinished() || buffers.size() == 1, "When there are multiple buffers, an unfinished bufferConsumer can not be at the head of the buffers queue."); if (buffers.size() == 1) { flushRequested = false; } if (bufferConsumer.isFinished()) { requireNonNull(buffers.poll()).getBufferConsumer().close(); decreaseBuffersInBacklogUnsafe(bufferConsumer.isBuffer()); } if (buffer.readableBytes() > 0) { break; } buffer.recycleBuffer(); buffer = null; if (!bufferConsumer.isFinished()) { break; } } if (buffer == null) { return null; } if (buffer.getDataType().isBlockingUpstream()) { isBlocked = true; } updateStatistics(buffer); return new BufferAndBacklog( buffer, getBuffersInBacklog(), isDataAvailableUnsafe() ? getNextBufferTypeUnsafe() : Buffer.DataType.NONE, sequenceNumber++); } }
Source:
<code>public InMemoryMessageExchangeStore(final NetworkConfig config, TokenProvider tokenProvider) { if (config == null) { throw new NullPointerException("Configuration must not be null"); } if (tokenProvider == null) { throw new NullPointerException("TokenProvider must not be null"); } this.tokenProvider = tokenProvider; this.config = config; <START> this.tokenLength = config.getInt(NetworkConfig.Keys.TOKEN_SIZE_LIMIT, MAX_TOKEN_LENGTH); <END> LOGGER.log(Level.CONFIG, "using tokens of {0} bytes in length", tokenLength); }</code><technical_language>Do need token length here? TokenProvider retrieves config itself, it</technical_language>

Target:
public InMemoryMessageExchangeStore(final NetworkConfig config, TokenProvider tokenProvider) { if (config == null) { throw new NullPointerException("Configuration must not be null"); } if (tokenProvider == null) { throw new NullPointerException("TokenProvider must not be null"); } this.tokenProvider = tokenProvider; this.config = config; }
Source:
<code>public <START> ChangeInfo format(RevisionResource <END> rsrc) throws OrmException { ChangeData cd = changeDataFactory.create(db.get(), rsrc.getControl()); Optional<PatchSet.Id> ps = Optional.of(rsrc.getPatchSet().getId()); return format(cd, ps); }</code><technical_language>format(RevisionResource) return a ChangeInfo (at least) a RevisionInfo? ideally return a Map<String, ActionInfo></technical_language>

Target:
public Map<String, ActionInfo> format(RevisionResource rsrc) throws OrmException { ChangeData cd = changeDataFactory.create(db.get(), rsrc.getControl()); return toRevisionActionInfoMap(cd, rsrc.getPatchSet().getId()); }
Source:
<code>private String putBlob(Router router, BlobProperties blobProperties, byte[] usermetadata, byte[] content, RouterOperationCallback<String> putBlobCallback) throws Exception { byte[] buf = new byte[content.length]; Utils.readBytesFromStream(new ByteArrayInputStream(content), buf, 0, content.length); ReadableStreamChannel blobDataChannel = new ByteBufferReadableStreamChannel(ByteBuffer.wrap(buf)); Future<String> putBlobFuture; if (putBlobCallback == null) { putBlobFuture = router.putBlob(blobProperties, usermetadata, blobDataChannel); } else { putBlobFuture = router.putBlob(blobProperties, usermetadata, blobDataChannel, putBlobCallback); if (!putBlobCallback.awaitCallback(1, TimeUnit.SECONDS)) { throw new IllegalStateException("putBlob() timed out"); } else if (putBlobCallback.getException() != null) { verifyExceptionMatch(putBlobCallback, putBlobFuture); throw putBlobCallback.getException(); } <START> assertTrue("PutBlob: Future is not done but callback has been received", putBlobFuture.isDone()); <END> assertEquals("PutBlob: Future BlobId and callback BlobId do not match", putBlobFuture.get(), putBlobCallback.getResult()); } return putBlobFuture.get(); }</code><technical_language>verifyExceptionMatch() blocks future.get(), isDone() true here, no? Also, if callback received, ensure future.get() returns immediately well, a timed get verifyExceptionMatch()</technical_language>

Target:
private String putBlob(Router router, BlobProperties blobProperties, byte[] usermetadata, byte[] content, RouterOperationCallback<String> putBlobCallback) throws Exception { ReadableStreamChannel blobDataChannel = new ByteBufferReadableStreamChannel(ByteBuffer.wrap(content)); Future<String> putBlobFuture; if (putBlobCallback == null) { putBlobFuture = router.putBlob(blobProperties, usermetadata, blobDataChannel); } else { putBlobFuture = router.putBlob(blobProperties, usermetadata, blobDataChannel, putBlobCallback); if (putBlobCallback.awaitCallback(1, TimeUnit.SECONDS)) { assertTrue("PutBlob: Future is not done but callback has been received", putBlobFuture.isDone()); if (putBlobCallback.getException() == null) { assertEquals("PutBlob: Future BlobId and callback BlobId do not match", putBlobFuture.get(), putBlobCallback.getResult()); } else { verifyFutureCallbackExceptionMatch(putBlobCallback, putBlobFuture); throw putBlobCallback.getException(); } } else { throw new IllegalStateException("putBlob() timed out"); } } return putBlobFuture.get(); }
Source:
<code>public Patient createFHIRPatient(Patient patient) { List<String> errors = new ArrayList<String>(); org.openmrs.Patient omrsPatient = FHIRPatientUtil.generateOmrsPatient(patient, errors); if (!errors.isEmpty()) { <START> StringBuilder errorMessage = new StringBuilder("The request cannot be processed due to the following issues \n"); <END> for (int i = 0; i < errors.size(); i++) { errorMessage.append((i + 1) + " : " + errors.get(i) + "\n"); } throw new UnprocessableEntityException(errorMessage.toString()); } org.openmrs.api.PatientService patientService = Context.getPatientService(); omrsPatient = patientService.savePatient(omrsPatient); return FHIRPatientUtil.generatePatient(omrsPatient); }</code><technical_language>This string messages.properties file</technical_language>

Target:
public Patient createFHIRPatient(Patient patient) { List<String> errors = new ArrayList<String>(); org.openmrs.Patient omrsPatient = FHIRPatientUtil.generateOmrsPatient(patient, errors); if (!errors.isEmpty()) { StringBuilder errorMessage = new StringBuilder("The request cannot be processed due to the following issues \n"); for (int i = 0; i < errors.size(); i++) { errorMessage.append((i + 1) + " : " + errors.get(i) + "\n"); } throw new UnprocessableEntityException(errorMessage.toString()); } org.openmrs.api.PatientService patientService = Context.getPatientService(); try { omrsPatient = patientService.savePatient(omrsPatient); } catch (Exception e) { StringBuilder errorMessage = new StringBuilder("The request cannot be processed due to the following issues \n"); errorMessage.append(e.getMessage()); throw new UnprocessableEntityException(errorMessage.toString()); } return FHIRPatientUtil.generatePatient(omrsPatient); }
Source:
<code>private static void enforceTaskCountLimit(int size) { if (size > Limits.maxWorkflowTasks()) { <START> throw new ConfigException("Too many for_range subtasks. Limit: " + Limits.maxWorkflowTasks()); <END> } }</code><technical_language>Showing size users understand wrong users actual number of tasks step</technical_language>

Target:
private static void enforceTaskCountLimit(int size) { if (size > Limits.maxWorkflowTasks()) { throw new ConfigException("Too many for_range subtasks (" + size + "). Limit: " + Limits.maxWorkflowTasks()); } }
Source:
<code>public void testAllCases() throws IOException { boolean crNewline = true; test("", new String[]{}, 5); test("1234\n", new String[]{"1234", "\n"}, 10); test("1234", new String[]{"1234", ""}, 10); test("123\r\n123\r\nabc\n", new String[]{"123", "\r\n", "123", "\r\n", "abc", "\n"}, 20); test("123\r123\r\nabc\n", new String[]{"123", "\r", "123", "\r\n", "abc", "\n"}, 20); test("1234\r", new String[]{"1234", "\r"}, 5); <START> test("1234\r\nabc\r\n", new String[]{"1234", "\r\n", "abc", "\r\n"}, 5); <END> test( "123456", new String[]{"123456", ""}, 5); test( "12345", new String[]{"12345", ""}, 5); test( "1234\rA", new String[]{"1234", "\r", "A", ""}, 5); }</code><technical_language>repeat this case sizes 4 6 (buffer carriage return, line feed)</technical_language>

Target:
public void testAllCases() throws IOException { for (int size = 1; size <= 20; ++size) { test("", new String[]{}, size); test("1234\n", new String[]{"1234", "\n"}, size); test("1234", new String[]{"1234", ""}, size); test("123\r\n123\r\nabc\n", new String[]{"123", "\r\n", "123", "\r\n", "abc", "\n"}, size); test("123\r123\r\nabc\n", new String[]{"123", "\r", "123", "\r\n", "abc", "\n"}, size); test("1234\r", new String[]{"1234", "\r"}, size); test("1234\r\nabc\r\n", new String[]{"1234", "\r\n", "abc", "\r\n"}, size); test( "123456", new String[]{"123456", ""}, size); test( "12345", new String[]{"12345", ""}, size); test( "1234\rA", new String[]{"1234", "\r", "A", ""}, size); } }
Source:
<code>public void stop() { log.info("Stopping task"); try { writer.closeQuietly(); } finally { try { <START> dialect.close(); <END> } finally { dialect = null; } } }</code><technical_language>org.apache.kafka.common.utils.Utils.closeQuietly</technical_language>

Target:
public void stop() { log.info("Stopping task"); try { writer.closeQuietly(); } finally { try { if (dialect != null) { dialect.close(); } } catch (Throwable t) { log.warn("Error while closing the dialect: ", dialect, t); } finally { dialect = null; } } }
Source:
<code>public void run() { SmppSession smppSession = smppClient.getSession(); if (smppSession != null && smppSession.isBound()) { try { smppSession.enquireLink(new EnquireLink(), enquireLinkTimeout); } catch (SmppTimeoutException | SmppChannelException | RecoverablePduException | UnrecoverablePduException error) { <START> Log.warning("Enquire link failed, executing reconnect: " + error); <END> smppClient.reconnect(); } catch (InterruptedException error) { Log.info("Enquire link interrupted, probably killed by reconnecting"); } } else { Log.error("Enquire link running while session is not connected"); } }</code><technical_language>Exception included a separate parameter</technical_language>

Target:
public void run() { SmppSession smppSession = smppClient.getSession(); if (smppSession != null && smppSession.isBound()) { try { smppSession.enquireLink(new EnquireLink(), enquireLinkTimeout); } catch (SmppTimeoutException | SmppChannelException | RecoverablePduException | UnrecoverablePduException error) { Log.warning("Enquire link failed, executing reconnect: ", error); smppClient.reconnect(); } catch (InterruptedException error) { Log.info("Enquire link interrupted, probably killed by reconnecting"); } } else { Log.warning("Enquire link running while session is not connected"); } }
Source:
<code>protected void postProcessing(boolean closeEarly) { if (sortGraph) { if (ghStorage.isCHPossible() && isCHPrepared()) throw new IllegalArgumentException("Sorting a prepared CHGraph is not possible yet. See #12"); GraphHopperStorage newGraph = GHUtility.newStorage(ghStorage); GHUtility.sortDFS(ghStorage, newGraph); logger.info("graph sorted (" + getMemInfo() + ")"); ghStorage = newGraph; } if (!hasInterpolated() && hasElevation()) { interpolateBridgesAndOrTunnels(); } initLocationIndex(); importPublicTransit(); if (lmPreparationHandler.isEnabled()) lmPreparationHandler.createPreparations(ghStorage, locationIndex); loadOrPrepareLM(closeEarly); if (chPreparationHandler.isEnabled()) chPreparationHandler.createPreparations(ghStorage); if (isCHPrepared()) { for (CHProfile profile : chPreparationHandler.getCHProfiles()) { <START> if (!getProfileHash(profile.getProfile()).isEmpty() <END> && !getProfileHash(profile.getProfile()).equals("" + profilesByName.get(profile.getProfile()).getVersion())) throw new IllegalArgumentException("CH preparation of " + profile.getProfile() + " already exists in storage and doesn't match configuration"); } } else { prepareCH(closeEarly); } }</code><technical_language>is isEmpty() treated special here? is for hash empty</technical_language>

Target:
protected void postProcessing(boolean closeEarly) { if (sortGraph) { if (ghStorage.isCHPossible() && isCHPrepared()) throw new IllegalArgumentException("Sorting a prepared CHGraph is not possible yet. See #12"); GraphHopperStorage newGraph = GHUtility.newStorage(ghStorage); GHUtility.sortDFS(ghStorage, newGraph); logger.info("graph sorted (" + getMemInfo() + ")"); ghStorage = newGraph; } if (!hasInterpolated() && hasElevation()) { interpolateBridgesAndOrTunnels(); } initLocationIndex(); importPublicTransit(); if (lmPreparationHandler.isEnabled()) lmPreparationHandler.createPreparations(ghStorage, locationIndex); loadOrPrepareLM(closeEarly); if (chPreparationHandler.isEnabled()) chPreparationHandler.createPreparations(ghStorage); if (isCHPrepared()) { for (CHProfile profile : chPreparationHandler.getCHProfiles()) { if (!getProfileVersion(profile.getProfile()).equals("" + profilesByName.get(profile.getProfile()).getVersion())) throw new IllegalArgumentException("CH preparation of " + profile.getProfile() + " already exists in storage and doesn't match configuration"); } } else { prepareCH(closeEarly); } }
Source:
<code>private Long getFirstValidPrivateId(List<InstanceGroup> instanceGroups) { LOGGER.debug("Get first valid PrivateId of instanceGroups"); <START> long highest = instanceGroups.stream() <END> .flatMap(ig -> ig.getAllInstanceMetaData().stream()) .filter(im -> im.getPrivateId() != null) .map(InstanceMetaData::getPrivateId) .max(Long::compare) .orElse(0L); LOGGER.debug("Highest privateId: {}", highest); return highest == 0 ? 0 : highest + 1; }</code><technical_language>this produce invalid output. if highest ID 0 return 0 valid id. this Optional<Long> return like: return highest.isPresent() ? highest.get() + 1 : 0; a test for this method break in future</technical_language>

Target:
private Long getFirstValidPrivateId(List<InstanceGroup> instanceGroups) { LOGGER.debug("Get first valid PrivateId of instanceGroups"); long id = instanceGroups.stream() .flatMap(ig -> ig.getAllInstanceMetaData().stream()) .filter(im -> im.getPrivateId() != null) .map(InstanceMetaData::getPrivateId) .map(i -> i + 1) .max(Long::compare) .orElse(0L); LOGGER.debug("First valid privateId: {}", id); return id; }
Source:
<code>public Node(String name, Id id) throws NodeException { Objects.requireNonNull(name); Objects.requireNonNull(id); <START> this.mName = name; <END> this.mId = id; }</code><technical_language>better, this.mName = Objects.requireNonNull(name);. check else</technical_language>

Target:
public Node(String name, Id id) throws NodeException { this.mName = Objects.requireNonNull(name); this.mId = Objects.requireNonNull(id); }
Source:
<code>public boolean Validate() { boolean isNew = getModel().getIsNew(); <START> int maxAllowedVms = configurator.getMaxVmsInPool(); <END> int assignedVms = getModel().getAssignedVms().AsConvertible().Integer(); getModel().getNumOfDesktops().ValidateEntity( new IValidation[] { new NotEmptyValidation(), new LengthValidation(4), new IntegerValidation(isNew ? 1 : 0, isNew ? maxAllowedVms : maxAllowedVms - assignedVms) }); getModel().getPrestartedVms().ValidateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(0, assignedVms) }); getModel().setIsGeneralTabValid(getModel().getIsGeneralTabValid() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid()); getModel().setIsPoolTabValid(true); return super.Validate() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid(); }</code><technical_language>Do configurator for fetching 'MaxVmsInPool' value? A lot of configuration values fetched in 'VmModelBehaviorBase' (e.g. GetMaxNumOfVmSockets) - try retrieve 'PoolModelBehaviorBase' if cumbersome</technical_language>

Target:
public boolean Validate() { boolean isNew = getModel().getIsNew(); int maxAllowedVms = getMaxVmsInPool(); int assignedVms = getModel().getAssignedVms().AsConvertible().Integer(); getModel().getNumOfDesktops().ValidateEntity( new IValidation[] { new NotEmptyValidation(), new LengthValidation(4), new IntegerValidation(isNew ? 1 : 0, isNew ? maxAllowedVms : maxAllowedVms - assignedVms) }); getModel().getPrestartedVms().ValidateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(0, assignedVms) }); getModel().setIsGeneralTabValid(getModel().getIsGeneralTabValid() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid()); getModel().setIsPoolTabValid(true); return super.Validate() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid(); }
Source:
<code>synchronized void flush() { if (_kafkaProducer != null) { try { <START> CompletableFutureUtils.within(CompletableFuture.runAsync(() -> _kafkaProducer.flush()), <END> Duration.ofMillis(_flushTimeout)).join(); } catch (CompletionException e) { Throwable cause = e.getCause(); if (cause instanceof InterruptException) { _log.warn("Kafka producer flush interrupted, closing producer {}.", _kafkaProducer); shutdownProducer(); throw (InterruptException) cause; } else if (cause instanceof java.util.concurrent.TimeoutException) { _log.warn("Kafka producer flush timed out after {}ms. Destination topic may be unavailable.", _flushTimeout); } throw e; } } }</code><technical_language>CompletableFuture.runAsync() common pool option for a potentially long blocking call Producer.flush(). if provide thread pool runAsync(), CompletableFuture get give a interrupt a Producer.flush() call exceeds allowed timeout, is necessary free thread-pool thread in question. This is calling cancel(true) a CompletableFuture returned runAsync() a cancellation exception propagated interrupting blocked thread pool. afraid option ExecutorService java // a single thread executor flush() is synchronized ExecutorService executor = Executors.newSingleThreadExecutor(); Future<?> future = executor.submit(() -> super.flush()); try { // Block timeout elapses future.get(_flushTimeout, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { ... // Interrupt Producer.flush() call free blocked thread future.cancel(true); ... }</technical_language>

Target:
synchronized void flush() { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<?> future = executor.submit(super::flush); try { future.get(_flushTimeoutMs, TimeUnit.MILLISECONDS); } catch (TimeoutException ex) { _log.warn("Flush call timed out after {}ms. Cancelling flush", _flushTimeoutMs); future.cancel(true); } catch (ExecutionException ex) { Throwable cause = ex.getCause(); if (cause instanceof InterruptException) { throw (InterruptException) cause; } else { _log.warn("Flush failed.", cause); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); } }
Source:
<code>public void testPropertyNameOnMethodName() throws NoSuchMethodException { class Hotel { String hotelName; public String getHotelName() { return hotelName; } } <START> Method m = Hotel.class.getDeclaredMethod("getHotelName"); assertMemberValue(m, "getHotelName"); <END> }</code><technical_language>GSON maintain full method names drop Java bean notation? I in Jackson's case this serialize hotelName (possibly HotelName completely handles casing)</technical_language>

Target:
public void testPropertyNameOnMethodName() throws NoSuchMethodException { class LocalHotel { String hotelName; public String getHotelName() { return hotelName; } } Method m = LocalHotel.class.getDeclaredMethod("getHotelName"); assertNull(serializer.convertMemberName(m)); }
Source:
<code>void oneParameterAndStatementUtilityConstructor() { LambdaExpr expr = new LambdaExpr(new Parameter(new UnknownType(), "a"), parseStatement("return 5;")); <START> assertEquals("a -> return 5;", expr.toString()); <END> }</code><technical_language>I this is valid Java code..</technical_language>

Target:
void oneParameterAndStatementUtilityConstructor() { LambdaExpr expr = new LambdaExpr(new Parameter(new UnknownType(), "a"), parseBlock("{return 5;}")); assertEqualsNoEol("a -> {\n return 5;\n}", expr.toString()); }
Source:
<code>public void useDefaultKeyPair() throws KeyStoreException { String alias = Config.<String>GetValue(ConfigValues.CertAlias); String p12 = Config.<String>GetValue(ConfigValues.keystoreUrl); <START> char[] password = Config.<String>GetValue(ConfigValues.keystorePass).toCharArray(); <END> KeyStore.PrivateKeyEntry entry; InputStream in = null; try { in = new FileInputStream(p12); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(in, password); entry = (KeyStore.PrivateKeyEntry)ks.getEntry( alias, new KeyStore.PasswordProtection(password) ); } catch (Exception e) { throw new KeyStoreException( String.format( "Failed to get certificate entry from key store: %1$s/%2$s", p12, alias ), e ); } finally { Arrays.fill(password, '*'); if (in != null) { try { in.close(); } catch(IOException e) { log.error("Cannot close key store", e); } } } if (entry == null) { throw new KeyStoreException( String.format( "Bad key store: %1$s/%2$s", p12, alias ) ); } setKeyPair( new KeyPair( entry.getCertificate().getPublicKey(), entry.getPrivateKey() ) ); }</code><technical_language>^ final</technical_language>

Target:
public void useDefaultKeyPair() throws KeyStoreException { final String alias = Config.<String>GetValue(ConfigValues.CertAlias); final String p12 = Config.<String>GetValue(ConfigValues.keystoreUrl); final char[] password = Config.<String>GetValue(ConfigValues.keystorePass).toCharArray(); KeyStore.PrivateKeyEntry entry; InputStream in = null; try { in = new FileInputStream(p12); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(in, password); entry = (KeyStore.PrivateKeyEntry)ks.getEntry( alias, new KeyStore.PasswordProtection(password) ); } catch (Exception e) { throw new KeyStoreException( String.format( "Failed to get certificate entry from key store: %1$s/%2$s", p12, alias ), e ); } finally { Arrays.fill(password, '*'); if (in != null) { try { in.close(); } catch(IOException e) { log.error("Cannot close key store", e); } } } if (entry == null) { throw new KeyStoreException( String.format( "Bad key store: %1$s/%2$s", p12, alias ) ); } setKeyPair( new KeyPair( entry.getCertificate().getPublicKey(), entry.getPrivateKey() ) ); }
Source:
<code>public static void main(String[] args) throws Exception { Optional.ofNullable(System.getProperty("logback.configurationFile")) .stream() <START> .forEach(file -> System.err.println("Load logging config from " + file)); <END> Configuration configuration = Configuration.builder() .useWorkingDirectoryEnvProperty() .build(); LOGGER.info("Loading configuration {}", configuration); GuiceJamesServer server = createServer(configuration) .combineWith(new JMXServerModule()); JamesServerMain.main(server); }</code><technical_language>rely System.out I printing error expected behavior</technical_language>

Target:
public static void main(String[] args) throws Exception { Configuration configuration = Configuration.builder() .useWorkingDirectoryEnvProperty() .build(); LOGGER.info("Loading configuration {}", configuration.toString()); GuiceJamesServer server = createServer(configuration) .combineWith(new JMXServerModule()); JamesServerMain.main(server); }
Source:
<code>public String createNewProcess() { try { createProcessHierarchy(); <START> if (Objects.nonNull(PrimeFaces.current())) { <END> PrimeFaces.current().executeScript("PF('sticky-notifications').renderMessage({'summary':'" + Helper.getTranslation("processSaving") + "','detail':'" + Helper.getTranslation( "youWillBeRedirected") + "','severity':'info'});"); } return processListPath; } catch (DataException e) { Helper.setErrorMessage("errorSaving", new Object[] {ObjectType.PROCESS.getTranslationSingular() }, logger, e); } catch (IOException | ProcessGenerationException e) { logger.error(e.getLocalizedMessage()); } return this.stayOnCurrentPage; }</code><technical_language>suggestion if (Objects.nonNull(PrimeFaces.current()) && Objects.nonNull(FacesContext.getCurrentInstance()) {</technical_language>

Target:
public String createNewProcess() { try { createProcessHierarchy(); if (Objects.nonNull(PrimeFaces.current()) && Objects.nonNull(FacesContext.getCurrentInstance())) { PrimeFaces.current().executeScript("PF('sticky-notifications').renderMessage({'summary':'" + Helper.getTranslation("processSaving") + "','detail':'" + Helper.getTranslation( "youWillBeRedirected") + "','severity':'info'});"); } return processListPath; } catch (DataException e) { Helper.setErrorMessage("errorSaving", new Object[] {ObjectType.PROCESS.getTranslationSingular() }, logger, e); } catch (IOException | ProcessGenerationException e) { logger.error(e.getLocalizedMessage()); } return this.stayOnCurrentPage; }
Source:
<code>private static void appendLib(StringBuilder classpath, String libDirName, boolean useLibJarsFormat) { File libDir = new File(libDirName); if (!libDir.exists()) { System.err.println("ERROR - Directory needed for classpath does not exist: " + libDirName); System.exit(-1); } if (useLibJarsFormat) { File[] files = libDir.listFiles(); Arrays.sort(files); for (File f : files) { if (f.isFile() && f.getName().endsWith(".jar")) { if (classpath.length() != 0) { classpath.append(","); } classpath.append(f.getAbsolutePath()); } } } else { if (classpath.length() != 0) { classpath.append(":"); } <START> classpath.append(libDir + "/*"); <END> } }</code><technical_language>this libDir.getAbsolutePath() f..getAbsolutePath() above</technical_language>

Target:
private static void appendLib(StringBuilder classpath, String libDirName, boolean useLibJarsFormat) { File libDir = new File(libDirName); if (!libDir.exists()) { System.err.println("ERROR - Directory needed for classpath does not exist: " + libDirName); System.exit(-1); } if (useLibJarsFormat) { File[] files = libDir.listFiles(); Arrays.sort(files); for (File f : files) { if (f.isFile() && f.getName().endsWith(".jar")) { if (classpath.length() != 0) { classpath.append(","); } classpath.append(f.getAbsolutePath()); } } } else { if (classpath.length() != 0) { classpath.append(":"); } classpath.append(libDir.getAbsolutePath() + "/*"); } }
Source:
<code>public boolean close() { synchronized (startStopLock) { if (!started.get() || executorService.isShutdown()) { LOG.info("Already shutdown, ignoring"); <START> return false; <END> } started.set(false); executorService.shutdownNow(); final ListenableFuture<?> future = this.future; if (future != null) { if (!future.isDone() && !future.cancel(true) && !future.isDone()) { LOG.error("Error cancelling future for topic [%s]", getKafkaTopic()); return false; } } if (!cacheManager.delete(factoryId)) { LOG.error("Error removing [%s] for topic [%s] from cache", factoryId, getKafkaTopic()); return false; } if (consumerConnector != null) { consumerConnector.shutdown(); } return true; } }</code><technical_language>calling stop multiple times return true thought</technical_language>

Target:
public boolean close() { synchronized (started) { if (!started.get() || executorService.isShutdown()) { LOG.info("Already shutdown, ignoring"); return !started.get(); } started.set(false); executorService.shutdownNow(); final ListenableFuture<?> future = this.future; if (future != null) { if (!future.isDone() && !future.cancel(true) && !future.isDone()) { LOG.error("Error cancelling future for topic [%s]", getKafkaTopic()); return false; } } if (!cacheManager.delete(factoryId)) { LOG.error("Error removing [%s] for topic [%s] from cache", factoryId, getKafkaTopic()); return false; } return true; } }
Source:
<code>public Metadata(Map<String, String[]> metadata) { <START> md = metadata; <END> }</code><technical_language>I check for null a copy of map</technical_language>

Target:
public Metadata(Map<String, String[]> metadata) { if (metadata == null) throw new NullPointerException(); md = metadata; }
Source:
<code>private void evaluateXPath() { Document document = getWebSourceCode().getDocument(expression.contains(":")); try { NodeList nodes = (NodeList) getXPathExpressionForDocument(document).evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { int lineNumber = getWebSourceCode().getLineForNode(nodes.item(i)); createViolation(lineNumber); } <START> } catch (XPathExpressionException exceptionNodeSet) { <END> try { Boolean result = (Boolean) getXPathExpressionForDocument(document).evaluate(document, XPathConstants.BOOLEAN); if (result) { createViolation(0); } } catch (XPathExpressionException exceptionBoolean) { throw new IllegalStateException(String.format("Can't evaluate expression \"%s\"", expression), exceptionBoolean); } } }</code><technical_language>![CRITICAL](<LINK_1> log rethrow this exception. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private void evaluateXPath() { Document document = getWebSourceCode().getDocument(expression.contains(":")); XPathExpression xPathExpression = getXPathExpressionForDocument(document); try { evaluateXPathForNodeSet(document, xPathExpression); } catch (XPathExpressionException exceptionNodeSet) { evaluateXPathForBoolean(document, xPathExpression); } }
Source:
<code>protected PageableResult doGetAll(RequestContext context) throws ResponseException { <START> return new AlreadyPaged<AutoGenerationOption>(Context.getService(IdentifierSourceService.class).getAutoGenerationOption(3), context); <END> }</code><technical_language>3 parameter mean</technical_language>

Target:
protected PageableResult doGetAll(RequestContext context) throws ResponseException { IdentifierSourceService identifierSourceService = Context.getService(IdentifierSourceService.class); List<AutoGenerationOption> optionMap = new ArrayList<AutoGenerationOption>(); List<PatientIdentifierType> identifierTypes = new ArrayList<PatientIdentifierType>(); Map<PatientIdentifierType, List<IdentifierSource>> availableSources = identifierSourceService.getIdentifierSourcesByType(false); for (PatientIdentifierType patientIdentifierType : Context.getPatientService().getAllPatientIdentifierTypes()) { List<AutoGenerationOption> options = identifierSourceService.getAutoGenerationOptions(patientIdentifierType); if (options != null && options.size() > 0) { optionMap.addAll(options); } if (availableSources.get(patientIdentifierType) != null && availableSources.get(patientIdentifierType).size() > 0) { identifierTypes.add(patientIdentifierType); } } return new NeedsPaging<AutoGenerationOption>(optionMap, context); }
Source:
<code>protected BinaryLogicalFilterPredicate(FilterPredicate left, FilterPredicate right) { Preconditions.checkNotNull(left, "left"); Preconditions.checkNotNull(right, "right"); this.left = left; <START> this.right = right; <END> String name = getClass().getSimpleName().toLowerCase(); this.toString = name + "(" + left + ", " + right + ")"; }</code><technical_language>here: this.left = checkNotNull(left, "left");</technical_language>

Target:
protected BinaryLogicalFilterPredicate(FilterPredicate left, FilterPredicate right) { this.left = checkNotNull(left, "left"); this.right = checkNotNull(right, "right"); String name = getClass().getSimpleName().toLowerCase(); this.toString = name + "(" + left + ", " + right + ")"; }
Source:
<code>public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) { enforceConnectivityInternalPermission(); enforceCrossUserPermission(userId); if <START> (LockdownVpnTracker.isEnabled()) <END> { return false; } synchronized (mVpns) { Vpn vpn = mVpns.get(userId); if (vpn == null) { Slog.w(TAG, "User " + userId + " has no Vpn configuration"); return false; } if (!vpn.setAlwaysOnPackage(packageName, lockdown)) { return false; } if (!startAlwaysOnVpn(userId)) { vpn.setAlwaysOnPackage(null, false); return false; } } return true; }</code><technical_language>this synchronized{} block ? Also, this simplified if (!mLockdownEnabled)</technical_language>

Target:
public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) { enforceConnectivityInternalPermission(); enforceCrossUserPermission(userId); synchronized (mVpns) { if (LockdownVpnTracker.isEnabled()) { return false; } Vpn vpn = mVpns.get(userId); if (vpn == null) { Slog.w(TAG, "User " + userId + " has no Vpn configuration"); return false; } if (!vpn.setAlwaysOnPackage(packageName, lockdown)) { return false; } if (!startAlwaysOnVpn(userId)) { vpn.setAlwaysOnPackage(null, false); return false; } } return true; }
Source:
<code>private FilterExpression parseQualifierContent(QualifierType type) { if (type == QualifierType.SORT) { return parseSortKeys(); <START> } else if (isCompoundId(type, lookAhead())) { <END> return parseCompoundId(); } else if (isRangeOperatorToken(lookAhead())) { return parseRangeOperator(type, lookAhead()); } else if (isDateToken(lookAhead())) { return parseDateOrDateRange(type); } else if (isNumberToken(lookAhead())) { return parseNumberOrNumberRange(type); } else if (isQuotedContentToken(lookAhead())) { Token quotedContent = consume(); return parseQuotedContent(type, quotedContent); } else if (isKeywordToken(lookAhead())) { return new Qualifier(type, consume().getValue()); } else { throw new ParseException(String.format("Invalid content for qualifier %s: %s", type, lookAhead())); } }</code><technical_language>Checking for failure leads a non-id qualifier a compound id a parse error. follow other parse* functions fail later, a semantic error? If for some reason want compound ids other qualifiers, easier</technical_language>

Target:
private FilterExpression parseQualifierContent(QualifierType type) { if (type == QualifierType.SORT) { return parseSortKeys(); } else if (isCompoundIdToken(type, lookAhead())) { return parseCompoundId(); } else if (isRangeOperatorToken(lookAhead())) { return parseRangeOperator(type, lookAhead()); } else if (isDateToken(lookAhead())) { return parseDateOrDateRange(type); } else if (isNumberToken(lookAhead())) { return parseNumberOrNumberRange(type); } else if (isQuotedContentToken(lookAhead())) { Token quotedContent = consume(); return parseQuotedContent(type, quotedContent); } else if (isKeywordToken(lookAhead())) { return new Qualifier(type, consume().getValue()); } else { throw new ParseException(String.format("Invalid content for qualifier %s: %s", type, lookAhead())); } }
Source:
<code>protected Optional<DominantHandProperty> getForEntity(Entity entity) { <START> if(!(entity instanceof EntityPlayer)) return Optional.empty(); <END> EnumHandSide hand = ((EntityPlayer) entity).getPrimaryHand(); HandType type = (HandType) (Object) hand; return Optional.of(new DominantHandProperty(type)); }</code><technical_language>if (, if statements require braces</technical_language>

Target:
protected Optional<DominantHandProperty> getForEntity(Entity entity) { if(!(entity instanceof EntityPlayer)) return Optional.empty(); EnumHandSide hand = ((EntityPlayer) entity).getPrimaryHand(); HandSide type = (HandSide) (Object) hand; return Optional.of(new DominantHandProperty(type)); }
Source:
<code>private boolean isUnregisteredDisk() { DiskImage unregisteredDisk; storagePoolId = BackendDataCenterHelper.lookupByStorageDomainId(this, storageDomainId); try { GetUnregisteredDiskQueryParameters getDiskParams = new GetUnregisteredDiskQueryParameters(guid, storageDomainId, storagePoolId); unregisteredDisk = <START> getEntity(DiskImage.class, <END> QueryType.GetUnregisteredDisk, getDiskParams, guid.toString()); } catch (WebApplicationException e) { if (e.getResponse().getStatus() == Response.Status.NOT_FOUND.getStatusCode()) { return false; } throw e; } return unregisteredDisk != null; }</code><technical_language>BTW: if "getEntity()" returns result throws a WebApplicationException exception "NOT_FOUND" status, code simplified "return true" end need in "unregisteredDisk" local variable all</technical_language>

Target:
private boolean isUnregisteredDisk() { DiskImage unregisteredDisk; Guid storagePoolId = BackendDataCenterHelper.lookupByStorageDomainId(this, storageDomainId); try { GetUnregisteredDiskQueryParameters getDiskParams = new GetUnregisteredDiskQueryParameters(guid, storageDomainId, storagePoolId); unregisteredDisk = getEntity(DiskImage.class, QueryType.GetUnregisteredDisk, getDiskParams, guid.toString()); } catch (WebApplicationException e) { if (e.getResponse().getStatus() == Response.Status.NOT_FOUND.getStatusCode()) { return false; } throw e; } return unregisteredDisk != null; }
Source:
<code>public long getFileSize(String ext) { Long size = sizeMap.get(ext); <START> return (size == null) ? 0 : size.longValue(); <END> }</code><technical_language>parens condition</technical_language>

Target:
public long getFileSize(String ext) { Long size = sizeMap.get(ext); return size == null ? 0 : size.longValue(); }
Source:
<code>public boolean tryAdvance(Consumer<? super BytesHandle> action) { try { FormatEntry nextEntry = getNextEntry(); if (nextEntry == null) { return false; } BytesHandle nextBytesHandle = readEntry(nextEntry); action.accept(nextBytesHandle); splitter.count++; } catch (IOException e) { <START> e.printStackTrace(); <END> } return true; }</code><technical_language>IDEs tend generate boilerplate code suppresses exceptions. is safe suppress exception, practice is throw exception. In this case, if encounter IOException, wrong zipfile. exception is a checked exception (like IOException) allowed signature (as tryAdvance() method), rethrow throw new RuntimeException("Could read ZipEntry", e); clear, issue affects other tryAdvance() method</technical_language>

Target:
public boolean tryAdvance(Consumer<? super BytesHandle> action) { try { FormatEntry nextEntry = getNextEntry(); if (nextEntry == null) { return false; } BytesHandle nextBytesHandle = readEntry(nextEntry); action.accept(nextBytesHandle); splitter.count++; } catch (IOException e) { throw new RuntimeException("Could not read ZipEntry", e); } return true; }
Source:
<code>public static ViewGroup.OnHierarchyChangeListener tryGetOnHierarchyChangeListenerHack( ViewGroup viewGroup) { if (sOnHierarchyChangeListenerField == null) { return null; } try { <START> return (ViewGroup.OnHierarchyChangeListener)sOnHierarchyChangeListenerField.get(viewGroup); <END> } catch (IllegalAccessException e) { throw new RuntimeException(e); } }</code><technical_language>This too, possibly</technical_language>

Target:
public static ViewGroup.OnHierarchyChangeListener tryGetOnHierarchyChangeListenerHack( ViewGroup viewGroup) { if (sOnHierarchyChangeListenerField == null) { return null; } return (ViewGroup.OnHierarchyChangeListener)ReflectionUtil.getFieldValue( sOnHierarchyChangeListenerField, viewGroup); }
Source:
<code>private HullConfig read(String shipName) { final HullConfig.Data configData = new HullConfig.Data(); configData.internalName = shipName; Json json = Assets.getJson(shipName); try { readProperties(json.getJsonValue(), configData); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("The JSON of ship " + shipName + " is missing, or has malformed, a required parameter" + e.getMessage().split(":")[1]); } catch (SerializationException e) { <START> throw new SerializationException("The JSON of ship " + shipName + " has invalid syntax" + e.getMessage().split(":")[1]); <END> } configData.tex = Assets.getAtlasRegion(shipName); configData.icon = Assets.getAtlasRegion(shipName + "Icon"); validateEngineConfig(configData); json.dispose(); return new HullConfig(configData); }</code><technical_language>a error message splitting is :wink: (hint: entire JSON file)</technical_language>

Target:
private HullConfig read(String shipName) { final HullConfig.Data configData = new HullConfig.Data(); configData.internalName = shipName; Json json = Assets.getJson(shipName); try { readProperties(json.getJsonValue(), configData); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("The JSON of ship " + shipName + " is missing, or has malformed, a required parameter" + e.getMessage().split(":")[1]); } catch (SerializationException e) { throw new SerializationException("The JSON of ship " + shipName + " has invalid syntax at " + e.getMessage().split(" near")[0].split("on ")[1]); } configData.tex = Assets.getAtlasRegion(shipName); configData.icon = Assets.getAtlasRegion(shipName + "Icon"); validateEngineConfig(configData); json.dispose(); return new HullConfig(configData); }
Source:
<code>public ImmutableValue<Entity> leashHolder() { <START> return new ImmutableSpongeEntityValue<>(Keys.LEASH_HOLDER, getValue()); <END> }</code><technical_language>This stored in a field</technical_language>

Target:
public ImmutableValue<Entity> leashHolder() { return this.value; }