auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void keepAliveTest() { HttpMethod[] HTTP_METHODS = {HttpMethod.POST, HttpMethod.GET, HttpMethod.HEAD, HttpMethod.DELETE}; EmbeddedChannel channel = createEmbeddedChannel(); for (HttpMethod httpMethod : HTTP_METHODS) { for (Map.Entry<RestServiceErrorCode, HttpResponseStatus> entry : REST_SERVICE_ERROR_CODE_TO_HTTP_RESPONSE_STATUS_MAP .entrySet()) { HttpHeaders httpHeaders = new DefaultHttpHeaders(); httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, entry.getKey()); channel.writeInbound(RestTestUtils .createRequest(httpMethod, TestingUri.OnResponseCompleteWithRestException.toString(), httpHeaders)); HttpResponse response = (HttpResponse) channel.readOutbound(); assertEquals("Unexpected response status", entry.getValue(), response.getStatus()); if (!(response instanceof FullHttpResponse)) { while (channel.readOutbound() != null) { <START> ; <END> } } boolean shouldBeAlive = !httpMethod.equals(HttpMethod.POST) && !NettyResponseChannel.CLOSE_CONNECTION_ERROR_STATUSES .contains(entry.getValue()); assertEquals("Channel state (open/close) not as expected", shouldBeAlive, channel.isActive()); assertEquals("Connection header should be consistent with channel state", shouldBeAlive, HttpHeaders.isKeepAlive(response)); if (!shouldBeAlive) { channel = createEmbeddedChannel(); } } } channel.close(); }</code><technical_language>need ;</technical_language>

Target:
public void keepAliveTest() { HttpMethod[] HTTP_METHODS = {HttpMethod.POST, HttpMethod.GET, HttpMethod.HEAD, HttpMethod.DELETE}; EmbeddedChannel channel = createEmbeddedChannel(); for (HttpMethod httpMethod : HTTP_METHODS) { for (Map.Entry<RestServiceErrorCode, HttpResponseStatus> entry : REST_ERROR_CODE_TO_HTTP_STATUS.entrySet()) { HttpHeaders httpHeaders = new DefaultHttpHeaders(); httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, entry.getKey()); channel.writeInbound(RestTestUtils .createRequest(httpMethod, TestingUri.OnResponseCompleteWithRestException.toString(), httpHeaders)); HttpResponse response = (HttpResponse) channel.readOutbound(); assertEquals("Unexpected response status", entry.getValue(), response.getStatus()); if (!(response instanceof FullHttpResponse)) { while (channel.readOutbound() != null) { ; } } boolean shouldBeAlive = !httpMethod.equals(HttpMethod.POST) && !NettyResponseChannel.CLOSE_CONNECTION_ERROR_STATUSES .contains(entry.getValue()); assertEquals("Channel state (open/close) not as expected", shouldBeAlive, channel.isActive()); assertEquals("Connection header should be consistent with channel state", shouldBeAlive, HttpHeaders.isKeepAlive(response)); if (!shouldBeAlive) { channel = createEmbeddedChannel(); } } } channel.close(); }
Source:
<code>private Mono<HttpRequest> validateLength(final HttpRequest request) { Flux<ByteBuffer> body = request.body(); if (body == null) { return Mono.just(request); } <START> Long expectedLength = Long.valueOf(request.headers().value("Content-Length")); <END> return FluxUtil.collectBytesInByteBufferStream(body).doOnNext(bb -> { if (bb.length > expectedLength) { throw new UnexpectedLengthException( String.format("Request body emitted more bytes than the expected %d bytes.", expectedLength), bb.length, expectedLength); } else if (bb.length != expectedLength) { throw new UnexpectedLengthException( String.format("Request body emitted less bytes than the expected %d bytes.", expectedLength), bb.length, expectedLength); } }).then(Mono.just(request)); }</code><technical_language>check continue run is Content-Length header is null? this is specific Storage, I of another SDK need this validation, is other places this check go? Potentially a pipeline policy a check in Storage Common</technical_language>

Target:
private Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.body(); if (bbFlux == null) { return Flux.empty(); } return Flux.defer(() -> { Long expectedLength = Long.valueOf(request.headers().value("Content-Length")); final long[] currentTotalLength = new long[1]; return bbFlux.doOnEach(s -> { if (s.isOnNext()) { ByteBuffer byteBuffer = s.get(); int currentLength = (byteBuffer == null) ? 0 : byteBuffer.remaining(); currentTotalLength[0] += currentLength; if (currentTotalLength[0] > expectedLength) { throw logger.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes more than the expected %d bytes.", currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } } else if (s.isOnComplete()) { if (expectedLength.compareTo(currentTotalLength[0]) != 0) { throw logger.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes less than the expected %d bytes.", currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } } }); }); }
Source:
<code>public static boolean isSystemDarkTheme () { boolean isDarkTheme = false; if (OS.WIN32_VERSION >= OS.VERSION (10, 0)) { <START> TCHAR key = new TCHAR (0, "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", true); TCHAR lpValueName = new TCHAR(0, "AppsUseLightTheme", true); END> try { int result = OS.readRegistryDword(OS.HKEY_CURRENT_USER, key, lpValueName); isDarkTheme = (result == 0); } catch (Exception e) { } } return isDarkTheme; }</code><technical_language>move this function, accepts String parameters</technical_language>

Target:
public static boolean isSystemDarkTheme () { boolean isDarkTheme = false; if (OS.WIN32_VERSION >= OS.VERSION (10, 0)) { try { int result = OS.readRegistryDword(OS.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", "AppsUseLightTheme"); isDarkTheme = (result == 0); } catch (Exception e) { } } return isDarkTheme; }
Source:
<code>public void checkAttributeSyntax(PerunSessionImpl perunSession, String key, Attribute attribute) throws InternalErrorException, WrongAttributeValueException { Integer minUID = attribute.valueAsInteger(); <START> if(minUID != null && minUID<1) throw new WrongAttributeValueException(attribute, "Attribute value must be min 1."); <END> }</code><technical_language>Similar change for maxUID</technical_language>

Target:
public void checkAttributeSyntax(PerunSessionImpl perunSession, String key, Attribute attribute) throws InternalErrorException, WrongAttributeValueException { Integer minUID = attribute.valueAsInteger(); if(minUID != null && minUID<1) throw new WrongAttributeValueException(attribute, "Attribute value must be bigger than 0."); }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BrowserInformation)) { return false; } BrowserInformation other = (BrowserInformation) o; <START> if (!this.getBrowserName().equals(other.getBrowserName())) { <END> return false; } return true; }</code><technical_language>@mach6 Fixed it</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BrowserInformation)) { return false; } return this.getBrowserName().equals(((BrowserInformation) o).getBrowserName()); }
Source:
<code>public void testStopTasklet() throws Exception { JobInstance jobInstance = new JobInstance(123L, job.getName()); JobExecution jobExecution = new JobExecution(jobInstance, 111L, jobParameters); <START> MockStoppableTasklet tasklet = new MockStoppableTasklet(); <END> TaskletStep taskletStep = new TaskletStep(); taskletStep.setTasklet(tasklet); MockJob job = new MockJob(); job.taskletStep = taskletStep; JobRegistry jobRegistry = mock(JobRegistry.class); TaskletStep step = mock(TaskletStep.class); when(step.getTasklet()).thenReturn(tasklet); when(step.getName()).thenReturn("test_job.step1"); when(jobRegistry.getJob(anyString())).thenReturn(job); when(jobExplorer.getJobExecution(111L)).thenReturn(jobExecution); jobOperator.setJobRegistry(jobRegistry); jobExplorer.getJobExecution(111L); jobRepository.update(jobExecution); jobOperator.stop(111L); assertEquals(BatchStatus.STOPPING, jobExecution.getStatus()); assertTrue(tasklet.stopped); }</code><technical_language>reasoning hard coded stub instead of Mockito</technical_language>

Target:
public void testStopTasklet() throws Exception { JobInstance jobInstance = new JobInstance(123L, job.getName()); JobExecution jobExecution = new JobExecution(jobInstance, 111L, jobParameters); StoppableTasklet tasklet = mock(StoppableTasklet.class); TaskletStep taskletStep = new TaskletStep(); taskletStep.setTasklet(tasklet); MockJob job = new MockJob(); job.taskletStep = taskletStep; JobRegistry jobRegistry = mock(JobRegistry.class); TaskletStep step = mock(TaskletStep.class); when(step.getTasklet()).thenReturn(tasklet); when(step.getName()).thenReturn("test_job.step1"); when(jobRegistry.getJob(anyString())).thenReturn(job); when(jobExplorer.getJobExecution(111L)).thenReturn(jobExecution); jobOperator.setJobRegistry(jobRegistry); jobExplorer.getJobExecution(111L); jobRepository.update(jobExecution); jobOperator.stop(111L); assertEquals(BatchStatus.STOPPING, jobExecution.getStatus()); }
Source:
<code>public void execute(Context context) throws SQLException { IntegerColumnDef userLoginColumn = IntegerColumnDef.newIntegerColumnDefBuilder() .setColumnName("user_id") .setIsNullable(false) .build(); VarcharColumnDef qProfileUuidColumn = VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("qprofile_uuid") .setIsNullable(false) <START> .setLimit(255) <END> .build(); context.execute(new CreateTableBuilder(getDialect(), TABLE_NAME) .addPkColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("uuid") .setIsNullable(false) .setLimit(40) .build()) .addColumn(userLoginColumn) .addColumn(qProfileUuidColumn) .addColumn(newBigIntegerColumnDefBuilder() .setColumnName("created_at") .setIsNullable(false) .build()) .build() ); context.execute( new CreateIndexBuilder(getDialect()) .setTable(TABLE_NAME) .setName(TABLE_NAME + "_user") .addColumn(userLoginColumn) .setUnique(false) .build()); context.execute( new CreateIndexBuilder(getDialect()) .setTable(TABLE_NAME) .setName(TABLE_NAME + "_qprofile") .addColumn(qProfileUuidColumn) .setUnique(false) .build()); }</code><technical_language>255 for a uuid column</technical_language>

Target:
public void execute(Context context) throws SQLException { IntegerColumnDef userLoginColumn = IntegerColumnDef.newIntegerColumnDefBuilder() .setColumnName("user_id") .setIsNullable(false) .build(); VarcharColumnDef qProfileUuidColumn = VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("qprofile_uuid") .setIsNullable(false) .setLimit(255) .build(); context.execute(new CreateTableBuilder(getDialect(), TABLE_NAME) .addPkColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("uuid") .setIsNullable(false) .setLimit(40) .build()) .addColumn(userLoginColumn) .addColumn(qProfileUuidColumn) .addColumn(newBigIntegerColumnDefBuilder() .setColumnName("created_at") .setIsNullable(false) .build()) .build() ); context.execute( new CreateIndexBuilder(getDialect()) .setTable(TABLE_NAME) .setName(TABLE_NAME + "_qprofile") .addColumn(qProfileUuidColumn) .setUnique(false) .build()); context.execute( new CreateIndexBuilder(getDialect()) .setTable(TABLE_NAME) .setName(TABLE_NAME + "_unique") .addColumn(userLoginColumn) .addColumn(qProfileUuidColumn) .setUnique(true) .build()); }
Source:
<code>public SparkZeppelinContext( SparkContext sc, SQLContext sql, InterpreterHookRegistry hooks, int maxResult) { super(hooks, maxResult); this.sc = sc; this.sqlContext = sql; interpreterClassMap = new HashMap<String, String>(); interpreterClassMap.put("spark", "org.apache.zeppelin.spark.SparkInterpreter"); interpreterClassMap.put("sql", "org.apache.zeppelin.spark.SparkSqlInterpreter"); interpreterClassMap.put("dep", "org.apache.zeppelin.spark.DepInterpreter"); interpreterClassMap.put("pyspark", "org.apache.zeppelin.spark.PySparkInterpreter"); this.supportedClasses = new ArrayList<>(); try { supportedClasses.add(this.getClass().forName("org.apache.spark.sql.Dataset")); } catch (ClassNotFoundException e) { } try { supportedClasses.add(this.getClass().forName("org.apache.spark.sql.DataFrame")); } catch (ClassNotFoundException e) { } try { supportedClasses.add(this.getClass().forName("org.apache.spark.sql.SchemaRDD")); } catch (ClassNotFoundException e) { } if (supportedClasses.isEmpty()) { <START> throw new InterpreterException("Can not road Dataset/DataFrame/SchemaRDD class"); <END> } }</code><technical_language>road -> load</technical_language>

Target:
public SparkZeppelinContext( SparkContext sc, SQLContext sql, InterpreterHookRegistry hooks, int maxResult) { super(hooks, maxResult); this.sc = sc; this.sqlContext = sql; interpreterClassMap = new HashMap<String, String>(); interpreterClassMap.put("spark", "org.apache.zeppelin.spark.SparkInterpreter"); interpreterClassMap.put("sql", "org.apache.zeppelin.spark.SparkSqlInterpreter"); interpreterClassMap.put("dep", "org.apache.zeppelin.spark.DepInterpreter"); interpreterClassMap.put("pyspark", "org.apache.zeppelin.spark.PySparkInterpreter"); this.supportedClasses = new ArrayList<>(); try { supportedClasses.add(this.getClass().forName("org.apache.spark.sql.Dataset")); } catch (ClassNotFoundException e) { } try { supportedClasses.add(this.getClass().forName("org.apache.spark.sql.DataFrame")); } catch (ClassNotFoundException e) { } try { supportedClasses.add(this.getClass().forName("org.apache.spark.sql.SchemaRDD")); } catch (ClassNotFoundException e) { } if (supportedClasses.isEmpty()) { throw new InterpreterException("Can not load Dataset/DataFrame/SchemaRDD class"); } }
Source:
<code>public Hooks list() { VdcQueryReturnValue result = <START> runQuery(VdcQueryType.GetVdsHooksById2, <END> new GetVdsHooksByIdParameters(asGuid(hostId))); HashMap<String, HashMap<String, HashMap<String, String>>> hooksMap = (HashMap<String, HashMap<String, HashMap<String, String>>>) result.getReturnValue(); Hooks hooks = mappingLocator.getMapper(HashMap.class, Hooks.class).map(hooksMap, null); return hooks; }</code><technical_language>please getEntity() instead of runQuery()</technical_language>

Target:
public Hooks list() { @SuppressWarnings("unchecked") HashMap<String, HashMap<String, HashMap<String, String>>> hooksMap = getEntity(HashMap.class, VdcQueryType.GetVdsHooksById2, new GetVdsHooksByIdParameters(asGuid(hostId)), null); return mapCollection(hooksMap); }
Source:
<code>public long getStartingAddress() { if (startingAddress.get() == Address.NON_ADDRESS) { <START> long dbStartingAddress = Optional.ofNullable(dataStore.get(STARTING_ADDRESS_RECORD)).orElse(ZERO_ADDRESS); <END> startingAddress.set(dbStartingAddress); } return startingAddress.get(); }</code><technical_language>change this name, db, trimMark</technical_language>

Target:
public long getStartingAddress() { if (startingAddress.get() == Address.NON_ADDRESS) { startingAddress.set(dataStore.get(STARTING_ADDRESS_RECORD, ZERO_ADDRESS)); } return startingAddress.get(); }
Source:
<code>public void testAllowCreatingEventTypeWithInformationalFieldsFromEffectiveSchema(){ final EventType et = EventTypeTestBuilder.builder() .category(EventCategory.DATA) .build(); et.setOrderingKeyFields(Collections.singletonList("metadata.occurred_at")); et.setOrderingInstanceIds(Collections.singletonList("metadata.partition")); <START> eventTypeService.create(et, true); <END> }</code><technical_language>test some validation step</technical_language>

Target:
public void testAllowCreatingEventTypeWithInformationalFieldsFromEffectiveSchema() { final EventType et = EventTypeTestBuilder.builder() .category(EventCategory.DATA) .build(); et.setOrderingKeyFields(Collections.singletonList("metadata.occurred_at")); et.setOrderingInstanceIds(Collections.singletonList("metadata.partition")); try { eventTypeService.create(et, true); } catch (final InvalidEventTypeException e) { fail("Cannot create event with informational fields from effective schema"); } }
Source:
<code>private List<String> getSubQuestions(Map<String, String[]> requestParameters, int numOfRubricSubQuestions) { List<String> rubricSubQuestions = new ArrayList<String>(); for (int i = 0; i < numOfRubricSubQuestions; i++) { String subQuestion = HttpRequestHelper.getValueFromParamMap(requestParameters, Const.ParamsNames.FEEDBACK_QUESTION_RUBRIC_SUBQUESTION + "-" + i); <START> if (!subQuestion.trim().isEmpty()) { <END> rubricSubQuestions.add(subQuestion); } } return rubricSubQuestions; }</code><technical_language>is smart remove this null check? calling trim object right</technical_language>

Target:
private List<String> getSubQuestions(Map<String, String[]> requestParameters, int numOfRubricSubQuestions) { List<String> rubricSubQuestions = new ArrayList<String>(); for (int i = 0; i < numOfRubricSubQuestions; i++) { String subQuestion = HttpRequestHelper.getValueFromParamMap(requestParameters, Const.ParamsNames.FEEDBACK_QUESTION_RUBRIC_SUBQUESTION + "-" + i); if (subQuestion != null) { rubricSubQuestions.add(subQuestion); } } return rubricSubQuestions; }
Source:
<code><START> @Override public String toString() { <END> return "ConfigKey{" + "type='" + type + '\'' + ", description='" + description + '\'' + ", alternateKey='" + alternateKey + '\'' + ", keyName='" + keyName + '\'' + ", value='" + value + '\'' + ", deprecated=" + deprecated + ", reloadable=" + reloadable + ", validValues=" + validValues + ", version='" + version + '\'' + ", valueHelper=" + valueHelper + ", defaultValue='" + defaultValue + '\'' + '}'; }</code><technical_language>Please put @Override standalone line</technical_language>

Target:
public String toString() { return new ToStringBuilder(this) .append("type", type) .append("description", description) .append("alternateKey", alternateKey) .append("keyName", keyName) .append("value", value) .append("deprecated", deprecated) .append("reloadable", reloadable) .append("validValues", validValues) .append("version", version) .append("valueHelper", valueHelper) .append("defaultValue", defaultValue) .toString(); }
Source:
<code>public void process(WatchedEvent e) { if (e.getType() == Event.EventType.None) { return; } <START> if (e.getState() == Event.KeeperState.SyncConnected) { <END> event = e; latch.countDown(); } }</code><technical_language>this capture state encountered? receive a Disconnected AuthFailed event is gracefully handle them? code for this change good of questions</technical_language>

Target:
public void process(WatchedEvent e) { if (e.getType() != Event.EventType.None && e.getState() == Event.KeeperState.SyncConnected) { watched = true; } event = e; latch.countDown(); }
Source:
<code>private LockManager() { <START> locks = new Hashtable<URI, LockProvider>(); <END> }</code><technical_language>point in Hashtable if protecting map synchronized methods</technical_language>

Target:
private LockManager() { locks = new HashMap<URI, LockProvider>(); }
Source:
<code><START> public static CompressionFactory getInstance() { <END> if (compressionFactoryInstance == null) { compressionFactoryInstance = new CompressionFactory(); } return compressionFactoryInstance; }</code><technical_language>If do lazy initialization for singleton, need careful concurrent calls getInstance. This class need lazy initialization, initialize declaring static variable. Then, worry concurrent calls</technical_language>

Target:
public static CompressionFactory getInstance() { return COMPRESSION_FACTORY_INSTANCE; }
Source:
<code><START> public ForwardIborRateObservationFn() { <END> super(); }</code><technical_language>This constructor is redundant</technical_language>

Target:
public ForwardIborRateObservationFn() { }
Source:
<code>public void removeJob(JobID jobId) throws Exception { Preconditions.checkState(DefaultJobLeaderService.State.STARTED == state, "The service is currently not running."); Tuple2<LeaderRetrievalService, DefaultJobLeaderService.JobManagerLeaderListener> entry = jobLeaderServices.remove(jobId); if (entry != null) { LOG.info("Remove job from job leader monitoring.", jobId); LeaderRetrievalService leaderRetrievalService = entry.f0; DefaultJobLeaderService.JobManagerLeaderListener jobManagerLeaderListener = entry.f1; <START> leaderRetrievalService.stop(); <END> jobManagerLeaderListener.stop(); } }</code><technical_language>If this throws exception, is leader listener closed</technical_language>

Target:
public void removeJob(JobID jobId) { Preconditions.checkState(DefaultJobLeaderService.State.STARTED == state, "The service is currently not running."); Tuple2<LeaderRetrievalService, DefaultJobLeaderService.JobManagerLeaderListener> entry = jobLeaderServices.remove(jobId); if (entry != null) { LOG.info("Remove job from job leader monitoring.", jobId); LeaderRetrievalService leaderRetrievalService = entry.f0; DefaultJobLeaderService.JobManagerLeaderListener jobManagerLeaderListener = entry.f1; jobManagerLeaderListener.stop(); try { leaderRetrievalService.stop(); } catch (Exception e) { LOG.info("Could not properly stop the LeaderRetrievalService for job {}.", jobId, e); } } }
Source:
<code>public BuildHistory(final AbstractBuild<?, ?> baseline, final Class<? extends ResultAction<? extends BuildResult>> type, final boolean usePreviousBuildAsReference, <START> final boolean useStableBuildAsReference) { <END> this.baseline = baseline; this.type = type; this.usePreviousBuildAsReference = usePreviousBuildAsReference; this.useStableBuildAsReference = useStableBuildAsReference; }</code><technical_language>BTW is easier for reviewers maintaining binary compatibility deprecated member is adjacent new one, forming diff hunk</technical_language>

Target:
public BuildHistory(final AbstractBuild<?, ?> baseline, final Class<? extends ResultAction<? extends BuildResult>> type, final boolean usePreviousBuildAsReference, final boolean useStableBuildAsReference) { this((Run<?, ?>) baseline, type, usePreviousBuildAsReference, useStableBuildAsReference); }
Source:
<code>public void addListener(MockitoListener listener) { <START> if (listener instanceof MockCreationListener) { <END> mockingProgress().addListener(listener); } }</code><technical_language>@szczepiq Is this needed? [MockingProgressImpl.mockingStarted()](<LINK_0> filters for MockCreationListener</technical_language>

Target:
public void addListener(MockitoListener listener) { assertNotNull(listener); mockingProgress().addListener(listener); }
Source:
<code>public void startHosts(List<VDS> hostWithPMInStatusReboot) { for (VDS host : hostWithPMInStatusReboot) { RestartVdsCommand<FenceVdsActionParameters> restartVdsCommand = new RestartVdsCommand<>(new FenceVdsActionParameters(host.getId()), null); if (new HostFenceActionExecutor(host).isHostPoweredOff()) { <START> if (host.getExternalStatus() != null && host.getExternalStatus() != ExternalStatus.Ok) { <END> log.warn("Host '{}' ({}) was not started by PM Health Check Manager becuse it has external-status: '{}'.", host.getName(), host.getId(), host.getExternalStatus()); continue; } ActionReturnValue retValue = backend.get().runInternalAction(ActionType.RestartVds, restartVdsCommand.getParameters()); if (retValue!= null && retValue.getSucceeded()) { log.info("Host '{}' was started successfully by PM Health Check Manager", host.getName()); } else { log.info("PM Health Check Manager failed to start Host '{}'", host.getName()); } } } }</code><technical_language>more readable? if(!ExternalStatus.OK.equals(host.getExternalStatus()) {</technical_language>

Target:
public void startHosts(List<VDS> hostWithPMInStatusReboot) { for (VDS host : hostWithPMInStatusReboot) { RestartVdsCommand<FenceVdsActionParameters> restartVdsCommand = new RestartVdsCommand<>(new FenceVdsActionParameters(host.getId()), null); if (new HostFenceActionExecutor(host).isHostPoweredOff()) { if (!ExternalStatus.Ok.equals(host.getExternalStatus())) { log.warn("Host '{}' ({}) was not started by PM Health Check Manager becuse it has external-status: '{}'.", host.getName(), host.getId(), host.getExternalStatus()); continue; } ActionReturnValue retValue = backend.get().runInternalAction(ActionType.RestartVds, restartVdsCommand.getParameters()); if (retValue!= null && retValue.getSucceeded()) { log.info("Host '{}' was started successfully by PM Health Check Manager", host.getName()); } else { log.info("PM Health Check Manager failed to start Host '{}'", host.getName()); } } } }
Source:
<code>public ServletApiAbstraction(ResourceLoader resourceLoader) { super(resourceLoader); this.asyncSupported = Reflections.isClassLoadable(ASYNC_LISTENER_CONTEXT_CLASS_NAME, resourceLoader); Class<ServletRequest> servletRequestClass = Reflections.loadClass(SERVLET_REQUEST_CLASS_NAME, resourceLoader); if (servletRequestClass != null) { try { isAsyncStartedMethod = servletRequestClass.getMethod(IS_ASYNC_STARTED_METHOD_NAME); } catch (NoSuchMethodException e) { <START> ServletLogger.LOG.warn(e); <END> } } }</code><technical_language>If this means running in pre Servlet 3.0 environment. do want pollute log a stack trace (we debug level). Instead, ignore this completely print info message "Running in Servlet 2.x environment. Asynchronous request support is disabled."</technical_language>

Target:
public ServletApiAbstraction(ResourceLoader resourceLoader) { super(resourceLoader); this.asyncSupported = Reflections.isClassLoadable(ASYNC_LISTENER_CONTEXT_CLASS_NAME, resourceLoader); Method isAsyncStartedMethodLocal = null; Class<ServletRequest> servletRequestClass = Reflections.loadClass(SERVLET_REQUEST_CLASS_NAME, resourceLoader); if (servletRequestClass != null) { try { isAsyncStartedMethodLocal = servletRequestClass.getMethod(IS_ASYNC_STARTED_METHOD_NAME); } catch (NoSuchMethodException e) { ServletLogger.LOG.servlet2Environment(); } } isAsyncStartedMethod = isAsyncStartedMethodLocal; }
Source:
<code>public AuthenticationResponse apply(HttpResponse from) { releasePayload(from); final CaseInsensitiveMap services = new CaseInsensitiveMap(); for (final Entry<String, String> entry : from.getHeaders().entries()) { if (entry.getKey().toLowerCase().endsWith(URL_SUFFIX.toLowerCase())) <START> services.put(entry.getKey(), getURI(entry.getValue())); <END> } AuthenticationResponse response = new AuthenticationResponse(checkNotNull(from.getFirstHeaderOrNull(AUTH_TOKEN), AUTH_TOKEN), services); logger.debug("will connect to: ", response); return response; }</code><technical_language>do like: Map<String, String> map = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);</technical_language>

Target:
public AuthenticationResponse apply(HttpResponse from) { releasePayload(from); Builder<String, URI> builder = ImmutableMap.builder(); for (Entry<String, String> entry : from.getHeaders().entries()) { if (entry.getKey().toLowerCase().endsWith(URL_SUFFIX.toLowerCase())) builder.put(entry.getKey(), getURI(entry.getValue())); } AuthenticationResponse response = new AuthenticationResponse(checkNotNull(from.getFirstHeaderOrNull(AUTH_TOKEN), AUTH_TOKEN), builder.build()); logger.debug("will connect to: ", response); return response; }
Source:
<code><START> public void add(ActiveSubscription theActiveSubscription) { <END> if (!myModelConfig.isSubscriptionMatchingEnabled()) { return; } String channelName = theActiveSubscription.getChannelName(); ourLog.info("Adding subscription to channel {}", theActiveSubscription.getId(), channelName); myActiveSubscriptionByChannelName.put(channelName, theActiveSubscription.getId()); if (mySubscriptionChannelCache.containsKey(channelName)) { ourLog.info("Channel already exists. Not creating.", channelName); return; } SubscribableChannel deliveryChannel; Optional<MessageHandler> deliveryHandler; deliveryChannel = mySubscriptionDeliveryChannelFactory.newDeliveryChannel(channelName); deliveryHandler = mySubscriptionDeliveryHandlerFactory.createDeliveryHandler(theActiveSubscription.getChannelType()); SubscriptionChannelWithHandlers subscriptionChannelWithHandlers = new SubscriptionChannelWithHandlers(channelName, deliveryChannel); deliveryHandler.ifPresent(subscriptionChannelWithHandlers::addHandler); mySubscriptionChannelCache.put(channelName, subscriptionChannelWithHandlers); }</code><technical_language>add/remove methods syncrhonized work a shared map</technical_language>

Target:
public synchronized void add(ActiveSubscription theActiveSubscription) { if (!myModelConfig.isSubscriptionMatchingEnabled()) { return; } String channelName = theActiveSubscription.getChannelName(); ourLog.info("Adding subscription to channel {}", theActiveSubscription.getId(), channelName); myActiveSubscriptionByChannelName.put(channelName, theActiveSubscription.getId()); if (mySubscriptionChannelCache.containsKey(channelName)) { ourLog.info("Channel already exists. Not creating.", channelName); return; } SubscribableChannel deliveryChannel; Optional<MessageHandler> deliveryHandler; deliveryChannel = mySubscriptionDeliveryChannelFactory.newDeliveryChannel(channelName); deliveryHandler = mySubscriptionDeliveryHandlerFactory.createDeliveryHandler(theActiveSubscription.getChannelType()); SubscriptionChannelWithHandlers subscriptionChannelWithHandlers = new SubscriptionChannelWithHandlers(channelName, deliveryChannel); deliveryHandler.ifPresent(subscriptionChannelWithHandlers::addHandler); mySubscriptionChannelCache.put(channelName, subscriptionChannelWithHandlers); }
Source:
<code>public void release(Statement statement) { log.tracev( "Releasing statement [{0}]", statement ); <START> final Set<ResultSet> resultSets = xref.get( statement ); <END> if ( resultSets != null ) { closeAll( resultSets ); xref.remove( statement ); } else if ( log.isDebugEnabled() ) { log.unregisteredStatement(); } close( statement ); if ( lastQuery == statement ) { lastQuery = null; } }</code><technical_language>final Set<ResultSet> resultSets = xref.remove( statement ); here, remove() call below? need access map once. change behavior slightly if closeAll throws exception xref, though. a good idea</technical_language>

Target:
public void release(Statement statement) { log.tracev( "Releasing statement [{0}]", statement ); if ( log.isDebugEnabled() && !xref.containsKey( statement ) ) { log.unregisteredStatement(); } else { final Set<ResultSet> resultSets = xref.get( statement ); if ( resultSets != null ) { closeAll( resultSets ); } xref.remove( statement ); } close( statement ); if ( lastQuery == statement ) { lastQuery = null; } }
Source:
<code>public JobMonitoringCoordinator( final String hostName, final JobSearchService jobSearchService, final ApplicationEventPublisher publisher, final ApplicationEventMulticaster eventMulticaster, final TaskScheduler scheduler, final Executor executor, final Registry registry, final Resource jobsDir, final JobsProperties jobsProperties, final JobSubmitterService jobSubmitterService ) throws IOException { this.hostName = hostName; this.jobSearchService = jobSearchService; this.publisher = publisher; this.eventMulticaster = eventMulticaster; this.scheduler = scheduler; this.executor = executor; this.registry = registry; this.jobsDir = jobsDir.getFile(); this.jobsProperties = jobsProperties; this.jobSubmitterService = jobSubmitterService; this.registry.mapSize("genie.jobs.running.gauge", this.jobs); <START> this.registry.methodValue("genie.jobs.active.gauge", this, "getNumActiveJobs"); <END> this.registry.methodValue("genie.jobs.memory.used.gauge", this, "getUsedMemory"); this.unableToCancel = registry.counter("genie.jobs.unableToCancel.rate"); this.unableToReAttach = registry.counter("genie.jobs.unableToReAttach.rate"); }</code><technical_language>tag status break way</technical_language>

Target:
public JobMonitoringCoordinator( final String hostName, final JobSearchService jobSearchService, final ApplicationEventPublisher publisher, final ApplicationEventMulticaster eventMulticaster, final TaskScheduler scheduler, final Executor executor, final Registry registry, final Resource jobsDir, final JobsProperties jobsProperties, final JobSubmitterService jobSubmitterService ) throws IOException { super(jobSubmitterService, scheduler, publisher, registry); this.hostName = hostName; this.jobSearchService = jobSearchService; this.eventMulticaster = eventMulticaster; this.executor = executor; this.jobsDir = jobsDir.getFile(); this.jobsProperties = jobsProperties; this.unableToReAttach = registry.counter("genie.jobs.unableToReAttach.rate"); }
Source:
<code>private HashMap<String, String> getCustomHeaders() { HashMap<String, String> customHeaders = new HashMap<>(); try { Set<String> allPropNames = getPropertyAccessor().getPropertyNames(NhincConstants.GATEWAY_PROPERTY_FILE); if (NullChecker.isNotNullish(allPropNames)) { for (String propName : allPropNames) { <START> if (NullChecker.isNotNullish(propName) && propName.startsWith(NhincConstants.CUSTOM_HTTP_HEADERS)) { <END> String propValue = getPropertyAccessor().getProperty(NhincConstants.GATEWAY_PROPERTY_FILE, propName); propName = trimPropertyName(propName); if (NullChecker.isNotNullish(propValue) && NullChecker.isNotNullish(propName)) { customHeaders.put(propName, propValue); } } } } } catch (PropertyAccessException ex) { LOG.warn("Unable to access properties for custom http headers.", ex); } if (NullChecker.isNotNullish(assertion.getCONNECTCustomHttpHeaders())) { for (CONNECTCustomHttpHeadersType header : assertion.getCONNECTCustomHttpHeaders()) { customHeaders.put(header.getHeaderName(), header.getHeaderValue()); } } return customHeaders; }</code><technical_language>![MAJOR](<LINK_0> Refactor this code nest more 3 if/for/while/switch/try statements. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
private HashMap<String, String> getCustomHeaders() { HashMap<String, String> customHeaders = new HashMap<>(); try { Set<String> allPropNames = getPropertyAccessor().getPropertyNames(NhincConstants.GATEWAY_PROPERTY_FILE); if (NullChecker.isNotNullish(allPropNames)) { addPropertiesToCustomHeaders(allPropNames, customHeaders); } } catch (PropertyAccessException ex) { LOG.warn("Unable to access properties for custom http headers.", ex.getLocalizedMessage()); } for (CONNECTCustomHttpHeadersType header : assertion.getCONNECTCustomHttpHeaders()) { customHeaders.put(header.getHeaderName(), header.getHeaderValue()); } return customHeaders; }
Source:
<code><START> public void testModemActivityInfoIsValid() { <END> ModemActivityInfo modemActivityInfo = new ModemActivityInfo(0, VALID_SLEEP_TIME_MS, VALID_IDLE_TIME_MS, new int[2], VALID_RX_TIME_MS); assertTrue("ModemActivityInfo should be valid", modemActivityInfo.isValid()); modemActivityInfo = new ModemActivityInfo(0, INVALID_SLEEP_TIME_MS, VALID_IDLE_TIME_MS, new int[2], VALID_RX_TIME_MS); assertFalse("ModemActivityInfo should be invalid because sleep time is invalid", modemActivityInfo.isValid()); modemActivityInfo = new ModemActivityInfo(0, VALID_SLEEP_TIME_MS, INVALID_IDLE_TIME_MS, new int[2], VALID_RX_TIME_MS); assertFalse("ModemActivityInfo should be invalid because idle time is invalid", modemActivityInfo.isValid()); modemActivityInfo = new ModemActivityInfo(0, VALID_SLEEP_TIME_MS, VALID_IDLE_TIME_MS, new int[2], INVALID_RX_TIME_MS); assertFalse("ModemActivityInfo should be invalid because receive time is invalid", modemActivityInfo.isValid()); }</code><technical_language>is a test transitPowerInfo invalid part? for (TransmitPower powerInfo : getTransmitPowerInfo()) { if(powerInfo.getTimeInMillis() < 0) { return false; } }</technical_language>

Target:
public void testModemActivityInfoIsValid() { ModemActivityInfo modemActivityInfo = new ModemActivityInfo(0, VALID_SLEEP_TIME_MS, VALID_IDLE_TIME_MS, VALID_TX_TIME_MS, VALID_RX_TIME_MS); assertTrue("ModemActivityInfo should be valid", modemActivityInfo.isValid()); modemActivityInfo = new ModemActivityInfo(0, INVALID_SLEEP_TIME_MS, VALID_IDLE_TIME_MS, VALID_TX_TIME_MS, VALID_RX_TIME_MS); assertFalse("ModemActivityInfo should be invalid because sleep time is invalid", modemActivityInfo.isValid()); modemActivityInfo = new ModemActivityInfo(0, VALID_SLEEP_TIME_MS, INVALID_IDLE_TIME_MS, VALID_TX_TIME_MS, VALID_RX_TIME_MS); assertFalse("ModemActivityInfo should be invalid because idle time is invalid", modemActivityInfo.isValid()); modemActivityInfo = new ModemActivityInfo(0, VALID_SLEEP_TIME_MS, VALID_IDLE_TIME_MS, VALID_TX_TIME_MS, INVALID_RX_TIME_MS); assertFalse("ModemActivityInfo should be invalid because receive time is invalid", modemActivityInfo.isValid()); modemActivityInfo = new ModemActivityInfo(0, VALID_SLEEP_TIME_MS, VALID_IDLE_TIME_MS, INVALID_TX_TIME_MS, INVALID_RX_TIME_MS); assertFalse("ModemActivityInfo should be invalid because transmit time is invalid", modemActivityInfo.isValid()); }
Source:
<code>public void setMaintenanceStatus(@Identification final String organisationIdentification, final String deviceIdentification, final boolean status) throws FunctionalException { final Device existingDevice = this.writableDeviceRepository.findByDeviceIdentification(deviceIdentification); if (existingDevice == null) { LOGGER.info("Device does not exist, cannot set maintenance status."); throw new FunctionalException(FunctionalExceptionType.UNKNOWN_DEVICE, ComponentType.WS_CORE, new UnknownEntityException(Device.class, deviceIdentification)); } else if (existingDevice.getOwner().getOrganisationIdentification().equals(organisationIdentification) || existingDevice.getOwner().getOrganisationIdentification().equals(this.netMangementOrganisation)) { existingDevice.updateInMaintenance(status); this.writableDeviceRepository.save(existingDevice); } else { throw new FunctionalException(FunctionalExceptionType.UNAUTHORIZED, ComponentType.WS_CORE, <START> new UnknownEntityException(Device.class, deviceIdentification)); <END> } }</code><technical_language>Please throw proper exception here. UnknownEntityException is right type of exception for this functional mistake a user made</technical_language>

Target:
public void setMaintenanceStatus(@Identification final String organisationIdentification, final String deviceIdentification, final boolean status) throws FunctionalException { final Device existingDevice = this.writableDeviceRepository.findByDeviceIdentification(deviceIdentification); if (existingDevice == null) { LOGGER.info("Device does not exist, cannot set maintenance status."); throw new FunctionalException(FunctionalExceptionType.UNKNOWN_DEVICE, ComponentType.WS_CORE, new UnknownEntityException(Device.class, deviceIdentification)); } else if (existingDevice.getOwner().getOrganisationIdentification().equals(organisationIdentification) || existingDevice.getOwner().getOrganisationIdentification().equals(this.netMangementOrganisation)) { existingDevice.updateInMaintenance(status); this.writableDeviceRepository.save(existingDevice); } else { throw new FunctionalException(FunctionalExceptionType.UNAUTHORIZED, ComponentType.WS_CORE, new NotAuthorizedException(organisationIdentification)); } }
Source:
<code>public void shareProjectNotPA() throws ESException { <START> try { <END> ProjectUtil.share(getUsersession(), getLocalProject()); } catch (final ESException ex) { boolean found = false; for (final StackTraceElement stackTraceElement : ex.getStackTrace()) { final String className = stackTraceElement.getClassName(); final String methodName = stackTraceElement.getMethodName(); if ("org.eclipse.emf.emfstore.internal.server.core.EMFStoreImpl".equals(className) && "invoke".equals(methodName)) { found = true; } } if (!found) { fail("EMFStoreImpl#invoke should fail already"); } throw ex; } }</code><technical_language>I tests utilizing actual logic preferable, utilizing ConnectionMock ESTestWithServer. Also, I consider testing AccessLevels important</technical_language>

Target:
public void shareProjectNotPA() throws ESException { try { ProjectUtil.share(getUsersession(), getLocalProject()); } catch (final ESException ex) { assertTrue(getServerMock().getServerSpace().getProjects().isEmpty()); throw ex; } }
Source:
<code><START> private static String guessApiUri(URL repositoryUrl) { <END> StringBuilder sb = new StringBuilder(); sb.append(repositoryUrl.getProtocol()); sb.append("://"); sb.append(repositoryUrl.getHost()); if (repositoryUrl.getPort() != -1) { sb.append(':'); sb.append(repositoryUrl.getPort()); } sb.append('/').append(GitHubSCMBuilder.API_V3); return GitHubConfiguration.normalizeApiUri(sb.toString()); }</code><technical_language>I need special-case github.com, <LINK_0> instead of <LINK_1>. I a concerned automatically computing API URI problematic if customers try do tricky proxies</technical_language>

Target:
private static String guessApiUri(URL repositoryUrl) { StringBuilder sb = new StringBuilder(); sb.append(repositoryUrl.getProtocol()); sb.append("://"); boolean isGitHub = GITHUB_COM.equals(repositoryUrl.getHost()); if(isGitHub){ sb.append(GITHUB_API_URL); }else { sb.append(repositoryUrl.getHost()); } if (repositoryUrl.getPort() != -1) { sb.append(':'); sb.append(repositoryUrl.getPort()); } if(!isGitHub) { sb.append('/').append(GitHubSCMBuilder.API_V3); } return GitHubConfiguration.normalizeApiUri(sb.toString()); }
Source:
<code>public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub) { if (FAKE_SIGNATURES) return true; if (Secp256k1Context.isEnabled()) { try { <START> return NativeSecp256k1.verify(data, signature.toCanonicalised().encodeToDER(), pub); <END> } catch (NativeSecp256k1Util.AssertFailException e) { log.error("Caught AssertFailException inside secp256k1", e); return false; } } ECDSASigner signer = new ECDSASigner(); ECPublicKeyParameters params = new ECPublicKeyParameters(CURVE.getCurve().decodePoint(pub), CURVE); signer.init(false, params); try { return signer.verifySignature(data, signature.r, signature.s); } catch (NullPointerException e) { log.error("Caught NPE inside bouncy castle", e); return false; } }</code><technical_language>@greenaddress touched native code signature verification. do of changes</technical_language>

Target:
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub) { if (FAKE_SIGNATURES) return true; if (Secp256k1Context.isEnabled()) { try { return NativeSecp256k1.verify(data, signature.encodeToDER(), pub); } catch (NativeSecp256k1Util.AssertFailException e) { log.error("Caught AssertFailException inside secp256k1", e); return false; } } ECDSASigner signer = new ECDSASigner(); ECPublicKeyParameters params = new ECPublicKeyParameters(CURVE.getCurve().decodePoint(pub), CURVE); signer.init(false, params); try { return signer.verifySignature(data, signature.r, signature.s); } catch (NullPointerException e) { log.error("Caught NPE inside bouncy castle", e); return false; } }
Source:
<code>public Response setBranchType(long branchUuid, BranchType newType) { BranchReadable branch = getBranchById(branchUuid); boolean modified = false; if (isDifferent(branch.getBranchType(), newType)) { <START> <END> activityLog.createEntry(BRANCH_OPERATION_TYPEID, ActivityLog.INITIAL_STATUS, String.format( "Branch Operation Set Branch Type {branchUUID: %s prevType: %s newType: %s accountId: %s serverId: %s clientId: %s}", branchUuid, branch.getBranchType(), newType, accountId, serverId, clientId)); Callable<?> op = getBranchOps().changeBranchType(branch, newType); executeCallable(op); modified = true; } return asResponse(modified); }</code><technical_language>try/catch</technical_language>

Target:
public Response setBranchType(long branchUuid, BranchType newType) { BranchReadable branch = getBranchById(branchUuid); boolean modified = false; if (isDifferent(branch.getBranchType(), newType)) { try { activityLog.createEntry(BRANCH_OPERATION_TYPEID, ActivityLog.INITIAL_STATUS, String.format( "Branch Operation Set Branch Type {branchUUID: %s prevType: %s newType: %s accountId: %s serverId: %s clientId: %s}", branchUuid, branch.getBranchType(), newType, RestUtil.getAccountId(httpHeaders), RestUtil.getServerId(httpHeaders), RestUtil.getClientId(httpHeaders))); } catch (OseeCoreException ex) { OseeLog.log(ActivityLog.class, OseeLevel.SEVERE_POPUP, ex); } Callable<?> op = getBranchOps().changeBranchType(branch, newType); executeCallable(op); modified = true; } return asResponse(modified); }
Source:
<code>public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); <START> if (!(input instanceof FileEditorInput)) { <END> throw new PartInitException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Expected editor input to be of type FileEditorInput")); } FileEditorInput fileInput = ((FileEditorInput)input); if (fileInput != null) { source = fileInput.getFile(); } }</code><technical_language>This occur setInput(input);</technical_language>

Target:
public void init(IEditorSite site, IEditorInput input) throws PartInitException { if (!(input instanceof FileEditorInput)) { throw new PartInitException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Expected editor input to be of type FileEditorInput")); } setSite(site); setInput(input); FileEditorInput fileInput = ((FileEditorInput) input); if (fileInput != null) { source = fileInput.getFile(); } }
Source:
<code>public static Font getFont(FontByDefinition fontByDefinition) { Font font = fontByDefinition.getResource(); IColorAndFontProvider provider = CSSActivator.getDefault().getColorAndFontProvider(); if (provider == null) { return font; } FontData[] fontDataFromDefinition = provider.getFont(fontByDefinition.getSymbolicName()); FontData[] currentFontData = font.getFontData(); if (!isFontDataValid(fontDataFromDefinition) || !isFontDataValid(currentFontData)) { return font; } String name = fontDataFromDefinition[0].getName(); int height = fontByDefinition.getHeight() == null? fontDataFromDefinition[0].getHeight(): fontByDefinition.getHeight(); int style = fontByDefinition.getStyle() == null? fontDataFromDefinition[0].getStyle(): fontByDefinition.getStyle(); if (height != currentFontData[0].getHeight() || style != currentFontData[0].getStyle() || !name.equals(currentFontData[0].getName())) { <START> font = new Font(font.getDevice(), new FontData(name, height, style)); <END> } return font; }</code><technical_language>This font needs cached somewhere, disposed appropriate</technical_language>

Target:
public static Font getFont(FontByDefinition fontByDefinition) { Font font = fontByDefinition.getResource(); IColorAndFontProvider provider = CSSActivator.getDefault().getColorAndFontProvider(); if (provider == null) { return font; } FontData[] fontDataFromDefinition = provider.getFont(fontByDefinition.getSymbolicName()); FontData[] currentFontData = font.getFontData(); if (!isFontDataValid(fontDataFromDefinition) || !isFontDataValid(currentFontData)) { return font; } String name = fontDataFromDefinition[0].getName(); int height = fontByDefinition.getHeight() == null? fontDataFromDefinition[0].getHeight(): fontByDefinition.getHeight(); int style = fontByDefinition.getStyle() == null? fontDataFromDefinition[0].getStyle(): fontByDefinition.getStyle(); if (height != currentFontData[0].getHeight() || style != currentFontData[0].getStyle() || !name.equals(currentFontData[0].getName())) { Device device = font.getDevice(); font.dispose(); font = new Font(device, new FontData(name, height, style)); fontByDefinition.setResource(font); } fontByDefinition.setValid(true); return font; }
Source:
<code><START> public static final byte[] readSome(final File path, final int limit) <END> throws FileNotFoundException, IOException { final FileInputStream in = new FileInputStream(path); try { ByteArrayOutputStream result = new ByteArrayOutputStream(limit); final byte[] buf = new byte[1024]; int read = in.read(buf); while (read > 0) { result.write(buf, 0, read); read = in.read(buf); } return result.toByteArray(); } finally { try { in.close(); } catch (IOException ignored) { } } }</code><technical_language>I unnecessary allocate a ByteArrayOutputStream here. Instead write method as: FileInputStream in = new FileInputStream(path); try { byte[] buf = new byte[limit]; int cnt = 0; for (;;) { int n = in.read(buf, cnt, buf.length - cnt); if (n <= 0) break; cnt += n; } if (cnt == buf.length) return buf; byte[] res = new byte[cnt]; System.arraycopy(buf, 0, res, 0, cnt); return res; } finally { try { in.close(); } catch (IOException ignored) { } }</technical_language>

Target:
public static final byte[] readSome(final File path, final int limit) throws FileNotFoundException, IOException { FileInputStream in = new FileInputStream(path); try { byte[] buf = new byte[limit]; int cnt = 0; for (;;) { int n = in.read(buf, cnt, buf.length - cnt); if (n <= 0) break; cnt += n; } if (cnt == buf.length) return buf; byte[] res = new byte[cnt]; System.arraycopy(buf, 0, res, 0, cnt); return res; } finally { try { in.close(); } catch (IOException ignored) { } } }