auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String getCountryNameFromCode(@NonNull String countryCode) { <START> return new Locale("", countryCode).getDisplayCountry(); <END> }</code><technical_language>builder normalized validated input; want port logic</technical_language>

Target:
public static String getCountryNameFromCode(@NonNull String countryCode) throws InvalidLocaleException { final String uppercaseRegion = countryCode.toUpperCase(Locale.ROOT); if (!isValidBcp47Alpha(uppercaseRegion, 2, 2)) { throw new InvalidLocaleException("Invalid region: " + countryCode); } return new Locale("", countryCode).getDisplayCountry(); }
Source:
<code><START> public void disableOkButton() { <END> modal.disableOkButton(); }</code><technical_language>I this package-private: suggestion void disableOkButton() {</technical_language>

Target:
void disableOkButton() { modal.disableOkButton(); }
Source:
<code>public ItemsWrapper<SubscriptionEventTypeStats> getSubscriptionStats( @PathVariable("id") final String subscriptionId, @RequestParam(value = "show_time_lag", required = false, defaultValue = "false") final boolean showTimeLag, final HttpServletRequest request) throws InconsistentStateException, NoSuchEventTypeException, NoSuchSubscriptionException, ServiceTemporarilyUnavailableException { final Span statsSpan = TracingService.extractSpan(request, "fetch_stats") .setTag("subscription_id", subscriptionId) <START> .setTag("time_lag", showTimeLag); <END> final StatsMode statsMode = showTimeLag ? StatsMode.TIMELAG : StatsMode.NORMAL; return subscriptionService.getSubscriptionStat(subscriptionId, statsMode, statsSpan); }</code><technical_language>I time_lag renamed show_time_lag</technical_language>

Target:
public ItemsWrapper<SubscriptionEventTypeStats> getSubscriptionStats( @PathVariable("id") final String subscriptionId, @RequestParam(value = "show_time_lag", required = false, defaultValue = "false") final boolean showTimeLag, final HttpServletRequest request) throws InconsistentStateException, NoSuchEventTypeException, NoSuchSubscriptionException, ServiceTemporarilyUnavailableException { final Span statsSpan = TracingService.extractSpan(request, "fetch_stats") .setTag("subscription_id", subscriptionId) .setTag("show_time_lag", showTimeLag); final StatsMode statsMode = showTimeLag ? StatsMode.TIMELAG : StatsMode.NORMAL; return subscriptionService.getSubscriptionStat(subscriptionId, statsMode, statsSpan); }
Source:
<code>public void onDestroy() { StatisticsService.sessionPause(); <START> StatisticsService.sessionStop(this); <END> super.onDestroy(); }</code><technical_language>sessionPause sessionStop together</technical_language>

Target:
public void onDestroy() { StatisticsService.sessionStop(this); super.onDestroy(); }
Source:
<code>private void onDomRetrieved(String dom) { webView.loadDataWithBaseURL( wikiUrl, <START> "<head>".concat(Wiki.getGlobalCustomCss()).concat("</head>").concat(StringEscapeUtils.unescapeHtml4(dom)), <END> "text/html", "utf-8", null); }</code><technical_language>For super huge wikis, majority of execution time is spent in unescapeHtml4, moving call WikiAsyncTask doInBackground completely alleviate main thread blocking</technical_language>

Target:
private void onDomRetrieved(String dom) { webView.loadDataWithBaseURL( wikiUrl, "<head>".concat(Wiki.getGlobalCustomCss()).concat("</head>").concat(dom), "text/html", "utf-8", null); }
Source:
<code>public AnonymousClassDeclarationContext(ObjectCreationExpr node, TypeSolver typeSolver) { super(node, typeSolver); Preconditions.checkArgument(node.getAnonymousClassBody().isPresent(), <START> "An anonymous class must have a body present"); <END> }</code><technical_language>"An anonymous class body present" "An anonymous class a body"</technical_language>

Target:
public AnonymousClassDeclarationContext(ObjectCreationExpr node, TypeSolver typeSolver) { super(node, typeSolver); Preconditions.checkArgument(node.getAnonymousClassBody().isPresent(), "An anonymous class must have a body"); }
Source:
<code>protected String buildAuthorizationHeaderString() { <START> return "Token " + paymentworksAuthorizationToken; <END> }</code><technical_language>this string literal a constant</technical_language>

Target:
protected String buildAuthorizationHeaderString() { return PaymentWorksConstants.TOKEN_HEADER_KEY + paymentworksAuthorizationToken; }
Source:
<code>public static void main(String args[]) throws DocumentException { Options options = new Options(); <START> options.addOption("h", false, "displays help"); <END> options.addOption("a", "addModule", true, "adds module to pom.xml in openmrs-project"); Option o = options.getOption("a"); o.setArgName("path"); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); if (cmd.hasOption('h')) { usage(options); } if (cmd.hasOption('a')) { String filePath = cmd.getOptionValue('a'); if (filePath == null) System.out.println("File Path missing."); else addModule(filePath); } } catch (ParseException e) { usage(options); } }</code><technical_language>long name "help"</technical_language>

Target:
public static void main(String args[]) throws DocumentException { Options options = new Options(); options.addOption("h", "help", false, "displays help"); options.addOption("a", "addModule", true, "adds module to pom.xml in openmrs-project"); Option o = options.getOption("a"); o.setArgName("path"); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); if (cmd.hasOption('h') | cmd.hasOption("help")) { usage(options); } if (cmd.hasOption('a') | cmd.hasOption("addModule")) { String filePath = cmd.getOptionValue('a'); if (filePath == null) info("File Path missing."); else addModule(filePath); } } catch (ParseException e) { usage(options); } }
Source:
<code>private GlusterBrickEntity getBrick(Guid clusterId, Guid volumeId, String brickInfo, int brickOrder) { String[] brickParts = brickInfo.split(":", -1); if (brickParts.length != 2) { throw new RuntimeException("Invalid brick representation [" + brickInfo + "]"); } String hostnameOrIp = brickParts[0]; String brickDir = brickParts[1]; VdsStatic server = dbUtils.getServer(clusterId, hostnameOrIp); if (server == null) { <START> log.errorFormat("Could not add brick {0} to volume {1} - server {2} not found in cluster {3}", brickInfo, volumeId, hostnameOrIp, clusterId); <END> return null; } return getBrickEntity(clusterId, volumeId, brickOrder, server, brickDir); }</code><technical_language>this WARN</technical_language>

Target:
private GlusterBrickEntity getBrick(Guid clusterId, Guid volumeId, String brickInfo, int brickOrder) { String[] brickParts = brickInfo.split(":", -1); if (brickParts.length != 2) { throw new RuntimeException("Invalid brick representation [" + brickInfo + "]"); } String hostnameOrIp = brickParts[0]; String brickDir = brickParts[1]; VdsStatic server = dbUtils.getServer(clusterId, hostnameOrIp); if (server == null) { log.warnFormat("Could not add brick {0} to volume {1} - server {2} not found in cluster {3}", brickInfo, volumeId, hostnameOrIp, clusterId); return null; } return getBrickEntity(clusterId, volumeId, brickOrder, server, brickDir); }
Source:
<code>public Optional<Config.ConfigProvider> create() { JsonNode node = null; try { String configDir = System.getProperty("jboss.server.config.dir"); <START> if (node == null && configDir != null) { <END> File f = new File(configDir + File.separator + "keycloak-server.json"); if (f.isFile()) { ServicesLogger.LOGGER.loadingFrom(f.getAbsolutePath()); node = new ObjectMapper().readTree(f); } } if (node == null) { URL resource = Thread.currentThread().getContextClassLoader().getResource("META-INF/keycloak-server.json"); if (resource != null) { ServicesLogger.LOGGER.loadingFrom(resource); node = new ObjectMapper().readTree(resource); } } } catch (IOException e) { LOG.warn("Failed to load JSON config", e); } return createJsonProvider(node); }</code><technical_language>I this already, node == null redundant here</technical_language>

Target:
public Optional<Config.ConfigProvider> create() { JsonNode node = null; try { String configDir = System.getProperty("jboss.server.config.dir"); if (configDir != null) { File f = new File(configDir + File.separator + "keycloak-server.json"); if (f.isFile()) { ServicesLogger.LOGGER.loadingFrom(f.getAbsolutePath()); node = JsonSerialization.mapper.readTree(f); } } if (node == null) { URL resource = Thread.currentThread().getContextClassLoader().getResource("META-INF/keycloak-server.json"); if (resource != null) { ServicesLogger.LOGGER.loadingFrom(resource); node = JsonSerialization.mapper.readTree(resource); } } } catch (IOException e) { LOG.warn("Failed to load JSON config", e); } return createJsonProvider(node); }
Source:
<code>protected List<VariantContext> getVCsAtThisLocation(final List<Haplotype> haplotypes, final int loc, final List<VariantContext> activeAllelesToGenotype) { final List<VariantContext> eventsAtThisLoc = new ArrayList<>(); if( activeAllelesToGenotype.isEmpty() ) { haplotypes.stream().map(h -> h.getEventMap().get(loc)) <START> .filter(vc -> vc != null && eventsAtThisLoc.stream().noneMatch(vc::hasSameAllelesAs)) <END> .forEach(eventsAtThisLoc::add); } else { int compCount = 0; for( final VariantContext compVC : activeAllelesToGenotype ) { if( compVC.getStart() == loc ) { int alleleCount = 0; for( final Allele compAltAllele : compVC.getAlternateAlleles() ) { final List<Allele> alleleSet = Arrays.asList(compVC.getReference(), compAltAllele); final String vcSourceName = "Comp" + compCount + "Allele" + alleleCount; final VariantContext candidateEventToAdd = new VariantContextBuilder(compVC).alleles(alleleSet).source(vcSourceName).make(); if (eventsAtThisLoc.stream().noneMatch(vc -> vc.hasSameAllelesAs(candidateEventToAdd))) { eventsAtThisLoc.add(candidateEventToAdd); } alleleCount++; } } compCount++; } } return eventsAtThisLoc; }</code><technical_language>I new code eventsAtThisLoc empty filter(), (with for loop) eventsAtThisLoc updated dynamically</technical_language>

Target:
protected List<VariantContext> getVCsAtThisLocation(final List<Haplotype> haplotypes, final int loc, final List<VariantContext> activeAllelesToGenotype) { final List<VariantContext> eventsAtThisLoc = new ArrayList<>(); if( activeAllelesToGenotype.isEmpty() ) { final List<VariantContext> events = haplotypes.stream().map(h -> h.getEventMap().get(loc)) .filter(Objects::nonNull).collect(Collectors.toList()); for (final VariantContext vc : events) { if (eventsAtThisLoc.stream().noneMatch(vc::hasSameAllelesAs)) { eventsAtThisLoc.add(vc); } } } else { int compCount = 0; for( final VariantContext compVC : activeAllelesToGenotype ) { if( compVC.getStart() == loc ) { int alleleCount = 0; for( final Allele compAltAllele : compVC.getAlternateAlleles() ) { final List<Allele> alleleSet = Arrays.asList(compVC.getReference(), compAltAllele); final String vcSourceName = "Comp" + compCount + "Allele" + alleleCount; final VariantContext candidateEventToAdd = new VariantContextBuilder(compVC).alleles(alleleSet).source(vcSourceName).make(); if (eventsAtThisLoc.stream().noneMatch(candidateEventToAdd::hasSameAllelesAs)) { eventsAtThisLoc.add(candidateEventToAdd); } alleleCount++; } } compCount++; } } return eventsAtThisLoc; }
Source:
<code>public void handle(CacheRpcCommand command, Reply reply, DeliverOrder order) { if (order == DeliverOrder.TOTAL) { unexpectedDeliverMode(command, order); } try { final int commandTopologyId = extractCommandTopologyId(command); final boolean onExecutorService = executeOnExecutorService(order, command); final BlockingRunnable runnable; switch (command.getCommandId()) { case SingleRpcCommand.COMMAND_ID: <START> if (isCommandSentBeforeFirstTopology(commandTopologyId)) { <END> reply.reply(CacheNotFoundResponse.INSTANCE); return; } runnable = createLockAwareRunnable(command, reply, commandTopologyId, true, onExecutorService, getLockPromise((SingleRpcCommand) command)); break; case MultipleRpcCommand.COMMAND_ID: if (isCommandSentBeforeFirstTopology(commandTopologyId)) { reply.reply(CacheNotFoundResponse.INSTANCE); return; } runnable = createLockAwareRunnable(command, reply, commandTopologyId, true, onExecutorService, getLockPromise((MultipleRpcCommand) command)); break; default: runnable = createDefaultRunnable(command, reply, commandTopologyId, command.getCommandId() != StateRequestCommand.COMMAND_ID, onExecutorService); break; } handleRunnable(runnable, onExecutorService); } catch (Throwable throwable) { reply.reply(exceptionHandlingCommand(command, throwable)); } }</code><technical_language>I problem of checking topology of command topology potentially topology set (so Integer.MAX_VALUE)</technical_language>

Target:
public void handle(CacheRpcCommand command, Reply reply, DeliverOrder order) { if (order == DeliverOrder.TOTAL) { unexpectedDeliverMode(command, order); } try { final int commandTopologyId = extractCommandTopologyId(command); final boolean onExecutorService = executeOnExecutorService(order, command); final BlockingRunnable runnable; switch (command.getCommandId()) { case SingleRpcCommand.COMMAND_ID: runnable = createReadyActionRunnable(command, reply, commandTopologyId, true, onExecutorService, createReadyActionForSingleRpcCommand(commandTopologyId, (SingleRpcCommand) command)); break; case MultipleRpcCommand.COMMAND_ID: runnable = createReadyActionRunnable(command, reply, commandTopologyId, true, onExecutorService, createReadyActionForMultipleRpcCommand(commandTopologyId, (MultipleRpcCommand) command)); break; default: runnable = createDefaultRunnable(command, reply, commandTopologyId, command.getCommandId() != StateRequestCommand.COMMAND_ID, onExecutorService); break; } handleRunnable(runnable, onExecutorService); } catch (Throwable throwable) { reply.reply(exceptionHandlingCommand(command, throwable)); } }
Source:
<code>public static BookingGridSettings changeLookupForScreening(BookingGridSettings settings) throws IOException { Map<String, Object> fieldsMap = new HashMap<>(); DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); DateFilter defaultDateFilter = DateFilter.TODAY; if (StringUtils.isBlank(settings.getFields())) { settings.setFields("{}"); } if (StringUtils.isBlank(settings.getLookup())) { settings.setLookup("Find By Date"); } else { String fields = settings.getFields(); fieldsMap = OBJECT_MAPPER.readValue(fields, new TypeReference<HashMap>() {}); if (settings.getLookup().equals("Find By Volunteer Name")) { settings.setLookup("Find By Date And Volunteer Name"); } else { settings.setLookup("Find By Date And Clinic Location"); } } <START> if (settings.getDateFilter() != null) { <END> defaultDateFilter = settings.getDateFilter(); } Map<String, String> dateRange = new HashMap<>(); if (defaultDateFilter == DateFilter.DATE_RANGE) { if (StringUtils.isNotBlank(settings.getStartDate())) { dateRange.put("min", settings.getStartDate()); } else { dateRange.put("min", ""); } if (StringUtils.isNotBlank(settings.getEndDate())) { dateRange.put("max", settings.getEndDate()); } else { dateRange.put("max", ""); } } else if(defaultDateFilter == DateFilter.TODAY) { dateRange.put("min", LocalDate.now().toString(formatter)); dateRange.put("max", LocalDate.now().toString(formatter)); } else if(defaultDateFilter == DateFilter.TOMORROW) { dateRange.put("min", LocalDate.now().plusDays(1).toString(formatter)); dateRange.put("max", LocalDate.now().plusDays(1).toString(formatter)); } else { dateRange.put("min", settings.getStartDate()); dateRange.put("max", LocalDate.now().plusDays(7).toString(formatter)); } fieldsMap.put(Screening.DATE_PROPERTY_NAME, dateRange); settings.setFields(OBJECT_MAPPER.writeValueAsString(fieldsMap)); return settings; }</code><technical_language>code in this condition, right if select filter checkbox default filter added</technical_language>

Target:
public static BookingGridSettings changeLookupForScreening(BookingGridSettings settings) throws IOException { Map<String, Object> fieldsMap = new HashMap<>(); DateFilter dateFilter = settings.getDateFilter(); if (dateFilter != null) { if (StringUtils.isBlank(settings.getFields())) { settings.setFields("{}"); } if (StringUtils.isBlank(settings.getLookup())) { settings.setLookup("Find By Date"); } else { fieldsMap = getFields(settings.getFields()); settings.setLookup(settings.getLookup() + " And Date"); } Map<String, String> rangeMap = new HashMap<>(); if (DateFilter.DATE_RANGE.equals(dateFilter)) { rangeMap.put("min", settings.getStartDate()); rangeMap.put("max", settings.getEndDate()); } else { Range<LocalDate> dateRange = dateFilter.getRange(); rangeMap.put("min", dateRange.getMin().toString(BookingAppConstants.SIMPLE_DATE_FORMAT)); rangeMap.put("max", dateRange.getMax().toString(BookingAppConstants.SIMPLE_DATE_FORMAT)); } fieldsMap.put(Screening.DATE_PROPERTY_NAME, rangeMap); settings.setFields(OBJECT_MAPPER.writeValueAsString(fieldsMap)); } return settings; }
Source:
<code>private static CustomXmlTraceDefinition lookupXmlDefinition(String definitionName, DocumentBuilder db, String source) throws SAXException, IOException { <START> File file = new File(source); <END> Document doc = db.parse(file); Element root = doc.getDocumentElement(); if (!root.getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) { return null; } NodeList nodeList = root.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element && node.getNodeName().equals(DEFINITION_ELEMENT) && definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) { return extractDefinition((Element) node); } } return null; }</code><technical_language>I need add file.exists() check</technical_language>

Target:
private static CustomXmlTraceDefinition lookupXmlDefinition(String definitionName, DocumentBuilder db, String source) throws SAXException, IOException { File file = new File(source); if( !file.exists()){ return null; } Document doc = db.parse(file); Element root = doc.getDocumentElement(); if (!root.getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) { return null; } NodeList nodeList = root.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element && node.getNodeName().equals(DEFINITION_ELEMENT) && definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) { return extractDefinition((Element) node); } } return null; }
Source:
<code>public static void injectResources() { Configuration.addDefaultResource(azkabanInjectFile); Configuration.addDefaultResource(azkabanLinksFile); <START> } <END></code><technical_language>extra space in front of }</technical_language>

Target:
public static void injectResources() { Configuration.addDefaultResource(injectFile); }
Source:
<code><START> public void onOffline(@Nonnull Computer computer, @CheckForNull OfflineCause cause) { <END> try { final boolean emitSystemEvents = DatadogUtilities.getDatadogGlobalDescriptor().isEmitSystemEvents(); if (!emitSystemEvents) { return; } logger.fine("Start DatadogComputerListener#onOffline"); DatadogClient client = DatadogUtilities.getDatadogClient(); Map<String, Set<String>> tags = TagsUtil.merge( DatadogUtilities.getDatadogGlobalDescriptor().getGlobalTags(), DatadogUtilities.getComputerTags(computer)); DatadogEvent event = new ComputerOfflineEventImpl(computer, cause, tags, false); client.sendEvent(event.createPayload()); String hostname = DatadogUtilities.getHostname("null"); client.incrementCounter("jenkins.computer.offline", hostname, tags); logger.fine("End DatadogComputerListener#onOffline"); } catch (Exception e) { logger.warning("Unexpected exception occurred - " + e.getMessage()); } }</code><technical_language>annotations</technical_language>

Target:
public void onOffline(@Nonnull Computer computer, @CheckForNull OfflineCause cause) { try { final boolean emitSystemEvents = DatadogUtilities.getDatadogGlobalDescriptor().isEmitSystemEvents(); if (!emitSystemEvents) { return; } logger.fine("Start DatadogComputerListener#onOffline"); DatadogClient client = DatadogUtilities.getDatadogClient(); Map<String, Set<String>> tags = TagsUtil.merge( DatadogUtilities.getTagsFromGlobalTags(), DatadogUtilities.getComputerTags(computer)); DatadogEvent event = new ComputerOfflineEventImpl(computer, cause, tags, false); client.sendEvent(event.createPayload()); String hostname = DatadogUtilities.getHostname("null"); client.incrementCounter("jenkins.computer.offline", hostname, tags); logger.fine("End DatadogComputerListener#onOffline"); } catch (Exception e) { logger.warning("Unexpected exception occurred - " + e.getMessage()); } }
Source:
<code>@Test public void smokeTest() throws Exception { boolean notNative = (platform != TestPlatform.NATIVE); int sleepSeconds = 0; if (notNative) { switch (platform) { case CENTOS: case UBUNTU: case TINI: case SIMPLE: sleepSeconds = 10; break; case ALPINE: case SLIM: sleepSeconds = 45; break; default: Assert.fail("Unknown enum value: " + platform); break; } } String script = String.format("echo hello world; sleep %s", sleepSeconds); Controller c = new BourneShellScript(script).launch(new EnvVars(), ws, launcher, listener); awaitCompletion(c); ByteArrayOutputStream baos = new ByteArrayOutputStream(); c.writeLog(ws,baos); assertEquals(0, c.exitStatus(ws, launcher, listener).intValue()); assertTrue(baos.toString().contains("hello world")); c.cleanup(ws); if (notNative) { <START> assertTrue("no zombies running", noZombies()); <END> } }</code><technical_language>question more this specific test is nonNative while others simpleOrTini(), this change code check for zombies anywhere, obvious is special native platform for this test other tests. strong opinion want zombie tests not. If give useful information other platforms, fine leave in accidentally making a change regresses behavior. If pointless of docker fixtures pass --init matter script does, remove them</technical_language>

Target:
@Test public void smokeTest() throws Exception { int sleepSeconds = -1; switch (platform) { case NATIVE: sleepSeconds = 0; break; case CENTOS: case UBUNTU: case UBUNTU_NO_BINARY: case SIMPLE: sleepSeconds = 10; break; case ALPINE: case SLIM: sleepSeconds = 45; break; default: Assert.fail("Unknown enum value: " + platform); break; } String script = String.format("echo hello world; sleep %s", sleepSeconds); Controller c = new BourneShellScript(script).launch(new EnvVars(), ws, launcher, listener); awaitCompletion(c); ByteArrayOutputStream baos = new ByteArrayOutputStream(); c.writeLog(ws,baos); assertEquals(0, c.exitStatus(ws, launcher, listener).intValue()); assertTrue(baos.toString().contains("hello world")); c.cleanup(ws); assertThat(getZombies(), isEmptyString()); }
Source:
<code>protected void logJobProperties() { if (this.jobProps != null && this.jobProps.getBoolean(JOB_DUMP_PROPERTIES_IN_LOG, false)){ try { Map<String,String> flattenedProps = this.jobProps.getFlattened(); this.info("****** Job properties ******"); this.info(String.format("- Note : value is masked if property name ends with '%s'.", SENSITIVE_JOB_PROP_NAME_SURFFIX )); for(Map.Entry<String, String> entry : flattenedProps.entrySet()){ String key = entry.getKey(); String value = key.endsWith(SENSITIVE_JOB_PROP_NAME_SURFFIX)? SENSITIVE_JOB_PROP_VALUE_PLACEHOLDER : entry.getValue(); this.info(String.format("%s=%s",key,value)); } this.info("****** End Job properties ******"); } catch (Exception ex){ <START> log.error("failed to log job properties ", ex); <END> } } }</code><technical_language>this Azkaban log file job log</technical_language>

Target:
protected void logJobProperties() { if (this.jobProps != null && this.jobProps.getBoolean(JOB_DUMP_PROPERTIES_IN_LOG, false)){ try { Map<String,String> flattenedProps = this.jobProps.getFlattened(); this.info("****** Job properties ******"); this.info(String.format("- Note : value is masked if property name ends with '%s'.", SENSITIVE_JOB_PROP_NAME_SUFFIX )); for(Map.Entry<String, String> entry : flattenedProps.entrySet()){ String key = entry.getKey(); String value = key.endsWith(SENSITIVE_JOB_PROP_NAME_SUFFIX)? SENSITIVE_JOB_PROP_VALUE_PLACEHOLDER : entry.getValue(); this.info(String.format("%s=%s",key,value)); } this.info("****** End Job properties ******"); } catch (Exception ex){ log.error("failed to log job properties ", ex); } } }
Source:
<code>private void getVersion(RequestMsg req, ChannelHandlerContext ctx, IServerRouter r) { <START> VersionInfo vi = new VersionInfo(serverContext.getServerConfig(), serverContext.getNodeIdBase64()); <END> HeaderMsg responseHeader = getHeaderMsg(req.getHeader(), false, true); ResponseMsg response = getResponseMsg(responseHeader, getVersionResponseMsg(vi)); r.sendResponse(response, ctx); }</code><technical_language>vi improved. versionInfo</technical_language>

Target:
private void getVersion(RequestMsg req, ChannelHandlerContext ctx, IServerRouter r) { VersionInfo versionInfo = new VersionInfo(serverContext.getServerConfig(), serverContext.getNodeIdBase64()); HeaderMsg responseHeader = getHeaderMsg(req.getHeader(), false, true); ResponseMsg response = getResponseMsg(responseHeader, getVersionResponseMsg(versionInfo)); r.sendResponse(response, ctx); }
Source:
<code>public TestMethodTestDescriptor(UniqueId uniqueId, Class<?> testClass, Method testMethod, JupiterConfiguration configuration) { super(uniqueId, testClass, testMethod, configuration); <START> this.interceptorCall = DEFAULT_INTERCEPTOR_CALL; <END> }</code><technical_language>suggestion this.interceptorCall = defaultInterceptorCall;</technical_language>

Target:
public TestMethodTestDescriptor(UniqueId uniqueId, Class<?> testClass, Method testMethod, JupiterConfiguration configuration) { super(uniqueId, testClass, testMethod, configuration); this.interceptorCall = defaultInterceptorCall; }
Source:
<code>public void handleFailure() { <START> log.error("Command id: '{} failed child command status for step '{}'", <END> getCommandId(), getParameters().getCommandStep()); }</code><technical_language>logging in perform next operation</technical_language>

Target:
public void handleFailure() { log.error("Command '{}' id '{}' failed executing step '{}'", getActionType(), getCommandId(), getParameters().getCommandStep()); }
Source:
<code>public void setUp() throws Exception { defaultTZ = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); <START> File inputFile = new File("/tmp/input/input.csv"); <END> FileUtils.writeLines(inputFile, ImmutableList.of("15/02/2016 10:15:00 +0000,1,paint1,11", "15/02/2016 10:16:00 +0000,2,paint2,12", "15/02/2016 10:17:00 +0000,3,paint3,13", "15/02/2016 10:18:00 +0000,4,paint4,14", "15/02/2016 10:19:00 +0000,5,paint5,15", "15/02/2016 10:10:00 +0000,6,abcde6,16")); }</code><technical_language>Instead of /tmp; create a directory target. Refer <LINK_0> for example</technical_language>

Target:
public void setUp() throws Exception { defaultTZ = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); outputFolder += testName.getMethodName() + "/"; }
Source:
<code>public void bindServiceToRoute(String serviceInstanceId, String routeId) throws CloudFoundryException { log.debug("bindRouteToService"); try { cfClient.serviceInstances() .bindToRoute(BindServiceInstanceToRouteRequest.builder() .serviceInstanceId(serviceInstanceId) .routeId(routeId) <START> .parameters(null).build()) <END> .get(Config.CF_API_TIMEOUT_IN_S, TimeUnit.SECONDS); } catch (RuntimeException r) { throw new CloudFoundryException(r); } }</code><technical_language>parameters null default</technical_language>

Target:
public void bindServiceToRoute(String serviceInstanceId, String routeId) throws CloudFoundryException { log.debug("bindRouteToService"); try { cfClient.serviceInstances() .bindToRoute(BindServiceInstanceToRouteRequest.builder() .serviceInstanceId(serviceInstanceId) .routeId(routeId).build()) .get(Config.CF_API_TIMEOUT_IN_S, TimeUnit.SECONDS); } catch (RuntimeException r) { throw new CloudFoundryException(r); } }
Source:
<code>public static void logThreadDump(String message) { try { ThreadInfo[] threadInfo = THREAD_MX_BEAN.dumpAllThreads(true, true); StringBuilder sb = new StringBuilder(); sb.append(message).append("\n"); for (ThreadInfo ti: threadInfo) { sb.append(toString(ti)).append("\n"); } <START> System.out.println(sb.toString()); <END> } catch (Exception e) { LOGGER.error("Could not get and log a thread dump.", e); } }</code><technical_language>previous impl log4j log. intend print stdout now</technical_language>

Target:
public static void logThreadDump(String message) { try { ThreadInfo[] threadInfo = THREAD_MX_BEAN.dumpAllThreads(true, true); StringBuilder sb = new StringBuilder(); sb.append(message).append("\n"); for (ThreadInfo ti: threadInfo) { sb.append(toString(ti)).append("\n"); } LOGGER.info(sb.toString()); } catch (Exception e) { LOGGER.error("Could not get and log a thread dump.", e); } }
Source:
<code>public boolean isAvailable() { <START> return !stopped && (asyncConfiguration.failSilently() || delegateAvailable || stateLock.hasCapacity()); <END> }</code><technical_language>updating delegateAvailable time this is invoked remedy issue of another timer task</technical_language>

Target:
public boolean isAvailable() { if (stopped) return false; if (asyncConfiguration.failSilently()) return true; boolean available = false; try { available = actual.isAvailable(); } catch (Throwable t) { log.debugf("Error encountered when calling isAvailable on %s: %s", actual, t); } availabilityLock.lock(); try { if (available != delegateAvailable) { delegateAvailable = available; if (delegateAvailable) availability.signalAll(); } } finally { availabilityLock.unlock(); } return delegateAvailable || stateLock.hasCapacity(); }
Source:
<code>protected void executeCommand() { GlusterGeoRepSession session = getGeoRepSession(); <START> VDSReturnValue returnValue = runVdsCommand(VDSCommandType.ResumeGeoRepSession, new GlusterVolumeGeoRepSessionVDSParameters(upServer.getId(), session.getMasterVolumeName(), session.getSlaveHostName(), session.getSlaveVolumeName(), parameters .isForce())); <END> setSucceeded(returnValue.getSucceeded()); if(!getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_GEO_REP_RESUME_FAILED, returnValue.getVdsError().getMessage()); return; } else { getGeoRepSession().setStatus(GeoRepSessionStatus.ACTIVE); getGlusterGeoRepDao().updateSession(getGeoRepSession()); } }</code><technical_language>please format</technical_language>

Target:
protected void executeCommand() { GlusterGeoRepSession session = getGeoRepSession(); VDSReturnValue returnValue = runVdsCommand(VDSCommandType.ResumeGeoRepSession, new GlusterVolumeGeoRepSessionVDSParameters(upServer.getId(), session.getMasterVolumeName(), session.getSlaveHostName(), session.getSlaveVolumeName(), parameters.isForce())); setSucceeded(returnValue.getSucceeded()); if (!getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_GEO_REP_RESUME_FAILED, returnValue.getVdsError().getMessage()); return; } }
Source:
<code>@Override protected void readChunk(ReadableByteChannel ch) throws IOException { <START> assert buf != null : "Buffer is used to deilver readed data to the used and cannot be null: " + this; <END> buf.rewind(); int readed = 0; int res; while (true) { res = ch.read(buf); if (res < 0) { if (transferred + readed != meta.count()) { throw new IOException("Input data channel reached its end, but file has not fully loaded " + "[transferred=" + transferred + ", readed=" + readed + ", total=" + meta.count() + ']'); } break; } readed += res; if (readed == buf.capacity() || buf.position() == buf.capacity()) break; } if (readed == 0) return; transferred += readed; buf.flip(); hnd.accept(buf); }</code><technical_language>AFAIK is word "readed". deilver -> deliver fully understand "Buffer is deilver readed data *used*"</technical_language>

Target:
@Override protected void readChunk(ReadableByteChannel ch) throws IOException { assert buf != null : "Buffer cannot be null since it is used to receive the data from channel: " + this; buf.rewind(); int read = 0; int res; while (true) { res = ch.read(buf); if (res < 0) { if (transferred + read != meta.count()) { throw new IOException("Input data channel reached its end, but file has not fully loaded " + "[transferred=" + transferred + ", read=" + read + ", total=" + meta.count() + ']'); } break; } read += res; if (read == buf.capacity() || buf.position() == buf.capacity()) break; } if (read == 0) return; transferred += read; buf.flip(); hnd.accept(buf); }
Source:
<code>public EmptyMarkupContainer(String id) { super(id); <START> setMarkupId(id); <END> setOutputMarkupId(true); }</code><technical_language>Is this needed? is a chance HTML elements id in DOM</technical_language>

Target:
public EmptyMarkupContainer(String id) { super(id); setOutputMarkupId(true); }
Source:
<code><START> public void beforeStartingVertx(VertxOptions options) { <END> }</code><technical_language>protected public</technical_language>

Target:
protected void beforeStartingVertx(VertxOptions options) { }
Source:
<code>public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { <START> List<TmfAnalysisRequirement> requirements = new ArrayList<>(); <END> List<String> eventNames = new ArrayList<>(); eventNames.add(UstMemoryStrings.MALLOC); eventNames.add(UstMemoryStrings.FREE); eventNames.add(UstMemoryStrings.CALLOC); eventNames.add(UstMemoryStrings.REALLOC); eventNames.add(UstMemoryStrings.MEMALIGN); eventNames.add(UstMemoryStrings.POSIX_MEMALIGN); TmfAnalysisRequirement eventsReq = new TmfAnalysisRequirement(SessionConfigStrings.CONFIG_ELEMENT_EVENT, eventNames, AnalysisRequirementValueLevel.MANDATORY); eventsReq.addInformation(Messages.UstMemoryAnalysisModule_EventsLoadingInformation); requirements.add(eventsReq); return requirements; }</code><technical_language>Alex a linkedList instead if do need access items index, initializing initial capacity a bit higher number of items ArrayList more efficient. Sets is a good option, do care order avoid duplicates. I block a patch for a reason. Others though... ;-)</technical_language>

Target:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { List<TmfAnalysisRequirement> requirements = new LinkedList<>(); List<String> eventNames = new LinkedList<>(); eventNames.add(UstMemoryStrings.MALLOC); eventNames.add(UstMemoryStrings.FREE); eventNames.add(UstMemoryStrings.CALLOC); eventNames.add(UstMemoryStrings.REALLOC); eventNames.add(UstMemoryStrings.MEMALIGN); eventNames.add(UstMemoryStrings.POSIX_MEMALIGN); TmfAnalysisRequirement eventsReq = new TmfAnalysisRequirement(SessionConfigStrings.CONFIG_ELEMENT_EVENT, eventNames, AnalysisRequirementValueLevel.MANDATORY); eventsReq.addInformation(Messages.UstMemoryAnalysisModule_EventsLoadingInformation); eventsReq.addInformation(Messages.UstMemoryAnalysisModule_EventsLoadingExampleInformation); TmfAnalysisRequirement domainReq = new TmfAnalysisRequirement(SessionConfigStrings.CONFIG_ELEMENT_DOMAIN); domainReq.addValue(SessionConfigStrings.CONFIG_ELEMENT_DOMAIN_TYPE_UST, AnalysisRequirementValueLevel.MANDATORY); requirements.add(domainReq); requirements.add(eventsReq); return requirements; }
Source:
<code>public <T> void get( final String key, final AsyncCallback<T> callback ) { final Class<?> asyncCallbackType = ReflectionUtil.getCallbackGenericType( callback ); ThreadPoolService.getPoolExecutor().execute( new Runnable() { @Override public void run() { try { T result = (T) get( key, asyncCallbackType ); ResponseCarrier.getInstance().deliverMessage( new AsyncMessage<T>( result, callback ) ); } catch( BackendlessException e ) { ResponseCarrier.getInstance().deliverMessage( new AsyncMessage<T>( new BackendlessFault( e ), callback ) ); } catch( Exception e ) { <START> callback.handleFault( new BackendlessFault( e.getMessage() ) ); <END> } } } ); }</code><technical_language>I ResponseCarrier.getInstance().deliverMessage( line 107</technical_language>

Target:
public <T> void get( final String key, final AsyncCallback<T> callback ) { final Class<?> asyncCallbackType = ReflectionUtil.getCallbackGenericType( callback ); ThreadPoolService.getPoolExecutor().execute( new Runnable() { @Override public void run() { try { T result = (T) get( key, asyncCallbackType ); ResponseCarrier.getInstance().deliverMessage( new AsyncMessage<T>( result, callback ) ); } catch( BackendlessException e ) { ResponseCarrier.getInstance().deliverMessage( new AsyncMessage<T>( new BackendlessFault( e ), callback ) ); } catch( Exception e ) { ResponseCarrier.getInstance().deliverMessage( new AsyncMessage<T>( new BackendlessFault( e ), callback ) ); } } } ); }
Source:
<code>public void createServer(int clientAwakeTime) { server = createServerBuilder(clientAwakeTime).build(); server.getPresenceService().addListener(new PresenceListener() { @Override public void onAwake(Registration registration) { if (registration.getEndpoint().equals(currentEndpointIdentifier.get())) { awakeNotifications++; } } @Override public void onSleeping(Registration registration) { awakeNotifications = 0; awakeLatch.countDown(); <START> scheduleUpdateAfterSleeping((int) SLEEPTIME); <END> } }); setupRegistrationMonitoring(); }</code><technical_language>this is needed. triggerUpdate in tests? (this is a speed tests)</technical_language>

Target:
public void createServer(int clientAwakeTime) { server = createServerBuilder(clientAwakeTime).build(); awakeNotifications.set(0); server.getPresenceService().addListener(new PresenceListener() { @Override public void onAwake(Registration registration) { if (registration.getEndpoint().equals(currentEndpointIdentifier.get())) { awakeNotifications.addAndGet(1); } } @Override public void onSleeping(Registration registration) { awakeNotifications.set(0); awakeLatch.countDown(); } }); setupRegistrationMonitoring(); }
Source:
<code>OCFileListFragment.class.getPackage().getName() : "com.owncloud.android.ui.fragment"; protected final static String ARG_ALLOW_CONTEXTUAL_MODE = MY_PACKAGE + ".ALLOW_CONTEXTUAL"; protected final static String ARG_HIDE_FAB = MY_PACKAGE + ".HIDE_FAB"; private static final String KEY_FILE = MY_PACKAGE + ".extra.FILE"; private static final String KEY_FAB_EVER_CLICKED = "FAB_EVER_CLICKED"; private static final String GRID_IS_PREFERED_PREFERENCE = "gridIsPrefered"; private static String DIALOG_CREATE_FOLDER = "DIALOG_CREATE_FOLDER"; private FileFragment.ContainerActivity mContainerActivity; private OCFile mFile = null; private FileListListAdapter mAdapter; <START> private LinearLayout uploadFilesLinearLayout; <END> private LinearLayout uploadFromCameraLinearLayout; private TextView uploadToTextView; private BottomSheetBehavior uploadBottomSheetBehavior; private int mStatusBarColorActionMode; private int mStatusBarColor; private boolean mHideFab = true; private boolean miniFabClicked = false; private ActionMode mActiveActionMode; private OCFileListFragment.MultiChoiceModeListener mMultiChoiceModeListener; public static OCFileListFragment newInstance( boolean justFolders, boolean hideFAB, boolean allowContextualMode ) { OCFileListFragment frag = new OCFileListFragment(); Bundle args = new Bundle(); args.putBoolean(ARG_JUST_FOLDERS, justFolders); args.putBoolean(ARG_HIDE_FAB, hideFAB); args.putBoolean(ARG_ALLOW_CONTEXTUAL_MODE, allowContextualMode); frag.setArguments(args); return frag; }</code><technical_language>variables do need declared globally, declare in registerFabUploadListeners method, used</technical_language>

Target:
OCFileListFragment.class.getPackage().getName() : "com.owncloud.android.ui.fragment"; protected final static String ARG_ALLOW_CONTEXTUAL_MODE = MY_PACKAGE + ".ALLOW_CONTEXTUAL"; protected final static String ARG_HIDE_FAB = MY_PACKAGE + ".HIDE_FAB"; private static final String KEY_FILE = MY_PACKAGE + ".extra.FILE"; private static final String KEY_FAB_EVER_CLICKED = "FAB_EVER_CLICKED"; private static final String GRID_IS_PREFERED_PREFERENCE = "gridIsPrefered"; private static String DIALOG_CREATE_FOLDER = "DIALOG_CREATE_FOLDER"; private FileFragment.ContainerActivity mContainerActivity; private OCFile mFile = null; private FileListListAdapter mAdapter; private int mStatusBarColorActionMode; private int mStatusBarColor; private boolean mHideFab = true; private boolean miniFabClicked = false; private ActionMode mActiveActionMode; private OCFileListFragment.MultiChoiceModeListener mMultiChoiceModeListener; public static OCFileListFragment newInstance( boolean justFolders, boolean hideFAB, boolean allowContextualMode ) { OCFileListFragment frag = new OCFileListFragment(); Bundle args = new Bundle(); args.putBoolean(ARG_JUST_FOLDERS, justFolders); args.putBoolean(ARG_HIDE_FAB, hideFAB); args.putBoolean(ARG_ALLOW_CONTEXTUAL_MODE, allowContextualMode); frag.setArguments(args); return frag; }
Source:
<code>private String processPositionRequest() { final List<Object> positions = _fileProcessors.values().stream() <START> .map(fileProcessor -> { <END> final FilePositionKey key = fileProcessor.getPositionKey(); final FilePositionValue value = fileProcessor.getPositionValue(); return ImmutableMap.of("key", key, "value", value); }) .collect(Collectors.toList()); return JsonUtils.toJson(positions); }</code><technical_language>java .map(fileProcessor -> ImmutableMap.of("key", fileProcessor.getPositionKey(), "value", fileProcessor.getPositionValue()))</technical_language>

Target:
private String processPositionRequest() { final List<Object> positions = _fileProcessors.values().stream() .map(processor -> ImmutableMap.of("key", processor.getPositionKey(), "value", processor.getPositionValue())) .collect(Collectors.toList()); return JsonUtils.toJson(positions); }
Source:
<code>public boolean isEmitter(final String wireComponentPid) { requireNonNull(wireComponentPid, wireMessages.wireComponentPidNonNull()); final BundleContext context = FrameworkUtil.getBundle(WireHelperServiceImpl.class).getBundleContext(); final ServiceReference<?>[] refs = ServiceUtil.getServiceReferences(context, WireComponent.class, null); try { for (final ServiceReference<?> ref : refs) { final WireComponent wc = (WireComponent) context.getService(ref); <START> if (ref.getProperty(KURA_SERVICE_PID).equals(wireComponentPid) && wc instanceof WireEmitter) { <END> return true; } } } finally { ServiceUtil.ungetServiceReferences(context, refs); } return false; }</code><technical_language>service instance is more expensive checking equals string instance. : 1. Check property service reference 2. If true, get service instance 3. Check if Emitter 4. If true, return instance</technical_language>

Target:
public boolean isEmitter(final String wireComponentPid) { requireNonNull(wireComponentPid, wireMessages.wireComponentPidNonNull()); final BundleContext context = FrameworkUtil.getBundle(WireHelperServiceImpl.class).getBundleContext(); final ServiceReference<?>[] refs = ServiceUtil.getServiceReferences(context, WireComponent.class, null); try { for (final ServiceReference<?> ref : refs) { if (ref.getProperty(KURA_SERVICE_PID).equals(wireComponentPid) && context.getService(ref) instanceof WireEmitter) { return true; } } } finally { ServiceUtil.ungetServiceReferences(context, refs); } return false; }
Source:
<code>private static String readMapping() throws IOException, ParseException { JSONParser parser = new JSONParser(); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); <START> InputStream inputStream = classloader.getResourceAsStream("mapping.json"); <END> String mapping = IOUtils.toString(inputStream, "UTF-8"); Object object = parser.parse(mapping); JSONObject jsonObject = (JSONObject) object; return jsonObject.toJSONString(); }</code><technical_language>open a stream object closing never. try-with-resources statement avoid / handle unhandled IOException here</technical_language>

Target:
private static String readMapping() throws ParseException { JSONParser parser = new JSONParser(); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); try (InputStream inputStream = classloader.getResourceAsStream("mapping.json")) { String mapping = IOUtils.toString(inputStream, "UTF-8"); Object object = parser.parse(mapping); JSONObject jsonObject = (JSONObject) object; return jsonObject.toJSONString(); } catch (IOException e) { logger.error(e); return ""; } }
Source:
<code>public static Boolean isGz(String fName) { if (Strings.isNullOrEmpty(fName)) { return false; } <START> return fName.endsWith(GZ_SUFFIX) && fName.length() > GZ_SUFFIX.length(); <END> }</code><technical_language>is this logic for .zip</technical_language>

Target:
public static boolean isGz(String fName) { if (Strings.isNullOrEmpty(fName)) { return false; } return fName.endsWith(GZ_SUFFIX) && fName.length() > GZ_SUFFIX.length(); }
Source:
<code>public void testupdateQueryWithParameters() { TestOutputOperator outputOperator = setupForOutputOperatorTest(); <START> outputOperator.input.setup(tpc); <END> outputOperator.setup(context); outputOperator.activate(context); UUID id = UUID.randomUUID(); TestPojo testPojo = new TestPojo(id, 20, "Laura", true, 10, 2.0, new HashSet<Integer>(), new ArrayList<Integer>(), null, new Date(System.currentTimeMillis())); outputOperator.beginWindow(0); outputOperator.input.process(testPojo); outputOperator.endWindow(); Assert.assertEquals("rows in db", 1, outputOperator.getNumOfEventsInStore()); String updateLastName = "Laurel"; String updateQuery = "update " + KEYSPACE + "." + TABLE_NAME + " set lastname='" + updateLastName + "' where id=?"; List<FieldInfo> fieldInfos = Lists.newArrayList(); fieldInfos.add(new FieldInfo("id", "id", null)); outputOperator.setQuery(updateQuery); outputOperator.setFieldInfos(fieldInfos); outputOperator.setup(context); outputOperator.activate(context); outputOperator.beginWindow(1); outputOperator.input.process(testPojo); outputOperator.endWindow(); String recordsQuery = "SELECT * from " + TABLE_NAME + ";"; ResultSet resultSetRecords = session.execute(recordsQuery); for (Row row : resultSetRecords) { Assert.assertEquals("Updated last name", updateLastName, row.getString("lastname")); } }</code><technical_language>Setup port operator</technical_language>

Target:
public void testupdateQueryWithParameters() throws InterruptedException { UUID id = UUID.fromString("94ab597c-a5ff-4997-8343-68993d446b14"); System.out.println(id); TestPojo testPojo = new TestPojo(id, 20, "Laura", true, 10, 2.0, new HashSet<Integer>(), new ArrayList<Integer>(), null, new Date(System.currentTimeMillis())); String insert = "INSERT INTO " + KEYSPACE + "." + TABLE_NAME + " (ID, age, lastname, test, floatValue, doubleValue)" + " VALUES (94ab597c-a5ff-4997-8343-68993d446b14, 20, 'Laura', true, 10, 2.0);"; session.execute(insert); String recordsQuery = "SELECT * from " + TABLE_NAME + ";"; ResultSet resultSetRecords = session.execute(recordsQuery); Row row = resultSetRecords.iterator().next(); Assert.assertEquals("Updated last name", "Laura", row.getString("lastname")); Thread.sleep(1000); String updateLastName = "Laurel"; String updateQuery = "update " + KEYSPACE + "." + TABLE_NAME + " set lastname='" + updateLastName + "' where id=?"; List<FieldInfo> fieldInfos = Lists.newArrayList(); fieldInfos.add(new FieldInfo("id", "id", null)); TestOutputOperator outputOperator = setupForOutputOperatorTest(); outputOperator.setQuery(updateQuery); outputOperator.setFieldInfos(fieldInfos); outputOperator.setup(context); outputOperator.input.setup(tpc); outputOperator.activate(context); outputOperator.beginWindow(1); outputOperator.input.process(testPojo); outputOperator.endWindow(); recordsQuery = "SELECT * from " + TABLE_NAME + ";"; resultSetRecords = session.execute(recordsQuery); row = resultSetRecords.iterator().next(); Assert.assertEquals("Updated last name", updateLastName, row.getString("lastname")); }
Source:
<code>public void step_execution_time_is_measured() throws Throwable { Long duration = 1234L; TestStep step = new PickleTestStep("uri", mock(PickleStep.class), definitionMatch); when(bus.getTime()) .thenReturn(0L) .thenReturn(1234L); <START> Result result = step.run(bus, language, scenario, false); <END> assertEquals(duration, result.getDuration()); }</code><technical_language>solution a neat trick in mockito API allows calls chained. invocation return result of thenReturn of on</technical_language>

Target:
public void step_execution_time_is_measured() throws Throwable { Long duration = 1234L; TestStep step = new PickleTestStep("uri", mock(PickleStep.class), definitionMatch); when(bus.getTime()).thenReturn(0l, 1234l); when(bus.getTime()) .thenReturn(0L) .thenReturn(1234L); Result result = step.run(bus, language, scenario, false); assertEquals(duration, result.getDuration()); }