auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void validateSourceInfoRequest(SourceInfoRequest sourceInfoRequest) { if (sourceInfoRequest == null) { IllegalArgumentException illegalArgumentException = new IllegalArgumentException( "SourceInfoRequest was null"); <START> logger.error("Received null sourceInfoRequest", illegalArgumentException); <END> throw illegalArgumentException; } }</code><technical_language>Yeah, generally add logging, in of situations log a full exception standalone useful slim logging output slightly cleaner code. EDIT: :)</technical_language>

Target:
private void validateSourceInfoRequest(SourceInfoRequest sourceInfoRequest) { if (sourceInfoRequest == null) { IllegalArgumentException illegalArgumentException = new IllegalArgumentException( "SourceInfoRequest was null"); logger.throwing(illegalArgumentException); throw illegalArgumentException; } }
Source:
<code>public void add(Marker reference) { <START> <END> }</code><technical_language>Agreed - this is a good candidate for unit tests</technical_language>

Target:
public void add(Marker reference) { references.add(reference); }
Source:
<code>public void init() { delegateShapeFactory .delegate(CaseManagementDiagram.class, new CaseManagementDiagramShapeDef(), () -> caseManagementShapeDefFactory) .delegate(AdHocSubprocess.class, new CaseManagementSubprocessShapeDef(), () -> caseManagementShapeDefFactory) .delegate(NoneTask.class, new CaseManagementTaskShapeDef(), () -> caseManagementShapeDefFactory) .delegate(UserTask.class, new CaseManagementTaskShapeDef(), () -> caseManagementShapeDefFactory) .delegate(ScriptTask.class, new CaseManagementTaskShapeDef(), () -> caseManagementShapeDefFactory) .delegate(BusinessRuleTask.class, new CaseManagementTaskShapeDef(), () -> caseManagementShapeDefFactory) .delegate(ReusableSubprocess.class, new CaseManagementReusableSubprocessTaskShapeDef(), () -> caseManagementShapeDefFactory) .delegate(StartNoneEvent.class, new NullShapeDef(), () -> caseManagementShapeDefFactory) <START> .delegate(StartNoneEvent.class, <END> new NullShapeDef(), () -> caseManagementShapeDefFactory) .delegate(ParallelGateway.class, new NullShapeDef(), () -> caseManagementShapeDefFactory) .delegate(ExclusiveDatabasedGateway.class, new NullShapeDef(), () -> caseManagementShapeDefFactory) .delegate(Lane.class, new NullShapeDef(), () -> caseManagementShapeDefFactory) .delegate(EndTerminateEvent.class, new NullShapeDef(), () -> caseManagementShapeDefFactory) .delegate(EndNoneEvent.class, new NullShapeDef(), () -> caseManagementShapeDefFactory) .delegate(SequenceFlow.class, new SequenceFlowConnectorDef(), () -> basicShapesFactory); }</code><technical_language>Duplicated node **StartNoneEvent**</technical_language>

Target:
public void init() { delegateShapeFactory .delegate(CaseManagementDiagram.class, new CaseManagementDiagramShapeDef(), () -> caseManagementShapeDefFactory) .delegate(AdHocSubprocess.class, new CaseManagementSubprocessShapeDef(), () -> caseManagementShapeDefFactory) .delegate(NoneTask.class, new CaseManagementTaskShapeDef(), () -> caseManagementShapeDefFactory) .delegate(UserTask.class, new CaseManagementTaskShapeDef(), () -> caseManagementShapeDefFactory) .delegate(ScriptTask.class, new CaseManagementTaskShapeDef(), () -> caseManagementShapeDefFactory) .delegate(BusinessRuleTask.class, new CaseManagementTaskShapeDef(), () -> caseManagementShapeDefFactory) .delegate(ReusableSubprocess.class, new CaseManagementReusableSubprocessTaskShapeDef(), () -> caseManagementShapeDefFactory) .delegate(StartNoneEvent.class, new NullShapeDef(), () -> caseManagementShapeDefFactory) .delegate(ParallelGateway.class, new NullShapeDef(), () -> caseManagementShapeDefFactory) .delegate(ExclusiveDatabasedGateway.class, new NullShapeDef(), () -> caseManagementShapeDefFactory) .delegate(Lane.class, new NullShapeDef(), () -> caseManagementShapeDefFactory) .delegate(EndTerminateEvent.class, new NullShapeDef(), () -> caseManagementShapeDefFactory) .delegate(EndNoneEvent.class, new NullShapeDef(), () -> caseManagementShapeDefFactory) .delegate(SequenceFlow.class, new SequenceFlowConnectorDef(), () -> basicShapesFactory); }
Source:
<code>public void testIfVerifyOptionIsPassedToTool() { if (!upgrade) { return; } Assert.assertEquals("", VERIFY_VALUE, indexUpgradeTool.getVerify()); <START> String values = indexUpgradeTool.getIndexToolArgValues(Mockito.anyString(), <END> Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); Assert.assertTrue(Arrays.asList(values).contains(VERIFY_VALUE)); Assert.assertTrue(Arrays.asList(values).contains("-v")); Assert.assertEquals("verify option and value is not passed consecutively", 1, Arrays.asList(values).indexOf(VERIFY_VALUE) - Arrays.asList(values).indexOf("-v")); }</code><technical_language>unusual Mockito.anyString() in a call setting a mock. reason dummy values</technical_language>

Target:
public void testIfVerifyOptionIsPassedToTool() { if (!upgrade) { return; } Assert.assertEquals("value passed with verify option does not match with provided value", DUMMY_STRING_VALUE, indexUpgradeTool.getVerify()); String values = indexUpgradeTool.getIndexToolArgValues(DUMMY_STRING_VALUE, DUMMY_STRING_VALUE, DUMMY_STRING_VALUE, DUMMY_STRING_VALUE, DUMMY_STRING_VALUE); List<String> argList = Arrays.asList(values); Assert.assertTrue(argList.contains(DUMMY_STRING_VALUE)); Assert.assertTrue(argList.contains("-v")); Assert.assertEquals("verify option and value are not passed consecutively", 1, argList.indexOf(DUMMY_STRING_VALUE) - argList.indexOf("-v")); }
Source:
<code>public void createSubjectRulesReviewTest() { KubernetesClient client = server.getClient(); createSubjectAccessReviewTest(); SelfSubjectRulesReview selfSubjectRulesReview = new SelfSubjectRulesReviewBuilder() .withNewSpec() .withNamespace("test") .endSpec() .withNewStatus() .withResourceRules(new ResourceRuleBuilder() .withResourceNames("pod") .withVerbs("create", "list", "get", "delete").build()).endStatus().build(); SelfSubjectRulesReview rulesReviewResponse = client.subjectAccessReviewAuth().list().create(selfSubjectRulesReview); assertNotNull(rulesReviewResponse); <START> ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); <END> SelfSubjectRulesReview reviewFromFile = null; try { reviewFromFile = mapper.readValue(getClass().getResourceAsStream("/test-selfsubjectrulesreview.yml"), SelfSubjectRulesReview.class); } catch (IOException e) { e.printStackTrace(); } assertNotNull(reviewFromFile); SelfSubjectRulesReview rulesReviewFromFileResponse = client.subjectAccessReviewAuth().list().create(reviewFromFile); assertNotNull(rulesReviewFromFileResponse); }</code><technical_language>Kubernetes-client provides means for Deserialization, please Serialization.unmarshal KubernetesClient#load deserialize class test tests codebase</technical_language>

Target:
public void createSubjectRulesReviewTest() { KubernetesClient client = server.getClient(); createSubjectAccessReviewTest(); SelfSubjectRulesReview selfSubjectRulesReview = new SelfSubjectRulesReviewBuilder() .withNewSpec() .withNamespace("test") .endSpec() .withNewStatus() .withResourceRules(new ResourceRuleBuilder() .withResourceNames("pod") .withVerbs("create", "list", "get", "delete").build()).endStatus().build(); SelfSubjectRulesReview rulesReviewResponse = client.subjectAccessReviewAuth().list().create(selfSubjectRulesReview); assertNotNull(rulesReviewResponse); }
Source:
<code>private void decorateWorkloadClusterPillarWithCsdDownloader(StackType stackType, Cluster cluster, Map<String, SaltPillarProperties> servicePillar) { <START> if (StackType.WORKLOAD.equals(stackType)) { <END> clusterHostServiceRunner.decoratePillarWithClouderaManagerCsds(cluster, servicePillar); } }</code><technical_language>please add a log message skipping CSD update a Data Lake</technical_language>

Target:
private void decorateWorkloadClusterPillarWithCsdDownloader(StackType stackType, Cluster cluster, Map<String, SaltPillarProperties> servicePillar) { if (StackType.WORKLOAD.equals(stackType)) { clusterHostServiceRunner.decoratePillarWithClouderaManagerCsds(cluster, servicePillar); } else { LOGGER.debug("Skipping the CSD downloading because the stack type is {}", stackType); } }
Source:
<code>public void importCustomEntryTypes(List<EntryType> checkedUnknownEntryTypes, List<EntryType> checkedDifferentEntryTypes) { if (!checkedUnknownEntryTypes.isEmpty()) { checkedUnknownEntryTypes.forEach(type -> EntryTypes.addOrModifyCustomEntryType((CustomEntryType) type, mode)); <START> CustomEntryTypesManager.saveCustomEntryTypes(Globals.prefs); <END> } if (!checkedDifferentEntryTypes.isEmpty()) { checkedUnknownEntryTypes.forEach(type -> EntryTypes.addOrModifyCustomEntryType((CustomEntryType) type, mode)); CustomEntryTypesManager.saveCustomEntryTypes(Globals.prefs); } }</code><technical_language>Please extract Globals.prefs dependency (and move saveCustomEntryTypes method preferences class)</technical_language>

Target:
public void importCustomEntryTypes(List<EntryType> checkedUnknownEntryTypes, List<EntryType> checkedDifferentEntryTypes) { if (!checkedUnknownEntryTypes.isEmpty()) { checkedUnknownEntryTypes.forEach(type -> EntryTypes.addOrModifyCustomEntryType((CustomEntryType) type, mode)); preferencesService.saveCustomEntryTypes(); } if (!checkedDifferentEntryTypes.isEmpty()) { checkedUnknownEntryTypes.forEach(type -> EntryTypes.addOrModifyCustomEntryType((CustomEntryType) type, mode)); preferencesService.saveCustomEntryTypes(); } }
Source:
<code>public Connector create(String catalogName, Map<String, String> config, ConnectorContext context) { requireNonNull(catalogName, "catalogName is null"); requireNonNull(config, "config is null"); try { Bootstrap app = new Bootstrap( new JsonModule(), new ElasticsearchConnectorModule(), binder -> { binder.bind(TypeManager.class).toInstance(context.getTypeManager()); binder.bind(NodeManager.class).toInstance(context.getNodeManager()); if (tableDescriptionSupplier.isPresent()) { <START> binder.bind(new TypeLiteral<Supplier<Map<SchemaTableName, ElasticsearchTableDescription>>>() {}).toInstance(tableDescriptionSupplier.get()); <END> } else { binder.bind(new TypeLiteral<Supplier<Map<SchemaTableName, ElasticsearchTableDescription>>>() {}).to(ElasticsearchTableDescriptionSupplier.class).in(Scopes.SINGLETON); } }); Injector injector = app.strictConfig() .doNotInitializeLogging() .setRequiredConfigurationProperties(config) .initialize(); return injector.getInstance(ElasticsearchConnector.class); } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>Please define interface for TypeLiteral<Supplier<Map<SchemaTableName, ElasticsearchTableDescription>>>. interface ElasticsearchTableDescriptionProvider { ElasticsearchTableDescription get(SchemaTableName table); }</technical_language>

Target:
public Connector create(String catalogName, Map<String, String> config, ConnectorContext context) { requireNonNull(catalogName, "catalogName is null"); requireNonNull(config, "config is null"); try { Bootstrap app = new Bootstrap( new JsonModule(), new ElasticsearchConnectorModule(), binder -> { binder.bind(TypeManager.class).toInstance(context.getTypeManager()); binder.bind(NodeManager.class).toInstance(context.getNodeManager()); binder.bind(ElasticsearchTableDescriptionProvider.class).in(Scopes.SINGLETON); }); Injector injector = app.strictConfig() .doNotInitializeLogging() .setRequiredConfigurationProperties(config) .initialize(); return injector.getInstance(ElasticsearchConnector.class); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public void testTemplateMemberAccessibilities() throws Exception { String code = getAboveComment(); <START> BindingAssertionHelper bh = new BindingAssertionHelper(code, true); <END> ICPPClassTemplate aTemplate = bh.assertNonProblem("ATemplate", 9); ICPPField defaultMemberVariable = bh.assertNonProblem("defaultMemberVariable", 21); assertAccessibility(ICPPClassType.a_private, aTemplate.getAccessibility(defaultMemberVariable)); ICPPField publicMemberVariable = bh.assertNonProblem("publicMemberVariable", 20); assertAccessibility(ICPPClassType.a_public, aTemplate.getAccessibility(publicMemberVariable)); ICPPField protectedMemberVariable = bh.assertNonProblem("protectedMemberVariable", 23); assertAccessibility(ICPPClassType.a_protected, aTemplate.getAccessibility(protectedMemberVariable)); ICPPField privateMemberVariable = bh.assertNonProblem("privateMemberVariable", 21); assertAccessibility(ICPPClassType.a_private, aTemplate.getAccessibility(privateMemberVariable)); }</code><technical_language>Simpler: BindingAssertionHelper bh = getAssertionHelper(); in other test</technical_language>

Target:
public void testTemplateMemberAccessibilities() throws Exception { BindingAssertionHelper bh = getAssertionHelper(); ICPPClassTemplate aTemplate = bh.assertNonProblem("ATemplate"); ICPPField defaultMemberVariable = bh.assertNonProblem("defaultMemberVariable"); VisibilityHelper.assertVisibility(ICPPClassType.v_private, aTemplate.getVisibility(defaultMemberVariable)); ICPPField publicMemberVariable = bh.assertNonProblem("publicMemberVariable"); VisibilityHelper.assertVisibility(ICPPClassType.v_public, aTemplate.getVisibility(publicMemberVariable)); ICPPField protectedMemberVariable = bh.assertNonProblem("protectedMemberVariable"); VisibilityHelper.assertVisibility(ICPPClassType.v_protected, aTemplate.getVisibility(protectedMemberVariable)); ICPPField privateMemberVariable = bh.assertNonProblem("privateMemberVariable"); VisibilityHelper.assertVisibility(ICPPClassType.v_private, aTemplate.getVisibility(privateMemberVariable)); }
Source:
<code>public void onFinish(SpanWrapper span, String operationName, long durationNanos) { final SpanContextInformation contextInfo = SpanContextInformation.forSpan(span); final MonitoredHttpRequest monitoredHttpRequest = contextInfo .getRequestAttribute(MONITORED_HTTP_REQUEST_ATTRIBUTE); if (monitoredHttpRequest == null) { return; } trackServletExceptions(span, monitoredHttpRequest.httpServletRequest); setParams(span, monitoredHttpRequest.httpServletRequest); setTrackingInformation(span, monitoredHttpRequest.httpServletRequest, monitoredHttpRequest.clientIp, monitoredHttpRequest.userAgentHeader); setStatus(span, monitoredHttpRequest.responseWrapper.getStatus()); span.setTag("bytes_written", monitoredHttpRequest.responseWrapper.getContentLength()); final Future<Void> userAgentParsedFuture = contextInfo.getRequestAttribute(USER_AGENT_PARSED_FUTURE_ATTRIBUTE); if (userAgentParsedFuture != null) { try { userAgentParsedFuture.get(); } catch (Exception e) { logger.warn("Suppressed exception", e); } } <START> final Long gcTime = contextInfo.getRequestAttribute(GC_TIME_ATTRIBUTE); <END> if (gcTime != null) { span.setTag("gc_time_ms", collectGcTimeMs() - gcTime); } }</code><technical_language>Move this a SpanEventListener. works for other request types well</technical_language>

Target:
public void onFinish(SpanWrapper span, String operationName, long durationNanos) { final SpanContextInformation contextInfo = SpanContextInformation.forSpan(span); final MonitoredHttpRequest monitoredHttpRequest = contextInfo .getRequestAttribute(MONITORED_HTTP_REQUEST_ATTRIBUTE); if (monitoredHttpRequest == null) { return; } trackServletExceptions(span, monitoredHttpRequest.httpServletRequest); setParams(span, monitoredHttpRequest.httpServletRequest); setTrackingInformation(span, monitoredHttpRequest.httpServletRequest, monitoredHttpRequest.clientIp, monitoredHttpRequest.userAgentHeader); setStatus(span, monitoredHttpRequest.responseWrapper.getStatus()); span.setTag("bytes_written", monitoredHttpRequest.responseWrapper.getContentLength()); final Future<Void> userAgentParsedFuture = contextInfo.getRequestAttribute(USER_AGENT_PARSED_FUTURE_ATTRIBUTE); if (userAgentParsedFuture != null) { try { userAgentParsedFuture.get(); } catch (Exception e) { logger.warn("Suppressed exception", e); } } }
Source:
<code>public Mono<T> one(T object) { return Mono.just(object).flatMap(o -> { CouchbaseDocument converted = template.support().encodeEntity(o); <START> Object updatedObject = template.support().applyUpdatedId(o, converted.getId()); <END> return template.getCollection(collection).reactive() .upsert(converted.getId(), converted.export(), buildUpsertOptions()).map(result -> { return (T) template.support().applyUpdatedCas(updatedObject, result.cas()); }); }).onErrorMap(throwable -> { if (throwable instanceof RuntimeException) { return template.potentiallyConvertRuntimeException((RuntimeException) throwable); } else { return throwable; } }); }</code><technical_language>sense move apply methods upsert map callback done in spot</technical_language>

Target:
public Mono<T> one(T object) { return Mono.just(object).flatMap(o -> { CouchbaseDocument converted = template.support().encodeEntity(o); return template.getCollection(collection).reactive() .upsert(converted.getId(), converted.export(), buildUpsertOptions()).map(result -> { Object updatedObject = template.support().applyUpdatedId(o, converted.getId()); return (T) template.support().applyUpdatedCas(updatedObject, result.cas()); }); }).onErrorMap(throwable -> { if (throwable instanceof RuntimeException) { return template.potentiallyConvertRuntimeException((RuntimeException) throwable); } else { return throwable; } }); }
Source:
<code>private byte[] receivedClientKeyExchange(final PSKClientKeyExchange message) throws HandshakeException { clientKeyExchange = message; String identity = message.getIdentity(); byte[] psk = pskStore.getKey(getIndicatedServerNames(), identity); String virtualHost = null; if (getIndicatedServerNames() == null) { LOGGER.debug("Client uses PSK identity [{}]", <START> new Object[]{getPeerAddress(), identity}); <END> } else { ServerName serverName = getIndicatedServerNames().getServerName(NameType.HOST_NAME); if (serverName == null) { LOGGER.debug("client provided invalid SNI extension which doesn't include a hostname"); } else { virtualHost = new String(serverName.getName(), ServerName.CHARSET); LOGGER.debug("Client uses PSK identity for server [{}]", new Object[]{getPeerAddress(), identity, virtualHost}); } } if (psk == null) { throw new HandshakeException( String.format("Cannot authenticate client, identity [%s] is unknown", identity), new AlertMessage(AlertLevel.FATAL, AlertDescription.UNKNOWN_PSK_IDENTITY, session.getPeer())); } else { session.setPeerIdentity(new PreSharedKeyIdentity(virtualHost, identity)); return generatePremasterSecretFromPSK(psk); } }</code><technical_language>Recently, explicit new Object[]{ ... }</technical_language>

Target:
private byte[] receivedClientKeyExchange(final PSKClientKeyExchange message) throws HandshakeException { clientKeyExchange = message; String identity = message.getIdentity(); byte[] psk = pskStore.getKey(getIndicatedServerNames(), identity); String virtualHost = null; if (getIndicatedServerNames() == null) { LOGGER.debug("Client uses PSK identity [{}]", getPeerAddress(), identity); } else { ServerName serverName = getIndicatedServerNames().getServerName(NameType.HOST_NAME); if (serverName == null) { LOGGER.debug("client provided invalid SNI extension which doesn't include a hostname"); } else { virtualHost = new String(serverName.getName(), ServerName.CHARSET); LOGGER.debug("Client uses PSK identity for server [{}]", getPeerAddress(), identity, virtualHost); } } if (psk == null) { throw new HandshakeException( String.format("Cannot authenticate client, identity [%s] is unknown", identity), new AlertMessage(AlertLevel.FATAL, AlertDescription.UNKNOWN_PSK_IDENTITY, session.getPeer())); } else { session.setPeerIdentity(new PreSharedKeyIdentity(virtualHost, identity)); return generatePremasterSecretFromPSK(psk); } }
Source:
<code>public static Thread findThreadById(final long threadId) { final Collection<Thread> result = findThreads(new ThreadIdPredicate(threadId)); <START> if(!result.iterator().hasNext()) { <END> return null; } else { return result.iterator().next(); } }</code><technical_language>result.isEmpty() instead avoid creating iterator instance</technical_language>

Target:
public static Thread findThreadById(final long threadId) { final Collection<Thread> result = findThreads(new ThreadIdPredicate(threadId)); if(result.isEmpty()) { return null; } else { return result.iterator().next(); } }
Source:
<code>protected boolean processResponseError(ReplicaId replicaId, ServerErrorCode serverErrorCode) throws CoordinatorException { switch (serverErrorCode) { case No_Error: return true; case IO_Error: case Data_Corrupt: return false; case Blob_Not_Found: <START> getResponsePolicy.blobNotFound(replicaId); <END> return false; case Blob_Deleted: getResponsePolicy.blobDeleted(replicaId); return false; case Blob_Expired: getResponsePolicy.blobExpired(replicaId); return false; default: logger.error("{} GetResponse for BlobId received from ReplicaId had unexpected error code {}", oc, blobId, replicaId, serverErrorCode); throw new CoordinatorException("Unexpected server error code in GetResponse.", CoordinatorError.UnexpectedInternalError); } }</code><technical_language>This is super hard read. policy for main loop leave rest inlined a strong reason abstract this policies</technical_language>

Target:
protected boolean processResponseError(ReplicaId replicaId, ServerErrorCode serverErrorCode) throws CoordinatorException { switch (serverErrorCode) { case No_Error: return true; case IO_Error: case Data_Corrupt: return false; case Blob_Not_Found: blobNotFoundCount++; if (blobNotFoundCount == replicaIdCount) { throw new CoordinatorException("Blob not found.", CoordinatorError.BlobDoesNotExist); } return false; case Blob_Deleted: blobDeletedCount++; if (blobDeletedCount >= min(Blob_Deleted_Count_Threshold, replicaIdCount)) { throw new CoordinatorException("Blob deleted.", CoordinatorError.BlobDeleted); } return false; case Blob_Expired: blobExpiredCount++; if (blobExpiredCount >= min(Blob_Expired_Count_Threshold, replicaIdCount)) { throw new CoordinatorException("Blob expired.", CoordinatorError.BlobExpired); } return false; default: CoordinatorException e = new CoordinatorException("Server returned unexpected error for GetOperation.", CoordinatorError.UnexpectedInternalError); logger.error("{} GetResponse for BlobId received from ReplicaId had unexpected error code {}: {}", context, blobId, replicaId, serverErrorCode, e); throw e; } }
Source:
<code>public void setUpTtl(final long inactivityDuration, final long inactivityDurationInitialDelay, final boolean useKeepAlive) { this.useKeepAlive = useKeepAlive; this.maxInactivityDuration = inactivityDuration; <START> new Thread(new Runnable() { <END> @Override public void run() { if (inactivityDurationInitialDelay > 0) { try { ttlLatch.await(inactivityDurationInitialDelay, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } } if (inactivityDuration >= 0) { connectionEntry.ttl = inactivityDuration; } } }).start(); checkInactivity(); }</code><technical_language>thread... Scheduled Executor.. this is good!!!</technical_language>

Target:
public void setUpTtl(final long inactivityDuration, final long inactivityDurationInitialDelay, final boolean useKeepAlive) { this.useKeepAlive = useKeepAlive; this.maxInactivityDuration = inactivityDuration; protocolManager.getScheduledPool().schedule(new Runnable() { @Override public void run() { if (inactivityDuration >= 0) { connectionEntry.ttl = inactivityDuration; } } }, inactivityDurationInitialDelay, TimeUnit.MILLISECONDS); checkInactivity(); }
Source:
<code>protected Object decodeEavsys( String sentence, Channel channel, SocketAddress remoteAddress) { Parser parser = new Parser(PATTERN_EAVSYS, sentence); if (!parser.matches()) { return null; } DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next()); if (deviceSession == null) { return null; } Position position = new Position(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); if (!getLastLocation(position, null)) { return null; } position.set(Position.KEY_ICCID, parser.next()); <START> String unused = parser.next(); <END> unused = parser.next(); int hardware = parser.nextHexInt(); position.set(Position.KEY_VERSION_HW, (hardware == 0x12) ? "SF-Lite" : (hardware == 0x52) ? "S911 Lola" : null); position.set(Position.KEY_VERSION_FW, String.format("%d.%02d.%02d", parser.nextInt(), parser.nextInt(), parser.nextInt())); return position; }</code><technical_language>capture unused data</technical_language>

Target:
protected Object decodeEavsys( String sentence, Channel channel, SocketAddress remoteAddress) { Parser parser = new Parser(PATTERN_EAVSYS, sentence); if (!parser.matches()) { return null; } DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next()); if (deviceSession == null) { return null; } Position position = new Position(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); getLastLocation(position, null); position.set(Position.KEY_ICCID, parser.next()); position.set(Position.KEY_PHONE, parser.next()); position.set(Position.KEY_VERSION_FW, parser.next()); return position; }
Source:
<code><START> private DataSetReference.Builder handleAdditionalIds(OafEntity oafEntity, DataSetReference.Builder metaBuilder) { <END> Map<CharSequence, CharSequence> additionalIds = new HashMap<CharSequence, CharSequence>(); if (CollectionUtils.isNotEmpty(oafEntity.getPidList())) { for (StructuredProperty currentPid : oafEntity.getPidList()) { if (StringUtils.isNotBlank(currentPid.getQualifier().getClassid()) && StringUtils.isNotBlank(currentPid.getValue()) && fieldApprover.approve(currentPid.getDataInfo())) { additionalIds.put(currentPid.getQualifier().getClassid(), currentPid.getValue()); if (ID_TYPE_DOI_LOWERCASED.equalsIgnoreCase(currentPid.getQualifier().getClassid())) { metaBuilder.setReferenceType(ID_TYPE_DOI_LOWERCASED); metaBuilder.setIdForGivenType(currentPid.getValue()); } } } } if (!additionalIds.isEmpty()) { metaBuilder.setAlternateIdentifiers(additionalIds); if (metaBuilder.getReferenceType() == null) { Entry<CharSequence,CharSequence> firstIdsPair = additionalIds.entrySet().iterator().next(); metaBuilder.setReferenceType(firstIdsPair.getKey()); metaBuilder.setIdForGivenType(firstIdsPair.getValue()); } } return metaBuilder; }</code><technical_language>Object returned this method is e.g. method return void</technical_language>

Target:
private void handleAdditionalIds(OafEntity oafEntity, DataSetReference.Builder metaBuilder) { List<StructuredProperty> filtered = oafEntity.getPidList().stream() .filter(x -> StringUtils.isNotBlank(x.getQualifier().getClassid())) .filter(x -> StringUtils.isNotBlank(x.getValue())) .filter(x -> fieldApprover.approve(x.getDataInfo())) .collect(Collectors.toList()); Map<CharSequence, CharSequence> additionalIds = filtered.stream() .collect(Collectors.toMap(k -> k.getQualifier().getClassid(), v -> v.getValue())); Optional.ofNullable( filtered.stream().filter(x -> ID_TYPE_DOI_LOWERCASED.equalsIgnoreCase(x.getQualifier().getClassid())) .collect(Collectors.toCollection(LinkedList::new)).peekLast()) .ifPresent(last -> { metaBuilder.setReferenceType(ID_TYPE_DOI_LOWERCASED); metaBuilder.setIdForGivenType(last.getValue()); }); if (!additionalIds.isEmpty()) { metaBuilder.setAlternateIdentifiers(additionalIds); if (metaBuilder.getReferenceType() == null) { Entry<CharSequence, CharSequence> firstIdsPair = additionalIds.entrySet().iterator().next(); metaBuilder.setReferenceType(firstIdsPair.getKey()); metaBuilder.setIdForGivenType(firstIdsPair.getValue()); } } }
Source:
<code>private static PrimitiveTypeInfo getType(String name, Schema schema) { Schema.Type type = schema.isNullable() ? schema.getNonNullable().getType() : schema.getType(); switch (type) { case BOOLEAN: return TypeInfoFactory.booleanTypeInfo; case INT: return TypeInfoFactory.intTypeInfo; case LONG: return TypeInfoFactory.longTypeInfo; case FLOAT: return TypeInfoFactory.floatTypeInfo; case DOUBLE: return TypeInfoFactory.doubleTypeInfo; case STRING: return TypeInfoFactory.stringTypeInfo; case BYTES: return TypeInfoFactory.binaryTypeInfo; default: throw new IllegalArgumentException(String.format( <START> "Schema contains field '%s' with unsupported type %s", name, type)); <END> } }</code><technical_language>corrective action if this problem happen</technical_language>

Target:
private static PrimitiveTypeInfo getType(String name, Schema schema) { Schema.Type type = schema.isNullable() ? schema.getNonNullable().getType() : schema.getType(); switch (type) { case BOOLEAN: return TypeInfoFactory.booleanTypeInfo; case INT: return TypeInfoFactory.intTypeInfo; case LONG: return TypeInfoFactory.longTypeInfo; case FLOAT: return TypeInfoFactory.floatTypeInfo; case DOUBLE: return TypeInfoFactory.doubleTypeInfo; case STRING: return TypeInfoFactory.stringTypeInfo; case BYTES: return TypeInfoFactory.binaryTypeInfo; default: throw new IllegalArgumentException(String.format( "Schema contains field '%s' with unsupported type %s. " + "You should provide an schema with this field dropped to work with this table.", name, type)); } }
Source:
<code>public void start() throws Exception { <START> load(); <END> VIEW_INJECTED_VARS.setEnabled(getConfiguration().isEnablePermissions()); }</code><technical_language>for call load</technical_language>

Target:
public void start() throws Exception { VIEW_INJECTED_VARS.setEnabled(getConfiguration().isEnablePermissions()); }
Source:
<code><START> public void categoryTest_003_checkPagination(){ <END> MobileCategoryPageObject mobile = new MobileCategoryPageObject(driver); mobile.openCategory(wikiURL); mobile.openArticlesWithPagination(); mobile.verifyPagination(); }</code><technical_language>space</technical_language>

Target:
public void categoryTest_003_checkPagination() { MobileCategoryPageObject mobile = new MobileCategoryPageObject(driver); mobile.openCategory(wikiURL); mobile.openArticle(2); mobile.verifyArticlesCount(25); String firstArticle = mobile.getFirstArticleName(); String lastArticle = mobile.getLastArticleName(); mobile.showNextArticles(); String firstArticle2 = mobile.getFirstArticleName(); mobile.verifyArticlesNotEquals(firstArticle, firstArticle2); mobile.showPreviousArticles(); mobile.verifyArticlesCount(25); String firstArticle3 = mobile.getFirstArticleName(); String lastArticle3 = mobile.getLastArticleName(); mobile.verifyArticlesEquals(firstArticle, firstArticle3); mobile.verifyArticlesEquals(lastArticle, lastArticle3); }
Source:
<code><START> public int lengthOfMonth() { <END> return InternationalFixedChronology.DAYS_IN_MONTH; }</code><technical_language>Need return 1 leap-day year-day</technical_language>

Target:
public int lengthOfMonth() { return this.month > 0 ? DAYS_IN_MONTH : 1; }
Source:
<code>public APIResult submit( @Context HttpServletRequest request, @Dimension("entityType") @PathParam("type") final String type, @Dimension("colo") @QueryParam("colo") final String ignore) { final HttpServletRequest bufferedRequest = getBufferedRequest(request); final Entity entity = getEntity(bufferedRequest, type); Map<String, APIResult> results = new HashMap<String, APIResult>(); final Set<String> colos = getApplicableColos(type, entity); <START> doesEntityHasExtensionJobTag(entity); <END> validateEntity(entity, colos); results.put(FALCON_TAG, new EntityProxy(type, entity.getName()) { @Override protected Set<String> getColosToApply() { return colos; } @Override protected APIResult doExecute(String colo) throws FalconException { return getConfigSyncChannel(colo).invoke("submit", bufferedRequest, type, colo); } }.execute()); if (!embeddedMode) { results.put(PRISM_TAG, super.submit(bufferedRequest, type, currentColo)); } return consolidateResult(results, APIResult.class); }</code><technical_language>Method name, entityHasExtensionJobTag, is good enough</technical_language>

Target:
public APIResult submit( @Context HttpServletRequest request, @Dimension("entityType") @PathParam("type") final String type, @Dimension("colo") @QueryParam("colo") final String ignore) { final HttpServletRequest bufferedRequest = getBufferedRequest(request); final Entity entity = getEntity(bufferedRequest, type); Map<String, APIResult> results = new HashMap<String, APIResult>(); final Set<String> colos = getApplicableColos(type, entity); entityHasExtensionJobTag(entity); validateEntity(entity, colos); results.put(FALCON_TAG, new EntityProxy(type, entity.getName()) { @Override protected Set<String> getColosToApply() { return colos; } @Override protected APIResult doExecute(String colo) throws FalconException { return getConfigSyncChannel(colo).invoke("submit", bufferedRequest, type, colo); } }.execute()); if (!embeddedMode) { results.put(PRISM_TAG, super.submit(bufferedRequest, type, currentColo)); } return consolidateResult(results, APIResult.class); }
Source:
<code>private ObjectNode _createMappingsNode() { ObjectMapper mapper = new ObjectMapper(); ObjectNode propertiesNode = mapper.createObjectNode(); propertiesNode.put(RecordType.SCOPE.getName(), _createFieldNode("text")); propertiesNode.put(RecordType.METRIC.getName(), _createFieldNode("text")); propertiesNode.put(RecordType.TAGK.getName(), _createFieldNode("text")); propertiesNode.put(RecordType.TAGV.getName(), _createFieldNode("text")); propertiesNode.put(RecordType.NAMESPACE.getName(), _createFieldNode("text")); <START> propertiesNode.put("mts", _createFieldNode("date")); <END> ObjectNode typeNode = mapper.createObjectNode(); typeNode.put("properties", propertiesNode); ObjectNode mappingsNode = mapper.createObjectNode(); mappingsNode.put(TYPE_NAME, typeNode); return mappingsNode; }</code><technical_language>this a name createdDateMillis etc? add a reference RecordType enum fields</technical_language>

Target:
private ObjectNode _createMappingsNode() { ObjectMapper mapper = new ObjectMapper(); ObjectNode propertiesNode = mapper.createObjectNode(); propertiesNode.put(RecordType.SCOPE.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.METRIC.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.TAGK.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.TAGV.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.NAMESPACE.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put("mts", _createFieldNode(FIELD_TYPE_DATE)); ObjectNode typeNode = mapper.createObjectNode(); typeNode.put("properties", propertiesNode); ObjectNode mappingsNode = mapper.createObjectNode(); mappingsNode.put(TYPE_NAME, typeNode); return mappingsNode; }
Source:
<code>private static List<EClass> advancedSortEClasses(List<EClass> eclasses) { List<EClass> sortedEClasses = new LinkedList<EClass>(); Map<EClass, Integer> mapOfUnsortedEClasses = new HashMap<EClass, Integer>(); for(EClass eclass : eclasses){ mapOfUnsortedEClasses.put(eclass, eclass.getESuperTypes().size()); } while(mapOfUnsortedEClasses.size()>0){ EClass processedEClass = null; Iterator<Map.Entry<EClass, Integer>> iterator = mapOfUnsortedEClasses.entrySet().iterator(); while(iterator.hasNext() && processedEClass == null){ Map.Entry<EClass, Integer> entry = iterator.next(); if(entry.getValue() == 0){ processedEClass = entry.getKey(); sortedEClasses.add(processedEClass); } } <START> mapOfUnsortedEClasses.remove(processedEClass); for(Map.Entry<EClass, Integer> entry : mapOfUnsortedEClasses.entrySet()){ if(entry.getKey().getESuperTypes().contains(processedEClass)) entry.setValue(entry.getValue()-1); } <END> if(processedEClass == null) return null; } return sortedEClasses; }</code><technical_language>This executed if processedEClass==null</technical_language>

Target:
private static List<EClass> advancedSortEClasses(List<EClass> eclasses) { List<EClass> sortedEClasses = new LinkedList<EClass>(); Map<EClass, Integer> mapOfUnsortedEClasses = new HashMap<EClass, Integer>(); for(EClass eclass : eclasses){ mapOfUnsortedEClasses.put(eclass, eclass.getESuperTypes().size()); } while(mapOfUnsortedEClasses.size()>0){ EClass processedEClass = null; Iterator<Map.Entry<EClass, Integer>> iterator = mapOfUnsortedEClasses.entrySet().iterator(); while(iterator.hasNext() && processedEClass == null){ Map.Entry<EClass, Integer> entry = iterator.next(); if(entry.getValue() == 0){ processedEClass = entry.getKey(); sortedEClasses.add(processedEClass); } } mapOfUnsortedEClasses.remove(processedEClass); if(processedEClass != null){ for(Map.Entry<EClass, Integer> entry : mapOfUnsortedEClasses.entrySet()){ if(entry.getKey().getESuperTypes().contains(processedEClass)) entry.setValue(entry.getValue()-1); } } if(processedEClass == null) return null; } return sortedEClasses; }
Source:
<code><START> public Response fetchWorkflowInstance(@ApiParam("Internal id for workflow instance") @PathParam("id") long id, <END> @QueryParam("include") @ApiParam(value = INCLUDE_PARAM_DESC, allowableValues = INCLUDE_PARAM_VALUES, allowMultiple = true) String include, @QueryParam("maxActions") @ApiParam("Maximum number of actions returned for each workflow instance") Long maxActions) { try { return ok(super.fetchWorkflowInstance(id, include, maxActions, workflowInstances, listWorkflowConverter)).build(); } catch (@SuppressWarnings("unused") EmptyResultDataAccessException e) { return status(NOT_FOUND).entity(format("Workflow instance %s not found", id)).build(); } }</code><technical_language>I this needs @ApiResponse if changing return type swagger describe api correctly</technical_language>

Target:
public Response fetchWorkflowInstance(@ApiParam("Internal id for workflow instance") @PathParam("id") long id, @QueryParam("include") @ApiParam(value = INCLUDE_PARAM_DESC, allowableValues = INCLUDE_PARAM_VALUES, allowMultiple = true) String include, @QueryParam("maxActions") @ApiParam("Maximum number of actions returned for each workflow instance") Long maxActions) { try { return ok(super.fetchWorkflowInstance(id, include, maxActions, workflowInstances, listWorkflowConverter)).build(); } catch (@SuppressWarnings("unused") EmptyResultDataAccessException e) { return status(NOT_FOUND).entity(new ErrorResponse(format("Workflow instance %s not found", id))).build(); } }
Source:
<code>private void setTimeZoneFromCourseTimeZoneIfRequired() { if (isFollowingCourseTimeZone) { return; } <START> Course course = Ref.create(Key.create(Course.class, courseId)).get(); <END> ZoneId courseTimeZone = Const.DEFAULT_TIME_ZONE; if (course == null) { log.severe("Could not retrieve course \"" + courseId + "\"; defaulting to UTC for session: " + feedbackSessionId); } else { try { courseTimeZone = ZoneId.of(course.getTimeZone()); } catch (DateTimeException e) { log.severe("Invalid time zone \"" + course.getTimeZone() + "\" encountered for course \"" + courseId + "\"; defaulting to UTC for session: " + feedbackSessionId); } } timeZone = courseTimeZone.getId(); isFollowingCourseTimeZone = true; }</code><technical_language>This removed data migration, right</technical_language>

Target:
private void setTimeZoneFromCourseTimeZoneIfRequired() { if (isFollowingCourseTimeZone) { wasFollowingCourseTimeZone = true; return; } Course course = Ref.create(Key.create(Course.class, courseId)).get(); ZoneId courseTimeZone = Const.DEFAULT_TIME_ZONE; if (course == null) { log.severe("Could not retrieve course \"" + courseId + "\"; defaulting to UTC for session: " + feedbackSessionId); } else { try { courseTimeZone = ZoneId.of(course.getTimeZone()); } catch (DateTimeException e) { log.severe("Invalid time zone \"" + course.getTimeZone() + "\" encountered for course \"" + courseId + "\"; defaulting to UTC for session: " + feedbackSessionId); } } timeZone = courseTimeZone.getId(); isFollowingCourseTimeZone = true; }
Source:
<code>public void testForOutOfBoundsException() { DefaultDescription desc = new DefaultDescription(); <START> score(0, scorer.score(itemWithTitle("Storage Hunters"), of(itemWithTitle(":Storage Hunters: UK")), desc)); <END> }</code><technical_language>tests returning a score of 0. need some tests return a good score for cases</technical_language>

Target:
public void testForOutOfBoundsException() { DefaultDescription desc = new DefaultDescription(); score(0, scorer.score(itemWithTitle("Storage Hunters"), of(itemWithTitle(":Storage Hunters: UK")), desc)); score(2, scorer.score(itemWithTitle("Storage Hunters"), of(itemWithTitle(":Storage Hunters:")), desc)); }
Source:
<code>protected void configure(final HttpSecurity http) throws Exception { <START> final SecurityFilter filter = new SecurityFilterWithSkipCondition(config, "HeaderClient") { <END> @Override protected boolean skip(HttpServletRequest request, String authTokenHeader) { final String path = request.getServletPath(); String authToken = request.getHeader(authTokenHeader); return path.startsWith("/api/v1/concepts") && Strings.isNullOrEmpty(authToken); } }; http .antMatcher("/api/**") .addFilterBefore(filter, BasicAuthenticationFilter.class) .csrf() .disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER); }</code><technical_language>add /api/v1/concepts http config permitAll instead of constructing filter</technical_language>

Target:
protected void configure(final HttpSecurity http) throws Exception { final SecurityFilter filter = new SecurityFilter(config, "HeaderClient,AnonymousClient"); http .antMatcher("/api/**") .addFilterBefore(filter, BasicAuthenticationFilter.class) .csrf() .disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER); }
Source:
<code>public VmUniverseParams data() { if (data.isPresent()) { return data.get(); } CorfuClusterParams clusterParams = cluster.build(); FixtureUtil fixtureUtil = fixtureUtilBuilder.build(); ImmutableList<CorfuServerParams> serversParams = fixtureUtil.buildVmServers( clusterParams, servers, vmPrefix ); serversParams.forEach(clusterParams::add); ConcurrentMap<String, String> vmIpAddresses = new ConcurrentHashMap<>(); for (int i = 0; i < clusterParams.getNumNodes(); i++) { <START> vmIpAddresses.put(vmPrefix + (i + 1), "0.0.0.0"); <END> } VmUniverseParams universeParams = universe .vmIpAddresses(vmIpAddresses) .build(); universeParams.add(clusterParams); data = Optional.of(universeParams); return universeParams; }</code><technical_language>Please put this a ANY_ADDRESS constant</technical_language>

Target:
public VmUniverseParams data() { if (data.isPresent()) { return data.get(); } CorfuClusterParams clusterParams = cluster.build(); FixtureUtil fixtureUtil = fixtureUtilBuilder.build(); ImmutableList<CorfuServerParams> serversParams = fixtureUtil.buildVmServers( clusterParams, servers, vmPrefix ); serversParams.forEach(clusterParams::add); ConcurrentMap<String, String> vmIpAddresses = new ConcurrentHashMap<>(); for (int i = 0; i < clusterParams.getNumNodes(); i++) { vmIpAddresses.put(vmPrefix + (i + 1), ANY_ADDRESS); } VmUniverseParams universeParams = universe .vmIpAddresses(vmIpAddresses) .build(); universeParams.add(clusterParams); data = Optional.of(universeParams); return universeParams; }
Source:
<code>void close() throws StoreException { <START> final Timer.Context context = metrics.indexShutdownTimeInMs.time(); <END> try { persistor.write(); if (hardDeleter != null) { try { hardDeleter.shutdown(); } catch (Exception e) { logger.error("Index : " + dataDir + " error while persisting cleanup token ", e); } } try { cleanShutdownFile.createNewFile(); } catch (IOException e) { logger.error("Index : " + dataDir + " error while creating clean shutdown file ", e); } } finally { context.close(); } }</code><technical_language>do need Timer for metrics? track rate, do we? A Histogram suffice</technical_language>

Target:
void close() throws StoreException { long startTimeInMs = time.milliseconds(); try { persistor.write(); if (hardDeleter != null) { try { hardDeleter.shutdown(); } catch (Exception e) { logger.error("Index : " + dataDir + " error while persisting cleanup token ", e); } } try { cleanShutdownFile.createNewFile(); } catch (IOException e) { logger.error("Index : " + dataDir + " error while creating clean shutdown file ", e); } } finally { metrics.indexShutdownTimeInMs.update(time.milliseconds() - startTimeInMs); } }
Source:
<code>public void channelActive(ChannelHandlerContext ctx) { log.info("channelActive: Outgoing connection established to: from id={}", ctx.channel().remoteAddress(), ctx.channel().localAddress()); HeaderMsg header = getHeaderMsg(0, CorfuMessage.PriorityLevel.NORMAL, 0, <START> UUID.fromString("00000000-0000-0000-0000-000000000000"), this.clientId, false, true); <END> RequestMsg request = getRequestMsg(header, getHandshakeRequestMsg(this.clientId, this.nodeId)); ctx.writeAndFlush(request); log.debug("channelActive: Add to channel pipeline.", READ_TIMEOUT_HANDLER); ctx.pipeline().addBefore(ctx.name(), READ_TIMEOUT_HANDLER, new ReadTimeoutHandler(this.handshakeTimeout)); }</code><technical_language>"00000000-0000-0000-0000-000000000000" a constant, put in a utility class constant instead of a string</technical_language>

Target:
public void channelActive(ChannelHandlerContext ctx) { log.info("channelActive: Outgoing connection established to: from id={}", ctx.channel().remoteAddress(), ctx.channel().localAddress()); HeaderMsg header = getHeaderMsg(0, CorfuMessage.PriorityLevel.NORMAL, 0, DEFAULT_UUID, this.clientId, false, true); RequestMsg request = getRequestMsg(header, getHandshakeRequestMsg(this.clientId, this.nodeId)); ctx.writeAndFlush(request); log.debug("channelActive: Add to channel pipeline.", READ_TIMEOUT_HANDLER); ctx.pipeline().addBefore(ctx.name(), READ_TIMEOUT_HANDLER, new ReadTimeoutHandler(this.handshakeTimeout)); }
Source:
<code>public Document getResult() { Document aggregateDocument = new Document(); for (String alias : this.orderedAliases) { AggregateValue aggregateValue = this.aliasToValue.get(alias); if (aggregateValue.getResult() != null) { Map<String, Object> map = new HashMap<>(); <START> map.put(alias, aggregateValue.getResult()); <END> aggregateDocument.set(alias, aggregateValue.getResult()); } } return aggregateDocument; }</code><technical_language>is of map</technical_language>

Target:
public Document getResult() { Document aggregateDocument = new Document(); for (String alias : this.orderedAliases) { AggregateValue aggregateValue = this.aliasToValue.get(alias); if (aggregateValue.getResult() != null) { aggregateDocument.set(alias, aggregateValue.getResult()); } } return aggregateDocument; }
Source:
<code>protected void appendCharacterBuffer(char ch[], int start, int length) { <START> if (characterBuffer != null) { <END> for (int i = start; i < start + length; i++) { characterBuffer.append(ch[i]); } } }</code><technical_language>characterBuffer null? question for getAndResetCharacterBuffer()</technical_language>

Target:
protected void appendCharacterBuffer(char ch[], int start, int length) { for (int i = start; i < start + length; i++) { characterBuffer.append(ch[i]); } }
Source:
<code>public static String getRequiredProperty(String key, String defaultValue, String[] validValues, String errorMessage) { assertTrue(StringUtils.isNotBlank(key)); String value = System.getProperty(key); if (StringUtils.isBlank(value)) { <START> if (defaultValue != null && !defaultValue.isEmpty()) { <END> log.info("Required property " + key + " is not defined, will use default value: " + defaultValue); value = defaultValue; } else { throw new AssertionError(errorMessage); } } else { log.info("System property defined: " + key + "=" + value); } if (validValues != null && validValues.length > 0) { assertThat(Arrays.asList(validValues), hasItem(value)); } return value; }</code><technical_language>StringUtils#isBlank for readability</technical_language>

Target:
public static String getRequiredProperty(String key, String defaultValue, String[] validValues, String errorMessage) { assertTrue(StringUtils.isNotBlank(key)); String value = System.getProperty(key); if (StringUtils.isBlank(value)) { if (defaultValue != null && !StringUtils.isBlank(defaultValue)) { log.info("Required property " + key + " is not defined, will use default value: " + defaultValue); value = defaultValue; } else { throw new AssertionError(errorMessage); } } else { log.info("System property defined: " + key + "=" + value); } if (validValues != null && validValues.length > 0) { assertThat(Arrays.asList(validValues), hasItem(value)); } return value; }