auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static String getGerritPluginName(File srcFile) throws IOException { String fileName = srcFile.getName(); if (isJarPlugin(fileName)) { JarFile jarFile = new JarFile(srcFile); try { return jarFile.getManifest().getMainAttributes() .getValue("Gerrit-PluginName"); } finally { jarFile.close(); } } if (isJsPlugin(fileName)) { return fileName.substring(0, fileName.length() - 3); } throw new RuntimeException(String.format("Unknown plugin file: %s", fileName)); }

Target:
private static String getGerritPluginName(File srcFile) throws IOException { String fileName = srcFile.getName(); if (isJarPlugin(fileName)) { JarFile jarFile = new JarFile(srcFile); try { return jarFile.getManifest().getMainAttributes() .getValue("Gerrit-PluginName"); } finally { jarFile.close(); } } if (isJsPlugin(fileName)) { return fileName.substring(0, fileName.length() - 3); } return null; }
Source:
private void sizeCheck() { long minRecordToWait = Long.MAX_VALUE; int pageRowCountLimit = props.getPageRowCountLimit(); long rowCountForNextRowCountCheck = rowCount + pageRowCountLimit; for (ColumnWriterBase writer : columns.values()) { long usedMem = writer.getCurrentPageBufferedSize(); long rows = rowCount - writer.getRowsWrittenSoFar(); long remainingMem = props.getPageSizeThreshold() - usedMem; if (remainingMem <= thresholdTolerance || rows >= pageRowCountLimit) { writer.writePage(); remainingMem = props.getPageSizeThreshold(); } else { rowCountForNextRowCountCheck = min(rowCountForNextRowCountCheck, writer.getRowsWrittenSoFar() + pageRowCountLimit); } long rowsToFillPage = usedMem == 0 ? props.getMaxRowCountForPageSizeCheck() : (long) (rows) / usedMem * remainingMem; if (rowsToFillPage < minRecordToWait) { minRecordToWait = rowsToFillPage; } } if (minRecordToWait == Long.MAX_VALUE) { minRecordToWait = props.getMinRowCountForPageSizeCheck(); } if (props.estimateNextSizeCheck()) { rowCountForNextSizeCheck = rowCount + min( max(minRecordToWait / 2, props.getMinRowCountForPageSizeCheck()), props.getMaxRowCountForPageSizeCheck()); } else { rowCountForNextSizeCheck = rowCount + props.getMinRowCountForPageSizeCheck(); } if (rowCountForNextRowCountCheck < rowCountForNextSizeCheck) { rowCountForNextSizeCheck = rowCountForNextRowCountCheck; } }

Target:
private void sizeCheck() { long minRecordToWait = Long.MAX_VALUE; int pageRowCountLimit = props.getPageRowCountLimit(); long rowCountForNextRowCountCheck = rowCount + pageRowCountLimit; for (ColumnWriterBase writer : columns.values()) { long usedMem = writer.getCurrentPageBufferedSize(); long rows = rowCount - writer.getRowsWrittenSoFar(); long remainingMem = props.getPageSizeThreshold() - usedMem; if (remainingMem <= thresholdTolerance || rows >= pageRowCountLimit) { writer.writePage(); remainingMem = props.getPageSizeThreshold(); } else { rowCountForNextRowCountCheck = min(rowCountForNextRowCountCheck, writer.getRowsWrittenSoFar() + pageRowCountLimit); } long rowsToFillPage = usedMem == 0 ? props.getMaxRowCountForPageSizeCheck() : (long) rows / usedMem * remainingMem; if (rowsToFillPage < minRecordToWait) { minRecordToWait = rowsToFillPage; } } if (minRecordToWait == Long.MAX_VALUE) { minRecordToWait = props.getMinRowCountForPageSizeCheck(); } if (props.estimateNextSizeCheck()) { rowCountForNextSizeCheck = rowCount + min( max(minRecordToWait / 2, props.getMinRowCountForPageSizeCheck()), props.getMaxRowCountForPageSizeCheck()); } else { rowCountForNextSizeCheck = rowCount + props.getMinRowCountForPageSizeCheck(); } if (rowCountForNextRowCountCheck < rowCountForNextSizeCheck) { rowCountForNextSizeCheck = rowCountForNextRowCountCheck; } }
Source:
public boolean shouldSchedule(Queue.Task p, List<Action> actions) { for (Action action : actions) { if (action instanceof CauseAction) { for (Cause c : ((CauseAction) action).getCauses()) { if (c instanceof BranchIndexingCause) { if (p instanceof Job) { Job j = (Job) p; OverrideIndexTriggersJobProperty overrideProp = (OverrideIndexTriggersJobProperty) j.getProperty(OverrideIndexTriggersJobProperty.class); if (overrideProp != null && !overrideProp.getEnableTriggers()) { return false; } } } } } } return true; }

Target:
public boolean shouldSchedule(Queue.Task p, List<Action> actions) { for (Action action : actions) { if (action instanceof CauseAction) { for (Cause c : ((CauseAction) action).getCauses()) { if (c instanceof BranchIndexingCause) { if (p instanceof Job) { Job<?,?> j = (Job) p; OverrideIndexTriggersJobProperty overrideProp = j.getProperty(OverrideIndexTriggersJobProperty.class); if (overrideProp != null) { return overrideProp.getEnableTriggers(); } else { return true; } } } } } } return true; }
Source:
public LocalDateDoubleTimeSeries withValues(double[] values) { validate(_times, values); return new ImmutableLocalDateDoubleTimeSeries(_times, values.clone()); }

Target:
public LocalDateDoubleTimeSeries withValues(double[] values) { validateLength(_times, values); return new ImmutableLocalDateDoubleTimeSeries(_times, values.clone()); }
Source:
public BoundedIterable<Long> newAllEntriesReader() { @SuppressWarnings( "unchecked" ) BoundedIterable<Long>[] entries = Arrays.stream( instancesAs( BoundedIterable.class, IndexAccessor::newAllEntriesReader ) ) .filter( notNull() ) .toArray( BoundedIterable[]::new ); return new BoundedIterable<Long>() { @Override public long maxCount() { long[] maxCounts = new long[entries.length]; long sum = 0; for ( int i = 0; i < entries.length; i++ ) { maxCounts[i] = entries[i].maxCount(); sum += maxCounts[i]; } return existsUnknownMaxCount( maxCounts ) ? UNKNOWN_MAX_COUNT : sum; } private boolean existsUnknownMaxCount( long... maxCounts ) { for ( long maxCount : maxCounts ) { if ( maxCount == UNKNOWN_MAX_COUNT ) { return true; } } return false; } @SuppressWarnings( "unchecked" ) @Override public void close() throws Exception { forAll( BoundedIterable::close, entries ); } @Override public Iterator<Long> iterator() { return Iterables.concat( entries ).iterator(); } }; }

Target:
public BoundedIterable<Long> newAllEntriesReader() { BoundedIterable<Long>[] entries = instancesAs( BoundedIterable.class, IndexAccessor::newAllEntriesReader ); return new BoundedIterable<Long>() { @Override public long maxCount() { long[] maxCounts = new long[entries.length]; long sum = 0; for ( int i = 0; i < entries.length; i++ ) { maxCounts[i] = entries[i].maxCount(); sum += maxCounts[i]; } return existsUnknownMaxCount( maxCounts ) ? UNKNOWN_MAX_COUNT : sum; } private boolean existsUnknownMaxCount( long... maxCounts ) { for ( long maxCount : maxCounts ) { if ( maxCount == UNKNOWN_MAX_COUNT ) { return true; } } return false; } @SuppressWarnings( "unchecked" ) @Override public void close() throws Exception { forAll( BoundedIterable::close, entries ); } @Override public Iterator<Long> iterator() { return Iterables.concat( entries ).iterator(); } }; }
Source:
public boolean canContribute(IStatus status) { return !StringUtils.isEmpty(doAnalyze()); }

Target:
public boolean canContribute(IStatus status) { return getPlatformDetailsConfiguration().contains(sectionTitle); }
Source:
public static void main(String[] args) { try { try(KubernetesClient client = new DefaultKubernetesClient()){ if (!client.supportsApiPath("/apis/apiextensions.k8s.io/v1beta1") && !client.supportsApiPath("/apis/apiextensions.k8s.io/v1")) { System.out.println("WARNING this cluster does not support the API Group apiextensions.k8s.io"); return; } CustomResourceDefinitionList list = client.customResourceDefinitions().list(); if (list == null) { System.out.println("ERROR no list returned!"); return; } List<CustomResourceDefinition> items = list.getItems(); for (CustomResourceDefinition item : items) { System.out.println("CustomResourceDefinition " + item.getMetadata().getName() + " has version: " + item.getApiVersion()); } } } catch (KubernetesClientException e) { System.out.println("Failed: " + e); e.printStackTrace(); } }}

Target:
public static void main(String[] args) { try(KubernetesClient client = new DefaultKubernetesClient()){ if (!client.supportsApiPath("/apis/apiextensions.k8s.io/v1beta1") && !client.supportsApiPath("/apis/apiextensions.k8s.io/v1")) { System.out.println("WARNING this cluster does not support the API Group apiextensions.k8s.io"); return; } CustomResourceDefinitionList list = client.customResourceDefinitions().list(); if (list == null) { System.out.println("ERROR no list returned!"); return; } List<CustomResourceDefinition> items = list.getItems(); for (CustomResourceDefinition item : items) { System.out.println("CustomResourceDefinition " + item.getMetadata().getName() + " has version: " + item.getApiVersion()); } } catch (KubernetesClientException e) { System.out.println("Failed: " + e); e.printStackTrace(); } }}
Source:
public TumorType(TumorType otherTumorType) { code = otherTumorType.code; color = otherTumorType.color; name = otherTumorType.name; mainType = otherTumorType.mainType; NCI = new ArrayList<String>(otherTumorType.NCI); UMLS = new ArrayList<String>(otherTumorType.UMLS); tissue = otherTumorType.tissue; children = new HashMap<String, TumorType>(otherTumorType.children); parent = otherTumorType.parent; deprecated = otherTumorType.deprecated; history = new ArrayList<String>(otherTumorType.history); level = otherTumorType.level; }

Target:
public TumorType(TumorType otherTumorType) { this.code = otherTumorType.code; this.color = otherTumorType.color; this.name = otherTumorType.name; this.mainType = otherTumorType.mainType; this.externalReferences = new HashMap<String, List<String>>(otherTumorType.externalReferences); this.tissue = otherTumorType.tissue; this.children = new HashMap<String, TumorType>(otherTumorType.children); this.parent = otherTumorType.parent; this.history = new ArrayList<String>(otherTumorType.history); this.level = otherTumorType.level; }
Source:
public void testPutWithTimestamp() throws Exception { final EntityId entityId = mTable.getEntityId("foo"); final KijiDataRequest request = KijiDataRequest.create("info", "name"); KijiTableWriter writer = mTable.openTableWriter(); writer.put(entityId, "info", "name", 123L, "old"); writer.close(); mBufferedWriter.put(entityId, KijiColumnName.create("info", "name"), 123L, "baz"); final String actual = mReader.get(entityId, request).getValue("info", "name", 123L).toString(); assertEquals("old", actual); mBufferedWriter.flush().get(); final String actual2 = mReader.get(entityId, request).getValue("info", "name", 123L).toString(); assertEquals("baz", actual2); }

Target:
public void testPutWithTimestamp() throws Exception { final EntityId entityId = mTable.getEntityId("foo"); final KijiDataRequest request = KijiDataRequest.create("info", "name"); KijiTableWriter writer = mTable.openTableWriter(); try { writer.put(entityId, "info", "name", 123L, "old"); } finally { writer.close(); } mBufferedWriter.put(entityId, KijiColumnName.create("info", "name"), 123L, "baz"); final String actual = mReader.get(entityId, request).getValue("info", "name", 123L).toString(); assertEquals("old", actual); mBufferedWriter.flush().get(); final String actual2 = mReader.get(entityId, request).getValue("info", "name", 123L).toString(); assertEquals("baz", actual2); }
Source:
public static List<ProtoGrade> gradingRequestHandler(final Institution institution, final ItemRequest request, final String authId, final String userId) throws DatabaseAccessException, InvalidProtocolBufferException, AuthenticationException { final GradingQuery query = GradingQuery.parseFrom(request.getAdvanceQuery()); final boolean instructor = query.getPermissionLevel() == GradingQuery.PermissionLevel.INSTRUCTOR; final boolean student = query.getPermissionLevel() == GradingQuery.PermissionLevel.STUDENT; final boolean allGrades = query.getSearchType() == GradingQuery.SearchType.ALL_GRADES; final boolean singleGrade = query.getSearchType() == GradingQuery.SearchType.SINGLE_GRADE; LOG.debug("Query State instructor: {}, student: {}, allGrades: {}, singleGrade: {}", instructor, student, allGrades, singleGrade); List<ProtoGrade> returnList = new ArrayList<>(); if (instructor && allGrades) { returnList = institution.getAllAssignmentGradesInstructor(request.getItemId(COURSE_INDEX), authId); } else if (student && allGrades) { returnList = institution.getAllAssignmentGradesStudent(request.getItemId(COURSE_INDEX), authId, userId); } else { final ProtoGrade gradeData = ProtoGrade.newBuilder() .setUserId(request.getItemId(USER_INDEX)) .setCourseId(request.getItemId(COURSE_INDEX)) .setAssignmentId(request.getItemId(ASSIGNMENT_INDEX)) .setProblemId(request.getItemId(PROBLEM_INDEX)) .build(); returnList.add(institution.getGrade(userId, authId, gradeData)); } return returnList; }

Target:
public static List<ProtoGrade> gradingRequestHandler(final Institution institution, final ItemRequest request, final String authId, final String userId) throws DatabaseAccessException, InvalidProtocolBufferException, AuthenticationException { final GradingQuery query = GradingQuery.parseFrom(request.getAdvanceQuery()); final boolean instructor = query.getPermissionLevel() == GradingQuery.PermissionLevel.INSTRUCTOR; final boolean student = query.getPermissionLevel() == GradingQuery.PermissionLevel.STUDENT; final boolean allGrades = query.getSearchType() == GradingQuery.SearchType.ALL_GRADES; final boolean singleGrade = query.getSearchType() == GradingQuery.SearchType.SINGLE_GRADE; LOG.debug("Query State instructor: {}, student: {}, allGrades: {}, singleGrade: {}", instructor, student, allGrades, singleGrade); List<ProtoGrade> returnList = new ArrayList<>(); if (instructor && allGrades) { returnList = institution.getAllAssignmentGradesInstructor(authId, request.getItemId(COURSE_INDEX)); } else if (student && allGrades) { returnList = institution.getAllAssignmentGradesStudent(userId, authId, request.getItemId(COURSE_INDEX)); } else { final ProtoGrade gradeData = ProtoGrade.newBuilder() .setUserId(request.getItemId(USER_INDEX)) .setCourseId(request.getItemId(COURSE_INDEX)) .setAssignmentId(request.getItemId(ASSIGNMENT_INDEX)) .setProblemId(request.getItemId(PROBLEM_INDEX)) .build(); returnList.add(institution.getGrade(userId, authId, gradeData)); } return returnList; }
Source:
public DataTransactionResult set(DataHolder dataHolder, DyeableData manipulator, MergeFunction function) { if (!supports(dataHolder)) { return DataTransactionResult.failResult(manipulator.type().asImmutable()); } DyeableData original = from(dataHolder).get(); DyeableData merged = function.merge(original, manipulator); ((IMixinTileEntityShulkerBox) dataHolder).setColor((EnumDyeColor) (Object) merged.type().get()); return DataTransactionResult.successReplaceResult(original.type().asImmutable(), merged.type().asImmutable()); }

Target:
public DataTransactionResult set(DataHolder dataHolder, DyeableData manipulator, MergeFunction function) { DyeableData original = dataHolder.require(DyeableData.class); DyeableData merged = function.merge(original, manipulator); Value<DyeColor> mergedValue = merged.type(); ((IMixinTileEntityShulkerBox) dataHolder).setColor((EnumDyeColor) (Object) mergedValue.get()); return DataTransactionResult.successReplaceResult(original.type().asImmutable(), mergedValue.asImmutable()); }
Source:
public void testTransformInternet() throws Exception { if (!TestHelper.isInternetConnected()) { return; } assertEquals("94.142.215.39", t.transform(new MockInputRow().put(col, "eobjects.org"))[0]); }

Target:
public void testTransformInternet() throws Exception { Assume.assumeTrue(TestHelper.isInternetConnected()); assertEquals("94.142.215.39", t.transform(new MockInputRow().put(col, "eobjects.org"))[0]); }
Source:
private void reset() { logger.info("Resetting the routing table."); for (String key: _routingTableRefMap.keySet()) { PropertyType propertyType = _routingTableRefMap.get(key).get().getPropertyType(); if (propertyType == PropertyType.CUSTOMIZEDVIEW) { String stateType = _routingTableRefMap.get(key).get().getStateType(); RoutingTable newRoutingTable = new CustomizedViewRoutingTable(propertyType, stateType); _routingTableRefMap.get(key).set(newRoutingTable); } else { RoutingTable newRoutingTable = new RoutingTable(propertyType); _routingTableRefMap.get(key).set(newRoutingTable); } } }

Target:
private void reset() { logger.info("Resetting the routing table."); RoutingTable newRoutingTable; for (String key: _routingTableRefMap.keySet()) { PropertyType propertyType = _routingTableRefMap.get(key).get().getPropertyType(); if (propertyType == PropertyType.CUSTOMIZEDVIEW) { String stateType = _routingTableRefMap.get(key).get().getStateType(); newRoutingTable = new CustomizedViewRoutingTable(propertyType, stateType); } else { newRoutingTable = new RoutingTable(propertyType); } _routingTableRefMap.get(key).set(newRoutingTable); } }
Source:
protected VDSGroup lookupClusterByName(String name) { return getEntity(VDSGroup.class, VdcQueryType.GetVdsGroupByName, new NameQueryParameters(name), "GetVdsGroupByName"); }

Target:
protected VDSGroup lookupClusterByName(String name) { return getEntity(VDSGroup.class, VdcQueryType.GetVdsGroupByName, new NameQueryParameters(name), "Cluster: name=" + name); }
Source:
public @ResponseBody Map<String, Object> cswRequest(@RequestParam String xml){ try { String decodedXML = java.net.URLDecoder.decode(xml, "UTF-8"); String response = this.metadataService.cswRequest(decodedXML); return ResultSet.success(response); } catch (URISyntaxException | HttpException | IOException e) { return ResultSet.error("Error while updating Sld: " + e.getMessage()); } }

Target:
public @ResponseBody Map<String, Object> cswRequest(@RequestParam String xml){ try { String decodedXML = java.net.URLDecoder.decode(xml, "UTF-8"); String response = this.metadataService.cswRequest(decodedXML); return ResultSet.success(response); } catch (URISyntaxException | HttpException | IOException e) { return ResultSet.error("Error during csw-transaction: " + e.getMessage()); } }
Source:
public void selectNthItem(int n) { requestFocus(); assert(getItems().size() < n); getSelectionModel().clearAndSelect(n - 1); scrollAndShow(n - 1); selectedIndex = Optional.of(n - 1); onItemSelected.accept(selectedIndex.get()); }

Target:
public void selectNthItem(int n) { requestFocus(); assert n <= getItems().size() && n > 0; getSelectionModel().clearAndSelect(n - 1); scrollAndShow(n - 1); selectedIndex = Optional.of(n - 1); onItemSelected.accept(selectedIndex.get()); }
Source:
private static TypeReference[] computeExceptions(IClassHierarchy cha, IR ir, SSAInstruction s) throws InvalidClassFileException { Collection<TypeReference> c = null; Language l = ir.getMethod().getDeclaringClass().getClassLoader().getLanguage(); if (s instanceof SSAInvokeInstruction) { SSAInvokeInstruction call = (SSAInvokeInstruction) s; c = l.inferInvokeExceptions(call.getDeclaredTarget(), cha); } else { c = s.getExceptionTypes(); } if (c == null) { return null; } else { TypeReference[] exceptions = new TypeReference[c.size()]; Iterator<TypeReference> it = c.iterator(); Arrays.setAll(exceptions, i -> it.next()); return exceptions; } }

Target:
private static TypeReference[] computeExceptions(IClassHierarchy cha, IR ir, SSAInstruction s) throws InvalidClassFileException { final Collection<TypeReference> c; Language l = ir.getMethod().getDeclaringClass().getClassLoader().getLanguage(); if (s instanceof SSAInvokeInstruction) { SSAInvokeInstruction call = (SSAInvokeInstruction) s; c = l.inferInvokeExceptions(call.getDeclaredTarget(), cha); } else { c = s.getExceptionTypes(); } return c == null ? null : c.toArray(new TypeReference[0]); }
Source:
public void findAllSortedAsync_onSubObjectField() { Realm realm = looperThread.realm; populateTestRealm(realm, TEST_DATA_SIZE); RealmResults<AllTypes> results = realm.where(AllTypes.class) .findAllSorted(AllTypes.FIELD_REALMOBJECT + "." + Dog.FIELD_AGE); looperThread.keepStrongReference.add(results); results.addChangeListener(new RealmChangeListener<RealmResults<AllTypes>>() { @Override public void onChange(RealmResults<AllTypes> results) { assertEquals(0, results.get(0).getColumnRealmObject().getAge()); assertEquals(TEST_DATA_SIZE - 1, results.get(TEST_DATA_SIZE - 1).getColumnRealmObject().getAge()); looperThread.testComplete(); } }); }

Target:
public void findAllSortedAsync_onSubObjectField() { Realm realm = looperThread.realm; populateTestRealm(realm, TEST_DATA_SIZE); RealmResults<AllTypes> results = realm.where(AllTypes.class) .findAllSortedAsync(AllTypes.FIELD_REALMOBJECT + "." + Dog.FIELD_AGE); looperThread.keepStrongReference.add(results); results.addChangeListener(new RealmChangeListener<RealmResults<AllTypes>>() { @Override public void onChange(RealmResults<AllTypes> results) { assertEquals(0, results.get(0).getColumnRealmObject().getAge()); assertEquals(TEST_DATA_SIZE - 1, results.get(TEST_DATA_SIZE - 1).getColumnRealmObject().getAge()); looperThread.testComplete(); } }); }
Source:
private static int getMajorJavaVersion() { int major = 0; String version = WildFlySecurityManager.getPropertyPrivileged("java.specification.version", null); if (version != null) { if (version.contains(".")) { major = Integer.parseInt(version.split("\\.")[1]); } else { major = Integer.parseInt(version); } } return major; }

Target:
private static int getMajorJavaVersion() { int major = 8; String version = WildFlySecurityManager.getPropertyPrivileged("java.specification.version", null); if (version != null) { Matcher matcher = Pattern.compile("^(?:1\\.)?(\\d+)$").matcher(version); if (matcher.find()) { major = Integer.valueOf(matcher.group(1)); } } return major; }}
Source:
public ImageDescriptor createImageDescriptor() { Program program = ProgramFinder.findProgram(extension.toLowerCase()); if (program == null || program.getImageData() == null) { return null; } return ImageDescriptor.createFromImageData(program.getImageData()); }

Target:
public ImageDescriptor createImageDescriptor() { Program program = ProgramFinder.findProgram(extension); if (program == null || program.getImageData() == null) { return null; } return ImageDescriptor.createFromImageData(program.getImageData()); }
Source:
@Override public Observable<Boolean> observeInternetConnectivity(final int initialIntervalInMs, final int intervalInMs, final String host, final int port, final int timeoutInMs, final ErrorHandler errorHandler) { Preconditions.checkGreaterOrEqualToZero(initialIntervalInMs, "initialIntervalInMs is not a positive number"); Preconditions.checkGreaterThanZero(intervalInMs, "intervalInMs is not a positive number"); Preconditions.checkNotNullOrEmpty(host, "host is null or empty"); Preconditions.checkGreaterThanZero(port, "port is not a positive number"); Preconditions.checkGreaterThanZero(timeoutInMs, "timeoutInMs is not a positive number"); Preconditions.checkNotNull(errorHandler, "errorHandler is null"); return Observable.interval(initialIntervalInMs, intervalInMs, TimeUnit.MILLISECONDS, Schedulers.io()).map(new Function<Long, Boolean>() { @Override public Boolean apply(@NonNull Long aLong) throws Exception { return isConnected(host, port, timeoutInMs, errorHandler); } }).distinctUntilChanged(); }

Target:
@Override public Observable<Boolean> observeInternetConnectivity(final int initialIntervalInMs, final int intervalInMs, final String host, final int port, final int timeoutInMs, final ErrorHandler errorHandler) { Preconditions.checkGreaterOrEqualToZero(initialIntervalInMs, "initialIntervalInMs is not a positive number"); Preconditions.checkGreaterThanZero(intervalInMs, "intervalInMs is not a positive number"); Preconditions.checkNotNullOrEmpty(host, "host is null or empty"); Preconditions.checkGreaterThanZero(port, "port is not a positive number"); Preconditions.checkGreaterThanZero(timeoutInMs, "timeoutInMs is not a positive number"); Preconditions.checkNotNull(errorHandler, "errorHandler is null"); return Observable.interval(initialIntervalInMs, intervalInMs, TimeUnit.MILLISECONDS, Schedulers.io()).map(new Function<Long, Boolean>() { @Override public Boolean apply(@NonNull Long tick) throws Exception { return isConnected(host, port, timeoutInMs, errorHandler); } }).distinctUntilChanged(); }
Source:
private void terminateWindowsApplication() { List<String> cmd = new ArrayList<>(); cmd.add("WMIC"); cmd.add("PROCESS"); cmd.add("WHERE"); cmd.add("CommandLine like '%vertx.id=" + id + "%'"); cmd.add("CALL"); cmd.add("TERMINATE"); try { final Process process = new ProcessBuilder(cmd).start(); out.println("Application '" + id + "' stopped"); process.waitFor(); } catch (Exception e) { out.println("Failed to stop application '" + id + "'"); e.printStackTrace(out); } }

Target:
private void terminateWindowsApplication() { List<String> cmd = Arrays.asList( "WMIC", "PROCESS", "WHERE", "CommandLine like '%vertx.id=" + id + "%'", "CALL", "TERMINATE" ); try { final Process process = new ProcessBuilder(cmd).start(); out.println("Application '" + id + "' stopped"); process.waitFor(); } catch (Exception e) { out.println("Failed to stop application '" + id + "'"); e.printStackTrace(out); } }
Source:
protected static boolean shouldUpdate(OskariLayer layer) { Date lastUpdated = layer.getCapabilitiesLastUpdated(); if (lastUpdated == null) { LOG.debug("Should update layer:", layer.getId(), "last updated unknown and update rate is positive"); return true; } int rate = layer.getCapabilitiesUpdateRateSec(); long nextUpdate = lastUpdated.getTime() + TimeUnit.SECONDS.toMillis(rate); long now = System.currentTimeMillis(); LOG.debug("Layer:", layer.getId(), "next scheduled update is:", nextUpdate, "now is", now); if (nextUpdate <= now) { return true; } LOG.debug("Skipping layerId:", layer.getId(), "as recently updated"); return false; }

Target:
protected static boolean shouldUpdate(OskariLayer layer) { Date lastUpdated = layer.getCapabilitiesLastUpdated(); if (lastUpdated == null) { LOG.debug("Should update layer:", layer.getId(), "last updated unknown"); return true; } int rate = layer.getCapabilitiesUpdateRateSec(); long nextUpdate = lastUpdated.getTime() + TimeUnit.SECONDS.toMillis(rate); long now = System.currentTimeMillis(); LOG.debug("Layer:", layer.getId(), "next scheduled update is:", nextUpdate, "now is", now); if (nextUpdate <= now) { return true; } LOG.debug("Skipping layerId:", layer.getId(), "as recently updated"); return false; }
Source:
public DataUriSchemeParser(String url) { this.url = url; }

Target:
public DataUriSchemeParser(String url) { this.url = Preconditions.checkNotNull(url, "url"); }
Source:
public Class<? extends StreamOperator> getStreamOperatorClass(ClassLoader classLoader) { return AbstractStreamingCommitterOperator.class; }

Target:
public Class<? extends StreamOperator> getStreamOperatorClass(ClassLoader classLoader) { return StreamingCommitterOperator.class; }
Source:
public void deleteAlias(String alias) { mapLock.lock(); try { List<String> jobs = alias2jobs.get(alias); alias2jobs.remove(alias); if ((jobs != null) && !jobs.isEmpty()) { for (String job : jobs) { String aliasVal = job2alias.get(job); if (Objects.equals(aliasVal, alias)) { job2alias.remove(job); } } } } finally { mapLock.unlock(); } spawnDataStore.deleteChild(ALIAS_PATH, alias); ac.deleteAlias(alias); }

Target:
public void deleteAlias(String alias) throws Exception { spawnDataStore.deleteChild(ALIAS_PATH, alias); if( !Strings.isNullOrEmpty(spawnDataStore.getChild(ALIAS_PATH, alias))) { log.error("Fail to delete alias from spawn datastore", alias); return; } mapLock.lock(); try { List<String> jobs = alias2jobs.get(alias); alias2jobs.remove(alias); if ((jobs != null) && !jobs.isEmpty()) { for (String job : jobs) { String aliasVal = job2alias.get(job); if (Objects.equals(aliasVal, alias)) { job2alias.remove(job); } } } } finally { mapLock.unlock(); } ac.deleteAlias(alias); }
Source:
protected void doExecute() throws Exception { if (defaultOutputDirSet) { outputDirectory = new File(project.getBuild().getDirectory(), "liberty-alt-output-dir"); } if (skip || skipLibertyPackage) { return; } if (isInstall) { installServerAssembly(); } else { log.info(MessageFormat.format(messages.getString("info.install.type.preexisting"), "")); checkServerHomeExists(); checkServerDirectoryExists(); } log.info(MessageFormat.format(messages.getString("info.server.package"), serverName)); ServerTask serverTask = initializeJava(); copyConfigFiles(); serverTask.setOperation("package"); validateIncludeAndPackageType(); setPackageFilePath(); serverTask.setArchive(packageFile); serverTask.setInclude(include); serverTask.setOs(os); serverTask.setServerRoot(serverRoot); log.info(MessageFormat.format(messages.getString("info.server.package.file.location"), packageFile.getCanonicalPath())); serverTask.execute(); if ("liberty-assembly".equals(project.getPackaging())) { project.getArtifact().setFile(packageFile); } else if (attach) { if (packageFileType.getValue() != project.getPackaging()) { throw new MojoFailureException("packageType must match project packaging type."); } project.getArtifact().setFile(packageFile); } }

Target:
protected void doExecute() throws Exception { if (defaultOutputDirSet) { outputDirectory = new File(project.getBuild().getDirectory(), "liberty-alt-output-dir"); } if (skip || skipLibertyPackage) { return; } if (isInstall) { installServerAssembly(); } else { log.info(MessageFormat.format(messages.getString("info.install.type.preexisting"), "")); checkServerHomeExists(); checkServerDirectoryExists(); } log.info(MessageFormat.format(messages.getString("info.server.package"), serverName)); ServerTask serverTask = initializeJava(); copyConfigFiles(); serverTask.setOperation("package"); setPackageFilePath(); serverTask.setArchive(packageFile); serverTask.setInclude(include); serverTask.setOs(os); serverTask.setServerRoot(serverRoot); log.info(MessageFormat.format(messages.getString("info.server.package.file.location"), packageFile.getCanonicalPath())); serverTask.execute(); if ("liberty-assembly".equals(project.getPackaging())) { project.getArtifact().setFile(packageFile); } else if (attach) { if (packageFileType.getValue() != project.getPackaging()) { throw new MojoFailureException("packageType must match project packaging type."); } project.getArtifact().setFile(packageFile); } }
Source:
private void createCacheWithXMLConfiguration() { String cacheName = "CacheWithXMLConfiguration"; String xml = String.format("<infinispan>" + "<cache-container>" + "<distributed-cache name=\"%s\" mode=\"SYNC\">" + "<locking isolation=\"READ_COMMITTED\"/>" + "<transaction mode=\"NON_XA\"/>" + "<expiration lifespan=\"60000\" interval=\"20000\"/>" + "</distributed-cache>" + "</cache-container>" + "</infinispan>" , cacheName); manager.administration().getOrCreateCache(cacheName, new XMLStringConfiguration(xml)); System.out.println("Cache with configuration exists or is created"); }

Target:
private void createCacheWithXMLConfiguration() { String cacheName = "CacheWithXMLConfiguration"; String xml = String.format("<infinispan>" + "<cache-container>" + "<distributed-cache name=\"%s\" mode=\"SYNC\">" + "<locking isolation=\"READ_COMMITTED\"/>" + "<transaction mode=\"NON_XA\"/>" + "<expiration lifespan=\"60000\" interval=\"20000\"/>" + "</distributed-cache>" + "</cache-container>" + "</infinispan>" , cacheName); manager.administration().getOrCreateCache(cacheName, new XMLStringConfiguration(xml)); System.out.println("Cache with configuration exists or is created."); }
Source:
protected boolean validate() { StoragePoolValidator spValidator = new StoragePoolValidator(getStoragePool()); if (!validate(spValidator.isUp())) { return false; } if (getParameters().getImportAsTemplate()) { if (getParameters().getClusterId() == null) { addValidationMessage(EngineMessage.VDS_CLUSTER_IS_NOT_VALID); return false; } setClusterId(getParameters().getClusterId()); if (getCluster() == null) { addValidationMessage(EngineMessage.VDS_CLUSTER_IS_NOT_VALID); return false; } if (getCluster().getArchitecture() == ArchitectureType.undefined) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CLUSTER_UNDEFINED_ARCHITECTURE); } setStoragePoolId(getParameters().getStoragePoolId()); } DiskImage diskImage = null; try { diskImage = getDiskImage(); } catch (OpenStackImageException e) { log.error("Unable to get the disk image from the provider proxy: ({}) {}", e.getErrorType(), e.getMessage()); switch (e.getErrorType()) { case UNSUPPORTED_CONTAINER_FORMAT: case UNSUPPORTED_DISK_FORMAT: return failValidation(EngineMessage.ACTION_TYPE_FAILED_IMAGE_NOT_SUPPORTED); case UNABLE_TO_DOWNLOAD_IMAGE: return failValidation(EngineMessage.ACTION_TYPE_FAILED_IMAGE_DOWNLOAD_ERROR); case UNRECOGNIZED_IMAGE_FORMAT: return failValidation(EngineMessage.ACTION_TYPE_FAILED_IMAGE_UNRECOGNIZED); } } if (diskImage == null) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_DISK_NOT_EXIST); } if (!validate(createDiskImagesValidator(diskImage).isQcowVersionSupportedForDcVersion(getStoragePool().getStoragePoolFormatType()))) { return false; } return validateSpaceRequirements(diskImage); }

Target:
protected boolean validate() { if (!validate(new StoragePoolValidator(getStoragePool()).isUp())) { return false; } if (getParameters().getImportAsTemplate()) { if (getParameters().getClusterId() == null) { addValidationMessage(EngineMessage.VDS_CLUSTER_IS_NOT_VALID); return false; } setClusterId(getParameters().getClusterId()); if (getCluster() == null) { addValidationMessage(EngineMessage.VDS_CLUSTER_IS_NOT_VALID); return false; } if (getCluster().getArchitecture() == ArchitectureType.undefined) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CLUSTER_UNDEFINED_ARCHITECTURE); } setStoragePoolId(getParameters().getStoragePoolId()); } DiskImage diskImage = null; try { diskImage = getDiskImage(); } catch (OpenStackImageException e) { log.error("Unable to get the disk image from the provider proxy: ({}) {}", e.getErrorType(), e.getMessage()); switch (e.getErrorType()) { case UNSUPPORTED_CONTAINER_FORMAT: case UNSUPPORTED_DISK_FORMAT: return failValidation(EngineMessage.ACTION_TYPE_FAILED_IMAGE_NOT_SUPPORTED); case UNABLE_TO_DOWNLOAD_IMAGE: return failValidation(EngineMessage.ACTION_TYPE_FAILED_IMAGE_DOWNLOAD_ERROR); case UNRECOGNIZED_IMAGE_FORMAT: return failValidation(EngineMessage.ACTION_TYPE_FAILED_IMAGE_UNRECOGNIZED); } } if (diskImage == null) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_DISK_NOT_EXIST); } if (!validate(createDiskImagesValidator(diskImage).isQcowVersionSupportedForDcVersion(getStoragePool().getStoragePoolFormatType()))) { return false; } return validateSpaceRequirements(diskImage); }
Source:
protected void startUpdateCheck() { try { updateTask = UpdateTask.getNewInstance(); updateTask.startPinnedNotification(this); updateTask.registerTaskListener(this); } catch (IllegalStateException e) { enterErrorState("There is already an existing update task instance."); return; } catch (TaskListenerRegistrationException e) { enterErrorState("Attempting to register a TaskListener to an " + "already registered task."); return; } String ref = ResourceInstallUtils.getDefaultProfileRef(); updateTask.execute(ref); uiState.downloadingUiState(); }

Target:
protected void startUpdateCheck() { try { updateTask = UpdateTask.getNewInstance(); updateTask.startPinnedNotification(this); updateTask.registerTaskListener(this); } catch (IllegalStateException e) { connectToRunningTask(); return; } catch (TaskListenerRegistrationException e) { enterErrorState("Attempting to register a TaskListener to an " + "already registered task."); return; } String ref = ResourceInstallUtils.getDefaultProfileRef(); updateTask.execute(ref); uiState.downloadingUiState(); }
Source:
public List<String> normalize(String... strings) { final Map<String, Pair<String, String>> stringParts = new HashMap<>(strings.length); Arrays.stream(strings) .filter(Objects::nonNull) .forEach(str -> stringParts.put(str, decompose(str))); final int maxNumericSuffixLength = stringParts.values() .stream() .filter(Objects::nonNull) .collect(Collectors.summarizingInt(pair -> pair.getSecond().length())) .getMax(); return Arrays.stream(strings) .map(str -> compose(str, stringParts, maxNumericSuffixLength)) .collect(Collectors.toList()); }

Target:
public List<String> normalize(String... strings) { List<TextWithNumericSuffix> inputAsTextWithNumericSuffix = Arrays.stream(strings) .map(this::decompose) .collect(Collectors.toList()); return inputAsTextWithNumericSuffix.stream() .map(e -> compose(e, countMaximumSuffixLength(inputAsTextWithNumericSuffix))) .collect(Collectors.toList()); }
Source:
private void processSimpleType(final XmlSchemaElement xmlSchemaElement) { final QName baseTypeName = xmlSchemaElement.getSchemaType() != null ? getBaseTypeQName((XmlSchemaSimpleType) xmlSchemaElement.getSchemaType()) : getBaseTypeQName(xmlSchemaElement.getSchemaTypeName()); if (baseTypeName != null) { mapSchemaElement(xmlSchemaElement, baseTypeName); } else { LOGGER.debug("Could not find the base type for simple type: {}", xmlSchemaElement.getQName()); } }

Target:
private void processSimpleType(final XmlSchemaElement xmlSchemaElement) { final QName baseTypeName = getBaseTypeQName((XmlSchemaSimpleType) xmlSchemaElement.getSchemaType()); if (baseTypeName != null) { mapSchemaElement(xmlSchemaElement, baseTypeName); } else { LOGGER.debug("Could not find the base type for simple type: {}", xmlSchemaElement.getQName()); } }
Source:
protected void checkContainmentConflict(Comparison comparison, ReferenceChange diff, ReferenceChange candidate) { if (candidate.getReference().isContainment()) { ConflictKind kind = ConflictKind.REAL; final boolean diffIsDelete = isDeleteOrUnsetDiff(diff); final boolean candidateIsDelete = isDeleteOrUnsetDiff(candidate); if (diffIsDelete && candidateIsDelete) { kind = ConflictKind.PSEUDO; } else if (diff.getMatch() == candidate.getMatch() && diff.getReference() == candidate.getReference()) { if (!diffIsDelete && !candidateIsDelete && matchingIndices(comparison, diff.getMatch(), diff.getReference(), diff.getValue(), candidate.getValue())) { kind = ConflictKind.PSEUDO; } } conflictOn(comparison, diff, candidate, kind); } else if (diff.getKind() == DifferenceKind.DELETE) { if (candidate.getKind() == DifferenceKind.DELETE) { } else if (isDiffOfPseudoDeleteConflict(candidate)) { } else { conflictOn(comparison, diff, candidate, ConflictKind.REAL); } } }

Target:
protected void checkContainmentConflict(Comparison comparison, ReferenceChange diff, ReferenceChange candidate) { final boolean candidateIsDelete = isDeleteOrUnsetDiff(candidate); if (candidate.getReference().isContainment()) { ConflictKind kind = ConflictKind.REAL; final boolean diffIsDelete = isDeleteOrUnsetDiff(diff); if (diffIsDelete && candidateIsDelete) { kind = ConflictKind.PSEUDO; } else if (diff.getMatch() == candidate.getMatch() && diff.getReference() == candidate.getReference()) { if (!diffIsDelete && !candidateIsDelete && matchingIndices(comparison, diff.getMatch(), diff.getReference(), diff.getValue(), candidate.getValue())) { kind = ConflictKind.PSEUDO; } } conflictOn(comparison, diff, candidate, kind); } else if (diff.getKind() == DifferenceKind.DELETE) { if (candidateIsDelete) { } else { conflictOn(comparison, diff, candidate, ConflictKind.REAL); } } }
Source:
public Integer getPage(String data) { int beginIndex = data.indexOf("via"); beginIndex = data.indexOf("patient", beginIndex) + 8; int endIndex = data.indexOf('/', beginIndex); return Integer.parseInt(data.substring(beginIndex, endIndex - 2 )); }

Target:
public Integer getPage(String data) { int beginIndex = data.indexOf("via"); beginIndex = data.indexOf("patient", beginIndex) + "patient/".length(); int endIndex = data.indexOf('/', beginIndex) - "\" ".length(); return Integer.parseInt(data.substring(beginIndex, endIndex)); }
Source:
public void testSetClassNameProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.setClassNameProperty(JavaBeanDescriptor.class.getName()); }); JavaBeanDescriptor descriptor1 = new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_CLASS); String oldValue1 = descriptor1.setClassNameProperty(JavaBeanDescriptor.class.getName()); Assertions.assertNull(oldValue1); String oldValue2 = descriptor1.setClassNameProperty(JavaBeanDescriptor.class.getName()); Assertions.assertEquals(oldValue2, descriptor1.getClassNameProperty()); }

Target:
public void testSetClassNameProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.setClassNameProperty(JavaBeanDescriptor.class.getName()); }); JavaBeanDescriptor descriptor = new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_CLASS); String oldValue1 = descriptor.setClassNameProperty(JavaBeanDescriptor.class.getName()); Assertions.assertNull(oldValue1); String oldValue2 = descriptor.setClassNameProperty(JavaBeanDescriptor.class.getName()); Assertions.assertEquals(oldValue2, descriptor.getClassNameProperty()); }
Source:
protected void onMethodInvocationFound(MethodInvocationTree mit) { MethodTree method = findEnclosingMethod(mit); if (method != null) { Arguments args = mit.arguments(); if (SET_SSL_ON_CONNECT.matches(mit) && LiteralUtils.isTrue(args.get(0))) { MethodBodyApacheVisitor apacheVisitor = new MethodBodyApacheVisitor(); method.accept(apacheVisitor); if (!apacheVisitor.isSecured) { reportIssue(mit, "Enable server identity validation on this SMTP SSL connection."); } } else if (HASHTABLE_PUT.matches(mit) && parametersSocketFactoryMatch(args.get(0), args.get(1))) { MethodBodyHashtableVisitor hashVisitor = new MethodBodyHashtableVisitor(); method.accept(hashVisitor); if (!hashVisitor.isSecured) { reportIssue(mit, "Enable server identity validation, set \"mail.smtp.ssl.checkserveridentity\" to true"); } } } super.onMethodInvocationFound(mit); }

Target:
protected void onMethodInvocationFound(MethodInvocationTree mit) { MethodTree method = findEnclosingMethod(mit); if (method != null) { Arguments args = mit.arguments(); if (SET_SSL_ON_CONNECT.matches(mit) && LiteralUtils.isTrue(args.get(0))) { MethodBodyApacheVisitor apacheVisitor = new MethodBodyApacheVisitor(); method.accept(apacheVisitor); if (!apacheVisitor.isSecured) { reportIssue(mit, "Enable server identity validation on this SMTP SSL connection."); } } else if (HASHTABLE_PUT.matches(mit) && "mail.smtp.socketFactory.class".equals(ConstantUtils.resolveAsStringConstant(args.get(0))) && "javax.net.ssl.SSLSocketFactory".equals(ConstantUtils.resolveAsStringConstant(args.get(1)))) { MethodBodyHashtableVisitor hashVisitor = new MethodBodyHashtableVisitor(); method.accept(hashVisitor); if (!hashVisitor.isSecured) { reportIssue(mit, "Enable server identity validation, set \"mail.smtp.ssl.checkserveridentity\" to true"); } } } super.onMethodInvocationFound(mit); }
Source:
public CassandraHttpSession getSession(String id) { Select select = QueryBuilder.select("id", "creation_time", "last_accessed", "max_inactive_interval_in_seconds", "attributes") .from(this.tableName); select.where(QueryBuilder.eq("id", UUID.fromString(id))); select.setConsistencyLevel(this.consistencyLevel); Row row = this.cassandraOperations.getSession().execute(select).one(); if (row == null) { return null; } long creationTime = row.getLong(1); long lastAccessed = row.getLong(2); int maxInactiveIntervalInSeconds = row.getInt(3); Map<String, String> attributes = row.getMap(4, String.class, String.class); CassandraHttpSession result = new CassandraHttpSession(id); result.setCreationTime(creationTime); result.setLastAccessedTime(lastAccessed); result.setMaxInactiveIntervalInSeconds(maxInactiveIntervalInSeconds); this.sessionAttributeDeserializer.inflateSession(attributes, result); result.onSave(); return result; }

Target:
public CassandraHttpSession getSession(String id) { Select select = QueryBuilder.select("id", "creation_time", "last_accessed", "max_inactive_interval_in_seconds", "attributes") .from(this.tableName); select.where(QueryBuilder.eq("id", UUID.fromString(id))); select.setConsistencyLevel(this.consistencyLevel); Row row = this.cassandraOperations.getSession().execute(select).one(); if (row == null) { return null; } long creationTime = row.getLong("creation_time"); long lastAccessed = row.getLong("last_accessed"); int maxInactiveIntervalInSeconds = row.getInt("max_inactive_interval_in_seconds"); Map<String, String> attributes = row.getMap("attributes", String.class, String.class); CassandraHttpSession result = new CassandraHttpSession(id); result.setCreationTime(creationTime); result.setLastAccessedTime(lastAccessed); result.setMaxInactiveIntervalInSeconds(maxInactiveIntervalInSeconds); this.sessionAttributeDeserializer.inflateSession(attributes, result); result.onSave(); return result; }
Source:
private void deleteRecords(List<String> recordIds) throws SQLException { Integer deletedRecordsCount = 0; try (Connection connection = getConnection(); PreparedStatement deleteStatement = connection.prepareStatement(DELETE_STATEMENT)) { deleteStatement.setArray(1, connection.createArrayOf("varchar", recordIds.toArray())); deletedRecordsCount = deleteStatement.executeUpdate(); } LOGGER.info("Cleaned records from database", deletedRecordsCount); }

Target:
private int deleteRecords(List<String> recordIds) throws SQLException { int deletedRecordsCount = 0; try (Connection connection = getConnection(); PreparedStatement deleteStatement = connection.prepareStatement(DELETE_STATEMENT)) { deleteStatement.setArray(DELETE_STATEMENT_LIST_PARAM_INDEX, connection.createArrayOf("varchar", recordIds.toArray())); deletedRecordsCount = deleteStatement.executeUpdate(); } return deletedRecordsCount; }
Source:
public Optional<PageReader> readColumnInBlock(int blockIndex, ColumnDescriptor columnDescriptor) throws IOException { BlockMetaData block = blocks.get(blockIndex); if (block.getRowCount() == 0) { throw new RuntimeException("Illegal row group of 0 rows"); } Optional<ColumnChunkMetaData> mc = findColumnByPath(block, columnDescriptor.getPath()); if (mc.isPresent()) { ColumnChunkMetaData column = mc.get(); ChunkDescriptor chunk = new ChunkDescriptor(columnDescriptor, column, column.getStartingPos(), (int) column.getTotalSize()); return Optional.of(readChunk(f, chunk)); } return Optional.empty(); }

Target:
Optional<PageReader> readColumnInBlock(int blockIndex, ColumnDescriptor columnDescriptor) { BlockMetaData block = blocks.get(blockIndex); if (block.getRowCount() == 0) { throw new RuntimeException("Illegal row group of 0 rows"); } Optional<ColumnChunkMetaData> mc = findColumnByPath(block, columnDescriptor.getPath()); return mc.map(column -> new ChunkDescriptor(columnDescriptor, column, column.getStartingPos(), (int) column.getTotalSize())) .map(chunk -> readChunk(f, chunk)); }
Source:
public CollectionSet build(CollectionAgent agent, Object message, Long timestamp) throws ScriptException { final CollectionSetBuilder builder = new CollectionSetBuilder(agent); if (timestamp != null) { builder.withTimestamp(new Date(timestamp)); } final SimpleBindings globals = new SimpleBindings(); globals.put("agent", agent); globals.put("builder", builder); globals.put("msg", message); compiledScript.eval(globals); return builder.build(); }

Target:
public CollectionSet build(CollectionAgent agent, Object message, Long timestamp) throws ScriptException { final CollectionSetBuilder builder = new CollectionSetBuilder(agent); if (timestamp != null && timestamp > 0) { builder.withTimestamp(new Date(timestamp)); } final SimpleBindings globals = new SimpleBindings(); globals.put("agent", agent); globals.put("builder", builder); globals.put("msg", message); compiledScript.eval(globals); return builder.build(); }