auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<InputRow> parseBatch(Map<String, Object> theMap) { final List<String> dimensions = parseSpec.getDimensionsSpec().hasCustomDimensions() ? parseSpec.getDimensionsSpec().getDimensionNames() : Lists.newArrayList( Sets.difference( theMap.keySet(), parseSpec.getDimensionsSpec() .getDimensionExclusions() ) ); final DateTime timestamp; try { timestamp = parseSpec.getTimestampSpec().extractTimestamp(theMap); if (timestamp == null) { final String input = theMap.toString(); throw new NullPointerException( StringUtils.format( "Null timestamp in input: %s", input.length() < 100 ? input : input.substring(0, 100) + "..." ) ); } } catch (Exception e) { <START> throw new ParseException(e, "Unparseable timestamp found! Event: " + theMap); <END> } return ImmutableList.of(new MapBasedInputRow(timestamp.getMillis(), dimensions, theMap)); }</code><technical_language>nit: ParseException supports formatted string</technical_language>

Target:
public List<InputRow> parseBatch(Map<String, Object> theMap) { final List<String> dimensions = parseSpec.getDimensionsSpec().hasCustomDimensions() ? parseSpec.getDimensionsSpec().getDimensionNames() : Lists.newArrayList( Sets.difference( theMap.keySet(), parseSpec.getDimensionsSpec() .getDimensionExclusions() ) ); final DateTime timestamp; try { timestamp = parseSpec.getTimestampSpec().extractTimestamp(theMap); if (timestamp == null) { final String input = theMap.toString(); throw new NullPointerException( StringUtils.format( "Null timestamp in input: %s", input.length() < 100 ? input : input.substring(0, 100) + "..." ) ); } } catch (Exception e) { throw new ParseException(e, "Unparseable timestamp found! Event: %s", theMap); } return ImmutableList.of(new MapBasedInputRow(timestamp.getMillis(), dimensions, theMap)); }
Source:
<code>public int write(ByteBuffer src) throws ClosedChannelException { if (!src.hasArray()) { throw new IllegalArgumentException( "NettyResponseChannel does not work with ByteBuffers that are not backed by " + "byte arrrays"); } <START> return addToResponseBody(src); <END> }</code><technical_language>Is addToResponseBody() other method? this method all? Alternatively, do this single check write() do other checks addToResponseBody()</technical_language>

Target:
public int write(ByteBuffer src) throws ClosedChannelException { if (!src.hasArray()) { throw new IllegalArgumentException( "NettyResponseChannel does not work with ByteBuffers that are not backed by byte arrays"); } if (!responseMetadataWritten.get()) { maybeWriteResponseMetadata(responseMetadata); } verifyChannelActive(); int bytesWritten = 0; if (ctx.channel().isWritable()) { emptyingFlushRequired.set(true); int bytesToWrite = Math.min(src.remaining(), ctx.channel().config().getWriteBufferLowWaterMark()); logger.trace("Adding bytes of data to response on channel {}", bytesToWrite, ctx.channel()); ByteBuf buf = Unpooled.wrappedBuffer(src.array(), src.arrayOffset() + src.position(), bytesToWrite).order(src.order()); ChannelFuture writeFuture = writeToChannel(new DefaultHttpContent(buf), ChannelWriteType.Safe); if (!writeFuture.isDone() || writeFuture.isSuccess()) { bytesWritten = bytesToWrite; src.position(src.position() + bytesToWrite); } } else if (emptyingFlushRequired.compareAndSet(true, false)) { flush(); } return bytesWritten; }
Source:
<code>public void play() { <START> if (hasMediaSession()) { <END> LOGD(TAG, "Start PLAY"); if (isEnded) { load(0); isEnded = false; stopTimer(); startTimer(); updateState(State.Playing); return; } mRemoteMediaPlayer.play(mApiClient).setResultCallback(new ResultCallback<RemoteMediaPlayer.MediaChannelResult>() { @Override public void onResult(RemoteMediaPlayer.MediaChannelResult mediaChannelResult) { Status status = mediaChannelResult.getStatus(); LOGD(TAG, "play status " + status.isSuccess()); if (status.isSuccess()) { startTimer(); updateState(State.Playing); } } }); } }</code><technical_language>Instead of wrapping "positive" code if, exit function negative case. changes in code, changes easy see, lines shorter. for other functions below</technical_language>

Target:
public void play() { if (!hasMediaSession()) { return; } LOGD(TAG, "Start PLAY"); if (isEnded) { load(0); isEnded = false; stopTimer(); startTimer(); updateState(State.Playing); return; } mRemoteMediaPlayer.play(mApiClient).setResultCallback(new ResultCallback<RemoteMediaPlayer.MediaChannelResult>() { @Override public void onResult(RemoteMediaPlayer.MediaChannelResult mediaChannelResult) { Status status = mediaChannelResult.getStatus(); LOGD(TAG, "play status " + status.isSuccess()); if (status.isSuccess()) { startTimer(); updateState(State.Playing); } } }); }
Source:
<code>public void test_IborInterpolatedRateObservation() { PricingEnvironment mockEnv = mock(PricingEnvironment.class); double rate3M = 0.0123d; double rate6M = 0.0234d; when(mockEnv.iborIndexRate(GBP_LIBOR_3M, FIXING_DATE)) .thenReturn(rate3M); when(mockEnv.iborIndexRate(GBP_LIBOR_6M, FIXING_DATE)) .thenReturn(rate6M); IborInterpolatedRateObservation ro = IborInterpolatedRateObservation.of(GBP_LIBOR_3M, GBP_LIBOR_6M, FIXING_DATE); ForwardIborInterpolatedRateObservationFn obs = ForwardIborInterpolatedRateObservationFn.DEFAULT; LocalDate fixingStartDate = ro.getShortIndex().calculateEffectiveFromFixing(ro.getFixingDate()); LocalDate fixingEndDate3M = ro.getShortIndex().calculateMaturityFromEffective(fixingStartDate); LocalDate fixingEndDate6M = ro.getLongIndex().calculateMaturityFromEffective(fixingStartDate); double days3M = fixingEndDate3M.toEpochDay() - ro.getFixingDate().toEpochDay(); double days6M = fixingEndDate6M.toEpochDay() - ro.getFixingDate().toEpochDay(); double daysCpn = ACCRUAL_END_DATE.toEpochDay() - ro.getFixingDate().toEpochDay(); double weight3M = (days6M - daysCpn) / (days6M - days3M); double weight6M = (daysCpn - days3M) / (days6M - days3M); double rateExpected = (weight3M * rate3M + weight6M * rate6M); double rateComputed = obs.rate(mockEnv, ro, ACCRUAL_START_DATE, ACCRUAL_END_DATE); assertEquals(rateExpected, rateComputed, TOLERANCE_RATE, <START> "DefaultIborInterpolatedRateProviderFn: rate on fixing date"); <END> }</code><technical_language>need for message in assertEquals - generally for debugging</technical_language>

Target:
public void test_IborInterpolatedRateObservation() { PricingEnvironment mockEnv = mock(PricingEnvironment.class); double rate3M = 0.0123d; double rate6M = 0.0234d; when(mockEnv.iborIndexRate(GBP_LIBOR_3M, FIXING_DATE)) .thenReturn(rate3M); when(mockEnv.iborIndexRate(GBP_LIBOR_6M, FIXING_DATE)) .thenReturn(rate6M); IborInterpolatedRateObservation ro = IborInterpolatedRateObservation.of(GBP_LIBOR_3M, GBP_LIBOR_6M, FIXING_DATE); ForwardIborInterpolatedRateObservationFn obs = ForwardIborInterpolatedRateObservationFn.DEFAULT; LocalDate fixingStartDate = ro.getShortIndex().calculateEffectiveFromFixing(ro.getFixingDate()); LocalDate fixingEndDate3M = ro.getShortIndex().calculateMaturityFromEffective(fixingStartDate); LocalDate fixingEndDate6M = ro.getLongIndex().calculateMaturityFromEffective(fixingStartDate); double days3M = fixingEndDate3M.toEpochDay() - ro.getFixingDate().toEpochDay(); double days6M = fixingEndDate6M.toEpochDay() - ro.getFixingDate().toEpochDay(); double daysCpn = ACCRUAL_END_DATE.toEpochDay() - ro.getFixingDate().toEpochDay(); double weight3M = (days6M - daysCpn) / (days6M - days3M); double weight6M = (daysCpn - days3M) / (days6M - days3M); double rateExpected = (weight3M * rate3M + weight6M * rate6M); double rateComputed = obs.rate(mockEnv, ro, ACCRUAL_START_DATE, ACCRUAL_END_DATE); assertEquals(rateExpected, rateComputed, TOLERANCE_RATE); }
Source:
<code>private void set(BigDecimal amount, final User player, final CommandSource sender) throws MaxMoneyException { BigDecimal minBalance = ess.getSettings().getMinMoney(); BigDecimal maxBalance = ess.getSettings().getMaxMoney(); boolean underMinimum = (amount.compareTo(minBalance) < 0); boolean aboveMax = (amount.compareTo(maxBalance) > 0); if (isPercent) { <START> player.percentHandler(amount, sender, UserBalanceUpdateEvent.Cause.COMMAND_ECO, 2); <END> } else { player.setMoney(underMinimum ? minBalance : aboveMax ? maxBalance : amount, UserBalanceUpdateEvent.Cause.COMMAND_ECO); player.sendMessage(tl("setBal", NumberUtil.displayCurrency(player.getMoney(), ess))); if (sender != null) { sender.sendMessage(tl("setBalOthers", player.getDisplayName(), NumberUtil.displayCurrency(player.getMoney(), ess))); } } }</code><technical_language>This implementation line implementation below... I get non-congruent methods this messages missing</technical_language>

Target:
private void set(BigDecimal amount, final User player, final CommandSource sender) throws MaxMoneyException { BigDecimal minBalance = ess.getSettings().getMinMoney(); BigDecimal maxBalance = ess.getSettings().getMaxMoney(); boolean underMinimum = (amount.compareTo(minBalance) < 0); boolean aboveMax = (amount.compareTo(maxBalance) > 0); player.setMoney(underMinimum ? minBalance : aboveMax ? maxBalance : amount, UserBalanceUpdateEvent.Cause.COMMAND_ECO); player.sendMessage(tl("setBal", NumberUtil.displayCurrency(player.getMoney(), ess))); if (sender != null) { sender.sendMessage(tl("setBalOthers", player.getDisplayName(), NumberUtil.displayCurrency(player.getMoney(), ess))); } }
Source:
<code>private String getWorldText(Future<ServerInfoMessage> info) { try { List<String> codedWorldInfo = new ArrayList<>(); ServerInfoMessage serverInfoMessage = info.get(); if(serverInfoMessage == null) <START> return FontColor.getColored(translationSystem.translate("${engine:menu#connection-failed}"), Color.RED); <END> for (WorldInfo wi : serverInfoMessage.getWorldInfoList()) { float timeInDays = wi.getTime() / (float) WorldTime.DAY_LENGTH; codedWorldInfo.add(String.format("%s (%.2f days)", wi.getTitle(), timeInDays)); } return Joiner.on('\n').join(codedWorldInfo); } catch (ExecutionException | InterruptedException e) { return FontColor.getColored(translationSystem.translate("${engine:menu#connection-failed}"), Color.RED); } }</code><technical_language>Please put brackets body of if. Terasology, brackets if/while if a single line</technical_language>

Target:
private String getWorldText(Future<ServerInfoMessage> info) { try { List<String> codedWorldInfo = new ArrayList<>(); ServerInfoMessage serverInfoMessage = info.get(); if (serverInfoMessage == null) { return FontColor.getColored(translationSystem.translate("${engine:menu#connection-failed}"), Color.RED); } for (WorldInfo wi : serverInfoMessage.getWorldInfoList()) { float timeInDays = wi.getTime() / (float) WorldTime.DAY_LENGTH; codedWorldInfo.add(String.format("%s (%.2f days)", wi.getTitle(), timeInDays)); } return Joiner.on('\n').join(codedWorldInfo); } catch (ExecutionException | InterruptedException e) { return FontColor.getColored(translationSystem.translate("${engine:menu#connection-failed}"), Color.RED); } }
Source:
<code>private RTCPReportBlock[] makeReportBlocks() { if (stream == null) { logger.warn("stream is null."); return MIN_RTCP_REPORT_BLOCKS_ARRAY; } StreamRTPManager streamRTPManager = stream.getStreamRTPManager(); if (streamRTPManager == null) { logger.warn("streamRTPManager is null."); return MIN_RTCP_REPORT_BLOCKS_ARRAY; } <START> Collection<ReceiveStream> receiveStreams = stream.getReceiveStreams(); <END> if (receiveStreams == null || receiveStreams.isEmpty()) { logger.info( "There are no receive streams to build report blocks for."); return MIN_RTCP_REPORT_BLOCKS_ARRAY; } SSRCCache cache = stream.getRTPTranslator().getSSRCCache(); if (cache == null) { logger.info("cache is null."); return MIN_RTCP_REPORT_BLOCKS_ARRAY; } Collection<RTCPReportBlock> reportBlocks = new ArrayList<>(); for (ReceiveStream receiveStream : receiveStreams) { SSRCInfo info = cache.cache.get((int) receiveStream.getSSRC()); if (info == null) { logger.warn("We have a ReceiveStream but not an SSRCInfo for " + "that ReceiveStream."); continue; } if (!info.ours && info.sender) { RTCPReportBlock reportBlock = info.makeReceiverReport(getLastProcessTime()); reportBlocks.add(reportBlock); } } return reportBlocks.toArray(new RTCPReportBlock[reportBlocks.size()]); }</code><technical_language>Whaaaaaat? rely FMJs ReceiveStream-s for this. I missing of whatsoever in bridge (they fully decoded streams)</technical_language>

Target:
private RTCPReportBlock[] makeReportBlocks() { if (stream == null) { logger.warn("stream is null."); return MIN_RTCP_REPORT_BLOCKS_ARRAY; } StreamRTPManager streamRTPManager = stream.getStreamRTPManager(); if (streamRTPManager == null) { logger.warn("streamRTPManager is null."); return MIN_RTCP_REPORT_BLOCKS_ARRAY; } Collection<ReceiveStream> receiveStreams = stream.getReceiveStreams(); if (receiveStreams == null || receiveStreams.isEmpty()) { logger.debug( "There are no receive streams to build report blocks for."); return MIN_RTCP_REPORT_BLOCKS_ARRAY; } SSRCCache cache = stream.getRTPTranslator().getSSRCCache(); if (cache == null) { logger.info("cache is null."); return MIN_RTCP_REPORT_BLOCKS_ARRAY; } Collection<RTCPReportBlock> reportBlocks = new ArrayList<>(); for (ReceiveStream receiveStream : receiveStreams) { SSRCInfo info = cache.cache.get((int) receiveStream.getSSRC()); if (info == null) { logger.warn("We have a ReceiveStream but not an SSRCInfo for " + "that ReceiveStream."); continue; } if (!info.ours && info.sender) { RTCPReportBlock reportBlock = info.makeReceiverReport(getLastProcessTime()); reportBlocks.add(reportBlock); } } return reportBlocks.toArray(new RTCPReportBlock[reportBlocks.size()]); }
Source:
<code>public void testAllThreadsAreStopped() throws Exception { PooledExecutionServiceConfiguration configuration = new PooledExecutionServiceConfiguration(); configuration.addDefaultPool("dflt", 0, 1); PooledExecutionService pooledExecutionService = new PooledExecutionService(configuration); pooledExecutionService.start(null); pooledExecutionService.getScheduledExecutor("dflt") .schedule(new Runnable() { @Override public void run() { }}, 10, TimeUnit.HOURS); pooledExecutionService.stop(); Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); for(Thread thread : threadSet) { <START> assertThat(thread.getName()).doesNotContain("pool"); <END> } }</code><technical_language>This matches string underlying ThreadPoolExecutor... validate "dflt" pool threads away. (Which implying starting a task run shutdown)</technical_language>

Target:
public void testAllThreadsAreStopped() throws Exception { PooledExecutionServiceConfiguration configuration = new PooledExecutionServiceConfiguration(); configuration.addDefaultPool("dflt", 0, 1); pooledExecutionService = new PooledExecutionService(configuration); pooledExecutionService.start(null); final CountDownLatch latch = new CountDownLatch(1); pooledExecutionService.getScheduledExecutor("dflt") .execute(new Runnable() { @Override public void run() { latch.countDown(); }}); latch.await(30, TimeUnit.SECONDS); pooledExecutionService.stop(); detectLeakingThreads(); }
Source:
<code>public static List<URL> readAllDepsAsUrls(List<String> prjDeps) { List<URL> deps = new ArrayList<>(); for(String dep:prjDeps){ try { deps.add(new URL(dep)); }catch (MalformedURLException e){ logger.error(e.getMessage()); } } <START> if(deps.size()>0) { <END> return deps; }else{ return Collections.emptyList(); } }</code><technical_language>This if-else is redundand. Please replace return deps; If deps added in for loop, deps empty ;) in method below</technical_language>

Target:
public static List<URL> readAllDepsAsUrls(List<String> prjDeps) { List<URL> deps = new ArrayList<>(); for (String dep : prjDeps) { try { deps.add(new URL(dep)); } catch (MalformedURLException e) { logger.error(e.getMessage()); } } return deps; }
Source:
<code><START> public MutableRate getApplyTransactionLatency() { <END> return applyTransactionLatency; }</code><technical_language>is this exposed? I in tests</technical_language>

Target:
public MutableRate getApplyTransactionLatency() { return applyTransaction; }
Source:
<code>public void run() throws Exception { WebResource webResource = getClient().resource(endpoint + "/v1/applications"); <START> ClientResponse clientResponse = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); <END> String jsonResponse = clientResponse.getEntity(String.class); List<Application> applications = getJsonParser().readValue(jsonResponse, new TypeReference<List<Application>>() { }); for (Application application : applications) { getOut().printf("%20s %10s\n",application.getSpec().getName(), application.getStatus()); } }</code><technical_language>Check response code</technical_language>

Target:
public void run() throws Exception { WebResource webResource = getClient().resource(endpoint + "/v1/applications"); ClientResponse clientResponse = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); if (clientResponse.getStatus() != Response.Status.OK.getStatusCode()) { String err = getErrorMessage(clientResponse); throw new CommandExecutionException(err); } String jsonResponse = clientResponse.getEntity(String.class); List<Application> applications = getJsonParser().readValue(jsonResponse, new TypeReference<List<Application>>() {}); for (Application application : applications) { getOut().printf("%s [%s]\n",application.getSpec().getName(), application.getStatus()); } }
Source:
<code>public boolean isContainerRunning(String container) throws IOException, InterruptedException { ProcessBuilder pBuilder = cmd("ps").add("-q", "--filter", "\"id=" + container + '"').build(); Process psProcess = pBuilder.start(); <START> psProcess.waitFor(); <END> if (psProcess.exitValue() == 0) { String psOutput = IOUtils.toString(psProcess.getInputStream()); if (psOutput.contains(container)) { return true; } } return false; }</code><technical_language>If a lot of running containers this exit writing output block read..</technical_language>

Target:
public boolean isContainerRunning(String container) throws IOException, InterruptedException { ProcessBuilder pBuilder = cmd("ps").add("-q", "--filter", "\"id=" + container + '"').build(); Process psProcess = pBuilder.start(); String psOutput = IOUtils.toString(psProcess.getInputStream()); int pExit = psProcess.waitFor(); if (pExit == 0) { return psOutput.contains(container); } System.err.println("docker ps failed with code: " + pExit + (psOutput != null ? " and output: " + psOutput : " and provided no output")); return false; }
Source:
<code>public void afterPropertiesSet() throws Exception { try { String[] flowIds = flowDefinitionRegistry.getFlowDefinitionIds(); flowIds = (String[]) ArrayUtils.removeElement(flowIds, FLOW_ID_LOGIN); LOGGER.debug("Detected flow configurations: [{}]", flowIds.length, Arrays.toString(flowIds)); LOGGER.debug("Configuring webflow for multifactor authentication..."); setupWebflow(flowIds); LOGGER.debug("Configured webflow for multifactor authentication."); <START> LOGGER.debug("Registering default credentials-to-principal resolver..."); <END> final List resolvers = this.context.getBean("mfaCredentialsToPrincipalResolvers", List.class); final UsernamePasswordCredentialsToPrincipalResolver defaultResolver = new UsernamePasswordCredentialsToPrincipalResolver(); final IPersonAttributeDao attributeRepository = this.context.getBean("attributeRepository", IPersonAttributeDao.class); defaultResolver.setAttributeRepository(attributeRepository); resolvers.add(defaultResolver); LOGGER.debug("Registered default credentials-to-principal resolver."); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } }</code><technical_language>Move this block a separate method</technical_language>

Target:
public void afterPropertiesSet() throws Exception { try { String[] flowIds = flowDefinitionRegistry.getFlowDefinitionIds(); flowIds = (String[]) ArrayUtils.removeElement(flowIds, FLOW_ID_LOGIN); LOGGER.debug("Detected flow configurations: [{}]", flowIds.length, Arrays.toString(flowIds)); LOGGER.debug("Configuring webflow for multifactor authentication..."); setupWebflow(flowIds); LOGGER.debug("Configured webflow for multifactor authentication."); LOGGER.debug("Registering default credentials-to-principal resolver..."); registerDefaultCredentialsToPrincipalResolver(); LOGGER.debug("Registered default credentials-to-principal resolver."); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } }
Source:
<code><START> public void removePreAllocation(QueryId queryId) <END> { synchronized (this) { preAllocations.remove(queryId); } MemoryPoolInfo info = pools.get(GENERAL_POOL).getInfo(); for (Consumer<MemoryPoolInfo> listener : changeListeners.get(GENERAL_POOL)) { listenerExecutor.execute(() -> listener.accept(info)); } }</code><technical_language>reason this change? changeListeners pools GuardedBy this, this change removes synchronization them</technical_language>

Target:
public synchronized void removePreAllocation(QueryId queryId) { preAllocations.remove(queryId); MemoryPoolInfo info = pools.get(GENERAL_POOL).getInfo(); for (Consumer<MemoryPoolInfo> listener : changeListeners.get(GENERAL_POOL)) { listenerExecutor.execute(() -> listener.accept(info)); } }
Source:
<code>public static void serialize(ByteBuffer outputBuffer, UpdateRecord updateRecord) { int startOffset = outputBuffer.position(); outputBuffer.putShort(Update_Version_V3); outputBuffer.putShort(updateRecord.getAccountId()); outputBuffer.putShort(updateRecord.getContainerId()); outputBuffer.putLong(updateRecord.getUpdateTimeInMs()); outputBuffer.putShort((short) updateRecord.getType().ordinal()); switch (updateRecord.getType()) { case DELETE: <START> Delete_Format_V1.serialize(outputBuffer, updateRecord.getDeleteRecord()); <END> break; default: throw new IllegalArgumentException("Unknown update record type: " + updateRecord.getType()); } Crc32 crc = new Crc32(); crc.update(outputBuffer.array(), startOffset, getRecordSize(updateRecord.getType()) - Crc_Size); outputBuffer.putLong(crc.getValue()); }</code><technical_language>Call this Delete_SubFormat_V1 something? I initially confused reusing existing Delete_Format_V1</technical_language>

Target:
public static void serialize(ByteBuffer outputBuffer, UpdateRecord updateRecord) { int startOffset = outputBuffer.position(); outputBuffer.putShort(Update_Version_V3); outputBuffer.putShort(updateRecord.getAccountId()); outputBuffer.putShort(updateRecord.getContainerId()); outputBuffer.putLong(updateRecord.getUpdateTimeInMs()); outputBuffer.putShort((short) updateRecord.getType().ordinal()); switch (updateRecord.getType()) { case DELETE: Delete_Sub_Format_V1.serialize(outputBuffer, updateRecord.getDeleteSubRecord()); break; default: throw new IllegalArgumentException("Unknown update record type: " + updateRecord.getType()); } Crc32 crc = new Crc32(); crc.update(outputBuffer.array(), startOffset, getRecordSize(updateRecord.getType()) - Crc_Size); outputBuffer.putLong(crc.getValue()); }
Source:
<code>private static boolean recursiveDeleteDirectoryContent(File file) { if (file.isDirectory()) { File[] contents = file.listFiles(); if (contents.length > 0) { for (File f : contents) { if(!recursiveDelete(f)) { <START> return false; <END> } } } } return true; }</code><technical_language>I abort deletion process if file/folder deleted. store failure in a boolean flag, deletion return flag end of method</technical_language>

Target:
private static boolean recursiveDeleteDirectoryContent(File file) { Boolean deleteSuccessful = true; if (file.isDirectory()) { File[] contents = file.listFiles(); if (contents.length > 0) { for (File f : contents) { if(!recursiveDelete(f)) { deleteSuccessful = false; } } } } return deleteSuccessful; }
Source:
<code>public void transportClientClusterHealth() { try (ElasticsearchContainer container = new ElasticsearchContainer()) { container.start(); TcpHost tcpHost = container.getTcpHost(); TransportAddress transportAddress = new TransportAddress(new InetSocketAddress(tcpHost.getHostname(), tcpHost.getPort())); String expectedClusterName = "docker-cluster"; Settings settings = Settings.builder().put("cluster.name", expectedClusterName).build(); try (TransportClient transportClient = new PreBuiltTransportClient(settings) .addTransportAddress(transportAddress)) { ClusterHealthResponse healths = transportClient.admin().cluster().prepareHealth().get(); String clusterName = healths.getClusterName(); <START> assertThat("Wrong cluster name", CoreMatchers.equalTo(clusterName).matches(expectedClusterName)); <END> } } }</code><technical_language>write like: suggestion assertThat(clusterName, is(expectedClusterName));</technical_language>

Target:
public void transportClientClusterHealth() { try (ElasticsearchContainer container = new ElasticsearchContainer()) { container.start(); TransportAddress transportAddress = new TransportAddress(container.getTcpHost()); String expectedClusterName = "docker-cluster"; Settings settings = Settings.builder().put("cluster.name", expectedClusterName).build(); try (TransportClient transportClient = new PreBuiltTransportClient(settings) .addTransportAddress(transportAddress)) { ClusterHealthResponse healths = transportClient.admin().cluster().prepareHealth().get(); String clusterName = healths.getClusterName(); assertThat(clusterName, is(expectedClusterName)); } } }
Source:
<code>protected RoutesBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:moes") .toD("http://localhost:" + PORT + "/moes?throwExceptionOnFailure=false&drink=${header.drink}"); from("direct:joes") .toD("http://localhost:" + PORT + "/joes?throwExceptionOnFailure=false&drink=${header.drink}"); <START> from("direct:vokda") <END> .setHeader(Exchange.HTTP_PATH, constant("shouldnotcauseproblems")) .setHeader(Exchange.HTTP_QUERY, constant("drink=coke")) .toD("http://localhost:" + PORT + "/joes?throwExceptionOnFailure=false&drink=vodka"); } }; }</code><technical_language>@davsclaus , thanks, desirable feature, small misprint in vodka :smiley:</technical_language>

Target:
protected RoutesBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:moes") .toD("http://localhost:" + PORT + "/moes?throwExceptionOnFailure=false&drink=${header.drink}"); from("direct:joes") .toD("http://localhost:" + PORT + "/joes?throwExceptionOnFailure=false&drink=${header.drink}"); from("direct:vodka") .setHeader(Exchange.HTTP_PATH, constant("shouldnotcauseproblems")) .setHeader(Exchange.HTTP_QUERY, constant("drink=coke")) .toD("http://localhost:" + PORT + "/joes?throwExceptionOnFailure=false&drink=vodka"); } }; }
Source:
<code>public void propertyChange(PropertyChangeEvent event) { <START> if (event.getPropertyName().equals(DisplayResolutionDependentFBOs.PRE_FBO_REGENERATION)) { <END> refractiveReflectiveFbo.detachDepthBuffer(); } else if (event.getPropertyName().equals(DisplayResolutionDependentFBOs.POST_FBO_REGENERATION)) { lastUpdatedGBuffer.attachDepthBufferTo(refractiveReflectiveFbo); } else { if (event.getPropertyName().equals(RenderingConfig.NORMAL_MAPPING)) { normalMappingIsEnabled = renderingConfig.isNormalMapping(); if (normalMappingIsEnabled) { addDesiredStateChange(setTerrainNormalsInputTexture); if (parallaxMappingIsEnabled) { addDesiredStateChange(setTerrainHeightInputTexture); } } else { removeDesiredStateChange(setTerrainNormalsInputTexture); if (parallaxMappingIsEnabled) { removeDesiredStateChange(setTerrainHeightInputTexture); } } } else if (event.getPropertyName().equals(RenderingConfig.PARALLAX_MAPPING)) { parallaxMappingIsEnabled = renderingConfig.isParallaxMapping(); if (normalMappingIsEnabled) { if (parallaxMappingIsEnabled) { addDesiredStateChange(setTerrainHeightInputTexture); } else { removeDesiredStateChange(setTerrainHeightInputTexture); } } } else if (event.getPropertyName().equals(RenderingConfig.ANIMATE_WATER)) { animatedWaterIsEnabled = renderingConfig.isAnimateWater(); } worldRenderer.requestTaskListRefresh(); } }</code><technical_language>1. store getEventPropertyName() in a string reuse that. 2. remove DRSDFBOs string, mentioned earlier, importing constants directly</technical_language>

Target:
public void propertyChange(PropertyChangeEvent event) { String propertyName = event.getPropertyName(); switch (propertyName) { case PRE_FBO_REGENERATION: refractiveReflectiveFbo.detachDepthBuffer(); return; case POST_FBO_REGENERATION: lastUpdatedGBuffer.attachDepthBufferTo(refractiveReflectiveFbo); return; case RenderingConfig.NORMAL_MAPPING: normalMappingIsEnabled = renderingConfig.isNormalMapping(); if (normalMappingIsEnabled) { addDesiredStateChange(setTerrainNormalsInputTexture); if (parallaxMappingIsEnabled) { addDesiredStateChange(setTerrainHeightInputTexture); } } else { removeDesiredStateChange(setTerrainNormalsInputTexture); if (parallaxMappingIsEnabled) { removeDesiredStateChange(setTerrainHeightInputTexture); } } break; case RenderingConfig.PARALLAX_MAPPING: if (normalMappingIsEnabled) { parallaxMappingIsEnabled = renderingConfig.isParallaxMapping(); if (parallaxMappingIsEnabled) { addDesiredStateChange(setTerrainHeightInputTexture); } else { removeDesiredStateChange(setTerrainHeightInputTexture); } } break; case RenderingConfig.ANIMATE_WATER: animatedWaterIsEnabled = renderingConfig.isAnimateWater(); break; } worldRenderer.requestTaskListRefresh(); }
Source:
<code>public static Double sphericalDistance(OGCGeometry leftGeometry, OGCGeometry rightGeometry) { if (leftGeometry.isEmpty() || rightGeometry.isEmpty()) { return null; } <START> validateSphericalType("ST_Distance", leftGeometry, EnumSet.of(POINT)); <END> validateSphericalType("ST_Distance", rightGeometry, EnumSet.of(POINT)); Point leftPoint = (Point) leftGeometry.getEsriGeometry(); Point rightPoint = (Point) rightGeometry.getEsriGeometry(); return greatCircleDistance(leftPoint.getY(), leftPoint.getX(), rightPoint.getY(), rightPoint.getX()) * 1000; }</code><technical_language>Store this enum set a constant</technical_language>

Target:
public static Double sphericalDistance(OGCGeometry leftGeometry, OGCGeometry rightGeometry) { if (leftGeometry.isEmpty() || rightGeometry.isEmpty()) { return null; } validateSphericalType("ST_Distance", leftGeometry, ALLOWED_SPHERICAL_DISTANCE_TYPES); validateSphericalType("ST_Distance", rightGeometry, ALLOWED_SPHERICAL_DISTANCE_TYPES); Point leftPoint = (Point) leftGeometry.getEsriGeometry(); Point rightPoint = (Point) rightGeometry.getEsriGeometry(); return greatCircleDistance(leftPoint.getY(), leftPoint.getX(), rightPoint.getY(), rightPoint.getX()) * 1000; }
Source:
<code>static void setup() { <START> <END> packages.add("symfony/polyfill-mbstring"); packages.add("psr/log"); packages.add("symfony/polyfill-ctype"); packages.add("guzzlehttp/psr7"); }</code><technical_language>Cosmetic: empty lines over. sens put empty line a logical block stand out, in this case, a bit much. mind removing (here in other method)? Thanks! :)</technical_language>

Target:
static void setup() { packages.add("symfony/polyfill-mbstring"); packages.add("symfony/polyfill-ctype"); packages.add("guzzlehttp/psr7/library"); packages.add("psr/log"); packages.add("symfony/console"); packages.add("symfony/event-dispatcher/1.2.4-dev/library"); packages.add("symfony/finder"); packages.add("symfony/debug"); packages.add("doctrine/instantiator"); packages.add("symfony/process/v1.3.5-p"); packages.add("psr/http-message"); packages.add("magicbart/zf2-log/library"); packages.add("phpbe/ui-category-tree"); packages.add("zhilayun/bbc/v1.4.6"); packages.add("abdulmatinsanni/api-x"); packages.add("gesagtgetan/krakenoptimizer"); packages.add("razielsd/beanstalk-logger"); packages.add("vargas/translate-bundle/composer-plugin"); packages.add("pidsolutions/logger/project"); packages.add("pidsolutions/request"); packages.add("pidsolutions/i18n"); }
Source:
<code>public long extractTimestamp(Tuple tuple) { StreamlineEvent event = (StreamlineEvent) tuple.getValueByField(StreamlineEvent.STREAMLINE_EVENT); Object ts = event.get(fieldName); if (ts == null) { throw new IllegalArgumentException("Streamline event does not contain field: " + fieldName); } <START> if (!(ts instanceof Number)) { <END> throw new IllegalArgumentException("Streamline event does not contain a long value in field: " + fieldName); } return ((Number) ts).longValue(); }</code><technical_language>timestamp "milliseconds January 1, 1970 UTC", putting values other long (byte, short, int) represent dates Jan 1970. IMO, retain instanceof Long explicitly state Streamline event a long in field in exception. a case customer passing seconds (instead of millis) in a long field causing issues. great if catch also. E.g. If is 2 Billion log a WARNING</technical_language>

Target:
public long extractTimestamp(Tuple tuple) { StreamlineEvent event = (StreamlineEvent) tuple.getValueByField(StreamlineEvent.STREAMLINE_EVENT); Object ts = event.get(fieldName); if (ts == null || !(ts instanceof Long)) { throw new IllegalArgumentException("Streamline event does not contain a long value in field: " + fieldName); } return (long) ts; }
Source:
<code>public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); FailureCollector collector = pipelineConfigurer.getStageConfigurer().getFailureCollector(); if (!S3_LOG.equals(config.logFormat) && !CLF_LOG.equals(config.logFormat) && !CLOUDFRONT_LOG.equals(config.logFormat)) { LOG.error("Log format not currently supported."); <START> collector.addFailure(String.format("Unsupported log format: '%s'", config.logFormat), <END> "Log format must be one of the following: S3, CLF, or CLOUDFRONT.").withConfigProperty("logFormat"); } Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { if (!inputSchema.getType().equals(Schema.Type.RECORD)) { collector.addFailure("Only Input Schema of type Schema.Type.RECORD is supported", "Input Schema type should be of type Schema.Type.RECORD"); } Schema.Field inputNameSchema = inputSchema.getField(config.inputName); if (inputNameSchema == null) { collector.addFailure(String.format("Field '%s' is not present in the input schema", config.inputName), String.format("The field '%s' must be provided", config.inputName)) .withConfigProperty("inputName").withInputSchemaField(config.inputName); } else { validateInputSchemaType(inputNameSchema.getSchema().getType(), collector); } } pipelineConfigurer.getStageConfigurer().setOutputSchema(LOG_SCHEMA); }</code><technical_language>error : Format '%s' is supported. corrective action : Supported formats are: %s</technical_language>

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); FailureCollector collector = pipelineConfigurer.getStageConfigurer().getFailureCollector(); if (!S3_LOG.equals(config.logFormat) && !CLF_LOG.equals(config.logFormat) && !CLOUDFRONT_LOG.equals(config.logFormat)) { LOG.error("Log format not currently supported."); collector.addFailure(String.format("Format '%s' is not supported.", config.logFormat), String.format("Supported formats are: %s, %s, and %s.", S3_LOG, CLF_LOG, CLOUDFRONT_LOG)) .withConfigProperty(LOG_FORMAT); } Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { if (!inputSchema.getType().equals(Schema.Type.RECORD)) { collector.addFailure("Input schema must be of type record.", null); } else { Schema.Field inputNameSchema = inputSchema.getField(config.inputName); if (inputNameSchema == null) { collector.addFailure( String.format("Field '%s' must be present in the input schema.", config.inputName), null) .withConfigProperty(INPUT_NAME); } else { Schema schema = inputNameSchema.getSchema(); if (schema.isNullable()) { schema = schema.getNonNullable(); } validateInputSchemaType(schema, config.inputName, collector); } } } pipelineConfigurer.getStageConfigurer().setOutputSchema(LOG_SCHEMA); }
Source:
<code><START> public String toString() { <END> return "SubchainInfo [" + "storageDomainId=" + storageDomainId + ", imageGroupId=" + imageGroupId + ", baseImageId=" + baseImageId + ", topImageId=" + topImageId + ']'; }</code><technical_language>Please ToStringBuilder.forInstance(this) .append("id", id) .append("name", name) .append("extra_specs", extraSpecs) .build(); yes, need change locationinfo class :)</technical_language>

Target:
public String toString() { return ToStringBuilder.forInstance(this) .append("storageDomainId", storageDomainId) .append("imageGroupId", imageGroupId) .append("baseImageId", baseImageId) .append("topImageId", topImageId) .build(); }
Source:
<code>PeerEurekaNode(PeerAwareInstanceRegistry registry, String targetHost, String serviceUrl, HttpReplicationClient replicationClient, EurekaServerConfig config, int batchSize, long maxBatchingDelayMs, long retrySleepTimeMs, long serverUnavailableSleepTimeMs) { this.registry = registry; this.targetHost = targetHost; this.replicationClient = replicationClient; this.serviceUrl = serviceUrl; this.config = config; this.maxProcessingDelayMs = config.getMaxTimeForReplication(); String batcherName = getBatcherName(); ReplicationTaskProcessor taskProcessor = new ReplicationTaskProcessor(targetHost, replicationClient); this.batchingDispatcher = TaskDispatchers.createBatchingTaskDispatcher( batcherName, config.getMaxElementsInPeerReplicationPool(), batchSize, config.getMaxThreadsForPeerReplication(), maxBatchingDelayMs, serverUnavailableSleepTimeMs, retrySleepTimeMs, taskProcessor ); this.nonBatchingDispatcher = TaskDispatchers.createNonBatchingTaskDispatcher( targetHost, config.getMaxElementsInStatusReplicationPool(), config.getMaxThreadsForStatusReplication(), <START> MAX_BATCHING_DELAY_MS, <END> serverUnavailableSleepTimeMs, retrySleepTimeMs, taskProcessor ); }</code><technical_language>static configurable value</technical_language>

Target:
PeerEurekaNode(PeerAwareInstanceRegistry registry, String targetHost, String serviceUrl, HttpReplicationClient replicationClient, EurekaServerConfig config, int batchSize, long maxBatchingDelayMs, long retrySleepTimeMs, long serverUnavailableSleepTimeMs) { this.registry = registry; this.targetHost = targetHost; this.replicationClient = replicationClient; this.serviceUrl = serviceUrl; this.config = config; this.maxProcessingDelayMs = config.getMaxTimeForReplication(); String batcherName = getBatcherName(); ReplicationTaskProcessor taskProcessor = new ReplicationTaskProcessor(targetHost, replicationClient); this.batchingDispatcher = TaskDispatchers.createBatchingTaskDispatcher( batcherName, config.getMaxElementsInPeerReplicationPool(), batchSize, config.getMaxThreadsForPeerReplication(), maxBatchingDelayMs, serverUnavailableSleepTimeMs, retrySleepTimeMs, taskProcessor ); this.nonBatchingDispatcher = TaskDispatchers.createNonBatchingTaskDispatcher( targetHost, config.getMaxElementsInStatusReplicationPool(), config.getMaxThreadsForStatusReplication(), maxBatchingDelayMs, serverUnavailableSleepTimeMs, retrySleepTimeMs, taskProcessor ); }
Source:
<code>public static Optional<SortExpressionContext> extractSortExpression(Set<Symbol> buildSymbols, Expression filter) { if (!DeterminismEvaluator.isDeterministic(filter)) { return Optional.empty(); } List<Expression> filterConjuncts = ExpressionUtils.extractConjuncts(filter); SortExpressionVisitor visitor = new SortExpressionVisitor(buildSymbols); List<SortExpressionContext> sortExpressionCandidates = filterConjuncts.stream() .map(visitor::process) .filter(Optional::isPresent) .map(Optional::get) .collect(groupingBy(SortExpressionContext::getSortExpression, reducing(SortExpressionExtractor::merge))) .values() .stream() <START> .map(Optional::get) <END> .collect(toImmutableList()); return sortExpressionCandidates .stream() .sorted(comparing(context -> -context.getSearchExpressions().size())) .findFirst(); }</code><technical_language>This suspicious: call Optional.get .ifPresent. avoid misleading Optional-s, if replace .collect(groupingBy(...)) .collect(toMap(SortExpressionContext::getSortExpression, c->c, SortExpressionExtractor::merge)</technical_language>

Target:
public static Optional<SortExpressionContext> extractSortExpression(Set<Symbol> buildSymbols, Expression filter) { List<Expression> filterConjuncts = ExpressionUtils.extractConjuncts(filter); SortExpressionVisitor visitor = new SortExpressionVisitor(buildSymbols); List<SortExpressionContext> sortExpressionCandidates = filterConjuncts.stream() .filter(DeterminismEvaluator::isDeterministic) .map(visitor::process) .filter(Optional::isPresent) .map(Optional::get) .collect(toMap(SortExpressionContext::getSortExpression, identity(), SortExpressionExtractor::merge)) .values() .stream() .collect(toImmutableList()); return sortExpressionCandidates.stream() .sorted(comparing(context -> -1 * context.getSearchExpressions().size())) .findFirst(); }
Source:
<code>public void setBaseUri(String baseUri) { this.baseUri = baseUri; <START> } <END></code><technical_language>add this.endpoint.setBaseUri(baseUri)</technical_language>

Target:
public void setBaseUri(String baseUri) { this.baseUri = baseUri; this.endpoint.setUri(baseUri); }
Source:
<code>public void simpleMoveTest() { String[] inputFile = { "0a", "00" }; runs = new Run[] { move(0), checkPitch(inputFile), move(1), checkPitch(new String[] { <START> "03", <END> "0a" }), move(1), checkPitch(new String[] { "03", "a3" }), move(1), checkPitch(new String[] { "a3", "33" }), move(1), checkPitch(new String[] { "3a", "33" }), move(4), checkPitch(inputFile), quit() }; sessionTest(runs, Input.getFile(inputFile), "rule=90-90-90-90-90"); }</code><technical_language>Yeah, sheet is confusing (how mixes "Zug" "Schritt" etc.). Praktomat's lazyAnt sportyAnt tests succeed interpretation? I replicate interpretation, tests fail for (all others succeed)</technical_language>

Target:
public void simpleMoveTest() { String[] inputFile = { "0a", "00" }; runs = new Run[] { move(0), checkPitch(inputFile), move(1), checkPitch(new String[] { "00", "0a" }), move(1), checkPitch(new String[] { "00", "a3" }), move(1), checkPitch(new String[] { "a0", "33" }), move(1), checkPitch(new String[] { "3a", "33" }), move(4), checkPitch(inputFile), quit() }; sessionTest(runs, Input.getFile(inputFile), "rule=90-90-90-90-90"); }
Source:
<code>public List<Proxy> select(URI uri) { <START> return (nonProxyHostsPattern == null || !nonProxyHostsPattern.matcher(uri.getHost()).find()) <END> ? Collections.singletonList(new Proxy(proxyType, proxyAddress)) : null; }</code><technical_language>change partial match instead of string match</technical_language>

Target:
public List<Proxy> select(URI uri) { return (nonProxyHostsPattern == null || !nonProxyHostsPattern.matcher(uri.getHost()).matches()) ? Collections.singletonList(new Proxy(proxyType, proxyAddress)) : null; }
Source:
<code>public void recalculateJobStates(CuratorFramework client, PathChildrenCache jobDeployments) throws Exception { for (Iterator<String> iterator = new ChildPathIterator<String>(deploymentNameConverter, jobDeployments); <START> iterator.hasNext();) { <END> String jobName = iterator.next(); Job job = deploymentLoader.loadJob(client, jobName, jobFactory); if (job != null) { String jobModulesPath = Paths.build(Paths.JOB_DEPLOYMENTS, jobName); List<ModuleDeploymentStatus> statusList = new ArrayList<ModuleDeploymentStatus>(); List<String> moduleDeployments = client.getChildren().forPath(jobModulesPath); for (String moduleDeployment : moduleDeployments) { JobDeploymentsPath jobDeploymentsPath = new JobDeploymentsPath( Paths.build(jobModulesPath, moduleDeployment)); statusList.add(new ModuleDeploymentStatus( jobDeploymentsPath.getContainer(), new ModuleDescriptor.Key(jobName, ModuleType.job, jobDeploymentsPath.getModuleLabel()), ModuleDeploymentStatus.State.deployed, null)); } DeploymentUnitStatus status = stateCalculator.calculate(job, new JobModuleDeploymentPropertiesProvider(job), statusList); logger.info("Deployment state for job: {}", status); String statusPath = Paths.build(Paths.JOB_DEPLOYMENTS, job.getName(), Paths.STATUS); if (client.checkExists().forPath(statusPath) != null) { client.delete().forPath(statusPath); } client.create().withMode(CreateMode.EPHEMERAL).forPath(statusPath, ZooKeeperUtils.mapToBytes(status.toMap())); } } }</code><technical_language>whitespace suspicious</technical_language>

Target:
public void recalculateJobStates(CuratorFramework client, PathChildrenCache jobDeployments) throws Exception { for (Iterator<String> iterator = new ChildPathIterator<String>(deploymentNameConverter, jobDeployments); iterator.hasNext();) { String jobName = iterator.next(); Job job = deploymentLoader.loadJob(client, jobName, jobFactory); if (job != null) { String jobModulesPath = Paths.build(Paths.JOB_DEPLOYMENTS, jobName); List<ModuleDeploymentStatus> statusList = new ArrayList<ModuleDeploymentStatus>(); List<String> moduleDeployments = client.getChildren().forPath(jobModulesPath); for (String moduleDeployment : moduleDeployments) { JobDeploymentsPath jobDeploymentsPath = new JobDeploymentsPath( Paths.build(jobModulesPath, moduleDeployment)); statusList.add(new ModuleDeploymentStatus( jobDeploymentsPath.getContainer(), new ModuleDescriptor.Key(jobName, ModuleType.job, jobDeploymentsPath.getModuleLabel()), ModuleDeploymentStatus.State.deployed, null)); } DeploymentUnitStatus status = stateCalculator.calculate(job, new JobModuleDeploymentPropertiesProvider(job), statusList); logger.info("Deployment status for job '{}': {}", job.getName(), status); String statusPath = Paths.build(Paths.JOB_DEPLOYMENTS, job.getName(), Paths.STATUS); Stat stat = client.checkExists().forPath(statusPath); if (stat != null) { logger.warn("Found unexpected path {}; stat: {}", statusPath, stat); client.delete().forPath(statusPath); } client.create().withMode(CreateMode.EPHEMERAL).forPath(statusPath, ZooKeeperUtils.mapToBytes(status.toMap())); } } }
Source:
<code>private void doRuntimeExceptionRouterTest(RestMethod restMethod) throws Exception { RestRequest restRequest = createRestRequest(restMethod, "/", null, null); RestResponseChannel restResponseChannel = new MockRestResponseChannel(); try { switch (restMethod) { case GET: case DELETE: case HEAD: doOperation(restRequest, restResponseChannel); fail(restMethod + " should have detected a RestServiceException because of a bad router"); break; case POST: JSONObject headers = new JSONObject(); setAmbryHeaders(headers, 0, Utils.Infinite_Time, false, "test-serviceID", "text/plain", "test-ownerId"); restRequest = createRestRequest(restMethod, "/", headers, null); doOperation(restRequest, restResponseChannel); fail("POST should have detected a RestServiceException because of a bad router"); break; case PUT: <START> headers = new JSONObject(); <END> setAmbryHeaders(headers, 0, Utils.Infinite_Time, false, "test-serviceID", "text/plain", "test-ownerId"); restRequest = createRestRequest(restMethod, "/", headers, null); try { doOperation(restRequest, restResponseChannel); } catch (RestServiceException e) { assertEquals("Unexpected error message", "PUT is not supported", e.getMessage()); } break; default: throw new IllegalArgumentException("Unrecognized RestMethod: " + restMethod); } } catch (RuntimeException e) { assertEquals("Unexpected error message", InMemoryRouter.OPERATION_THROW_EARLY_RUNTIME_EXCEPTION, e.getMessage()); } }</code><technical_language>this is required PUT reach router</technical_language>

Target:
private void doRuntimeExceptionRouterTest(RestMethod restMethod) throws Exception { RestRequest restRequest = createRestRequest(restMethod, "/", null, null); RestResponseChannel restResponseChannel = new MockRestResponseChannel(); try { switch (restMethod) { case GET: case DELETE: case HEAD: doOperation(restRequest, restResponseChannel); fail(restMethod + " should have detected a RestServiceException because of a bad router"); break; case POST: JSONObject headers = new JSONObject(); setAmbryHeaders(headers, 0, Utils.Infinite_Time, false, "test-serviceID", "text/plain", "test-ownerId"); restRequest = createRestRequest(restMethod, "/", headers, null); doOperation(restRequest, restResponseChannel); fail("POST should have detected a RestServiceException because of a bad router"); break; default: throw new IllegalArgumentException("Unrecognized RestMethod: " + restMethod); } } catch (RuntimeException e) { assertEquals("Unexpected error message", InMemoryRouter.OPERATION_THROW_EARLY_RUNTIME_EXCEPTION, e.getMessage()); } }