auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> protected HdfsSinkConnectorConfig(Map<String, String> props) { <END> this(CONFIG_DEF, props); }</code><technical_language>keeping public constructor instead adding default properties if missing: public HdfsSinkConnectorConfig(Map<String, String> props) { this(CONFIG_DEF, addDefaults(props)); } private static Map<String, String> addDefaults(Map<String, String> props) { ConcurrentMap<String, String> propsCopy = new ConcurrentHashMap<>(props); propsCopy.putIfAbsent(StorageCommonConfig.STORAGE_CLASS_CONFIG, HdfsStorage.class.getName()); propsCopy.putIfAbsent(HdfsSinkConnectorConfig.FORMAT_CLASS_CONFIG, AvroFormat.class.getName()); return propsCopy; } benefit is public constructor stays same, in case people extend this connector/class. if a worry. reduce number of changes constructor is used</technical_language>

Target:
public HdfsSinkConnectorConfig(Map<String, String> props) { this(CONFIG_DEF, addDefaults(props)); }
Source:
<code><START> FluxToMessageChannelResultAdapter fluxToMessageChannelResultAdapter() { <END> return new FluxToMessageChannelResultAdapter(); }</code><technical_language>public</technical_language>

Target:
public FluxToMessageChannelResultAdapter fluxToMessageChannelResultAdapter() { return new FluxToMessageChannelResultAdapter(); }
Source:
<code>Collection<Session> getSessions() { final Collection<Session> closedSessions = listeningSessions.values().stream() .flatMap(sessions -> sessions.values().stream()) <START> .filter(session -> !session.isOpen()) <END> .collect(Collectors.toSet()); closedSessions.forEach(this::removeSession); return listeningSessions.values().stream() .flatMap(sessions -> sessions.values().stream()) .collect(Collectors.toSet()); }</code><technical_language>I if prefer statically import Predicate#not write this: suggestion .filter(not(Session::isOpen))</technical_language>

Target:
Collection<Session> getSessions() { final Collection<Session> closedSessions = listeningSessions.values().stream() .flatMap(sessions -> sessions.values().stream()) .filter(Predicate.not(Session::isOpen)) .collect(Collectors.toSet()); closedSessions.forEach(this::removeSession); return listeningSessions.values().stream() .flatMap(sessions -> sessions.values().stream()) .collect(Collectors.toSet()); }
Source:
<code>public void testInstrumentationWithAdvancedOpt() { CompilerOptions options = createCompilerOptions(); String blahExtern = lines( " ", " ", "let ist_arr;" ); externs = ImmutableList.of( new TestExternsBuilder() .addArray() .addAlert() .addExtra( blahExtern) .buildExternsFile("externs")); String source = lines("function foo (x) {", "if(x) { alert(x+5); }", "} foo(true); foo(false);"); String expected = lines( "function a(b) {", getInstrumentCodeLine("G"),";", <START> "b ? (", getInstrumentCodeLine("C"),",alert(b+5)) : ", getInstrumentCodeLine("E"),";", <END> "}", "a(!0);" , "a(!1);"); CompilationLevel.ADVANCED_OPTIMIZATIONS.setOptionsForCompilationLevel(options); test(options, source, instrumentCodeExpected.concat(expected)); }</code><technical_language>formatting</technical_language>

Target:
public void testInstrumentationWithAdvancedOpt() { CompilerOptions options = createCompilerOptions(); String blahExtern = lines( " ", " ", "let ist_arr;"); externs = ImmutableList.of( new TestExternsBuilder() .addArray() .addAlert() .addExtra(blahExtern) .buildExternsFile("externs")); String source = lines( "function foo (x) {", " if(x) { " , " alert(x+5); ", " }", "} ", "foo(true); foo(false);"); String expected = lines( "function a(b) {", getInstrumentCodeLine("G"), ";", "b ? (", getInstrumentCodeLine("C"), ", alert(b+5)) : ", getInstrumentCodeLine("E"), ";", "}", "a(!0);", "a(!1);"); CompilationLevel.ADVANCED_OPTIMIZATIONS.setOptionsForCompilationLevel(options); test(options, source, instrumentCodeExpected.concat(expected)); }
Source:
<code>public void onMatch(RelOptRuleCall call) { LogicalWatermarkAssigner watermarkAssigner = call.rel(0); LogicalTableScan scan = call.rel(1); FlinkContext context = (FlinkContext) call.getPlanner().getContext(); TableConfig config = context.getTableConfig(); GeneratedWatermarkGenerator generatedWatermarkGenerator = WatermarkGeneratorCodeGenerator.generateWatermarkGenerator( config, FlinkTypeFactory.toLogicalRowType(scan.getRowType()), watermarkAssigner.watermarkExpr(), "context"); Configuration configuration = context.getTableConfig().getConfiguration(); WatermarkGeneratorSupplier<RowData> supplier = new DefaultWatermarkGeneratorSupplier(configuration, generatedWatermarkGenerator); String digest = String.format("watermark=[%s]", watermarkAssigner.watermarkExpr()); WatermarkStrategy<RowData> watermarkStrategy = WatermarkStrategy.forGenerator(supplier); Duration idleTimeout = configuration.get(ExecutionConfigOptions.TABLE_EXEC_SOURCE_IDLE_TIMEOUT); if (!idleTimeout.isZero() && !idleTimeout.isNegative()) { watermarkStrategy.withIdleness(idleTimeout); digest = String.format("%s idletimeout=[%s]", digest, idleTimeout.toMillis()); } TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class); DynamicTableSource newDynamicTableSource = tableSourceTable.tableSource().copy(); ((SupportsWatermarkPushDown) newDynamicTableSource).applyWatermark(watermarkStrategy); TableSourceTable newTableSourceTable = tableSourceTable.copy( newDynamicTableSource, watermarkAssigner.getRowType(), new String[]{digest}); <START> LogicalTableScan newScan = new LogicalTableScan( <END> scan.getCluster(), scan.getTraitSet(), scan.getHints(), newTableSourceTable); call.transformTo(newScan); }</code><technical_language>nit: LogicalTableScan.create instead</technical_language>

Target:
public void onMatch(RelOptRuleCall call) { FlinkLogicalWatermarkAssigner watermarkAssigner = call.rel(0); FlinkLogicalTableSourceScan scan = call.rel(1); FlinkContext context = (FlinkContext) call.getPlanner().getContext(); FlinkLogicalTableSourceScan newScan = getNewScan(watermarkAssigner, watermarkAssigner.watermarkExpr(), scan, context.getTableConfig(), true); call.transformTo(newScan); }
Source:
<code>public void testSensitivityAtConstantDepth(final double expected, final File metricsFile, final double alleleFraction, final int depth, final int sampleSize, final double tolerance) throws Exception { final MetricsFile Metrics = new MetricsFile(); <START> Metrics.read(new FileReader(metricsFile)); <END> final List<Histogram<Integer>> histograms = Metrics.getAllHistograms(); final Histogram<Integer> qualityHistogram = histograms.get(1); for (int i = 0;i < 3;i++) { double result = TheoreticalSensitivity.sensitivityAtConstantDepth(depth, qualityHistogram, 3, sampleSize, alleleFraction, i); Assert.assertEquals(result, expected, tolerance); } }</code><technical_language>try-with-resources</technical_language>

Target:
public void testSensitivityAtConstantDepth(final double expected, final File metricsFile, final double alleleFraction, final int depth, final int sampleSize, final double tolerance) throws Exception { final MetricsFile metrics = new MetricsFile(); try (final FileReader metricsFileReader = new FileReader(metricsFile)) { metrics.read(metricsFileReader); } final List<Histogram<Integer>> histograms = metrics.getAllHistograms(); final Histogram<Integer> qualityHistogram = histograms.get(1); for (int i = 0;i < 3;i++) { double result = TheoreticalSensitivity.sensitivityAtConstantDepth(depth, qualityHistogram, 3, sampleSize, alleleFraction, i); Assert.assertEquals(result, expected, tolerance); } }
Source:
<code>public void validateDestinationDomainValid() { DiskImage disk = new DiskImage(); initializeCommand(disk, VmEntityType.VM); disk.getStorageIds().add(destStorageId); initSrcStorageDomain(); initDestStorageDomain(StorageType.NFS); command.getParameters().setStorageDomainId(destStorageId); command.setStorageDomainId(destStorageId); command.getStorageDomain().setId(destStorageId); <START> ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_DESTINATION_STORAGE_DOMAIN_IS_NOT_VALID); <END> }</code><technical_language>I split line :)</technical_language>

Target:
public void validateDestinationDomainValid() { DiskImage disk = new DiskImage(); initializeCommand(disk, VmEntityType.VM); disk.getStorageIds().add(destStorageId); initSrcStorageDomain(); initDestStorageDomain(StorageType.NFS); command.getParameters().setStorageDomainId(destStorageId); command.setStorageDomainId(destStorageId); command.getStorageDomain().setId(destStorageId); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_DESTINATION_STORAGE_DOMAIN_ALREADY_CONTAINS_THE_DISK); }
Source:
<code>private HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds) { <START> final String expiration = String.valueOf(System.currentTimeMillis()/1000 + timeInSeconds); <END> HttpRequest req = request.toBuilder().replaceHeader(HttpHeaders.DATE, expiration).build(); final String signature = authSigner.sign(authSigner.createStringToSign(req)); req = req.toBuilder() .addQueryParam("Signature", signature) .addQueryParam(HttpHeaders.EXPIRES, expiration) .addQueryParam("AWSAccessKeyId", identity) .build(); return req; }</code><technical_language>final? Similar methods in jclouds variables final required e.g. anonymous class</technical_language>

Target:
private HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds) { String dateString = request.getFirstHeaderOrNull(HttpHeaders.DATE); if (dateString == null) { dateString = timeStampProvider.get(); } Date date = dateService.rfc1123DateParse(dateString); String expiration = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(date.getTime()) + timeInSeconds); HttpRequest.Builder<?> builder = request.toBuilder().replaceHeader(HttpHeaders.DATE, expiration); final String signature = authSigner.sign(authSigner.createStringToSign(builder.build())); return builder.addQueryParam("Signature", signature) .addQueryParam(HttpHeaders.EXPIRES, expiration) .addQueryParam("AWSAccessKeyId", identity) .build(); }
Source:
<code>private String getKeyForLRUCache(Uri contentUri) { String[] split = contentUri.toString().split("/"); <START> return split[split.length-1]; <END> }</code><technical_language>Consider Uri.getLastPathSegment()-it do want is more efficient</technical_language>

Target:
private String getKeyForLRUCache(Uri contentUri) { return contentUri.getLastPathSegment(); }
Source:
<code>private FireHydrant makeNewCurrIndex(long minTimestamp, DataSchema schema) { final IncrementalIndexSchema indexSchema = new IncrementalIndexSchema.Builder() .withMinTimestamp(minTimestamp) .withQueryGranularity(schema.getGranularitySpec().getQueryGranularity()) .withDimensionsSpec(schema.getParser()) .withMetrics(schema.getAggregators()) .build(); final IncrementalIndex newIndex = new OnheapIncrementalIndex( indexSchema, config.getMaxRowsInMemory() ); final FireHydrant old; synchronized (hydrantLock) { old = currHydrant; int newCount = 0; int numHydrants = hydrants.size(); if (numHydrants > 0) { FireHydrant lastHydrant = hydrants.get(numHydrants - 1); newCount = lastHydrant.getCount() + 1; <START> if(!indexSchema.getDimensionsSpec().hasCustomDimensions()) { <END> if (lastHydrant.hasSwapped()) { QueryableIndex oldIndex = lastHydrant.getSegment().asQueryableIndex(); newIndex.loadDimensionIterable(oldIndex.getAvailableDimensions()); } else { IncrementalIndex oldIndex = lastHydrant.getIndex(); newIndex.loadDimensionOrder(oldIndex.getDimensionOrder()); } } } currHydrant = new FireHydrant(newIndex, newCount, getSegment().getIdentifier()); hydrants.add(currHydrant); } return old; }</code><technical_language>apply code style</technical_language>

Target:
private FireHydrant makeNewCurrIndex(long minTimestamp, DataSchema schema) { final IncrementalIndexSchema indexSchema = new IncrementalIndexSchema.Builder() .withMinTimestamp(minTimestamp) .withQueryGranularity(schema.getGranularitySpec().getQueryGranularity()) .withDimensionsSpec(schema.getParser()) .withMetrics(schema.getAggregators()) .build(); final IncrementalIndex newIndex = new OnheapIncrementalIndex( indexSchema, config.getMaxRowsInMemory() ); final FireHydrant old; synchronized (hydrantLock) { old = currHydrant; int newCount = 0; int numHydrants = hydrants.size(); if (numHydrants > 0) { FireHydrant lastHydrant = hydrants.get(numHydrants - 1); newCount = lastHydrant.getCount() + 1; if (!indexSchema.getDimensionsSpec().hasCustomDimensions()) { if (lastHydrant.hasSwapped()) { QueryableIndex oldIndex = lastHydrant.getSegment().asQueryableIndex(); for (String dim : oldIndex.getAvailableDimensions()) { dimOrder.add(dim); } } else { IncrementalIndex oldIndex = lastHydrant.getIndex(); dimOrder.addAll(oldIndex.getDimensionOrder()); } newIndex.loadDimensionIterable(dimOrder); } } currHydrant = new FireHydrant(newIndex, newCount, getSegment().getIdentifier()); hydrants.add(currHydrant); } return old; }
Source:
<code>@Inject public StatusResource(KeywhizConfig keywhizConfig, Environment environment) { this.environment = environment; Duration cacheExpiry = keywhizConfig.getStatusCacheExpiry(); <START> cachedResult = CacheBuilder.newBuilder() <END> .maximumSize(1) .expireAfterWrite(cacheExpiry.toMillis(), TimeUnit.MILLISECONDS) .build( new CacheLoader<HealthCheckRegistry, SortedMap<String, HealthCheck.Result>>() { public SortedMap<String, HealthCheck.Result> load(HealthCheckRegistry checks) { return checks.runHealthChecks(); } }); }</code><technical_language>Prefer Suppliers.memoizeWithExpiration instead of a cache: <LINK_0></technical_language>

Target:
@Inject public StatusResource(KeywhizConfig keywhizConfig, Environment environment) { Duration cacheExpiry = keywhizConfig.getStatusCacheExpiry(); memoizedCheck = Suppliers.memoizeWithExpiration(() -> environment.healthChecks().runHealthChecks(), cacheExpiry.toMillis(), TimeUnit.MILLISECONDS); }
Source:
<code>private static void fillChecksFromAnnotationPackage() { NAME_TO_FULL_MODULE_NAME.put("AnnotationLocationCheck", <START> "com.puppycrawl.tools.checkstyle.checks.annotation.AnnotationLocationCheck"); <END> NAME_TO_FULL_MODULE_NAME.put("AnnotationUseStyleCheck", "com.puppycrawl.tools.checkstyle.checks.annotation.AnnotationUseStyleCheck"); NAME_TO_FULL_MODULE_NAME.put("MissingDeprecatedCheck", "com.puppycrawl.tools.checkstyle.checks.annotation.MissingDeprecatedCheck"); NAME_TO_FULL_MODULE_NAME.put("MissingOverrideCheck", "com.puppycrawl.tools.checkstyle.checks.annotation.MissingOverrideCheck"); NAME_TO_FULL_MODULE_NAME.put("PackageAnnotationCheck", "com.puppycrawl.tools.checkstyle.checks.annotation.PackageAnnotationCheck"); NAME_TO_FULL_MODULE_NAME.put("SuppressWarningsCheck", "com.puppycrawl.tools.checkstyle.checks.annotation.SuppressWarningsCheck"); }</code><technical_language>do define BASE_PACKAGE for some checks? of them</technical_language>

Target:
private static void fillChecksFromAnnotationPackage() { NAME_TO_FULL_MODULE_NAME.put("AnnotationLocationCheck", BASE_PACKAGE + ".checks.annotation.AnnotationLocationCheck"); NAME_TO_FULL_MODULE_NAME.put("AnnotationUseStyleCheck", BASE_PACKAGE + ".checks.annotation.AnnotationUseStyleCheck"); NAME_TO_FULL_MODULE_NAME.put("MissingDeprecatedCheck", BASE_PACKAGE + ".checks.annotation.MissingDeprecatedCheck"); NAME_TO_FULL_MODULE_NAME.put("MissingOverrideCheck", BASE_PACKAGE + ".checks.annotation.MissingOverrideCheck"); NAME_TO_FULL_MODULE_NAME.put("PackageAnnotationCheck", BASE_PACKAGE + ".checks.annotation.PackageAnnotationCheck"); NAME_TO_FULL_MODULE_NAME.put("SuppressWarningsCheck", BASE_PACKAGE + ".checks.annotation.SuppressWarningsCheck"); }
Source:
<code>public boolean isEmpty() { return getPrimary() == null && getCountry() == null && getFormatted() == null && getLocality() == null && getPostalcode() == null && getRegion() == null && getStreetaddress() == null && <START> getType() == null; <END> }</code><technical_language>is empty if for example type is valid empty string</technical_language>

Target:
public boolean isEmpty() { return getPrimary() == null && Strings.isNullOrEmpty(getCountry()) && Strings.isNullOrEmpty(getFormatted()) && Strings.isNullOrEmpty(getLocality()) && Strings.isNullOrEmpty(getPostalcode()) && Strings.isNullOrEmpty(getRegion()) && Strings.isNullOrEmpty(getStreetaddress()) && Strings.isNullOrEmpty(getType()); }
Source:
<code>private void doOperation( ThrowingConsumer<Suspendable,Throwable> operation, String description ) { ErrorHandler.certainOperations( description, suspendables.stream() .map( (Function<Suspendable,ErrorHandler.ThrowingRunnable>) suspendable -> () -> operation.accept( suspendable ) ) <START> .toArray( ErrorHandler.ThrowingRunnable[]::new ) ); <END> }</code><technical_language>This is a complicated of calling a method. overload method ErrorHandler takes Collection<T> Consumer<T></technical_language>

Target:
private void doOperation( ThrowingConsumer<Suspendable,Throwable> operation, String description ) { ErrorHandler.runAll( description, suspendables.stream() .map( (Function<Suspendable,ErrorHandler.ThrowingRunnable>) suspendable -> () -> operation.accept( suspendable ) ) .toArray( ErrorHandler.ThrowingRunnable[]::new ) ); }
Source:
<code>public static BlobHttpHeaders extractHttpHeaders(List<FileAttribute<?>> fileAttributes, ClientLogger logger) { BlobHttpHeaders headers = new BlobHttpHeaders(); for (Iterator<FileAttribute<?>> it = fileAttributes.iterator(); it.hasNext();) { FileAttribute<?> attr = it.next(); boolean propertyFound = true; switch (attr.name()) { <START> case "Content-Type": <END> headers.setContentType(attr.value().toString()); break; case "Content-Language": headers.setContentLanguage(attr.value().toString()); break; case "Content-Disposition": headers.setContentDisposition(attr.value().toString()); break; case "Content-Encoding": headers.setContentEncoding(attr.value().toString()); break; case "Content-MD5": if ((attr.value() instanceof byte[])) { headers.setContentMd5((byte[]) attr.value()); } else { throw Utility.logError(logger, new UnsupportedOperationException("Content-MD5 attribute must be a byte[]")); } break; case "Cache-Control": headers.setCacheControl(attr.value().toString()); break; default: propertyFound = false; break; } if (propertyFound) { it.remove(); } } return headers; }</code><technical_language>constants anywhere</technical_language>

Target:
public static BlobHttpHeaders extractHttpHeaders(List<FileAttribute<?>> fileAttributes, ClientLogger logger) { BlobHttpHeaders headers = new BlobHttpHeaders(); for (Iterator<FileAttribute<?>> it = fileAttributes.iterator(); it.hasNext();) { FileAttribute<?> attr = it.next(); boolean propertyFound = true; switch (attr.name()) { case AzureFileSystemProvider.CONTENT_TYPE: headers.setContentType(attr.value().toString()); break; case AzureFileSystemProvider.CONTENT_LANGUAGE: headers.setContentLanguage(attr.value().toString()); break; case AzureFileSystemProvider.CONTENT_DISPOSITION: headers.setContentDisposition(attr.value().toString()); break; case AzureFileSystemProvider.CONTENT_ENCODING: headers.setContentEncoding(attr.value().toString()); break; case AzureFileSystemProvider.CONTENT_MD5: if ((attr.value() instanceof byte[])) { headers.setContentMd5((byte[]) attr.value()); } else { throw Utility.logError(logger, new UnsupportedOperationException("Content-MD5 attribute must be a byte[]")); } break; case AzureFileSystemProvider.CACHE_CONTROL: headers.setCacheControl(attr.value().toString()); break; default: propertyFound = false; break; } if (propertyFound) { it.remove(); } } return headers; }
Source:
<code>private void fetchAppUpdateInfo() { mAppUpdateManager.getAppUpdateInfo() .addOnSuccessListener(info -> { mAppUpdateInfo = info; mUpdateAvailability = info.updateAvailability(); mInstallStatus = info.installStatus(); <START> Logger.log(TAG, "fetchAppUpdateInfo|success with UpdateAvailability : " <END> + mUpdateAvailability + ", and InstallStatus : " + mInstallStatus); publishStatus(); }) .addOnFailureListener(exception -> { mAppUpdateInfo = null; mUpdateAvailability = UpdateAvailability.UNKNOWN; mInstallStatus = InstallStatus.UNKNOWN; Logger.log(TAG, "fetchAppUpdateInfo|failed with : " + exception.getMessage()); publishStatus(); }); }</code><technical_language>omit success logs this triggered time user Home screen</technical_language>

Target:
private void fetchAppUpdateInfo() { mAppUpdateManager.getAppUpdateInfo() .addOnSuccessListener(info -> { mAppUpdateInfo = info; mUpdateAvailability = info.updateAvailability(); mInstallStatus = info.installStatus(); publishStatus(); }) .addOnFailureListener(exception -> { mAppUpdateInfo = null; mUpdateAvailability = UpdateAvailability.UNKNOWN; mInstallStatus = InstallStatus.UNKNOWN; Logger.log(TAG, "fetchAppUpdateInfo|failed with : " + exception.getMessage()); publishStatus(); }); }
Source:
<code>protected void setOverrideExcludePatterns(String excludePatterns) { if (excludedPatterns != null && excludedPatterns.size() > 0) { LOG.warn("Overriding excluded patterns with [{}], be aware that this affects all instances and safety of your application!", excludedPatterns, excludePatterns); } else { <START> LOG.debug("Overriding excluded patterns with [{}], be aware that this affects all instances and safety of your application!", <END> excludedPatterns, excludePatterns); } excludedPatterns = new HashSet<Pattern>(); for (String pattern : TextParseUtil.commaDelimitedStringToSet(excludePatterns)) { excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } }</code><technical_language>LOG.debug("Overriding excluded patterns [{}]", excludePatterns);</technical_language>

Target:
protected void setOverrideExcludePatterns(String excludePatterns) { if (excludedPatterns != null && excludedPatterns.size() > 0) { LOG.warn("Overriding excluded patterns with [{}], be aware that this affects all instances and safety of your application!", excludedPatterns, excludePatterns); } else { LOG.debug("Overriding excluded patterns with [{}]", excludePatterns); } excludedPatterns = new HashSet<Pattern>(); for (String pattern : TextParseUtil.commaDelimitedStringToSet(excludePatterns)) { excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } }
Source:
<code>private static void loadPayload() { <START> patterns = defaultPatterns; <END> for (String line : getJsFunctionPayloads().get()) { patterns.add(Pattern.compile("\\b" + line + "\\b", Pattern.CASE_INSENSITIVE)); } }</code><technical_language>this meant patterns = new HashSet(defaultPatterns);? change defaultPatterns</technical_language>

Target:
private static void loadPayload() { patterns = new ArrayList<>(defaultPatterns); for (String line : getJsFunctionPayloads().get()) { addPattern(line, patterns); } }
Source:
<code>public void handleRequireAccessOnDependentTable(String request, String userName, TableName dependentTable, String requestTable, Set<Action> requireAccess, Set<Action> accessExists) throws IOException { if (!isStrictMode) { AUDITLOG.warn("Strict mode is not enabled, so " + request + " is allowed but User:" + userName + " will not have following access " + requireAccess + " to the existing dependent physical table " + dependentTable); return; } Set<Action> unionSet = new HashSet<Action>(); unionSet.addAll(requireAccess); <START> unionSet.addAll(accessExists); <END> AUDITLOG.info(request + ": Automatically granting access to index table during creation of view:" + requestTable + authString(userName, dependentTable, requireAccess)); grantPermissions(userName, dependentTable.getName(), unionSet.toArray(new Action[0])); }</code><technical_language>sense remove isStrictMode option? index data table permissions in sync</technical_language>

Target:
public void handleRequireAccessOnDependentTable(String request, String userName, TableName dependentTable, String requestTable, Set<Action> requireAccess, Set<Action> accessExists) throws IOException { Set<Action> unionSet = new HashSet<Action>(); unionSet.addAll(requireAccess); unionSet.addAll(accessExists); AUDITLOG.info(request + ": Automatically granting access to index table during creation of view:" + requestTable + authString(userName, dependentTable, requireAccess)); grantPermissions(userName, dependentTable.getName(), unionSet.toArray(new Action[0])); }
Source:
<code>public Response getRouteCsv( @QueryParam("deviceId") final List<Long> deviceIds, @QueryParam("groupId") final List<Long> groupIds, @QueryParam("from") String from, @QueryParam("to") String to) throws SQLException { return Response.ok(Route.getCsv(getUserId(), deviceIds, groupIds, JsonConverter.parseDate(from), JsonConverter.parseDate(to))) <START> .header("Content-Disposition", "attachment; filename=route.csv") <END> .build(); }</code><technical_language>nice some constants here. Header name constant already. a constant (we filename report.csv)</technical_language>

Target:
public Response getRouteCsv( @QueryParam("deviceId") final List<Long> deviceIds, @QueryParam("groupId") final List<Long> groupIds, @QueryParam("from") String from, @QueryParam("to") String to) throws SQLException { return Response.ok(Route.getCsv(getUserId(), deviceIds, groupIds, JsonConverter.parseDate(from), JsonConverter.parseDate(to))) .header(HttpHeaders.CONTENT_DISPOSITION, CONTENT_DISPOSITION_VALUE) .build(); }
Source:
<code>public void equalityTest() { <START> DateTimeType dt1 = new DateTimeType(Calendar.getInstance()); <END> DateTimeType dt2 = DateTimeType.valueOf(dt1.toString()); assertTrue(dt1.toString().equals(dt2.toString())); assertTrue(dt1.equals(dt2)); assertTrue(dt1.getCalendar().equals(dt2.getCalendar())); assertTrue(dt1.equals(dt2)); }</code><technical_language>For completeness sense do a java assertEquals(dt.getZonedDateTime(), sdt.getZonedDateTime());</technical_language>

Target:
public void equalityTest() { DateTimeType dt1 = new DateTimeType(Calendar.getInstance()); DateTimeType dt2 = DateTimeType.valueOf(dt1.toFullString()); assertTrue(dt1.toString().equals(dt2.toString())); assertTrue(dt1.equals(dt2)); assertTrue(dt1.getCalendar().equals(dt2.getCalendar())); assertTrue(dt1.equals(dt2)); }
Source:
<code>public ProjectGeneralPreferencesPane(Session session) { sessionInfo_ = session.getSessionInfo(); Grid grid = new Grid(6, 2); grid.addStyleName(RESOURCES.styles().workspaceGrid()); grid.setCellSpacing(8); Label infoLabel = new Label("Use (Default) to inherit the global default setting"); infoLabel.addStyleName(PreferencesDialogBaseResources.INSTANCE.styles().infoLabel()); grid.setWidget(0, 0, infoLabel); grid.setWidget(1, 0, new Label("Restore .RData into workspace at startup")); grid.setWidget(1, 1, restoreWorkspace_ = new YesNoAskDefault(false)); grid.setWidget(2, 0, new Label("Save workspace to .RData on exit")); grid.setWidget(2, 1, saveWorkspace_ = new YesNoAskDefault(true)); grid.setWidget(3, 0, new Label("Always save history (even if not saving .RData)")); grid.setWidget(3, 1, alwaysSaveHistory_ = new YesNoAskDefault(false)); <START> grid.setWidget(4, 0, executeRprofile_ = new CheckBox("Execute .Rprofile on session start")); <END> grid.setWidget(5, 0, quitChildProcessesOnExit_ = new CheckBox("Quit child processes on exit")); add(grid); }</code><technical_language>Do if in packrat mode? If do, disable hide this in packrat mode (since do there)</technical_language>

Target:
public ProjectGeneralPreferencesPane(Session session) { sessionInfo_ = session.getSessionInfo(); Grid grid = new Grid(6, 2); grid.addStyleName(RESOURCES.styles().workspaceGrid()); grid.setCellSpacing(8); Label infoLabel = new Label("Use (Default) to inherit the global default setting"); infoLabel.addStyleName(PreferencesDialogBaseResources.INSTANCE.styles().infoLabel()); grid.setWidget(0, 0, infoLabel); grid.setWidget(1, 0, new Label("Restore .RData into workspace at startup")); grid.setWidget(1, 1, restoreWorkspace_ = new YesNoAskDefault(false)); grid.setWidget(2, 0, new Label("Save workspace to .RData on exit")); grid.setWidget(2, 1, saveWorkspace_ = new YesNoAskDefault(true)); grid.setWidget(3, 0, new Label("Always save history (even if not saving .RData)")); grid.setWidget(3, 1, alwaysSaveHistory_ = new YesNoAskDefault(false)); grid.setWidget(4, 0, disableExecuteRprofile_ = new CheckBox("Disable .Rprofile execution on session start/resume")); grid.setWidget(5, 0, quitChildProcessesOnExit_ = new CheckBox("Quit child processes on exit")); add(grid); }
Source:
<code>private IRegisterGroupDescriptor createGroupDescriptor(final String groupName, final IRegisterDescriptor[] iSelectedRegisters) { IRegisterGroupDescriptor groupDescriptor = new IRegisterGroupDescriptor() { @Override public boolean isEnabled() { return true; } @Override public String getName() { return groupName; } @Override public String getContainerId() { return null; <START> } <END> @Override public IRegisterDescriptor[] getChildren() throws CoreException { return iSelectedRegisters; } }; return groupDescriptor; }</code><technical_language>move this a default method in actual interface, thanks Java 8</technical_language>

Target:
private IRegisterGroupDescriptor createGroupDescriptor(final String groupName, final IRegisterDescriptor[] iSelectedRegisters) { IRegisterGroupDescriptor groupDescriptor = new IRegisterGroupDescriptor() { @Override public boolean isEnabled() { return true; } @Override public String getName() { return groupName; } @Override public IRegisterDescriptor[] getChildren() throws CoreException { return iSelectedRegisters; } }; return groupDescriptor; }
Source:
<code>protected void setValuesFromAlignment(final SAMRecord rec, final SAMRecord alignment, final boolean needsSafeReverseComplement) { alignment.getAttributes().stream() .filter(attr -> (!isReservedTag(attr.tag) || this.attributesToRetain.contains(attr.tag)) && !this.attributesToRemove.contains(attr.tag)) <START> .forEach(attr -> rec.setAttribute(attr.tag, attr.value)); <END> rec.setReadUnmappedFlag(alignment.getReadUnmappedFlag()); rec.setReferenceName(alignment.getReferenceName()); rec.setAlignmentStart(alignment.getAlignmentStart()); rec.setReadNegativeStrandFlag(alignment.getReadNegativeStrandFlag()); rec.setNotPrimaryAlignmentFlag(alignment.getNotPrimaryAlignmentFlag()); rec.setSupplementaryAlignmentFlag(alignment.getSupplementaryAlignmentFlag()); if (!alignment.getReadUnmappedFlag()) { rec.setCigar(alignment.getCigar()); rec.setMappingQuality(alignment.getMappingQuality()); } if (rec.getReadPairedFlag()) { rec.setProperPairFlag(alignment.getProperPairFlag()); } if (rec.getReadNegativeStrandFlag()) { if(needsSafeReverseComplement) { rec.reverseComplement(); } else { rec.reverseComplement(true); } } }</code><technical_language>Is this clearer</technical_language>

Target:
protected void setValuesFromAlignment(final SAMRecord rec, final SAMRecord alignment, final boolean needsSafeReverseComplement) { for (final SAMRecord.SAMTagAndValue attr : alignment.getAttributes()) { if ((!isReservedTag(attr.tag) || this.attributesToRetain.contains(attr.tag)) && !this.attributesToRemove.contains(attr.tag)) { rec.setAttribute(attr.tag, attr.value); } } rec.setReadUnmappedFlag(alignment.getReadUnmappedFlag()); rec.setReferenceName(alignment.getReferenceName()); rec.setAlignmentStart(alignment.getAlignmentStart()); rec.setReadNegativeStrandFlag(alignment.getReadNegativeStrandFlag()); rec.setNotPrimaryAlignmentFlag(alignment.getNotPrimaryAlignmentFlag()); rec.setSupplementaryAlignmentFlag(alignment.getSupplementaryAlignmentFlag()); if (!alignment.getReadUnmappedFlag()) { rec.setCigar(alignment.getCigar()); rec.setMappingQuality(alignment.getMappingQuality()); } if (rec.getReadPairedFlag()) { rec.setProperPairFlag(alignment.getProperPairFlag()); } if (rec.getReadNegativeStrandFlag()) { if(needsSafeReverseComplement) { rec.reverseComplement(); } else { rec.reverseComplement(true); } } }
Source:
<code><START> public BeanDefinition getOAuth2AuthorizationRequestRedirectFilter() { <END> return oauth2AuthorizationRequestRedirectFilter; }</code><technical_language>Please change private for public methods in this class</technical_language>

Target:
BeanDefinition getOAuth2AuthorizationRequestRedirectFilter() { return oauth2AuthorizationRequestRedirectFilter; }
Source:
<code>protected Vector<String> getAllMatchingTests(String match) { Class<? extends AbstractJDITest> theClass = this.getClass(); java.lang.reflect.Method[] methods = theClass.getDeclaredMethods(); Vector<String> result = new Vector<>(); for (int i = 0; i < methods.length; i++) { java.lang.reflect.Method m = methods[i]; String name = m.getName(); Class<?>[] parameters = m.getParameterTypes(); if (parameters.length == 0 && name.startsWith(match)) { if (!isExcludedTest(name)) { result.add(name); } else <START> { <END> System.out.println(name + " is excluded."); } } } return result; }</code><technical_language>Please remove formatting changes in a separate patch. Understanding real code change is difficult otherwise</technical_language>

Target:
protected Vector<String> getAllMatchingTests(String match) { Class<? extends AbstractJDITest> theClass = this.getClass(); java.lang.reflect.Method[] methods = theClass.getDeclaredMethods(); Vector<String> result = new Vector<>(); for (int i = 0; i < methods.length; i++) { java.lang.reflect.Method m = methods[i]; String name = m.getName(); Class<?>[] parameters = m.getParameterTypes(); if (parameters.length == 0 && name.startsWith(match)) { if (!isExcludedTest(name)) { result.add(name); } else System.out.println(name + " is excluded."); } } return result; }
Source:
<code>static void <START> setDefaultLocales(Locales <END> locales) { Locale.setDefault(locales.locale); Locale.setDefault(DISPLAY, locales.displayLocale); Locale.setDefault(FORMAT, locales.formatLocale); }</code><technical_language>put this method Locales called setDefaultLocales(), perhaps. Alternative suggestion (bit more work, feel free ignore): clearer helper store defaults. e.g. class DefaultLocalesTestHelper { private Locale originalUncategorizedLocale; private Locale originalDisplayLocale; private Locale originalFormatLocale; public DefaultLocalesTestHelper setDefaultUncategorizedLocale(Locale newUncategorizedDefault) { assertNull(originalUncategorizedLocale); originalUncategorizedLocale = Locale.getDefault(); Locale.setDefault(newUncategorizedDefault); } ... others category impls... public void resetDefaults() { ... if (originalUncategorizedLocale != null) { Locale.setDefault(originalUncategorizedLocale); } } } a bit more work, test becomes: DefaultLocalesTestHelper helper = new DefaultLocalesTestHelper(); helper.setDefaultUncategorizedLocale(x).setDefaultDisplayLocale(y).setDefaultFormatLocale(z); try { .... } finally { helper.resetDefaults(); } Clearly, if want knowledge of ordering requirements hidden a single setDefault(x,y,z) method do</technical_language>

Target:
static void setDefaultLocales(Locales locales) { Locale.setDefault(locales.uncategorizedLocale); Locale.setDefault(DISPLAY, locales.displayLocale); Locale.setDefault(FORMAT, locales.formatLocale); assertEquals(locales, getDefaultLocales()); }
Source:
<code>public void assemble(ByteBuffer udfBuffer, int udafIndex) throws Throwable { assert(m_paramCount == 1); int argNum = udfBuffer.getInt(); while (argNum-- > 0) { Object[] paramsIn = new Object[m_paramCount]; <START> for (int i = 0; i < m_paramCount; i++) { <END> paramsIn[i] = getValueFromBuffer(udfBuffer, m_paramTypes[i]); if (m_boxUpByteArray[i]) { paramsIn[i] = SerializationHelper.boxUpByteArray((byte[])paramsIn[i]); } } m_assembleMethod.invoke(m_functionInstances.get(udafIndex), paramsIn); } }</code><technical_language>m_paramCount == 1 this for loop removed</technical_language>

Target:
public void assemble(ByteBuffer udfBuffer, int udafIndex) throws Throwable { assert(m_paramCount == 1); int argNum = udfBuffer.getInt(); while (argNum-- > 0) { Object[] paramsIn = new Object[m_paramCount]; paramsIn[0] = getValueFromBuffer(udfBuffer, m_paramTypes[0]); if (m_boxUpByteArray[0]) { paramsIn[0] = SerializationHelper.boxUpByteArray((byte[])paramsIn[0]); } m_assembleMethod.invoke(m_functionInstances.get(udafIndex), paramsIn); } }
Source:
<code>private BucketMeta processPurge(Bucket bucket, BucketMeta bmeta, HashSet<String> filesToDelete) throws IOException { if (bmeta.files.isEmpty()) return bmeta; WriteCache frozen = bucket.frozenWriteCache; if (frozen.getPurges() == null || frozen.getPurges().isEmpty()) return bmeta; BucketMeta bucketMetaCopy = kryo.copy(getMeta(bucket.bucketKey)); Iterator<BucketFileMeta> fileIter = bmeta.files.values().iterator(); while (fileIter.hasNext()) { BucketFileMeta fmeta = fileIter.next(); <START> Range<Slice> frange = new Range<>(fmeta.startKey, getEndKey(bucket.bucketKey, fmeta)); <END> RangeSet<Slice> rset = frozen.getPurges().getOverlappingRanges(frange); if (rset.isEmpty()) continue; writeFileWithPurge(bucket, fmeta, rset, filesToDelete, bucketMetaCopy); } return bucketMetaCopy; }</code><technical_language>do continue checking startKey is < purgeRange endKey</technical_language>

Target:
private BucketMeta processPurge(Bucket bucket, BucketMeta bmeta, HashSet<String> filesToDelete) throws IOException { if (bmeta.files.isEmpty()) { LOG.debug("No existing files to purge data from bucket {}", bucket); return bmeta; } WriteCache frozen = bucket.frozenWriteCache; if (frozen.getPurges() == null || frozen.getPurges().isEmpty()) { LOG.debug("No Pending purge requests for bucket {}", bucket); return bmeta; } BucketMeta bucketMetaCopy = kryo.copy(getMeta(bucket.bucketKey)); Iterator<BucketFileMeta> fileIter = bmeta.files.values().iterator(); Slice last = frozen.getPurges().getLast(); while (fileIter.hasNext()) { BucketFileMeta fmeta = fileIter.next(); if (keyComparator.compare(fmeta.startKey, last) > 0) break; Range<Slice> frange = new Range<>(fmeta.startKey, getEndKey(bucket.bucketKey, fmeta, frozen.getPurges())); RangeSet<Slice> rset = frozen.getPurges().getOverlappingRanges(frange); if (rset.isEmpty()) continue; writeFileWithPurge(bucket, fmeta, rset, filesToDelete, bucketMetaCopy); } return bucketMetaCopy; }
Source:
<code>public void <START> setVariants( <END> Set<BaseVariantData> variants) { mVariants = variants; }</code><technical_language>fits a single line</technical_language>

Target:
public void setVariants(Set<BaseVariantData> variants) { this.variants = variants; }
Source:
<code>public CbclReader(final List<File> cbcls, final Map<Integer, File> filterFileMap, final int[] outputLengths, int tileNum, List<AbstractIlluminaPositionFileReader.PositionInfo> locs, boolean headerOnly) { super(outputLengths); surfaceToTileToCbclMap = sortCbcls(cbcls); this.filterFileMap = filterFileMap; cycleData = new CycleData[cycles]; cachedTile = new byte[cycles][]; cachedTilePosition = new int[cycles]; for (int i = 1; i <= cycles; i++) { <START> allTiles.put(i, new ArrayList<>()); <END> } readSurfaceTile(tileNum, locs, headerOnly); close(); }</code><technical_language>this represented array instead of a map</technical_language>

Target:
public CbclReader(final List<File> cbcls, final Map<Integer, File> filterFileMap, final int[] outputLengths, int tileNum, List<AbstractIlluminaPositionFileReader.PositionInfo> locs, boolean headerOnly) { super(outputLengths); surfaceToTileToCbclMap = sortCbcls(cbcls); this.filterFileMap = filterFileMap; cycleData = new CycleData[cycles]; cachedTile = new byte[cycles][]; cachedTilePosition = new int[cycles]; for (int i = 1; i <= cycles; i++) { allTiles.put(i, new ArrayList<>()); } try { readSurfaceTile(tileNum, locs, headerOnly); } finally { close(); } }
Source:
<code>public void decoratePillarWithClouderaManagerSettings(Map<String, SaltPillarProperties> servicePillar, ClouderaManagerRepo clouderaManagerRepo, Stack stack) { ServiceLocationMap serviceLocations = clusterApiConnectors.getConnector(stack.getCluster()).getServiceLocations(); String cmVersion = clouderaManagerRepo.getVersion(); servicePillar.put("cloudera-manager-settings", new SaltPillarProperties("/cloudera-manager/settings.sls", singletonMap("cloudera-manager", Map.of( "settings", Map.of( "heartbeat_interval", cmHeartbeatInterval, "missed_heartbeat_interval", cmMissedHeartbeatInterval, "set_cdp_env", isVersionNewerOrEqualThanLimited(cmVersion, CLOUDERAMANAGER_VERSION_7_0_2), "deterministic_uid_gid", isVersionNewerOrEqualThanLimited(cmVersion, CLOUDERAMANAGER_VERSION_7_2_1), "cloudera_scm_sudo_access", CMRepositoryVersionUtil.isSudoAccessNeededForHostCertRotation(clouderaManagerRepo)), <START> "directories", serviceLocations.getAllVolumePath())))); <END> }</code><technical_language>call mgmt_service_directories instead</technical_language>

Target:
public void decoratePillarWithClouderaManagerSettings(Map<String, SaltPillarProperties> servicePillar, ClouderaManagerRepo clouderaManagerRepo, Stack stack) { ServiceLocationMap serviceLocations = clusterApiConnectors.getConnector(stack.getCluster()).getServiceLocations(); String cmVersion = clouderaManagerRepo.getVersion(); servicePillar.put("cloudera-manager-settings", new SaltPillarProperties("/cloudera-manager/settings.sls", singletonMap("cloudera-manager", Map.of( "settings", Map.of( "heartbeat_interval", cmHeartbeatInterval, "missed_heartbeat_interval", cmMissedHeartbeatInterval, "set_cdp_env", isVersionNewerOrEqualThanLimited(cmVersion, CLOUDERAMANAGER_VERSION_7_0_2), "deterministic_uid_gid", isVersionNewerOrEqualThanLimited(cmVersion, CLOUDERAMANAGER_VERSION_7_2_1), "cloudera_scm_sudo_access", CMRepositoryVersionUtil.isSudoAccessNeededForHostCertRotation(clouderaManagerRepo)), "mgmt_service_directories", serviceLocations.getAllVolumePath())))); }
Source:
<code>public FileUtils.FileCopyResult getSegmentFiles(String region, String container, String path, File outDir) throws SegmentLoadingException { CloudFilesObjectApiProxy objectApi = new CloudFilesObjectApiProxy(cloudFilesApi, region, container); CloudFilesObject cloudFilesObject = objectApi.get(path); try { <START> final InputStream inputStream = cloudFilesObject.getPayload().openStream(); <END> final FileUtils.FileCopyResult result = CompressionUtils.unzip(inputStream, outDir); log.info("Loaded %d bytes from [%s] to [%s]", result.size(), cloudFilesObject.getPath(), outDir.getAbsolutePath()); return result; } catch (Exception e) { try { org.apache.commons.io.FileUtils.deleteDirectory(outDir); } catch (IOException ioe) { log.warn(ioe, "Failed to remove output directory [%s] for segment pulled from [%s]", outDir.getAbsolutePath(), cloudFilesObject.getPath()); } throw new SegmentLoadingException(e, e.getMessage()); } }</code><technical_language>Suggest com.metamx.common.CompressionUtils#unzip(com.google.common.io.ByteSource, java.io.File, com.google.common.base.Predicate<java.lang.Throwable>, boolean) this is missing retries stream closing</technical_language>

Target:
public FileUtils.FileCopyResult getSegmentFiles(String region, String container, String path, File outDir) throws SegmentLoadingException { CloudFilesObjectApiProxy objectApi = new CloudFilesObjectApiProxy(cloudFilesApi, region, container); final CloudFilesByteSource byteSource = new CloudFilesByteSource(objectApi, path); try { final FileUtils.FileCopyResult result = CompressionUtils.unzip( byteSource, outDir, CloudFilesUtils.CLOUDFILESRETRY, true ); log.info("Loaded %d bytes from [%s] to [%s]", result.size(), path, outDir.getAbsolutePath()); return result; } catch (Exception e) { try { org.apache.commons.io.FileUtils.deleteDirectory(outDir); } catch (IOException ioe) { log.warn( ioe, "Failed to remove output directory [%s] for segment pulled from [%s]", outDir.getAbsolutePath(), path ); } throw new SegmentLoadingException(e, e.getMessage()); } finally { try { byteSource.closeStream(); } catch (IOException ioe) { log.warn(ioe, "Failed to close payload for segmente pulled from [%s]", path); } } }
Source:
<code>public void initialise() { <START> addDesiredStateChange(new BindFBO(DefaultDynamicFBOs.READ_ONLY_GBUFFER.getName(), dynamicFBOsManager)); END> }</code><technical_language>BindFBO default FBOs directly, write new BindFBO(READ_ONLY_GBUFFER, dynamicFBOsManager)</technical_language>

Target:
public void initialise() { addDesiredStateChange(new BindFBO(READ_ONLY_GBUFFER.getName(), displayResolutionDependentFBOs)); }
Source:
<code>private void logIncompatibleRegistration(String path, Type existingType, Type type) { if ( LOG.isTraceEnabled() ) { LOG.tracev( <START> "Skipped adding same named type incompatible property to base type [{0}] for property [{1}], existing type = [{2}], incoming type = [{3}]", <END> getEntityName(), path, existingType, type ); } }</code><technical_language>this, instead? "Skipped adding attribute [{1}] base-type [{0}] more sub-type defined attribute incompatible types (strictly speaking attributes inherited); existing type = [{2}], incoming type = [{3}]"</technical_language>

Target:
private void logIncompatibleRegistration(String path, Type existingType, Type type) { if ( LOG.isTraceEnabled() ) { LOG.tracev( "Skipped adding attribute [{1}] to base-type [{0}] as more than one sub-type defined the attribute using incompatible types (strictly speaking the attributes are not inherited); existing type = [{2}], incoming type = [{3}]", getEntityName(), path, existingType, type ); } }
Source:
<code>public Data deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException { final JsonNode root = jp.readValueAsTree(); if (root.isArray()) { final List<Data> list = stream(spliteratorUnknownSize(root.elements(), Spliterator.ORDERED), false) .map(elem -> { try { final Class<? extends Data> clazz = elem.isArray() ? DataList.class : DataValue.class; return ctxt.readValue(elem.traverse(jp.getCodec()), clazz); } catch (IOException e) { throw new UncheckedIOException(e); } }).collect(Collectors.toList()); return new DataList(list); } else if (root.isTextual()) { return new DataValue(root.textValue()); } else if (root.isNull()) { return NULL; } else { <START> throw from(jp, "Unknown value of type: " + root.getNodeType()); <END> } }</code><technical_language>I add JsonMappingException. for readability</technical_language>

Target:
public Data deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException { final JsonNode root = jp.readValueAsTree(); if (root.isArray()) { final List<Data> list = stream(spliteratorUnknownSize(root.elements(), Spliterator.ORDERED), false) .map(elem -> { try { return ctxt.readValue(elem.traverse(jp.getCodec()), Data.class); } catch (IOException e) { throw new UncheckedIOException(e); } }).collect(Collectors.toList()); return new DataList(list); } else if (root.isTextual()) { return new DataValue(root.textValue()); } else if (root.isNull()) { return NULL; } else { throw JsonMappingException.from(jp, "Unknown value of type: " + root.getNodeType()); } }