auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public void testExportWithStorageDomainName() throws Exception { <END> setUpEntityQueryExpectations(VdcQueryType.GetAllStorageDomains, VdcQueryParametersBase.class, new String[] {}, new Object[] {}, Collections.singletonList(getStorageDomain(2))); StorageDomain storageDomain = new StorageDomain(); storageDomain.setName(NAMES[2]); doTestExport(storageDomain, false); }</code><technical_language>please tests, for admin search (old code) for non-admin VdcQueryType.GetAllStorageDomains (new code), note setup filter=true header expectation for it</technical_language>

Target:
public void testExportWithStorageDomainName() throws Exception { setUpGetEntityExpectations("Storage: name=" + NAMES[2], SearchType.StorageDomain, getStorageDomain(2)); StorageDomain storageDomain = new StorageDomain(); storageDomain.setName(NAMES[2]); doTestExport(storageDomain, false); }
Source:
<code>public void onParagraphRemove(Paragraph p) { try { getJobManagerService().getNoteJobInfoByUnixTime(System.currentTimeMillis() - 5000, null, new JobManagerServiceCallback()); } catch (IOException ioe) { <START> LOG.warn("can not broadcast for job manager {}", ioe.getMessage()); <END> } }</code><technical_language>LOG.warn("can broadcast for job manager {}", ioe.getMessage(), ioe);</technical_language>

Target:
public void onParagraphRemove(Paragraph p) { try { getJobManagerService().getNoteJobInfoByUnixTime(System.currentTimeMillis() - 5000, null, new JobManagerServiceCallback()); } catch (IOException e) { LOG.warn("can not broadcast for job manager: " + e.getMessage(), e); } }
Source:
<code>private void generateUpdateMethod(Method method) { Parameter mainParameter = method.getParameters().stream() .filter(x -> x.getType() instanceof StructType) .findFirst() .orElse(null); if (mainParameter == null) { System.err.println("Method \"" + method + "\" doesn't have any struct parameter"); return; } Type mainType = mainParameter.getType(); JavaTypeReference mainTypeReference = schemaNames.getXjcTypeReference(mainType); javaBuffer.addImport(Consumes.class); javaBuffer.addImport(PUT.class); javaBuffer.addImports(mainTypeReference.getImports()); generateDoc(method); javaBuffer.addLine("@PUT"); javaBuffer.addLine("@Consumes({ %s })", generateMediaTypes()); javaBuffer.addLine(generateMethodSignature(mainTypeReference.getText(), "update(%s %s)", <START> <END> mainTypeReference.getText(), javaNames.getJavaMemberStyleName(mainParameter.getName())) ); javaBuffer.addLine(); }</code><technical_language>4 spaces for indentation</technical_language>

Target:
private void generateUpdateMethod(Method method) { Parameter mainParameter = method.getParameters().stream() .filter(x -> x.getType() instanceof StructType) .findFirst() .orElse(null); if (mainParameter == null) { System.err.println("Method \"" + method + "\" doesn't have any struct parameter"); return; } Type mainType = mainParameter.getType(); JavaTypeReference mainTypeReference = schemaNames.getXjcTypeReference(mainType); javaBuffer.addImport(Consumes.class); javaBuffer.addImport(PUT.class); javaBuffer.addImports(mainTypeReference.getImports()); generateDoc(method); javaBuffer.addLine("@PUT"); javaBuffer.addLine("@Consumes({ %s })", generateMediaTypes()); generateMethod(mainTypeReference.getText(), "update(%s %s)", mainTypeReference.getText(), javaNames.getJavaMemberStyleName(mainParameter.getName())); javaBuffer.addLine(); }
Source:
<code>public Avg(String fieldName, Schema fieldSchema) { this.fieldName = fieldName; boolean isNullable = fieldSchema.isNullable(); Schema.Type fieldType = isNullable ? fieldSchema.getNonNullable().getType() : fieldSchema.getType(); if (!(fieldType == Schema.Type.INT || fieldType == Schema.Type.LONG || fieldType == Schema.Type.FLOAT || fieldType == Schema.Type.DOUBLE)) { throw new IllegalArgumentException(String.format( <START> "Cannot compute avg on field %s because its type %s is not numeric", fieldName, fieldSchema)); <END> } outputSchema = isNullable ? Schema.nullableOf(Schema.of(Schema.Type.DOUBLE)) : Schema.of(Schema.Type.DOUBLE); }</code><technical_language>fieldType fieldSchema in message</technical_language>

Target:
public Avg(String fieldName, Schema fieldSchema) { this.fieldName = fieldName; boolean isNullable = fieldSchema.isNullable(); Schema.Type fieldType = isNullable ? fieldSchema.getNonNullable().getType() : fieldSchema.getType(); if (!(fieldType == Schema.Type.INT || fieldType == Schema.Type.LONG || fieldType == Schema.Type.FLOAT || fieldType == Schema.Type.DOUBLE)) { throw new IllegalArgumentException(String.format( "Cannot compute avg on field %s because its type %s is not numeric", fieldName, fieldType)); } outputSchema = isNullable ? Schema.nullableOf(Schema.of(Schema.Type.DOUBLE)) : Schema.of(Schema.Type.DOUBLE); }
Source:
<code>static String getFontSize(int theSize, boolean isSizeTag) { <START> loadFontMap(); <END> String theReturn = MEDIUM_FONT; if (isSizeTag) { Object[] theSizes = FONT_MAP.values().toArray(); if (theSize <= theSizes.length) { theReturn = (String) theSizes[theSize - 1]; } } else { Iterator<Integer> iter = FONT_MAP.keySet().iterator(); Iterator<String> value = FONT_MAP.values().iterator(); while (iter.hasNext()) { Integer theInt = iter.next(); String theString = value.next(); if (theSize <= theInt.intValue()) { theReturn = theString; break; } } } return theReturn; }</code><technical_language>Remove loadFontMap</technical_language>

Target:
private String getFontSize(int theSize, boolean isSizeTag) { String theReturn = MEDIUM_FONT; if (isSizeTag) { Object[] theSizes = FONT_MAP.values().toArray(); if (theSize <= theSizes.length) { theReturn = (String) theSizes[theSize - 1]; } } else { theReturn = FONT_MAP.ceilingEntry(theSize).getValue(); } return theReturn; }
Source:
<code>public static String getAttributionId(ContentResolver contentResolver) { try { String projection = {ATTRIBUTION_ID_COLUMN_NAME}; Cursor c = contentResolver.query(ATTRIBUTION_ID_CONTENT_URI, projection, null, null, null); if (c == null || !c.moveToFirst()) { <START> if (c != null) { <END> c.close(); } return null; } String attributionId = c.getString(c.getColumnIndex(ATTRIBUTION_ID_COLUMN_NAME)); c.close(); return attributionId; } catch (Exception e) { Log.d(TAG, "Caught unexpected exception in getAttributionId(): " + e.toString()); return null; } }</code><technical_language>I prefer add a finally block try/catch, close cursor there. This involve moving declaration of Cursor object of try/catch, is a clearer model. for other file. Also, please prepare PR dev branch master</technical_language>

Target:
public static String getAttributionId(ContentResolver contentResolver) { Cursor c = null; try { String projection = {ATTRIBUTION_ID_COLUMN_NAME}; c = contentResolver.query(ATTRIBUTION_ID_CONTENT_URI, projection, null, null, null); if (c == null || !c.moveToFirst()) { return null; } String attributionId = c.getString(c.getColumnIndex(ATTRIBUTION_ID_COLUMN_NAME)); return attributionId; } catch (Exception e) { Log.d(TAG, "Caught unexpected exception in getAttributionId(): " + e.toString()); return null; } finally { if (c != null) { c.close(); } } }
Source:
<code>public final Response toResponse(T exception) { String message = exception.getMessage(); ResponseBuilder builder = Response.status(status); try { log.error(message, exception); final SerializableError error; if (includeStackTrace) { StackTraceElement[] stackTrace = exception.getStackTrace(); error = SerializableError.of(message, exception.getClass(), Arrays.asList(stackTrace)); } else { String errorId = UUID.randomUUID().toString(); <START> log.error("error has been logged as {}", errorId, exception); <END> error = SerializableError.of(errorId, RuntimeException.class); } builder.type(MediaType.APPLICATION_JSON); String json = MAPPER.writeValueAsString(error); builder.entity(json); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to write out exception as json: {}", e.getMessage(), e); builder = Response.status(status); builder.type(MediaType.TEXT_PLAIN); builder.entity(message); } return builder.build(); }</code><technical_language>want reverse messages</technical_language>

Target:
public final Response toResponse(T exception) { String message = exception.getMessage(); ResponseBuilder builder = Response.status(status); try { final SerializableError error; if (includeStackTrace) { log.error(message, exception); StackTraceElement[] stackTrace = exception.getStackTrace(); error = SerializableError.of(message, exception.getClass(), Arrays.asList(stackTrace)); } else { String errorId = UUID.randomUUID().toString(); log.error("Error {}: {}", errorId, message, exception); error = SerializableError.of(errorId, RuntimeException.class); } builder.type(MediaType.APPLICATION_JSON); String json = MAPPER.writeValueAsString(error); builder.entity(json); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to write out exception as json: {}", e.getMessage(), e); builder = Response.status(status); builder.type(MediaType.TEXT_PLAIN); builder.entity(message); } return builder.build(); }
Source:
<code>public void testAddTaxItemsOnNewInvoice() throws Exception { final Account accountJson = createAccountNoPMBundleAndSubscriptionAndWaitForFirstInvoice(); assertEquals(accountApi.getInvoicesForAccount(accountJson.getAccountId(), true, false, false, false, AuditLevel.NONE, requestOptions).size(), 2); final BigDecimal taxAmount = BigDecimal.TEN; final UUID bundleId = UUID.randomUUID(); final InvoiceItem taxItem = new InvoiceItem(); taxItem.setAccountId(accountJson.getAccountId()); taxItem.setAmount(taxAmount); taxItem.setCurrency(accountJson.getCurrency()); taxItem.setBundleId(bundleId); final InvoiceItems input = new InvoiceItems(); input.add(taxItem); final List<InvoiceItem> createdTaxItems = invoiceApi.createTaxItems(accountJson.getAccountId(), input, true, clock.getUTCToday(), NULL_PLUGIN_PROPERTIES, requestOptions); assertEquals(createdTaxItems.size(), 1); final Invoice invoiceWithItems = invoiceApi.getInvoice(createdTaxItems.get(0).getInvoiceId(), true, null, AuditLevel.NONE, requestOptions); assertEquals(invoiceWithItems.getBalance().compareTo(taxAmount), 0); assertEquals(invoiceWithItems.getItems().size(), 1); <START> assertEquals(invoiceWithItems.getItems().get(0).getBundleId(), bundleId); <END> assertEquals(accountApi.getInvoicesForAccount(accountJson.getAccountId(), requestOptions).size(), 3); }</code><technical_language>Nit: check invoice item type</technical_language>

Target:
public void testAddTaxItemsOnNewInvoice() throws Exception { final Account accountJson = createAccountNoPMBundleAndSubscriptionAndWaitForFirstInvoice(); assertEquals(accountApi.getInvoicesForAccount(accountJson.getAccountId(), true, false, false, false, AuditLevel.NONE, requestOptions).size(), 2); final BigDecimal taxAmount = BigDecimal.TEN; final UUID bundleId = UUID.randomUUID(); final InvoiceItem taxItem = new InvoiceItem(); taxItem.setAccountId(accountJson.getAccountId()); taxItem.setAmount(taxAmount); taxItem.setCurrency(accountJson.getCurrency()); taxItem.setBundleId(bundleId); final InvoiceItems input = new InvoiceItems(); input.add(taxItem); final List<InvoiceItem> createdTaxItems = invoiceApi.createTaxItems(accountJson.getAccountId(), input, true, clock.getUTCToday(), NULL_PLUGIN_PROPERTIES, requestOptions); assertEquals(createdTaxItems.size(), 1); final Invoice invoiceWithItems = invoiceApi.getInvoice(createdTaxItems.get(0).getInvoiceId(), true, null, AuditLevel.NONE, requestOptions); assertEquals(invoiceWithItems.getBalance().compareTo(taxAmount), 0); assertEquals(invoiceWithItems.getItems().size(), 1); assertEquals(invoiceWithItems.getItems().get(0).getBundleId(), bundleId); assertEquals(invoiceWithItems.getItems().get(0).getItemType(), InvoiceItemType.TAX); assertEquals(accountApi.getInvoicesForAccount(accountJson.getAccountId(), requestOptions).size(), 3); }
Source:
<code>public void whenSchemaHasRefToOtherSchemaRootWithSameIdItShouldLoadTheTypes() throws Exception { URL jsonSchemaResource = getClass().getClassLoader().getResource("jsonSchema/jsonSchemaWithRefToRootWithSameId.json"); MetaDataModel metaDataModel = modelFactory.buildModel(jsonSchemaResource); Assert.assertThat(metaDataModel, CoreMatchers.instanceOf(DefaultStructuredMetadataModel.class)); DefaultStructuredMetadataModel model = (DefaultStructuredMetadataModel) metaDataModel; <START> Assert.assertThat(model.getFields().size(), CoreMatchers.is(1)); <END> Assert.assertThat(model.getFields().get(0).getName(), CoreMatchers.is("position")); Assert.assertThat(model.getFields().get(0).getMetaDataModel().getDataType(), CoreMatchers.is(DataType.JSON)); Assert.assertThat(model.getFields().get(0).getMetaDataModel(), CoreMatchers.instanceOf(DefaultStructuredMetadataModel.class)); assertWarehouseLocationModel((DefaultStructuredMetadataModel) model.getFields().get(0).getMetaDataModel()); }</code><technical_language>IsCollectionWithSize matcher</technical_language>

Target:
public void whenSchemaHasRefToOtherSchemaRootWithSameIdItShouldLoadTheTypes() throws Exception { URL jsonSchemaResource = getClass().getClassLoader().getResource("jsonSchema/jsonSchemaWithRefToRootWithSameId.json"); MetaDataModel metaDataModel = modelFactory.buildModel(jsonSchemaResource); Assert.assertThat(metaDataModel, CoreMatchers.instanceOf(DefaultStructuredMetadataModel.class)); DefaultStructuredMetadataModel model = (DefaultStructuredMetadataModel) metaDataModel; Assert.assertThat(model.getFields(), IsCollectionWithSize.hasSize(1)); Assert.assertThat(model.getFields().get(0).getName(), CoreMatchers.is("position")); Assert.assertThat(model.getFields().get(0).getMetaDataModel().getDataType(), CoreMatchers.is(DataType.JSON)); Assert.assertThat(model.getFields().get(0).getMetaDataModel(), CoreMatchers.instanceOf(DefaultStructuredMetadataModel.class)); assertWarehouseLocationModel((DefaultStructuredMetadataModel) model.getFields().get(0).getMetaDataModel()); }
Source:
<code>protected void handleGet(HttpServletRequest req, HttpServletResponse resp, Session session) throws IOException, ServletException { Map<String, String> templateVariableToValue = new HashMap<>(); if (GET_ALL_PROJECT_URI.equals(req.getRequestURI())) { String response = objectMapper.writeValueAsString(projectService.getAllProjects(session.getUser())); <START> this.writeResponse(resp, response); <END> return; } else if (GET_PROJECT_URI_TEMPLATE.match(req.getRequestURI(), templateVariableToValue)) { try { String projectId = templateVariableToValue.get(PROJECT_ID_KEY); try { Integer.parseInt(projectId); } catch (NumberFormatException e) { log.error("Invalid project id: ", projectId); sendErrorResponse(resp, HttpServletResponse.SC_BAD_REQUEST, "Invalid project id"); return; } String response = objectMapper.writeValueAsString(projectService.getProject(projectId)); this.writeResponse(resp, response); } catch (Exception e) { log.error("Exception while fetching project: " + e); sendErrorResponse(resp, HttpServletResponse.SC_NOT_FOUND, "Project id not found"); return; } } else { log.error("Invalid route for projects endpoint: " + req.getRequestURI()); sendErrorResponse(resp, HttpServletResponse.SC_NOT_IMPLEMENTED, "Unsupported projects API " + "endpoint"); return; } }</code><technical_language>Please utility method sendResponse instead HTTP status code Content Type set in response</technical_language>

Target:
protected void handleGet(HttpServletRequest req, HttpServletResponse resp, Session session) throws IOException, ServletException { Map<String, String> templateVariableToValue = new HashMap<>(); if (ALL_PROJECT_URI.equals(req.getRequestURI())) { sendResponse(resp, HttpServletResponse.SC_OK, projectService.getAllProjects(session.getUser())); return; } else if (GET_PROJECT_URI_TEMPLATE.match(req.getRequestURI(), templateVariableToValue)) { try { String projectId = templateVariableToValue.get(PROJECT_ID_KEY); try { Integer.parseInt(projectId); } catch (NumberFormatException e) { log.error("Invalid project id: ", projectId); sendErrorResponse(resp, HttpServletResponse.SC_BAD_REQUEST, "Invalid project id"); return; } sendResponse(resp, HttpServletResponse.SC_OK, projectService.getProject(projectId)); } catch (Exception e) { log.error("Exception while fetching project: " + e); sendErrorResponse(resp, HttpServletResponse.SC_NOT_FOUND, "Project id not found"); return; } } else { log.error("Invalid route for projects endpoint: " + req.getRequestURI()); sendErrorResponse(resp, HttpServletResponse.SC_NOT_FOUND, "Unsupported projects API " + "endpoint"); return; } }
Source:
<code>public void testClippingOfRecordWithDeletion() { final SAMFileHeader header = new SAMFileHeader(); header.addSequence(new SAMSequenceRecord("1", 1000)); final SAMRecord record = new SAMRecord(header); record.setReadPairedFlag(true); record.setCigar( <START> new Cigar(Arrays.asList( <END> new CigarElement(5, CigarOperator.M), new CigarElement(1, CigarOperator.D), new CigarElement(5, CigarOperator.M) ))); record.setReferenceIndex(0); record.setAlignmentStart(1); record.setMateAlignmentStart(5); record.setMateReferenceIndex(0); record.setReadBases("AAAAAAAAAA".getBytes()); final int numToClip = SAMUtils.getNumOverlappingAlignedBasesToClip(record); Assert.assertEquals(numToClip, 6); SAMUtils.clipOverlappingAlignedBases(record, numToClip, false); Assert.assertTrue(record.getCigar().equals(TextCigarCodec.decode("4M6S"))); }</code><technical_language>more :-)</technical_language>

Target:
public void testClippingOfRecordWithDeletion() { final SAMFileHeader header = new SAMFileHeader(); header.addSequence(new SAMSequenceRecord("1", 1000)); final SAMRecord record = new SAMRecord(header); record.setReadPairedFlag(true); record.setCigar(TextCigarCodec.decode("5M1D5M")); record.setReferenceIndex(0); record.setAlignmentStart(1); record.setMateAlignmentStart(5); record.setMateReferenceIndex(0); record.setReadBases("AAAAAAAAAA".getBytes()); final int numToClip = SAMUtils.getNumOverlappingAlignedBasesToClip(record); Assert.assertEquals(numToClip, 6); SAMUtils.clipOverlappingAlignedBases(record, numToClip, false); Assert.assertTrue(record.getCigar().equals(TextCigarCodec.decode("4M6S"))); }
Source:
<code>private void createFiles(String basePath, int numFiles, boolean matchPathFilter) throws IOException { for (int i = 0; i < numFiles; i++) { <START> new File(basePath).mkdirs(); <END> String fileName; if (matchPathFilter) { fileName = pathFilterString + "_" + i; } else { fileName = getRandomStringOfLen(10); } new File(basePath + File.separator + fileName).createNewFile(); } }</code><technical_language>Move out of loop</technical_language>

Target:
private void createFiles(String basePath, int numFiles, boolean matchPathFilter) throws IOException { new File(basePath).mkdirs(); for (int i = 0; i < numFiles; i++) { String fileName; if (matchPathFilter) { fileName = PATH_FILTER_MATCHED_PREFIX + i; } else { fileName = PATH_FILTER_NOT_MATCHED_PREFIX + i; } new File(basePath + File.separator + fileName).createNewFile(); } }
Source:
<code>public void sendPack(PackStatistics.Accumulator accumulator) throws IOException { if (wantAll.isEmpty()) { preUploadHook.onSendPack(UploadPack.this, wantIds, commonBase); } else { preUploadHook.onSendPack(UploadPack.this, wantAll, commonBase); } msgOut.flush(); PackConfig cfg = packConfig; if (cfg == null) cfg = new PackConfig(db); <START> @SuppressWarnings("resource") END> final PackWriter pw = new PackWriter(cfg, walk.getObjectReader(), accumulator); try { configurePackWriter(pw); if (commonBase.isEmpty() && refs != null) { Set<ObjectId> tagTargets = new HashSet<>(); for (Ref ref : refs.values()) { if (ref.getPeeledObjectId() != null) tagTargets.add(ref.getPeeledObjectId()); else if (ref.getObjectId() == null) continue; else if (ref.getName().startsWith(Constants.R_HEADS)) tagTargets.add(ref.getObjectId()); } pw.setTagTargets(tagTargets); } preparePack(pw, walk); writePack(pw); if (msgOut != NullOutputStream.INSTANCE) { String msg = pw.getStatistics().getMessage() + '\n'; msgOut.write(Constants.encode(msg)); msgOut.flush(); } } finally { statistics = pw.getStatistics(); if (statistics != null) { postUploadHook.onPostUpload(statistics); } pw.close(); } }</code><technical_language>Please reformat</technical_language>

Target:
public void sendPack(PackStatistics.Accumulator accumulator) throws IOException { if (wantAll.isEmpty()) { preUploadHook.onSendPack(UploadPack.this, wantIds, commonBase); } else { preUploadHook.onSendPack(UploadPack.this, wantAll, commonBase); } msgOut.flush(); PackConfig cfg = packConfig; if (cfg == null) cfg = new PackConfig(db); @SuppressWarnings("resource") final PackWriter pw = new PackWriter(cfg, walk.getObjectReader(), accumulator); try { configurePackWriter(pw); if (commonBase.isEmpty() && refs != null) { Set<ObjectId> tagTargets = new HashSet<>(); for (Ref ref : refs.values()) { if (ref.getPeeledObjectId() != null) tagTargets.add(ref.getPeeledObjectId()); else if (ref.getObjectId() == null) { continue; } else if (ref.getName().startsWith(Constants.R_HEADS)) { tagTargets.add(ref.getObjectId()); } } pw.setTagTargets(tagTargets); } preparePack(pw, walk); writePack(pw); if (msgOut != NullOutputStream.INSTANCE) { String msg = pw.getStatistics().getMessage() + '\n'; msgOut.write(Constants.encode(msg)); msgOut.flush(); } } finally { statistics = pw.getStatistics(); if (statistics != null) { postUploadHook.onPostUpload(statistics); } pw.close(); } }
Source:
<code>public void testLogoDetect() throws Exception { LogoDetection.detectLogo("resources/googlework_short.mp4"); String got = bout.toString(); <START> assertThat(got).contains("Description : Google Maps"); <END> assertThat(got).contains("Confidence"); assertThat(got).contains("Start Time Offset"); assertThat(got).contains("End Time Offset"); }</code><technical_language>suggestion assertThat(got).contains("Description");</technical_language>

Target:
public void testLogoDetect() throws IOException, ExecutionException, InterruptedException, TimeoutException { LogoDetection.detectLogo("resources/googlework_short.mp4"); String got = bout.toString(); assertThat(got).contains("Description"); assertThat(got).contains("Confidence"); assertThat(got).contains("Start Time Offset"); assertThat(got).contains("End Time Offset"); }
Source:
<code>public Optional<Integer> setMilestone(String repoId, int issueId, String issueTitle, Optional<Integer> issueMilestone) { Issue returnedIssue = getRepoState(repoId).setMilestone(issueId, issueMilestone); if (returnedIssue.getMilestone() == null) return Optional.empty(); <START> return Optional.of(returnedIssue.getMilestone().getNumber()); <END> }</code><technical_language>here. Edit: I mean, below</technical_language>

Target:
public Optional<Integer> setMilestone(String repoId, int issueId, String issueTitle, Optional<Integer> issueMilestone) { Issue returnedIssue = getRepoState(repoId).setMilestone(issueId, issueMilestone); return Optional.ofNullable(returnedIssue.getMilestone()) .map(Milestone::getNumber); }
Source:
<code>public static List lookupAllTimeZones() { if (timeZoneList == null) { List timeZones = null; Session session = HibernateFactory.getSession(); timeZones = session.getNamedQuery("RhnTimeZone.loadAll").list(); if (timeZones != null) { Collections.sort(timeZones, new Comparator() { public int compare(Object o1, Object o2) { RhnTimeZone t1 = (RhnTimeZone) o1; RhnTimeZone t2 = (RhnTimeZone) o2; int offSet1 = t1.getTimeZone().getRawOffset(); int offSet2 = t2.getTimeZone().getRawOffset(); if (offSet2 - offSet1 == 0) { return t2.getOlsonName().compareTo(t1.getOlsonName()); } if (offSet1 <= -18000000 && offSet1 >= -36000000 && offSet2 <= -18000000 && offSet2 >= -36000000 && <START> t1.getOlsonName().startsWith("America") && <END> t2.getOlsonName().startsWith("America")) { return offSet2 - offSet1; } if (offSet1 <= -18000000 && offSet1 >= -36000000 && t1.getOlsonName().startsWith("America")) { return -1; } if (offSet2 <= -18000000 && offSet2 >= -36000000 && t2.getOlsonName().startsWith("America")) { return 1; } return offSet1 - offSet2; } } ); } timeZoneList = timeZones; } return timeZoneList; }</code><technical_language>heuristics end switching Hawaii Midway. Canada(Regina) is in middle of 'United States' set. this piece of US-centrism is worth fragility. modify comparator puts GMT lists east-to-west there</technical_language>

Target:
public static List lookupAllTimeZones() { if (timeZoneList == null) { List timeZones = null; Session session = HibernateFactory.getSession(); timeZones = session.getNamedQuery("RhnTimeZone.loadAll").list(); if (timeZones != null) { Collections.sort(timeZones, new Comparator() { public int compare(Object o1, Object o2) { RhnTimeZone t1 = (RhnTimeZone) o1; RhnTimeZone t2 = (RhnTimeZone) o2; Integer offSet1 = t1.getTimeZone().getRawOffset(); Integer offSet2 = t2.getTimeZone().getRawOffset(); if (offSet1 == 0 && offSet2 != 0) { return -1; } if (offSet1 != 0 && offSet2 == 0) { return 1; } if (offSet2.equals(offSet1)) { return t2.getOlsonName().compareTo(t1.getOlsonName()); } return offSet2.compareTo(offSet1); } }); } timeZoneList = timeZones; } return timeZoneList; }
Source:
<code>public void handleCoupleMbusDeviceResponse(final DeviceMessageMetadata deviceMessageMetadata, final MbusChannelElementsResponseDto mbusChannelElementsResponseDto) throws FunctionalException { this.checkAndHandleIfChannelNotFound(mbusChannelElementsResponseDto); final String deviceIdentification = deviceMessageMetadata.getDeviceIdentification(); final SmartMeter gatewayDevice = this.domainHelperService.findSmartMeter(deviceIdentification); <START> this.checkAndHandleChannelOnGateway(gatewayDevice, mbusChannelElementsResponseDto); <END> this.handleChannelFound(deviceMessageMetadata, mbusChannelElementsResponseDto); }</code><technical_language>This check done request time</technical_language>

Target:
public void handleCoupleMbusDeviceResponse(final DeviceMessageMetadata deviceMessageMetadata, final MbusChannelElementsResponseDto mbusChannelElementsResponseDto) throws FunctionalException { final String deviceIdentification = deviceMessageMetadata.getDeviceIdentification(); final SmartMeter gatewayDevice = this.domainHelperService.findSmartMeter(deviceIdentification); this.checkAndHandleIfChannelNotFound(mbusChannelElementsResponseDto); this.checkAndHandleChannelOnGateway(gatewayDevice, mbusChannelElementsResponseDto); this.doCoupleMBusDevice(gatewayDevice, mbusChannelElementsResponseDto); }
Source:
<code>private Node processTextNode(Node node, Document doc) { <START> Node localNode = node; <END> String theText = localNode.getNodeValue(); theText = theText.replaceAll(ldquo.toString(), "\""); theText = theText.replaceAll(rdquo.toString(), "\""); theText = theText.replaceAll(lsquo.toString(), "'"); theText = theText.replaceAll(rsquo.toString(), "'"); localNode.setNodeValue(theText); return localNode; }</code><technical_language>This localNode variable serves purpose</technical_language>

Target:
private Node processTextNode(Node node, Document doc) { String theText = node.getNodeValue(); theText = theText.replaceAll(ldquo.toString(), "\""); theText = theText.replaceAll(rdquo.toString(), "\""); theText = theText.replaceAll(lsquo.toString(), "'"); theText = theText.replaceAll(rsquo.toString(), "'"); node.setNodeValue(theText); return node; }
Source:
<code>public void processBarrier(CheckpointBarrier receivedBarrier, InputChannelInfo channelInfo) throws IOException { final long barrierId = receivedBarrier.getId(); if (totalNumberOfInputChannels == 1) { <START> markCheckpointStart(receivedBarrier.getTimestamp()); markAlignmentEnd(0); <END> notifyCheckpoint(receivedBarrier); return; } if (LOG.isDebugEnabled()) { LOG.debug("Received barrier for checkpoint from channel {}", barrierId, channelInfo); } CheckpointBarrierCount barrierCount = null; int pos = 0; for (CheckpointBarrierCount next : pendingCheckpoints) { if (next.checkpointId == barrierId) { barrierCount = next; break; } pos++; } if (barrierCount != null) { int numBarriersNew = barrierCount.incrementBarrierCount(); if (numBarriersNew == totalNumberOfInputChannels) { for (int i = 0; i <= pos; i++) { pendingCheckpoints.pollFirst(); } if (!barrierCount.isAborted()) { if (LOG.isDebugEnabled()) { LOG.debug("Received all barriers for checkpoint {}", barrierId); } markAlignmentEnd(); notifyCheckpoint(receivedBarrier); } } } else { if (barrierId > latestPendingCheckpointID) { markCheckpointStart(receivedBarrier.getTimestamp()); latestPendingCheckpointID = barrierId; pendingCheckpoints.addLast(new CheckpointBarrierCount(barrierId)); if (pendingCheckpoints.size() > MAX_CHECKPOINTS_TO_TRACK) { pendingCheckpoints.pollFirst(); } } } }</code><technical_language>This suboptimal: markCheckpointStart calls resetAlignment calls markAlignmentEnd(0). call again, this time, completely behavior. need: * markCheckpointStart * markAlignmentStart (not for tracker for (Un)Aligner)) * markAlignmentEnd (just for (Un)Aligner)) * setAlignmentDuration (for all)</technical_language>

Target:
public void processBarrier(CheckpointBarrier receivedBarrier, InputChannelInfo channelInfo) throws IOException { final long barrierId = receivedBarrier.getId(); if (totalNumberOfInputChannels == 1) { markAlignmentStartAndEnd(receivedBarrier.getTimestamp()); notifyCheckpoint(receivedBarrier); return; } if (LOG.isDebugEnabled()) { LOG.debug("Received barrier for checkpoint from channel {}", barrierId, channelInfo); } CheckpointBarrierCount barrierCount = null; int pos = 0; for (CheckpointBarrierCount next : pendingCheckpoints) { if (next.checkpointId == barrierId) { barrierCount = next; break; } pos++; } if (barrierCount != null) { int numBarriersNew = barrierCount.incrementBarrierCount(); if (numBarriersNew == totalNumberOfInputChannels) { for (int i = 0; i <= pos; i++) { pendingCheckpoints.pollFirst(); } if (!barrierCount.isAborted()) { if (LOG.isDebugEnabled()) { LOG.debug("Received all barriers for checkpoint {}", barrierId); } markAlignmentEnd(); notifyCheckpoint(receivedBarrier); } } } else { if (barrierId > latestPendingCheckpointID) { markAlignmentStart(receivedBarrier.getTimestamp()); latestPendingCheckpointID = barrierId; pendingCheckpoints.addLast(new CheckpointBarrierCount(barrierId)); if (pendingCheckpoints.size() > MAX_CHECKPOINTS_TO_TRACK) { pendingCheckpoints.pollFirst(); } } } }
Source:
<code>protected void maybeCommitOffsets(Consumer<?, ?> consumer, boolean hardCommit) { if (_isFlushlessModeEnabled) { boolean isTimeToCommit = System.currentTimeMillis() - _lastCommittedTime > _offsetCommitInterval; if (hardCommit) { LOG.info("Calling flush on the producer."); _datastreamTask.getEventProducer().flush(); <START> commitWithRetries(consumer, Optional.empty()); <END> _flushlessProducer.clear(); _lastCommittedTime = System.currentTimeMillis(); } else if (isTimeToCommit) { LOG.info("Trying to commit offsets."); Map<TopicPartition, OffsetAndMetadata> offsets = new HashMap<>(); for (TopicPartition tp : consumer.assignment()) { _flushlessProducer.getAckCheckpoint(tp.topic(), tp.partition()) .ifPresent(o -> offsets.put(tp, new OffsetAndMetadata(o + 1))); } commitWithRetries(consumer, Optional.of(offsets)); _lastCommittedTime = System.currentTimeMillis(); } } else { super.maybeCommitOffsets(consumer, hardCommit); } }</code><technical_language>I suggest pass offsets commitWithRetries call here. get _flushlessProducer. This is safer avoid dataloss</technical_language>

Target:
protected void maybeCommitOffsets(Consumer<?, ?> consumer, boolean hardCommit) { if (_isFlushlessModeEnabled) { boolean isTimeToCommit = System.currentTimeMillis() - _lastCommittedTime > _offsetCommitInterval; if (hardCommit) { LOG.info("Calling flush on the producer."); _datastreamTask.getEventProducer().flush(); commitSafeOffsets(consumer); _flushlessProducer.clear(); } else if (isTimeToCommit) { commitSafeOffsets(consumer); } } else { super.maybeCommitOffsets(consumer, hardCommit); } }
Source:
<code>synchronized ClientJobState getClientJobState(JobId jobId) { if (!jobsMap.containsKey(jobId)) { List<InternalJob> internalJobs = dbManager.loadInternalJob(Arrays.asList(jobId.longValue())); if (!internalJobs.isEmpty()) { InternalJob internalJob = internalJobs.get(0); ClientJobState clientJobState = new ClientJobState(internalJob); <START> jobsMap.put(jobId, clientJobState); <END> } } return jobsMap.get(jobId); }</code><technical_language>Beware jobsMap.put(), job in memory housekeeping</technical_language>

Target:
synchronized ClientJobState getClientJobState(JobId jobId) { if (!jobsMap.containsKey(jobId)) { if (!finishedJobsLRUCache.containsKey(jobId)) { List<InternalJob> internalJobs = dbManager.loadInternalJob(jobId.longValue()); if (!internalJobs.isEmpty()) { InternalJob internalJob = internalJobs.get(0); ClientJobState clientJobState = new ClientJobState(internalJob); finishedJobsLRUCache.put(jobId, clientJobState); } } return finishedJobsLRUCache.get(jobId); } else { return jobsMap.get(jobId); } }
Source:
<code>public void testGetWorkflows() throws IOException { <START> System.out.println("End test :" + TestHelper.getTestMethodName()); <END> String body = get("clusters/" + CLUSTER_NAME + "/workflows", null, Response.Status.OK.getStatusCode(), true); JsonNode node = OBJECT_MAPPER.readTree(body); String workflowsStr = node.get(WorkflowAccessor.WorkflowProperties.Workflows.name()).toString(); Set<String> workflows = OBJECT_MAPPER.readValue(workflowsStr, OBJECT_MAPPER.getTypeFactory().constructCollectionType(Set.class, String.class)); Assert.assertEquals(workflows, _workflowMap.get(CLUSTER_NAME).keySet()); System.out.println("End test :" + TestHelper.getTestMethodName()); }</code><technical_language>End</technical_language>

Target:
public void testGetWorkflows() throws IOException { System.out.println("Start test :" + TestHelper.getTestMethodName()); String body = get("clusters/" + CLUSTER_NAME + "/workflows", null, Response.Status.OK.getStatusCode(), true); JsonNode node = OBJECT_MAPPER.readTree(body); String workflowsStr = node.get(WorkflowAccessor.WorkflowProperties.Workflows.name()).toString(); Set<String> workflows = OBJECT_MAPPER.readValue(workflowsStr, OBJECT_MAPPER.getTypeFactory().constructCollectionType(Set.class, String.class)); Assert.assertEquals(workflows, _workflowMap.get(CLUSTER_NAME).keySet()); System.out.println("End test :" + TestHelper.getTestMethodName()); }
Source:
<code>public UploadImagePopupView(EventBus eventBus) { super(eventBus); vmDiskPopupWidget = new VmDiskPopupWidget(false); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); <START> localize(); <END> driver.initialize(this); }</code><technical_language>add: UploadImagePopupView.ViewIdHandler.idHandler.generateAndSetIds(this);</technical_language>

Target:
public UploadImagePopupView(EventBus eventBus) { super(eventBus); vmDiskPopupWidget = new VmDiskPopupWidget(false); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); localize(); UploadImagePopupView.ViewIdHandler.idHandler.generateAndSetIds(this); driver.initialize(this); }
Source:
<code>public void testNullIdsForInputTransformers() throws Exception { List<ServiceReference<InputTransformer>> serviceReferences = new ArrayList<>(); ServiceReference<InputTransformer> serviceReference = mock(ServiceReference.class); serviceReferences.add(serviceReference); List<ServiceReference<InputTransformer>> serviceReferencesFiltered = serviceReferences .stream() .filter(ref -> ref.getProperty(Constants.SERVICE_ID) != null) .collect(Collectors.toList()); when(serviceReference.getProperty(SERVICE_ID)).thenReturn(null); when(bundleContext.getServiceReferences(InputTransformer.class, "(id=*)")) .thenReturn(serviceReferencesFiltered); <START> transformersCommand.inputOption = true; <END> transformersCommand.executeWithSubject(); assertThat( consoleOutput.getOutput(), containsString(TransformersCommand.getNoActiveString(TransformersCommand.INPUT))); }</code><technical_language>Add getter/setters for options instead of accessing field</technical_language>

Target:
public void testNullIdsForInputTransformers() throws Exception { List<ServiceReference<InputTransformer>> serviceReferences = new ArrayList<>(); ServiceReference<InputTransformer> serviceReference = mock(ServiceReference.class); serviceReferences.add(serviceReference); List<ServiceReference<InputTransformer>> serviceReferencesFiltered = serviceReferences .stream() .filter(ref -> ref.getProperty(Constants.SERVICE_ID) != null) .collect(Collectors.toList()); when(serviceReference.getProperty(SERVICE_ID)).thenReturn(null); when(bundleContext.getServiceReferences(InputTransformer.class, FILTER)) .thenReturn(serviceReferencesFiltered); transformersCommand.setInputOption(true); transformersCommand.executeWithSubject(); assertThat( consoleOutput.getOutput(), containsString(String.format("%s%n%n", "There are no active Input transformers"))); }
Source:
<code>public void update() { if(worldObj.isRemote) { return; } battery.tick(getWorld(), getPos()); battery.addPower(1000); EnumFacing currentSide = (EnumFacing) worldObj.getBlockState(pos).getProperties().get(BlockBCBase_Neptune.BLOCK_FACING_6); int target = 100000; if(currentSide == EnumFacing.UP.getOpposite()) { progress += 1000; } progress += battery.extractPower(0, target - progress); if (progress >= target) { progress = 0; int radius = 3; BlockPos offset = new BlockPos(currentSide.getDirectionVec()); offset = new BlockPos(offset.getX() * radius, offset.getY() * radius, offset.getZ() * radius); AxisAlignedBB aabb = new AxisAlignedBB(this.pos, this.pos).expandXyz(radius).offset(offset); List<EntityItem> entityItems = worldObj.getEntitiesWithinAABB(EntityItem.class, aabb); int index = 0, max = 3; for(EntityItem entityItem : entityItems) { ItemStack stack = entityItem.getEntityItem(); <START> stack = ItemTransactorHelper.getTransactor(this, currentSide).insert(stack, false, false); <END> if(stack == null) { entityItem.setDead(); } else { entityItem.setEntityItemStack(stack); } if(index++ >= max) { break; } } } putInInventories(currentSide); }</code><technical_language>inv (instead of ItemTransactorHelper.getTransactor(this, currentSide)) ItemHandlerSimple implements IItemTransactor already</technical_language>

Target:
public void update() { if (worldObj.isRemote) { return; } if (!(worldObj.getBlockState(pos).getBlock() instanceof BlockChute)) { return; } battery.tick(getWorld(), getPos()); battery.addPower(1000); EnumFacing currentSide = worldObj.getBlockState(pos).getValue(BlockBCBase_Neptune.BLOCK_FACING_6); int target = 100000; if (currentSide == EnumFacing.UP.getOpposite()) { progress += 1000; } progress += battery.extractPower(0, target - progress); if (progress >= target) { progress = 0; putItemsFromGround(currentSide); } putInInventories(currentSide); }
Source:
<code>public UserInfo[] getBrokerUsers() throws OperationCanceledException, AuthenticatorException, IOException { if (mBrokerProxy != null) { <START> return mBrokerProxy.getBrokerUsers(); <END> } return null; }</code><technical_language>Java ? operator</technical_language>

Target:
public UserInfo[] getBrokerUsers() throws OperationCanceledException, AuthenticatorException, IOException { return mBrokerProxy != null ? mBrokerProxy.getBrokerUsers() : null; }
Source:
<code>public void visitCaseClause(CaseClauseTree tree) { ExpressionTree expression = tree.expression(); if (expression.is(Kind.COMMA_OPERATOR)) { int nbCommas = getNumberOfCommas(expression); <START> String lastCase = ((BinaryExpressionTree)expression).rightOperand().toString(); <END> String msg = String.format(MESSAGE, nbCommas + 1, lastCase); addIssue(expression, msg); } super.visitCaseClause(tree); }</code><technical_language>@ivandalbosco please CheckUtils#asString instread of toString (+ more case unit test more advanced expression)</technical_language>

Target:
public void visitCaseClause(CaseClauseTree tree) { ExpressionTree expression = tree.expression(); if (expression.is(Kind.COMMA_OPERATOR)) { int nbCommas = getNumberOfCommas(expression); ExpressionTree rightOperand = ((BinaryExpressionTree)expression).rightOperand(); String lastCase = CheckUtils.asString(rightOperand); String msg = String.format(MESSAGE, nbCommas + 1, lastCase); addIssue(expression, msg); } super.visitCaseClause(tree); }
Source:
<code>public static String updateLocationEndpointInWsdl(InputStream wsdlStream, URL managedEndpoint, ApiVersionBean apiVersion, IStorage storage) throws StorageException { Document document = readWsdlInputStream(wsdlStream); Boolean updateStorage = false; <START> for(int i = 0; i < SOAP_ADDRESS.length;i++) { <END> NodeList nodeList = document.getDocumentElement().getElementsByTagName(SOAP_ADDRESS[i]); if (nodeList != null) { for (int j = 0; j < nodeList.getLength(); j++) { Node node = nodeList.item(j); String location = node.getAttributes().getNamedItem(LOCATION).getNodeValue(); String endpoint = managedEndpoint.toString(); if (!location.equals(endpoint)) { node.getAttributes().getNamedItem(LOCATION).setNodeValue(managedEndpoint.toString()); updateStorage = true; } } } } String wsdl = xmlDocumentToString(document); if (updateStorage) storage.updateApiDefinition(apiVersion, new ByteArrayInputStream(wsdl.getBytes(StandardCharsets.UTF_8))); return wsdl; }</code><technical_language>a for loop counters: for(Node node : nodeList)</technical_language>

Target:
public static String updateLocationEndpointInWsdl(InputStream wsdlStream, URL managedEndpoint, ApiVersionBean apiVersion, IStorage storage) throws StorageException { Document document = readWsdlInputStream(wsdlStream); Boolean updateStorage = false; for(int i = 0; i < SOAP_ADDRESS.length;i++) { NodeList nodeList = document.getDocumentElement().getElementsByTagName(SOAP_ADDRESS[i]); if (nodeList != null) { for (int j = 0; j < nodeList.getLength(); j++) { Node node = nodeList.item(j); String location = node.getAttributes().getNamedItem(LOCATION).getNodeValue(); String endpoint = managedEndpoint.toString(); if (!location.equals(endpoint)) { node.getAttributes().getNamedItem(LOCATION).setNodeValue(managedEndpoint.toString()); updateStorage = true; } } } } String wsdl = xmlDocumentToString(document); if (updateStorage) { storage.updateApiDefinition(apiVersion, new ByteArrayInputStream(wsdl.getBytes(StandardCharsets.UTF_8))); } return wsdl; }
Source:
<code>public void addListener_triggeredByLocalCommit() { final SharedRealm sharedRealm = getSharedRealm(); Table table = sharedRealm.getTable("test_table"); final AtomicInteger listenerCounter = new AtomicInteger(0); final AtomicBoolean transactionCommitted = new AtomicBoolean(false); final Collection collection = new Collection(sharedRealm, table.where()); looperThread.keepStrongReference.add(collection); collection.addListener(collection, new RealmChangeListener<Collection>() { @Override public void onChange(Collection collection1) { switch (listenerCounter.getAndIncrement()) { case 0: assertEquals(collection1.size(), 4); break; case 1: assertFalse(transactionCommitted.get()); assertEquals(collection1.size(), 5); sharedRealm.close(); break; } } }); addRow(sharedRealm); transactionCommitted.set(true); <START> looperThread.testComplete(); <END> }</code><technical_language>This change flow of this test. depending notification arriving looper, is triggered synchronously. a new test case listenerTriggeredOnCommit() tests change listener is triggered _both_ beginTransaction() commitTransaction()</technical_language>

Target:
public void addListener_triggeredByLocalCommit() { final SharedRealm sharedRealm = getSharedRealm(); Table table = sharedRealm.getTable("test_table"); final AtomicInteger listenerCounter = new AtomicInteger(0); final Collection collection = new Collection(sharedRealm, table.where()); looperThread.keepStrongReference.add(collection); collection.addListener(collection, new RealmChangeListener<Collection>() { @Override public void onChange(Collection collection1) { switch (listenerCounter.getAndIncrement()) { case 0: assertEquals(collection1.size(), 4); break; case 1: assertEquals(collection1.size(), 5); sharedRealm.close(); break; default: fail(); break; } } }); addRow(sharedRealm); assertEquals(2, listenerCounter.get()); looperThread.testComplete(); }
Source:
<code>public static boolean addPatientCorrelationPLQRecords(PatientLocationQueryResponseType plqRecords) { <START> dao = new CorrelatedIdentifiersDaoImpl(); <END> boolean result = false; for(PatientLocationResponse rec : plqRecords.getPatientLocationResponse()){ if(null != rec.getCorrespondingPatientId() && null != rec.getRequestedPatientId()){ AssigningAuthorityHomeCommunityMappingDAO mappingDao = new AssigningAuthorityHomeCommunityMappingDAO(); CorrelatedIdentifiers newId = new CorrelatedIdentifiers(); newId.setRlsId(rec.getHomeCommunityId()); newId.setCorrelatedPatientId(rec.getCorrespondingPatientId().getExtension()); newId.setCorrelatedPatientAssigningAuthorityId(rec.getCorrespondingPatientId().getRoot()); newId.setPatientId(rec.getRequestedPatientId().getExtension()); newId.setPatientAssigningAuthorityId(rec.getRequestedPatientId().getRoot()); dao.addPatientCorrelation(newId); mappingDao.storeMapping(rec.getHomeCommunityId(), rec.getHomeCommunityId()); result = true; } } return result; }</code><technical_language>Remove this assignment. initialized line 46</technical_language>

Target:
public static boolean addPatientCorrelationPLQRecords(PatientLocationQueryResponseType plqRecords) { CorrelatedIdentifiersDao dao = new CorrelatedIdentifiersDaoImpl(); boolean result = false; for(PatientLocationResponse rec : plqRecords.getPatientLocationResponse()){ if(null != rec.getCorrespondingPatientId() && null != rec.getRequestedPatientId()){ AssigningAuthorityHomeCommunityMappingDAO mappingDao = new AssigningAuthorityHomeCommunityMappingDAO(); CorrelatedIdentifiers newId = new CorrelatedIdentifiers(); newId.setRlsId(rec.getHomeCommunityId()); newId.setCorrelatedPatientId(rec.getCorrespondingPatientId().getExtension()); newId.setCorrelatedPatientAssigningAuthorityId(rec.getCorrespondingPatientId().getRoot()); newId.setPatientId(rec.getRequestedPatientId().getExtension()); newId.setPatientAssigningAuthorityId(rec.getRequestedPatientId().getRoot()); dao.addPatientCorrelation(newId); mappingDao.storeMapping(rec.getHomeCommunityId(), rec.getHomeCommunityId()); result = true; } } return result; }
Source:
<code>void shouldThrowExceptionWhenTheDefaultJobTimeoutIsNotValid() { <START> String defaultJobTimeout = "foo"; <END> CreateOrUpdateDefaultJobTimeoutCommand command = new CreateOrUpdateDefaultJobTimeoutCommand(defaultJobTimeout); cruiseConfig.server().setJobTimeout(defaultJobTimeout); assertThatCode(() -> command.isValid(cruiseConfig)) .isInstanceOf(GoConfigInvalidException.class) .hasMessage("Timeout should be a valid number as it represents number of minutes"); }</code><technical_language>call update cruise-config prior calling isValid. calling update command effect cruise-config valid</technical_language>

Target:
void shouldThrowExceptionWhenTheDefaultJobTimeoutIsNotValid() throws Exception { String defaultJobTimeout = "foo"; CreateOrUpdateDefaultJobTimeoutCommand command = new CreateOrUpdateDefaultJobTimeoutCommand(defaultJobTimeout); command.update(cruiseConfig); assertThatCode(() -> command.isValid(cruiseConfig)) .isInstanceOf(GoConfigInvalidException.class) .hasMessage("Timeout should be a valid number as it represents number of minutes"); }
Source:
<code>public MessageStoringChannel() { <START> this.setBeanName("input"); <END> }</code><technical_language>extract constant below</technical_language>

Target:
public MessageStoringChannel() { this.setBeanName(INPUT); }