auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void processPayloadState(ChannelHandlerContext ctx, ByteBuf in, Http2FrameListener listener) throws Http2Exception { if (in.readableBytes() < payloadLength) { return; } int remaining = in.readableBytes() - payloadLength; readingHeaders = true; switch (frameType) { case DATA: readDataFrame(ctx, in, remaining, listener); break; case HEADERS: readHeadersFrame(ctx, in, remaining, listener); break; case PRIORITY: readPriorityFrame(ctx, in, listener); break; case RST_STREAM: readRstStreamFrame(ctx, in, listener); break; case SETTINGS: readSettingsFrame(ctx, in, listener); break; case PUSH_PROMISE: readPushPromiseFrame(ctx, in, remaining, listener); break; case PING: readPingFrame(ctx, in.readLong(), listener); break; case GO_AWAY: readGoAwayFrame(ctx, in, remaining, listener); break; case WINDOW_UPDATE: readWindowUpdateFrame(ctx, in, listener); break; case CONTINUATION: readContinuationFrame(in, remaining, listener); break; default: readUnknownFrame(ctx, in, remaining, listener); break; } <START> in.readerIndex(in.writerIndex() - remaining); <END> }</code><technical_language>nit: I easier read in.skipBytes(payloadLength);</technical_language>

Target:
private void processPayloadState(ChannelHandlerContext ctx, ByteBuf in, Http2FrameListener listener) throws Http2Exception { if (in.readableBytes() < payloadLength) { return; } int payloadEndIndex = in.readerIndex() + payloadLength; readingHeaders = true; switch (frameType) { case DATA: readDataFrame(ctx, in, payloadEndIndex, listener); break; case HEADERS: readHeadersFrame(ctx, in, payloadEndIndex, listener); break; case PRIORITY: readPriorityFrame(ctx, in, listener); break; case RST_STREAM: readRstStreamFrame(ctx, in, listener); break; case SETTINGS: readSettingsFrame(ctx, in, listener); break; case PUSH_PROMISE: readPushPromiseFrame(ctx, in, payloadEndIndex, listener); break; case PING: readPingFrame(ctx, in.readLong(), listener); break; case GO_AWAY: readGoAwayFrame(ctx, in, payloadEndIndex, listener); break; case WINDOW_UPDATE: readWindowUpdateFrame(ctx, in, listener); break; case CONTINUATION: readContinuationFrame(in, payloadEndIndex, listener); break; default: readUnknownFrame(ctx, in, payloadEndIndex, listener); break; } in.readerIndex(payloadEndIndex); }
Source:
<code>private static void checkPlaceHolders(Method method, List<String> errors) { int count = 0; <START> if (PropertiesFileInfo.properties.getProperty(method.getName()) != null) { <END> Set<Integer> foundIndex = new HashSet<Integer>(); Set<Integer> requiredIndexes = determineRequiredIndexes(method.getParameterAnnotations()); int minRequired = requiredIndexes.size(); Matcher matcher = placeHolderPattern.matcher(PropertiesFileInfo.properties.getProperty(method.getName())); while (matcher.find()) { int placeHolderIndex = -1; try { placeHolderIndex = Integer.parseInt(matcher.group(1)); if (!foundIndex.contains(placeHolderIndex)) { count++; foundIndex.add(placeHolderIndex); requiredIndexes.remove(placeHolderIndex); } if (placeHolderIndex < 0 || placeHolderIndex >= getMaxMethodParameter(method.getParameterAnnotations())) { errors.add(method.getName() + " contains out of bound index " + placeHolderIndex + " in " + PropertiesFileInfo.fileName); } } catch (NumberFormatException nfe) { errors.add(method.getName() + " contains invalid key " + matcher.group(0) + " in " + PropertiesFileInfo.fileName); } } if (count < minRequired || count > getMaxMethodParameter(method.getParameterAnnotations())) { errors.add(method.getName() + " does not match the number of parameters in " + PropertiesFileInfo.fileName); } if (!requiredIndexes.isEmpty()) { errors.add(method.getName() + " is missing required indexes in " + PropertiesFileInfo.fileName); } } }</code><technical_language>Minor thing, worth extracting method.getName() local variable</technical_language>

Target:
private static void checkPlaceHolders(Method method, List<String> errors) { int count = 0; String methodName = method.getName(); if (PropertiesFileInfo.properties.getProperty(methodName) != null) { Set<Integer> foundIndex = new HashSet<Integer>(); Set<Integer> requiredIndexes = determineRequiredIndexes(method.getParameterAnnotations()); int minRequired = requiredIndexes.size(); Matcher matcher = placeHolderPattern.matcher(PropertiesFileInfo.properties.getProperty(methodName)); while (matcher.find()) { int placeHolderIndex = -1; try { placeHolderIndex = Integer.parseInt(matcher.group(1)); if (!foundIndex.contains(placeHolderIndex)) { count++; foundIndex.add(placeHolderIndex); requiredIndexes.remove(placeHolderIndex); } if (placeHolderIndex < 0 || placeHolderIndex >= getMethodParameterCount(method)) { errors.add(methodName + " contains out of bound index " + placeHolderIndex + " in " + PropertiesFileInfo.fileName); } } catch (NumberFormatException nfe) { errors.add(methodName + " contains invalid key " + matcher.group(0) + " in " + PropertiesFileInfo.fileName); } } if (count < minRequired || count > getMethodParameterCount(method)) { errors.add(methodName + " does not match the number of parameters in " + PropertiesFileInfo.fileName); } if (!requiredIndexes.isEmpty()) { errors.add(methodName + " is missing required indexes in " + PropertiesFileInfo.fileName); } } }
Source:
<code>Mono<Response<KeyVaultRestoreOperation>> restoreWithResponse(String backupFolderUrl, String sasToken, Context context) { String[] segments = backupFolderUrl.split("/"); String folderName = segments[segments.length - 1]; String containerUrl = backupFolderUrl.substring(0, backupFolderUrl.length() - folderName.length()); SASTokenParameter sasTokenParameter = new SASTokenParameter() .setStorageResourceUri(containerUrl) .setToken(sasToken); RestoreOperationParameters restoreOperationParameters = new RestoreOperationParameters() .setSasTokenParameters(sasTokenParameter) .setFolderToRestore(folderName); return clientImpl.fullRestoreOperationWithResponseAsync(vaultUrl, restoreOperationParameters, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Restoring from location - {}{}", containerUrl, folderName)) .doOnSuccess(response -> logger.info("Restored from location - {}{}", containerUrl, folderName)) .doOnError(error -> <START> logger.warning("Failed to restore from location - {}{}", containerUrl, folderName, error)) <END> .map(restoreOperationResponse -> new SimpleResponse<>(restoreOperationResponse.getRequest(), restoreOperationResponse.getStatusCode(), restoreOperationResponse.getHeaders(), (KeyVaultRestoreOperation) transformToLongRunningOperation(restoreOperationResponse.getValue()))); }</code><technical_language>nit: simplify below? suggestion logger.warning("Failed restore location - {}", backupFolderUrl, error))</technical_language>

Target:
Mono<Response<KeyVaultRestoreOperation>> restoreWithResponse(String backupFolderUrl, String sasToken, Context context) { String[] segments = backupFolderUrl.split("/"); String folderName = segments[segments.length - 1]; String containerUrl = backupFolderUrl.substring(0, backupFolderUrl.length() - folderName.length()); SASTokenParameter sasTokenParameter = new SASTokenParameter() .setStorageResourceUri(containerUrl) .setToken(sasToken); RestoreOperationParameters restoreOperationParameters = new RestoreOperationParameters() .setSasTokenParameters(sasTokenParameter) .setFolderToRestore(folderName); return clientImpl.fullRestoreOperationWithResponseAsync(vaultUrl, restoreOperationParameters, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.info("Restoring from location - {}", backupFolderUrl)) .doOnSuccess(response -> logger.info("Restored from location - {}", backupFolderUrl)) .doOnError(error -> logger.warning("Failed to restore from location - {}", backupFolderUrl, error)) .map(restoreOperationResponse -> new SimpleResponse<>(restoreOperationResponse.getRequest(), restoreOperationResponse.getStatusCode(), restoreOperationResponse.getHeaders(), (KeyVaultRestoreOperation) transformToLongRunningOperation(restoreOperationResponse.getValue()))); }
Source:
<code>public void truncateJobCancelWithOutForce() throws IOException, SignatureException, XmlProcessingException, URISyntaxException, InterruptedException { final int testTimeOutSeconds = 5; final String bucketName = "test_truncate_cancel_job"; final String book1 = "beowulf.txt"; final Path objPath1 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book1); final Ds3Object obj1 = new Ds3Object(book1, Files.size(objPath1)); final Ds3Object obj2 = new Ds3Object("place_holder", 5000000); <START> final Path dirPath = FileSystems.getDefault().getPath("output"); <END> try { client.putBucket(new PutBucketRequest(bucketName)); Ds3ClientHelpers.wrap(client).ensureBucketExists(bucketName); final Ds3ClientHelpers.Job putJob = Ds3ClientHelpers.wrap(client).startWriteJob(bucketName, Lists.newArrayList(obj1, obj2)); final UUID jobId = putJob.getJobId(); final SeekableByteChannel book1Channel = new ResourceObjectPutter(RESOURCE_BASE_NAME).buildChannel(book1); client.putObject(new PutObjectRequest(bucketName, book1, book1Channel, jobId, 0, Files.size(objPath1))); final long startTime = System.nanoTime(); long cachedSize =0; while (cachedSize == 0) { Thread.sleep(500); final MasterObjectList mol = client.getJobSpectraS3(new GetJobSpectraS3Request(jobId)).getMasterObjectListResult(); cachedSize = mol.getCachedSizeInBytes(); assertTrue((System.nanoTime() - startTime)/1000000000 < testTimeOutSeconds ); } final CancelJobSpectraS3Response failedResponse = client.cancelJobSpectraS3(new CancelJobSpectraS3Request(jobId)); failedResponse.checkStatusCode(400); final GetJobSpectraS3Response truncatedJob = client.getJobSpectraS3(new GetJobSpectraS3Request(jobId)); assertEquals(truncatedJob.getMasterObjectListResult().getOriginalSizeInBytes(), Files.size(objPath1)); } finally { deleteAllContents(client, bucketName); } }</code><technical_language>is this used</technical_language>

Target:
public void truncateJobCancelWithOutForce() throws IOException, SignatureException, XmlProcessingException, URISyntaxException, InterruptedException { final int testTimeOutSeconds = 5; final String book1 = "beowulf.txt"; final Path objPath1 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book1); final Ds3Object obj1 = new Ds3Object(book1, Files.size(objPath1)); final Ds3Object obj2 = new Ds3Object("place_holder", 5000000); try { final Ds3ClientHelpers.Job putJob = HELPERS.startWriteJob(BUCKET_NAME, Lists.newArrayList(obj1, obj2)); final UUID jobId = putJob.getJobId(); final SeekableByteChannel book1Channel = new ResourceObjectPutter(RESOURCE_BASE_NAME).buildChannel(book1); client.putObject(new PutObjectRequest(BUCKET_NAME, book1, book1Channel, jobId, 0, Files.size(objPath1))); waitForObjectToBeInCache(testTimeOutSeconds, jobId); final CancelJobSpectraS3Response failedResponse = client.cancelJobSpectraS3(new CancelJobSpectraS3Request(jobId)); assertThat(failedResponse.getStatusCode(),is(400)); final GetJobSpectraS3Response truncatedJob = client.getJobSpectraS3(new GetJobSpectraS3Request(jobId)); assertEquals(truncatedJob.getMasterObjectListResult().getOriginalSizeInBytes(), Files.size(objPath1)); } finally { deleteAllContents(client, BUCKET_NAME); } }
Source:
<code>public static BindingListenerAnnotationBeanPostProcessor bindToAnnotationBeanPostProcessor(@Lazy BinderAwareChannelResolver binderAwareChannelResolver, @Lazy CompositeMessageConverterFactory compositeMessageConverterFactory) { DefaultMessageHandlerMethodFactory messageHandlerMethodFactory = new DefaultMessageHandlerMethodFactory(); messageHandlerMethodFactory.setMessageConverter(compositeMessageConverterFactory.getMessageConverterForAllRegistered()); messageHandlerMethodFactory.afterPropertiesSet(); BindingListenerAnnotationBeanPostProcessor bindingListenerAnnotationBeanPostProcessor = new BindingListenerAnnotationBeanPostProcessor(binderAwareChannelResolver, messageHandlerMethodFactory); <START> return bindingListenerAnnotationBeanPostProcessor; <END> }</code><technical_language>return new instance w/o local var</technical_language>

Target:
public static StreamListenerAnnotationBeanPostProcessor bindToAnnotationBeanPostProcessor(@Lazy BinderAwareChannelResolver binderAwareChannelResolver, @Lazy CompositeMessageConverterFactory compositeMessageConverterFactory) { DefaultMessageHandlerMethodFactory messageHandlerMethodFactory = new DefaultMessageHandlerMethodFactory(); messageHandlerMethodFactory.setMessageConverter(compositeMessageConverterFactory.getMessageConverterForAllRegistered()); messageHandlerMethodFactory.afterPropertiesSet(); return new StreamListenerAnnotationBeanPostProcessor(binderAwareChannelResolver, messageHandlerMethodFactory); }
Source:
<code>protected TestQueryPlanDeterminism() { <START> super(TestQueryPlanDeterminism::createLocalQueryRunner, FeatureSelection.all().without(ENGINE_ONLY).build()); <END> }</code><technical_language>really? other (e.g: include engine/planner only) features</technical_language>

Target:
protected TestQueryPlanDeterminism() { super(TestQueryPlanDeterminism::createLocalQueryRunner); }
Source:
<code>private void assertAllDisksAreActive(Collection<Disk> disks) { for (Disk disk : disks){ if (disk instanceof LunDisk){ continue; } DiskImage diskImage = DiskImage.class.cast(disk); assertTrue("disk should be active", <START> diskImage.getActive()); <END> } }</code><technical_language>getActive is exposed Disk interface, lose cast</technical_language>

Target:
private void assertAllDisksAreActive(Collection<Disk> disks) { for (Disk disk : disks){ if (disk instanceof LunDisk){ continue; } DiskImage diskImage = (DiskImage) disk; assertTrue("disk should be active", diskImage.getActive()); } }
Source:
<code><START> public MarkerItem <END> getMarkerItem(IMarker marker) { if (markerToEntryMap == null) { Map<IMarker, MarkerEntry> newMarkerToEntryMap = new HashMap<>(); for (MarkerEntry markerEntry : markerEntryArray) { IMarker nextMarker = markerEntry.getMarker(); if (nextMarker != null) { newMarkerToEntryMap.put(nextMarker, markerEntry); } } markerToEntryMap = newMarkerToEntryMap; } synchronized (markerToEntryMap) { if (markerToEntryMap.containsKey(marker)) { return markerToEntryMap.get(marker); } } return null; }</code><technical_language>enough this method synchronized</technical_language>

Target:
public MarkerItem getMarkerItem(IMarker marker) { Map<IMarker, MarkerEntry> entryMap = markerToEntryMap; if (entryMap == null) { entryMap = new HashMap<>(); for (MarkerEntry markerEntry : markerEntryArray) { IMarker nextMarker = markerEntry.getMarker(); if (nextMarker != null) { entryMap.put(nextMarker, markerEntry); } } markerToEntryMap = entryMap; } if (entryMap.containsKey(marker)) { return entryMap.get(marker); } return null; }
Source:
<code>public int setVersion() { buffer[offset] |= 0x80; <START> return 1; <END> }</code><technical_language>I understand methods return int</technical_language>

Target:
public boolean setVersion() { if (isInvalid()) { return false; } buffer[offset] |= 0x80; return true; }
Source:
<code><START> public Dimension getFloatingItemOffset() { <END> if (editPart instanceof FloatingLabelEditPart) { return ((FloatingLabelEditPart) editPart).getFloatingItemOffset(); } return new Dimension(); }</code><technical_language>Multi return is forbidden</technical_language>

Target:
public Dimension getFloatingItemOffset() { Dimension offset = null; if (editPart instanceof FloatingLabelEditPart) { offset = ((FloatingLabelEditPart) editPart).getFloatingItemOffset(); } return offset != null ? offset : new Dimension(); }
Source:
<code>public void run() { <START> AbstractAbstractFileNode<?> fileNode = weakNodeRef.get(); <END> if (fileNode == null) { return; } List<ContentTag> tags = fileNode.getContentTagsFromDatabase(); CorrelationAttributeInstance attribute = fileNode.getCorrelationAttributeInstance(); SCOData scoData = new SCOData(); scoData.setScoreAndDescription(fileNode.getScorePropertyAndDescription(tags)); scoData.setComment(fileNode.getCommentProperty(tags, attribute)); if (!UserPreferences.hideCentralRepoCommentsAndOccurrences()) { scoData.setCountAndDescription(fileNode.getCountPropertyAndDescription(attribute)); } if (listener != null) { listener.propertyChange(new PropertyChangeEvent( AutopsyEvent.SourceType.LOCAL.toString(), AbstractAbstractFileNode.NodeSpecificEvents.SCO_AVAILABLE.toString(), null, scoData)); } }</code><technical_language>I this trouble Results section of tree BlackboardArtifactNodes</technical_language>

Target:
public void run() { AbstractContentNode<?> contentNode = weakNodeRef.get(); if (contentNode == null) { return; } List<Tag> tags = contentNode.getAllTagsFromDatabase(); CorrelationAttributeInstance attribute = contentNode.getCorrelationAttributeInstance(); SCOData scoData = new SCOData(); scoData.setScoreAndDescription(contentNode.getScorePropertyAndDescription(tags)); scoData.setComment(contentNode.getCommentProperty(tags, attribute)); if (!UserPreferences.hideCentralRepoCommentsAndOccurrences()) { scoData.setCountAndDescription(contentNode.getCountPropertyAndDescription(attribute)); } if (listener != null) { listener.propertyChange(new PropertyChangeEvent( AutopsyEvent.SourceType.LOCAL.toString(), AbstractAbstractFileNode.NodeSpecificEvents.SCO_AVAILABLE.toString(), null, scoData)); } }
Source:
<code>private static int getJUnitVersion(ClassTree classTree, List<MethodTree> methods) { if (isJunit3Class(classTree)) { return 3; } boolean containsJUnit4Tests = false; for (MethodTree methodTree : methods) { SymbolMetadata metadata = methodTree.symbol().metadata(); containsJUnit4Tests |= metadata.isAnnotatedWith("org.junit.Test"); <START> if (metadata.isAnnotatedWith("org.junit.jupiter.api.Test")) { <END> return 5; } } return containsJUnit4Tests ? 4 : -1; }</code><technical_language>JUnit 5 5 test annotations. Here, use: org.sonar.java.checks.helpers.UnitTestUtils#hasJUnit5TestAnnotation(...) support test: class JUnitMethodDeclarationCheck_JUnit5ParameterizedTest { public void setUp() { } // Noncompliant @ParameterizedTest @ValueSource(strings = {"a", "b", "c"}) void test(String value) { } }</technical_language>

Target:
private static int getJUnitVersion(ClassTree classTree, List<MethodTree> methods) { if (isJunit3Class(classTree)) { return 3; } boolean containsJUnit4Tests = false; for (MethodTree methodTree : methods) { SymbolMetadata metadata = methodTree.symbol().metadata(); containsJUnit4Tests |= metadata.isAnnotatedWith("org.junit.Test"); if (UnitTestUtils.hasJUnit5TestAnnotation(methodTree)) { return 5; } } return containsJUnit4Tests ? 4 : -1; }
Source:
<code>public void actionPerformed(ActionEvent e) { if (e.getSource() == chkProxy) { if (chkProxy.isSelected()) { txtHost.setEnabled(true); txtPort.setEnabled(true); if (!StringUtils.isNotEmptyNotNull(txtPort.getText())) { <START> txtPort.setText("80"); <END> } updateProxySettings(); } else { txtHost.setEnabled(false); txtPort.setEnabled(false); BriefcasePreferences.setBriefcaseProxyProperty(null); } } }</code><technical_language>Default HTTP proxy port is 8080</technical_language>

Target:
public void actionPerformed(ActionEvent e) { if (e.getSource() == chkProxy) { if (chkProxy.isSelected()) { txtHost.setEnabled(true); spinPort.setEnabled(true); if (!StringUtils.isNotEmptyNotNull(txtHost.getText())) { txtHost.setText("127.0.0.1"); } updateProxySettings(); } else { txtHost.setEnabled(false); spinPort.setEnabled(false); BriefcasePreferences.setBriefcaseProxyProperty(null); } } }
Source:
<code>private void releaseSharedLock(String key) { InternalLockView lock = locks.get(key); if (lock != null) { if (lock.getCount() > 0) { lock.decreaseCount(); log.debugFormat("The shared lock for key {0} is released.", key); if (lock.getCount() == 0) { locks.remove(key); log.debugFormat("The shared lock for key {0} is removed from map", key); } } else { <START> log.warnFormat("Trying decrease shared lock index which is 0 is for key {0}", key); <END> } } else { log.warnFormat("Trying release shared lock which is not exist for key {0}", key); } }</code><technical_language>message be: "Trying decrease a shared lock for key: {0} , shared index is 0"'</technical_language>

Target:
private void releaseSharedLock(String key) { InternalLockView lock = locks.get(key); if (lock != null) { if (lock.getCount() > 0) { lock.decreaseCount(); log.debugFormat("The shared lock for key {0} is released.", key); if (lock.getCount() == 0) { locks.remove(key); log.debugFormat("The shared lock for key {0} is removed from map", key); } } else { log.warnFormat("Trying to decrease a shared lock for key: {0} , but shared index is 0", key); } } else { log.warnFormat("Trying to release a shared lock for key: {0} , but lock does not exist", key); } }
Source:
<code>public void init(List<TransformFunction> arguments, Map<String, DataSource> dataSourceMap) { Preconditions .checkArgument(arguments.size() == 1, "Exactly 1 argument is required for transform function: %s", getName()); TransformFunction transformFunction = arguments.get(0); Preconditions.checkArgument(transformFunction.getResultMetadata().isSingleValue(), <START> "The argument must be single-valued for transform function: %s", getName()); <END> _transformFunction = transformFunction; _reader = new WKTReader(getGeometryFactory()); }</code><technical_language>check data type, STRING</technical_language>

Target:
public void init(List<TransformFunction> arguments, Map<String, DataSource> dataSourceMap) { Preconditions .checkArgument(arguments.size() == 1, "Exactly 1 argument is required for transform function: %s", getName()); TransformFunction transformFunction = arguments.get(0); Preconditions.checkArgument(transformFunction.getResultMetadata().isSingleValue(), "The argument must be single-valued for transform function: %s", getName()); Preconditions.checkArgument(transformFunction.getResultMetadata().getDataType() == FieldSpec.DataType.STRING, "The argument must be of string type"); _transformFunction = transformFunction; _reader = new WKTReader(getGeometryFactory()); }
Source:
<code>public String getAlgorithm() { <START> return ClearPassword.ALGORITHM_CLEAR; <END> }</code><technical_language>want qualify this in event a SecretKey algorithm name overlaps a Password - e.g. "password-" + passwordAlg</technical_language>

Target:
public String getAlgorithm() { return algorithm; }
Source:
<code>public List<IssueDetail> eval(BranchContext context, ValidationRule rule) throws Exception { checkArgument(type().equals(rule.getType()), "'%s' is not recognizable by this evaluator (accepts: %s)", rule, type()); return context.service(ObjectMapper.class) .<SnomedComponentValidationQuery<?, PageableCollectionResource<SnomedComponent>, SnomedComponent>>readValue(rule.getImplementation(), TYPE_REF) .prepareSearch() .all() .setFields(SnomedComponentDocument.Fields.ID, SnomedComponentDocument.Fields.MODULE_ID, SnomedComponentDocument.Fields.ACTIVE) .build() .execute(context) .stream() .map(component -> { final ComponentIdentifier affectedComponent = component.getComponentIdentifier(); final String moduleId = component.getModuleId(); final Map<String, Object> details = newHashMap(); details.put(SnomedRf2Headers.FIELD_MODULE_ID, moduleId); <START> details.put(SnomedRf2Headers.FIELD_ACTIVE, Boolean.valueOf(component.isActive())); <END> return new IssueDetail(affectedComponent, details); }) .collect(Collectors.toList()); }</code><technical_language>component.isActive() returns a wrapper object, need for Boolean.valueOf() call</technical_language>

Target:
public List<IssueDetail> eval(BranchContext context, ValidationRule rule) throws Exception { checkArgument(type().equals(rule.getType()), "'%s' is not recognizable by this evaluator (accepts: %s)", rule, type()); return context.service(ObjectMapper.class) .<SnomedComponentValidationQuery<?, PageableCollectionResource<SnomedComponent>, SnomedComponent>>readValue(rule.getImplementation(), TYPE_REF) .prepareSearch() .all() .setFields(SnomedComponentDocument.Fields.ID, SnomedComponentDocument.Fields.MODULE_ID, SnomedComponentDocument.Fields.ACTIVE) .build() .execute(context) .stream() .map(component -> { final ComponentIdentifier affectedComponent = component.getComponentIdentifier(); final String moduleId = component.getModuleId(); final Map<String, Object> details = newHashMap(); details.put(SnomedRf2Headers.FIELD_MODULE_ID, moduleId); details.put(SnomedRf2Headers.FIELD_ACTIVE, component.isActive()); return new IssueDetail(affectedComponent, details); }) .collect(Collectors.toList()); }
Source:
<code>public void setResponses(Map<String, Response> responses) { this.responses = responses; <START> if (this.responsesObject == null && responses != null) { <END> this.responsesObject = new Responses(); for (String key : responses.keySet()) { this.responsesObject.put(key, responses.get(key)); } } }</code><technical_language>remove added logic, logic is handled in getter</technical_language>

Target:
public void setResponses(Map<String, Response> responses) { this.responses = responses; }
Source:
<code>private void marshall(final Diagram diagram, final Promise.PromiseExecutorCallbackFn.ResolveCallbackFn<String> resolveCallbackFn, final Promise.PromiseExecutorCallbackFn.RejectCallbackFn rejectCallbackFn) { if (Objects.isNull(diagram)) { return; } final Graph graph = diagram.getGraph(); if (Objects.isNull(graph)) { return; } <START> final DMN12MarshallCallback jsCallback = r -> { <END> String xml = r; if (!xml.startsWith("<?xml version=\"1.0\" ?>")) { xml = "<?xml version=\"1.0\" ?>" + xml; } resolveCallbackFn.onInvoke(xml); }; try { final JSITDefinitions jsitDefinitions = dmnMarshallerKogitoMarshaller.marshall(graph); final DMN12 dmn12 = Js.uncheckedCast(JsUtils.newWrappedInstance()); JsUtils.setNameOnWrapped(dmn12, makeJSINameForDMN12()); JsUtils.setValueOnWrapped(dmn12, jsitDefinitions); MainJs.marshall(dmn12, jsitDefinitions.getNamespace(), jsCallback); } catch (Exception e) { GWT.log(e.getMessage(), e); rejectCallbackFn.onInvoke(e); } }</code><technical_language>r stands for result? if please update</technical_language>

Target:
private void marshall(final Diagram diagram, final Promise.PromiseExecutorCallbackFn.ResolveCallbackFn<String> resolveCallbackFn, final Promise.PromiseExecutorCallbackFn.RejectCallbackFn rejectCallbackFn) { if (Objects.isNull(diagram)) { return; } final Graph graph = diagram.getGraph(); if (Objects.isNull(graph)) { return; } final DMN12MarshallCallback jsCallback = result -> { String xml = result; if (!xml.startsWith("<?xml version=\"1.0\" ?>")) { xml = "<?xml version=\"1.0\" ?>" + xml; } resolveCallbackFn.onInvoke(xml); }; try { final JSITDefinitions jsitDefinitions = dmnMarshallerKogitoMarshaller.marshall(graph); final DMN12 dmn12 = Js.uncheckedCast(JsUtils.newWrappedInstance()); JsUtils.setNameOnWrapped(dmn12, makeJSINameForDMN12()); JsUtils.setValueOnWrapped(dmn12, jsitDefinitions); MainJs.marshall(dmn12, jsitDefinitions.getNamespace(), jsCallback); } catch (Exception e) { GWT.log(e.getMessage(), e); rejectCallbackFn.onInvoke(e); } }
Source:
<code>@Test public void putOverrides() throws Exception { LinkedHashTreeMap<String, String> map = new LinkedHashTreeMap<>(); assertThat(map.put("d", "donut")).isNull(); assertThat(map.put("e", "eclair")).isNull(); assertThat(map.put("f", "froyo")).isNull(); <START> assertThat(map.size()).isEqualTo(3); <END> assertThat(map.get("d")).isEqualTo("donut"); assertThat(map.put("d", "done")).isEqualTo("donut"); assertThat(map.size()).isEqualTo(3); }</code><technical_language>assertThat(map).hasSize(3)</technical_language>

Target:
@Test public void putOverrides() throws Exception { LinkedHashTreeMap<String, String> map = new LinkedHashTreeMap<>(); assertThat(map.put("d", "donut")).isNull(); assertThat(map.put("e", "eclair")).isNull(); assertThat(map.put("f", "froyo")).isNull(); assertThat(map.size()).isEqualTo(3); assertThat(map.get("d")).isEqualTo("donut"); assertThat(map.put("d", "done")).isEqualTo("donut"); assertThat(map).hasSize(3); }
Source:
<code>public MessageProducer createMessageProducer(Session session, Destination destination) throws JMSConnectorException { try { if ((JMSConstants.JMS_SPEC_VERSION_1_1.equals(jmsSpec)) || (JMSConstants.JMS_SPEC_VERSION_2_0 .equals(jmsSpec))) { return session.createProducer(destination); } else { if (this.destinationType.equals(JMSConstants.JMSDestinationType.QUEUE)) { <START> return ((QueueSession) session).createSender((Queue) destination); <END> } else { return ((TopicSession) session).createPublisher((Topic) destination); } } } catch (JMSException e) { throw new JMSConnectorException( "JMS Exception while creating the producer for the destination " + destinationName, e); } }</code><technical_language>Reason for changing this logic create sender</technical_language>

Target:
public MessageProducer createMessageProducer(Session session, Destination destination) throws JMSConnectorException { try { if ((JMSConstants.JMS_SPEC_VERSION_1_1.equals(jmsSpec)) || (JMSConstants.JMS_SPEC_VERSION_2_0 .equals(jmsSpec))) { return session.createProducer(destination); } else { if (JMSConstants.JMSDestinationType.QUEUE.equals(this.destinationType)) { return ((QueueSession) session).createSender((Queue) destination); } else { return ((TopicSession) session).createPublisher((Topic) destination); } } } catch (JMSException e) { throw new JMSConnectorException( "JMS Exception while creating the producer for the destination " + destinationName, e); } }
Source:
<code>public void selectItem(String path, int timeoutForWaitingItem) { String locator = " waitItem(path, timeoutForWaitingItem); try { new WebDriverWait(seleniumWebDriver, EXPECTED_MESS_IN_CONSOLE_SEC) .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(locator))) .click(); } catch (StaleElementReferenceException ex) { <START> LOG.error(ex.getLocalizedMessage(), ex); <END> waitProjectExplorer(); clickOnRefreshTreeButton(); waitItem(path); new WebDriverWait(seleniumWebDriver, EXPECTED_MESS_IN_CONSOLE_SEC) .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(locator))) .click(); } }</code><technical_language>IMHO log exception warn() interrupt execution of tests</technical_language>

Target:
public void selectItem(String path, int timeoutForWaitingItem) { String locator = " waitItem(path, timeoutForWaitingItem); try { new WebDriverWait(seleniumWebDriver, EXPECTED_MESS_IN_CONSOLE_SEC) .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(locator))) .click(); } catch (StaleElementReferenceException ex) { LOG.warn(ex.getLocalizedMessage(), ex); waitProjectExplorer(); clickOnRefreshTreeButton(); waitItem(path); new WebDriverWait(seleniumWebDriver, EXPECTED_MESS_IN_CONSOLE_SEC) .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(locator))) .click(); } }
Source:
<code><START> public GA4GHBeaconResponse() { <END> }</code><technical_language>Empty constructor is required, if I recall correctly class protected is enough</technical_language>

Target:
GA4GHBeaconResponse() { }
Source:
<code>private static Collection<SAXParseException> validate(final XML xml) { final Collection<SAXParseException> errors = new CopyOnWriteArrayList<SAXParseException>(); final int amountOfRetries = 3; try { final Validator validator = newValidator(); validator.setErrorHandler( new XSDDocument.ValidationHandler(errors) ); <START> final DOMSource domsrc = new DOMSource(xml.node()); <END> for (int retry = 0; retry < amountOfRetries; ++retry) { try { validator.validate(domsrc); retry = amountOfRetries; } catch (final SocketException ex) { Logger.error( StrictXML.class, "Try #%d of %d failed: %s: %s", retry, amountOfRetries, ex.getClass().getName(), ex.getMessage() ); if (amountOfRetries == retry + 1) { throw new IllegalStateException(ex); } } } } catch (final SAXException ex) { throw new IllegalStateException(ex); } catch (final IOException ex) { throw new IllegalStateException(ex); } return errors; }</code><technical_language>dom</technical_language>

Target:
private static Collection<SAXParseException> validate(final XML xml) { final Collection<SAXParseException> errors = new CopyOnWriteArrayList<SAXParseException>(); final int max = 3; try { final Validator validator = newValidator(); validator.setErrorHandler( new XSDDocument.ValidationHandler(errors) ); final DOMSource dom = new DOMSource(xml.node()); for (int retry = 1; retry <= max; ++retry) { try { validator.validate(dom); break; } catch (final SocketException ex) { Logger.error( StrictXML.class, "Try #%d of %d failed: %s: %s", retry, max, ex.getClass().getName(), ex.getMessage() ); if (retry == max) { throw new IllegalStateException(ex); } } } } catch (final SAXException ex) { throw new IllegalStateException(ex); } catch (final IOException ex) { throw new IllegalStateException(ex); } return errors; }
Source:
<code>public int read(byte[] buf, int off, int len) throws TTransportException { <START> if (!isOpen) { <END> throw new TTransportException(TTransportException.NOT_OPEN, "read: HTTP transport not open"); } if (readPos == currentFrame.length) { try { currentFrame = frameBuffer.take(); } catch (InterruptedException e) { throw new TTransportException(TTransportException.END_OF_FILE, e.getMessage()); } readPos = 0; } if (currentFrame == FRAME_BUFFER_CLOSED) { throw new TTransportException(TTransportException.END_OF_FILE); } len = Math.min(currentFrame.length - readPos, len); System.arraycopy(currentFrame, readPos, buf, off, len); readPos += len; return len; }</code><technical_language>If isOpen is synchronized this method needs synchronized</technical_language>

Target:
public int read(byte[] buf, int off, int len) throws TTransportException { if (!isOpen()) { throw new TTransportException(TTransportException.NOT_OPEN, "read: HTTP transport not open"); } if (readPos == currentFrame.length) { try { currentFrame = frameBuffer.take(); } catch (InterruptedException e) { throw new TTransportException(TTransportException.END_OF_FILE, e.getMessage()); } readPos = 0; } if (currentFrame == FRAME_BUFFER_CLOSED) { throw new TTransportException(TTransportException.END_OF_FILE); } len = Math.min(currentFrame.length - readPos, len); System.arraycopy(currentFrame, readPos, buf, off, len); readPos += len; return len; }
Source:
<code>public boolean addPredicates(AbstractSqlWriter writer) throws OseeCoreException { writer.write(getPredicate(writer, txsAlias, relAlias)); <START> writer.write(" AND "); <END> if (OptionsUtil.isHistorical(writer.getOptions())) { if (!OptionsUtil.areDeletedRelationsIncluded(writer.getOptions())) { writer.write(txsAlias); writer.write(".mod_type != "); writer.write(Integer.toString(ModificationType.DELETED.getValue())); writer.write(" AND "); } } else { writer.write(txsAlias); writer.write(".tx_current "); if (OptionsUtil.areDeletedRelationsIncluded(writer.getOptions())) { writer.write(" IN ("); writer.write(String.valueOf(TxChange.CURRENT.getValue())); writer.write(", "); writer.write(String.valueOf(TxChange.DELETED.getValue())); writer.write(", "); writer.write(String.valueOf(TxChange.ARTIFACT_DELETED.getValue())); writer.write(") AND"); } else { writer.write(" = "); writer.write(String.valueOf(TxChange.CURRENT.getValue())); writer.write(" AND "); } } if (withClause != null) { writer.write(txsAlias); writer.write(".transaction_id = "); writer.write(withClauseName); writer.write(".transaction_id AND "); } writer.write(writer.getTxBranchFilter(txsAlias)); return true; }</code><technical_language>block repeats getTxBranchFilter SqlWriter</technical_language>

Target:
public boolean addPredicates(AbstractSqlWriter writer) throws OseeCoreException { writer.write(getPredicate(writer, txsAlias, relAlias)); if (withClause != null) { writer.writeAndLn(); writer.write(txsAlias); writer.write(".transaction_id = "); writer.write(withClauseName); writer.write(".transaction_id"); } writer.writeAndLn(); boolean includeDeletedRelations = OptionsUtil.areDeletedRelationsIncluded(writer.getOptions()); writer.write(writer.getTxBranchFilter(txsAlias, includeDeletedRelations)); return true; }
Source:
<code>private List<Map<String, String>> availableConsoles(String userIdAsString) { List<Map<String, String>> jsonVms = new ArrayList<>(); Guid userGuid = null; try { if (StringUtils.isNotEmpty(userIdAsString)) { userGuid = Guid.createGuidFromString(userIdAsString); } } catch (IllegalArgumentException e) { log.debug("Could not read User GUID"); } if (userGuid != null) { VdcReturnValueBase loginResult = backend.runInternalAction(VdcActionType.LoginOnBehalf, new LoginOnBehalfParameters(userGuid)); <START> String engineSessionId = loginResult.getActionReturnValue(); <END> try { IdQueryParameters userParam = new IdQueryParameters(userGuid); VdcQueryReturnValue retVms = backend.runInternalQuery(VdcQueryType.GetAllVms, userParam); if (retVms != null) { List<VM> vmsList = retVms.getReturnValue(); for (VM vm : vmsList) { Map<String, String> jsonVm = new HashMap<String, String>(); if (vm.getRunOnVds() != null) { VdcQueryReturnValue retValue = backend.runInternalQuery(VdcQueryType.GetVdsByVdsId, new IdQueryParameters(vm.getRunOnVds())); if (retValue != null && retValue.getReturnValue() != null) { VDS vds = (VDS) retValue.getReturnValue(); jsonVm.put("vmid", vm.getId().toString()); jsonVm.put("vmname", vm.getName()); jsonVm.put("host", vds.getHostName()); jsonVm.put("console", "default"); jsonVms.add(jsonVm); } } } } } finally { if (StringUtils.isNotEmpty(engineSessionId)) { backend.runInternalAction(VdcActionType.LogoutSession, new VdcActionParametersBase(engineSessionId)); } } } return jsonVms; }</code><technical_language>need loginResult temp variable</technical_language>

Target:
private List<Map<String, String>> availableConsoles(String userIdAsString) { List<Map<String, String>> jsonVms = new ArrayList<>(); Guid userGuid = null; try { if (StringUtils.isNotEmpty(userIdAsString)) { userGuid = Guid.createGuidFromString(userIdAsString); } } catch (IllegalArgumentException e) { log.debug("Could not read User GUID"); } if (userGuid != null) { String engineSessionId = backend.runInternalAction(VdcActionType.LoginOnBehalf, new LoginOnBehalfParameters(userGuid)).getActionReturnValue(); if (StringUtils.isNotEmpty(engineSessionId)) { try { VdcQueryReturnValue retVms = backend.runInternalQuery(VdcQueryType.GetAllVms, new VdcQueryParametersBase(), new EngineContext().withSessionId(engineSessionId)); if (retVms != null) { List<VM> vmsList = retVms.getReturnValue(); for (VM vm : vmsList) { Map<String, String> jsonVm = new HashMap<String, String>(); if (vm.getRunOnVds() != null) { VdcQueryReturnValue retValue = backend.runInternalQuery(VdcQueryType.GetVdsByVdsId, new IdQueryParameters(vm.getRunOnVds())); if (retValue != null && retValue.getReturnValue() != null) { VDS vds = (VDS) retValue.getReturnValue(); jsonVm.put("vmid", vm.getId().toString()); jsonVm.put("vmname", vm.getName()); jsonVm.put("host", vds.getHostName()); jsonVm.put("console", "default"); jsonVms.add(jsonVm); } } } } } finally { backend.runInternalAction(VdcActionType.LogoutSession, new VdcActionParametersBase(engineSessionId)); } } } return jsonVms; }
Source:
<code>public int getCircuitBreakerAspectOrder() { <START> return Ordered.LOWEST_PRECEDENCE - 2; <END> }</code><technical_language>This read variable</technical_language>

Target:
public int getCircuitBreakerAspectOrder() { return circuitBreakerAspectOrder; }
Source:
<code><START> public String deflatePropertyName(Graph graph, String propertyName, Visibility propertyVisibility) { <END> String visibilityHash = getVisibilityHash(graph, propertyName, propertyVisibility); return this.nameSubstitutionStrategy.deflate(propertyName) + "_" + visibilityHash; }</code><technical_language>change this package scope instead of public</technical_language>

Target:
protected String deflatePropertyName(Graph graph, String propertyName, Visibility propertyVisibility) { String visibilityHash = getVisibilityHash(graph, propertyName, propertyVisibility); return this.nameSubstitutionStrategy.deflate(propertyName) + "_" + visibilityHash; }
Source:
<code>public ArrayList<CrfVersionMedia> findByCrfVersionId(int crf_version_id) { String query = "from " + getDomainClassName() + " crf_version_media where crf_version_media.crfVersion.crfVersionId = :crfversionid "; <START> org.hibernate.Query q = getCurrentSession().createQuery(query); <END> q.setInteger("crfversionid", crf_version_id); return (ArrayList<CrfVersionMedia>) q.list(); }</code><technical_language>Remove org.hibernate org.hibernate.Query</technical_language>

Target:
public ArrayList<CrfVersionMedia> findByCrfVersionId(int crf_version_id) { String query = "from " + getDomainClassName() + " crf_version_media where crf_version_media.crfVersion.crfVersionId = :crfversionid "; Query q = getCurrentSession().createQuery(query); q.setInteger("crfversionid", crf_version_id); return (ArrayList<CrfVersionMedia>) q.list(); }
Source:
<code>public String toString() { <START> return "UserToken [userId=" + userId + ", active=" + active + ", admin=" + admin + ", email=" + email + ", creationRequired=" + creationRequired + "]"; <END> }</code><technical_language>Consider String.format</technical_language>

Target:
public String toString() { return String.format("UserToken [userId=[%s], active=[%s], admin=[%s], email=[%s], creationRequired=[%s]", userId, active, admin, email, creationRequired); }
Source:
<code>public void addValue(long value) { nonNullValueCount++; minimum = Math.min(value, minimum); maximum = Math.max(value, maximum); <START> try { <END> sum = addExact(sum, value); } catch (ArithmeticException e) { overflow = true; } }</code><technical_language>I execute this try if overflow is set. this code is currently written, concerned repeated throws in a tight loop</technical_language>

Target:
public void addValue(long value) { nonNullValueCount++; minimum = Math.min(value, minimum); maximum = Math.max(value, maximum); if (!overflow) { try { sum = addExact(sum, value); } catch (ArithmeticException e) { overflow = true; } } }
Source:
<code>public Provider createProviderFromUser(User user) { Provider p = new Provider(); if (user == null || user.getPerson() == null) { <START> throw new RuntimeException("User can not be null"); <END> } else if (Context.getProviderService().getProvidersByPerson(user.getPerson()).isEmpty()) { p.setPerson(user.getPerson()); } else { throw new RuntimeException("Unable to create Provider from user"); } return Context.getProviderService().saveProvider(p); }</code><technical_language>This APIException</technical_language>

Target:
public Provider createProviderFromUser(User user) { Provider p = new Provider(); if (user == null || user.getPerson() == null) { throw new APIException("User can not be null"); } else if (Context.getProviderService().getProvidersByPerson(user.getPerson()).isEmpty()) { p.setPerson(user.getPerson()); return Context.getProviderService().saveProvider(p); } else { log.warn("Provider already exists for user"); return Context.getProviderService().getProvidersByPerson(user.getPerson()).iterator().next(); } }
Source:
<code>private boolean createAndUploadSegments() { File localTempDir = new File(FileUtils.getTempDirectory(), "pinot-compat-test-" + UUID.randomUUID()); File localOutputTempDir = new File(localTempDir, "output"); try { FileUtils.forceMkdir(localOutputTempDir); File segmentTarFile = generateSegment(localOutputTempDir); uploadSegment(segmentTarFile); <START> Pair<Long, Long> onlineSegmentCount = getOnlineSegmentCount(getTableExternalView()); <END> if (onlineSegmentCount.getFirst() <= 0 && onlineSegmentCount.getSecond() <= 0) { LOGGER.error("Uploaded segment not found or not in state.", _segmentName, STATE_ONLINE); return false; } LOGGER.info("Successfully verified segment and its current status is {}.", _segmentName, STATE_ONLINE); return true; } catch (Exception e) { LOGGER.error("Failed to create and upload segment for input data file {}.", _inputDataFileName, e); return false; } finally { FileUtils.deleteQuietly(localTempDir); } }</code><technical_language>takes some time for segment external view, is put this in a while loop. I suggest: while (segmentNotOnline()) { sleep(100ms) if (it more max time) { return false } } Max time hardcoded 30s</technical_language>

Target:
private boolean createAndUploadSegments() { File localTempDir = new File(FileUtils.getTempDirectory(), "pinot-compat-test-" + UUID.randomUUID()); localTempDir.deleteOnExit(); File localOutputTempDir = new File(localTempDir, "output"); try { FileUtils.forceMkdir(localOutputTempDir); File segmentTarFile = generateSegment(localOutputTempDir); uploadSegment(segmentTarFile); return verifySegmentInState(STATE_ONLINE); } catch (Exception e) { LOGGER.error("Failed to create and upload segment for input data file {}.", _inputDataFileName, e); return false; } finally { FileUtils.deleteQuietly(localTempDir); } }
Source:
<code>public boolean testSourceType(CommandSource source) { <START> return testPermission(source); <END> }</code><technical_language>What? This true in opinion</technical_language>

Target:
public boolean testSourceType(CommandSource source) { return true; }
Source:
<code>private boolean isTargetTable(Entity entity, Table targetTable) { <START> long targetWriteId = targetTable.getTTable().getWriteId(); long entityWriteId = entity.getTable().getTTable().getWriteId(); targetTable.getTTable().setWriteId(0L); entity.getTable().getTTable().setWriteId(0L); boolean result = targetTable.equals(entity.getTable()); targetTable.getTTable().setWriteId(targetWriteId); entity.getTable().getTTable().setWriteId(entityWriteId); return result; <END> }</code><technical_language>I prefer a new equalsWithIgnoreWriteId - named method in Table class</technical_language>

Target:
private boolean isTargetTable(Entity entity, Table targetTable) { return targetTable.equalsWithIgnoreWriteId(entity); }
Source:
<code><START> public static synchronized HttpTransport getStaticHttpTransport() <END> throws IOException, GeneralSecurityException { if (staticHttpTransport == null) { staticHttpTransport = HttpTransportFactory.createHttpTransport(HttpTransportType.JAVA_NET); } return staticHttpTransport; }</code><technical_language>This method request local GCE metadata service. For external HTTP requests need transport configured for GCS connector</technical_language>

Target:
private static synchronized HttpTransport getStaticHttpTransport() throws IOException, GeneralSecurityException { if (staticHttpTransport == null) { staticHttpTransport = HttpTransportFactory.createHttpTransport(HttpTransportType.JAVA_NET); } return staticHttpTransport; }
Source:
<code>protected Date convertFromString(String stringValue) { if (stringValue == null || stringValue.isEmpty() || stringValue.length() < 6) { return null; } int lastSeparator = stringValue.lastIndexOf('/'); if (stringValue.contains("-")) { return convertDate("yyyy-MM-dd", stringValue); } else if (lastSeparator == -1) { return new Date(Long.parseLong(stringValue)); <START> } else if (stringValue.length() - lastSeparator - 1 == 2) { <END> return convertDate("MM/dd/yy", stringValue); } else { return convertDate("MM/dd/yyyy", stringValue); } }</code><technical_language>extract this a function isSimpleYearFormat some semantics here? :)</technical_language>

Target:
protected Date convertFromString(String stringValue) { if (stringValue == null || stringValue.isEmpty() || stringValue.length() < 6) { return null; } int lastSeparator = stringValue.lastIndexOf('/'); if (stringValue.contains("-")) { return convertDate("yyyy-MM-dd", stringValue); } else if (isTimestampFormat(lastSeparator)) { return new Date(Long.parseLong(stringValue)); } else if (isSimpleYearFormat(stringValue, lastSeparator)) { return convertDate("MM/dd/yy", stringValue); } else { return convertDate("MM/dd/yyyy", stringValue); } }