auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected boolean validate() { if (!validateExternalVnicProfileMapping()) { return false; } initVmTemplate(); if (!super.validate()) { return false; } ArrayList<DiskImage> disks = new ArrayList(getVmTemplate().getDiskTemplateMap().values()); setImagesWithStoragePoolId(getStorageDomain().getStoragePoolId(), disks); getVmTemplate().setImages(disks); if (getParameters().isImagesExistOnTargetStorageDomain() && !validateUnregisteredEntity(vmTemplateFromConfiguration, ovfEntityData)) { return false; } return true; }

Target:
protected boolean validate() { initVmTemplate(); if (!super.validate()) { return false; } if (!validateExternalVnicProfileMapping()) { return false; } ArrayList<DiskImage> disks = new ArrayList(getVmTemplate().getDiskTemplateMap().values()); setImagesWithStoragePoolId(getStorageDomain().getStoragePoolId(), disks); getVmTemplate().setImages(disks); if (getParameters().isImagesExistOnTargetStorageDomain() && !validateUnregisteredEntity(vmTemplateFromConfiguration, ovfEntityData)) { return false; } return true; }
Source:
public void activate(Map<String, Object> config) { final int port = config.containsKey(KEY_PORT) ? Integer.parseInt(config.get(KEY_PORT).toString()) : DEFAULT_PORT; injector = Guice.createInjector(new RuntimeServerModule(scriptServiceUtil, scriptEngine)); new Thread(() -> { listen(port); }, "Language Server").start(); }

Target:
public void activate(Map<String, Object> config) { int port = DEFAULT_PORT; try { port = config.containsKey(KEY_PORT) ? Integer.parseInt(config.get(KEY_PORT).toString()) : DEFAULT_PORT; } catch (NumberFormatException e) { logger.warn("Couldn't parse '{}', using default port '{}' for the Language Server instead", config.get(KEY_PORT), DEFAULT_PORT); } final int serverPort = port; injector = Guice.createInjector(new RuntimeServerModule(scriptServiceUtil, scriptEngine)); new Thread(() -> { listen(serverPort); }, "Language Server").start(); }
Source:
public void confirmDelete() { clickArticleDeleteConfirmationButton("MediaWiki:Wikia.css"); }

Target:
public void confirmDelete() { clickArticleDeleteConfirmationButton(URLsContent.mediaWikiCss); }
Source:
private Resource loadFromClassLoader(Class<?> clazz, String path, ResourceSet resourceSet) throws IOException { final URL fileURL = clazz.getResource(path); final URI uri = URI.createURI(fileURL.toString()); List<URI> urisToLoad = Collections.singletonList(uri); for (IResourceSetHook hook : getMatchingHooks(urisToLoad)) { hook.preLoadingHook(resourceSet, urisToLoad); } final Resource existing = resourceSet.getResource(uri, false); if (existing != null) { return existing; } InputStream stream = null; Resource resource = null; try { resource = resourceSet.createResource(uri); stream = fileURL.openStream(); resource.load(stream, Collections.emptyMap()); } catch (IOException e) { } catch (WrappedException e) { } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { } } } for (IResourceSetHook hook : getMatchingHooks(urisToLoad)) { hook.postLoadingHook(resourceSet, urisToLoad); } return resource; }

Target:
private Resource loadFromClassLoader(Class<?> clazz, String path, ResourceSet resourceSet) throws IOException { final URL fileURL = clazz.getResource(path); final URI uri = URI.createURI(fileURL.toString()); final List<URI> urisToLoad = Collections.singletonList(uri); for (final IResourceSetHook hook : getMatchingHooks(urisToLoad)) { hook.preLoadingHook(resourceSet, urisToLoad); } final Resource existing = resourceSet.getResource(uri, false); if (existing != null) { return existing; } InputStream stream = null; Resource resource = null; try { resource = resourceSet.createResource(uri); stream = fileURL.openStream(); resource.load(stream, Collections.emptyMap()); } catch (final IOException e) { } catch (final WrappedException e) { } finally { if (stream != null) { try { stream.close(); } catch (final IOException e) { } } } for (final IResourceSetHook hook : getMatchingHooks(urisToLoad)) { hook.postLoadingHook(resourceSet, urisToLoad); } return resource; }
Source:
protected AsyncCompletionWaitor insertBreakpoint( final IBreakpointsTargetDMContext context, final Map<String, Object> attributes) throws InterruptedException { final AsyncCompletionWaitor waitor = new AsyncCompletionWaitor(); final DataRequestMonitor<IBreakpointDMContext> drm = new DataRequestMonitor<IBreakpointDMContext>(fBreakpointService.getExecutor(), null) { @Override protected void handleCompleted() { if (isSuccess()) { waitor.setReturnInfo(getData()); } waitor.waitFinished(getStatus()); } }; fBreakpointService.getExecutor().submit(new Runnable() { @Override public void run() { fBreakpointService.insertBreakpoint(context, attributes, drm); } }); waitor.waitUntilDone(TestsPlugin.massageTimeout(2000)); return waitor; }

Target:
protected IBreakpointDMContext insertBreakpoint( final IBreakpointsTargetDMContext context, final Map<String, Object> attributes) throws InterruptedException, ExecutionException { Query<IBreakpointDMContext> query = new Query<IBreakpoints.IBreakpointDMContext>() { @Override protected void execute(DataRequestMonitor<IBreakpointDMContext> rm) { fBreakpointService.insertBreakpoint(context, attributes, rm); } }; fBreakpointService.getExecutor().submit(query); return query.get(); }
Source:
public void testPublishWithBadTypeValue() { Response response = resource.publish(key, null, null, null, "Test", null, null); assertEquals(response.getStatusInfo(), Response.Status.BAD_REQUEST); }

Target:
public void testPublishWithBadTypeValue() { Response response = resource.publish(key, "Test", null, null, "Test", null, null); assertEquals(response.getStatusInfo(), Response.Status.BAD_REQUEST); }
Source:
public T createInstance() { if (!isGenericRecord(type)) { return InstantiationUtil.instantiate(type); } else { return (T) new GenericData.Record(schema.getAvroSchema()); } }

Target:
public T createInstance() { checkAvroInitialized(); return (T) avroData.newRecord(null, runtimeSchema); }
Source:
public boolean visit(QualifiedName node) { node.getParent(); IBinding b= node.resolveBinding(); if (b instanceof IVariableBinding) { int modifiers= ((IVariableBinding)b).getModifiers(); if ((modifiers & IModifierConstants.ACC_FINAL) == IModifierConstants.ACC_FINAL) { if (((IVariableBinding) b).isField()) { throw new AbortSearchException(); } } } return true; }

Target:
public boolean visit(QualifiedName node) { node.getParent(); IBinding binding= node.resolveBinding(); checkForUninitializedFinalReference(binding); return true; }
Source:
public Iterator<SequencingParameters> iterator() { try { return getSequencingParameters().iterator(); } catch (IOException e) { return Collections.emptyIterator(); } }

Target:
public Iterator<SequencingParameters> iterator() { try { return getSequencingParameters().iterator(); } catch (IOException e) { log.error("Failed to get sequencing parameters", e); return Collections.emptyIterator(); } }
Source:
public void createApplicationContextFrom_validBuilderContext_containingExtraComponent_shouldCreateAnApplicationContext() { String name = "workers"; ExecutorService workers = Executors.newFixedThreadPool(2); Map<Platform.ExtraComponentKey, Object> extraComponents = Maps.newHashMap(); extraComponents.put(new Platform.ExtraComponentKey(name, ExecutorService.class), workers); KasperPlatformConfiguration platformConfiguration = new KasperPlatformConfiguration(); final Platform.BuilderContext builderContext = new Platform.BuilderContext( platformConfiguration.configuration(), platformConfiguration.eventBus(), platformConfiguration.commandGateway(), platformConfiguration.queryGateway(), platformConfiguration.metricRegistry(), extraComponents ); ApplicationContext applicationContext = BuilderContextHelper.createApplicationContextFrom(builderContext); assertNotNull(applicationContext); assertEquals(workers, applicationContext.getBean(ExecutorService.class)); assertEquals(workers, applicationContext.getBean(name)); }

Target:
public void createApplicationContextFrom_validBuilderContext_containingExtraComponent_shouldCreateAnApplicationContext() { final String name = "workers"; final ExecutorService workers = Executors.newFixedThreadPool(2); final Map<Platform.ExtraComponentKey, Object> extraComponents = Maps.newHashMap(); extraComponents.put(new Platform.ExtraComponentKey(name, ExecutorService.class), workers); final KasperPlatformConfiguration platformConfiguration = new KasperPlatformConfiguration(); final Platform.BuilderContext builderContext = new Platform.BuilderContext( platformConfiguration.configuration(), platformConfiguration.eventBus(), platformConfiguration.commandGateway(), platformConfiguration.queryGateway(), platformConfiguration.metricRegistry(), extraComponents ); final ApplicationContext applicationContext = BuilderContextHelper.createApplicationContextFrom(builderContext); assertNotNull(applicationContext); assertEquals(workers, applicationContext.getBean(ExecutorService.class)); assertEquals(workers, applicationContext.getBean(name)); }
Source:
public Void visit(UnlockEvent unlockEvent) { for (LockDescriptor descriptor : unlockEvent.lockDescriptors()) { OptionalLong lastLocked = lockWatchState.getOrDefault(descriptor, LockWatchInfo.NOT_WATCHED).lastLocked(); lockWatchState.put(descriptor, LockWatchInfo.of(LockWatchInfo.State.UNLOCKED, lastLocked)); } return null; }

Target:
public Void visit(UnlockEvent unlockEvent) { for (LockDescriptor descriptor : unlockEvent.lockDescriptors()) { OptionalLong lastLocked = lockWatchState.getOrDefault(descriptor, LockWatchInfo.UNKNOWN).lastLocked(); lockWatchState.put(descriptor, LockWatchInfo.of(LockWatchInfo.State.UNLOCKED, lastLocked)); } return null; }
Source:
public static void insertPageProlog(StringBuilder buffer, int position) { StringBuilder pageProlog= new StringBuilder(60); pageProlog.append("<html>"); buffer.append("<head>"); appendStyleSheetWithBodyColorRules(pageProlog, FG_COLOR_RGB, BG_COLOR_RGB); buffer.append("</head>"); buffer.insert(position, pageProlog.toString()); }

Target:
public static void insertPageProlog(StringBuilder buffer, int position) { StringBuilder pageProlog= new StringBuilder(60); pageProlog.append("<html>"); pageProlog.append("<head>"); appendStyleSheetWithBodyColorRules(pageProlog, FG_COLOR_RGB, BG_COLOR_RGB); pageProlog.append("</head>"); buffer.insert(position, pageProlog.toString()); }
Source:
public void startIdentifiedAtlasDbTransactionGivesUsTimestampsInSequence() { UUID requestorUuid = UUID.randomUUID(); StartIdentifiedAtlasDbTransactionResponse firstResponse = startIdentifiedAtlasDbTransaction(requestorUuid); StartIdentifiedAtlasDbTransactionResponse secondResponse = startIdentifiedAtlasDbTransaction(requestorUuid); List<Long> temporalSequence = ImmutableList.of( firstResponse.immutableTimestamp().getImmutableTimestamp(), firstResponse.startTimestampAndPartition().timestamp(), secondResponse.startTimestampAndPartition().timestamp()); assertThat(temporalSequence).isSorted(); }

Target:
public void startIdentifiedAtlasDbTransactionGivesUsTimestampsInSequence() { UUID requestorUuid = UUID.randomUUID(); StartIdentifiedAtlasDbTransactionResponse firstResponse = startIdentifiedAtlasDbTransaction(requestorUuid); StartIdentifiedAtlasDbTransactionResponse secondResponse = startIdentifiedAtlasDbTransaction(requestorUuid); assertThat(ImmutableList.of( firstResponse.immutableTimestamp().getImmutableTimestamp(), firstResponse.startTimestampAndPartition().timestamp(), secondResponse.startTimestampAndPartition().timestamp())).isSorted(); assertThat(ImmutableList.of( firstResponse.immutableTimestamp().getImmutableTimestamp(), secondResponse.immutableTimestamp().getImmutableTimestamp(), secondResponse.startTimestampAndPartition().timestamp())).isSorted(); }
Source:
private void interpolate(long lo, long hi, Record mapRecord, long x1, long x2, MapValue x1Value, MapValue x2value) { computeYPoints(x1Value, x2value); for (long x = lo; x < hi; x = sampler.nextTimestamp(x)) { final MapValue result = findDataMapValue3(mapRecord, x); assert result != null && result.getByte(0) == 1; for (int i = 0; i < groupByTwoPointFunctionCount; i++) { GroupByFunction function = groupByTwoPointFunctions.getQuick(i); InterpolationUtil.INTERPOLATE_GAP.interpolateGapAndStore(function, result, sampler.getBucketSize(), x1Value, x2value); } for (int i = 0; i < groupByScalarFunctionCount; i++) { GroupByFunction function = groupByScalarFunctions.getQuick(i); interpolatorFunctions.getQuick(i).interpolateAndStore(function, result, x, x1, x2, yData + i * 16, yData + i * 16 + 8); } result.putByte(0, (byte) 0); } }

Target:
private void interpolate(long lo, long hi, Record mapRecord, long x1, long x2, MapValue x1Value, MapValue x2value) { computeYPoints(x1Value, x2value); for (long x = lo; x < hi; x = sampler.nextTimestamp(x)) { final MapValue result = findDataMapValue3(mapRecord, x); assert result != null && result.getByte(0) == 1; for (int i = 0; i < groupByTwoPointFunctionCount; i++) { GroupByFunction function = groupByTwoPointFunctions.getQuick(i); InterpolationUtil.interpolateGap(function, result, sampler.getBucketSize(), x1Value, x2value); } for (int i = 0; i < groupByScalarFunctionCount; i++) { GroupByFunction function = groupByScalarFunctions.getQuick(i); interpolatorFunctions.getQuick(i).interpolateAndStore(function, result, x, x1, x2, yData + i * 16, yData + i * 16 + 8); } result.putByte(0, (byte) 0); } }
Source:
protected OrderedSequenceNumber<Long> createSequenceNumber(Long sequenceNumber) { return null; }

Target:
protected OrderedSequenceNumber<Long> createSequenceNumber(Long sequenceNumber) { throw new UnsupportedOperationException(); }
Source:
public List<GitUser> getCommiters() throws GitException { List<GitUser> gitUsers = new ArrayList<GitUser>(); try { LogCommand logCommand = getGit().log(); for (RevCommit commit : logCommand.call()) { PersonIdent committerIdentity = commit.getCommitterIdent(); GitUser gitUser = newDto(GitUser.class).withName(committerIdentity.getName()) .withEmail(committerIdentity.getEmailAddress()); if (!gitUsers.contains(gitUser)) { gitUsers.add(gitUser); } } } catch (GitAPIException exception) { throw new GitException(exception.getMessage(), exception); } return gitUsers; }

Target:
public List<GitUser> getCommiters() throws GitException { List<GitUser> gitUsers = new ArrayList<>(); try { LogCommand logCommand = getGit().log(); for (RevCommit commit : logCommand.call()) { PersonIdent committerIdentity = commit.getCommitterIdent(); GitUser gitUser = newDto(GitUser.class).withName(committerIdentity.getName()) .withEmail(committerIdentity.getEmailAddress()); if (!gitUsers.contains(gitUser)) { gitUsers.add(gitUser); } } } catch (GitAPIException exception) { throw new GitException(exception.getMessage(), exception); } return gitUsers; }
Source:
public static Polygon parsePoints(String pointsStr, double growFactor) { String[] arr = pointsStr.split(","); double[] lats = new double[arr.length /2]; double[] lons = new double[arr.length /2]; for (int j = 0; j < arr.length; j++) { if (j % 2 == 0) { lats[j / 2] = Double.parseDouble(arr[j]); } else { lons[(j - 1) / 2] = Double.parseDouble(arr[j]); } } return new Polygon(lats, lons, growFactor); }

Target:
public static Polygon parsePoints(String pointsStr, double growFactor) { String[] arr = pointsStr.split(","); if (arr.length % 2 == 1) throw new IllegalArgumentException("incorrect polygon specified"); double[] lats = new double[arr.length /2]; double[] lons = new double[arr.length /2]; for (int j = 0; j < arr.length; j++) { if (j % 2 == 0) { lats[j / 2] = Double.parseDouble(arr[j]); } else { lons[(j - 1) / 2] = Double.parseDouble(arr[j]); } } return new Polygon(lats, lons, growFactor); }
Source:
protected boolean isPasswordValid(String password) { String regularExpression = this.realmConfiguration.getUserStoreProperty (LDAPServerManagerConstants.SERVICE_PASSWORD_REGEX_PROPERTY); if (regularExpression == null) { regularExpression = LDAPServerManagerConstants.DEFAULT_BE_PASSWORD_REGULAR_EXPRESSION; } log.info("Using service password format - " + regularExpression); return password != null && password.length() >= 1 && isFormatCorrect(regularExpression, password); }

Target:
protected boolean isPasswordValid(String password) { String regularExpression = this.realmConfiguration.getUserStoreProperty (LDAPServerManagerConstants.SERVICE_PASSWORD_REGEX_PROPERTY); if (regularExpression == null) { regularExpression = LDAPServerManagerConstants.DEFAULT_BE_PASSWORD_REGULAR_EXPRESSION; } log.info("Using service password format - " + regularExpression); return StringUtils.isNotEmpty(password) && isFormatCorrect(regularExpression, password); }
Source:
private String createRererencedCompositeDebugMsg(ReferencedComposite refComposite){ StringBuilder sb = new StringBuilder(); if (refComposite == null){ sb.append(" no referenced composite specified"); } else { sb.append(" referenced composite '"+refComposite.getClass()+"'"); } return sb.toString(); }

Target:
private String createRererencedCompositeDebugMsg(ReferencedComposite refComposite){ StringBuilder sb = new StringBuilder(); if (refComposite == null){ sb.append(" with no referenced composite specified"); } else { sb.append(" with referenced composite "+refComposite.getClass()); } return sb.toString(); }
Source:
public List<BetaDiscreteWithEventOutput> getModel(final String id) { return this.models.get(id); }

Target:
public ImmutableList<BetaDiscreteWithEventOutput> getModel(final String id) { return ImmutableList.copyOf(this.models.get(id)); }
Source:
public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { "255.255.255.255", 0xffffffffL }, { "1.1.1.1", 0x01010101 }, { "1.255.4.255", 0x01ff04ff }, { "0.128.0.7", 0x00800007 }, { "1.2.3.4", 0x01020304 }, { "127.63.31.7", 0x7f3f1f07 }, { "0.0.0.1", 0x00000001 }, { "1.1.1.1", 0x01010101 }, }); }

Target:
public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { "255.255.255.255", 0xffffffffL }, { "1.1.1.1", 0x01010101 }, { "1.255.4.255", 0x01ff04ff }, { "0.128.0.7", 0x00800007 }, { "1.2.3.4", 0x01020304 }, { "0.0.0.1", 0x00000001 }, { "1.1.1.1", 0x01010101 }, }); }
Source:
public boolean contains(T value) { PairNodes<T> pair = search(value); if (pair.R == null || pair.R.value != value) { return false; } return true; }

Target:
public boolean contains(T value) { Node<T> current = head.next.getReference(); while(current != null && !current.value.equals(value)) { current = current.next.getReference(); } return current != null && !current.next.isMarked() && current.value.compareTo(value) == 0; }
Source:
public static List<HaxeNamedComponent> getAllNamedSubComponentsFromClassType(HaxeClass haxeClass, HaxeComponentType... fromTypes) { List<HaxeNamedComponent> components = getNamedSubComponents(haxeClass); List<HaxeComponentType> types = Arrays.asList(fromTypes); HaxeComponentType type = HaxeComponentType.typeOf(haxeClass); if (types.contains(type)) { components.addAll(getNamedSubComponents(haxeClass)); } PsiClass[] supers = haxeClass.getSupers(); for (PsiClass superComponent : supers) { type = HaxeComponentType.typeOf(superComponent); if (types.contains(type)) { components.addAll(getNamedSubComponents((HaxeClass)superComponent)); } } return components; }

Target:
public static List<HaxeNamedComponent> getAllNamedSubComponentsFromClassType(HaxeClass haxeClass, HaxeComponentType... fromTypes) { List<HaxeNamedComponent> components = getNamedSubComponents(haxeClass); List<HaxeComponentType> types = Arrays.asList(fromTypes); components.addAll(Stream.of(haxeClass.getSupers()) .filter(superComponent -> types.contains(HaxeComponentType.typeOf(superComponent))) .map(superComponent -> getAllNamedSubComponentsFromClassType((HaxeClass)superComponent, fromTypes)) .flatMap(Collection::stream) .collect(Collectors.toList())); if (types.contains(HaxeComponentType.typeOf(haxeClass))) { components.addAll(getNamedSubComponents(haxeClass)); } return components; }
Source:
public void sum(Vector vector) { this.entryX += vector.entryX; this.entryY += vector.entryY; }

Target:
public void sum(Vector vector) { this.entryX += vector.getX(); this.entryY += vector.getY(); }
Source:
public OAuth2ResourceServerConfigurer<B> resourceServer() throws Exception { if (this.resourceServerConfigurer == null) { this.initResourceServerConfigurer(); } return this.resourceServerConfigurer; }

Target:
public OAuth2ResourceServerConfigurer<B> resourceServer() { if (this.resourceServerConfigurer == null) { this.initResourceServerConfigurer(); } return this.resourceServerConfigurer; }
Source:
public HeaderBearerTokenResolver(String header) { Assert.notNull(header, "header cannot be null"); Assert.hasText(header, "header cannot be empty"); this.header = header; }

Target:
public HeaderBearerTokenResolver(String header) { Assert.hasText(header, "header cannot be empty"); this.header = header; }
Source:
public static String getGDBVersion(final ILaunchConfiguration configuration) throws CoreException { String cmd = getGDBPath(configuration).toOSString(); String[] args = new String[] { cmd, "--version" }; Process process = null; Job timeoutJob = null; try { process = ProcessFactory.getFactory().exec(args, getLaunchEnvironment(configuration)); final Process finalProc = process; timeoutJob = new Job("GDB version timeout job") { { setSystem(true); } @Override protected IStatus run(IProgressMonitor arg) { finalProc.destroy(); return Status.OK_STATUS; } }; timeoutJob.schedule(10000); String streamOutput = readStream(process.getInputStream()); String gdbVersion = getGDBVersionFromText(streamOutput); if (gdbVersion == null || gdbVersion.isEmpty()) { Exception detailedException = null; if (!streamOutput.isEmpty()) { detailedException = new Exception("Unexpected output format: \n\n" + streamOutput); } else { streamOutput = readStream(process.getErrorStream()); if (!streamOutput.isEmpty()) { detailedException = new Exception(streamOutput); } } throw new DebugException(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Could not determine GDB version using command: " + cmd, detailedException)); } return gdbVersion; } catch (IOException e) { throw new DebugException(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Error with command: " + cmd, e)); } finally { if (timeoutJob != null) { timeoutJob.cancel(); } if (process != null) { process.destroy(); } } }

Target:
public static String getGDBVersion(final ILaunchConfiguration configuration) throws CoreException { String cmd = getGDBPath(configuration).toOSString(); String[] args = new String[] { cmd, "--version" }; Process process = null; Job timeoutJob = null; try { process = ProcessFactory.getFactory().exec(args, getLaunchEnvironment(configuration)); final Process finalProc = process; timeoutJob = new Job("GDB version timeout job") { { setSystem(true); } @Override protected IStatus run(IProgressMonitor arg) { finalProc.destroy(); return Status.OK_STATUS; } }; timeoutJob.schedule(10000); String streamOutput = readStream(process.getInputStream()); String gdbVersion = getGDBVersionFromText(streamOutput); if (gdbVersion == null || gdbVersion.isEmpty()) { Exception detailedException = null; if (!streamOutput.isEmpty()) { detailedException = new Exception("Unexpected output format: \n\n" + streamOutput); } else { streamOutput = readStream(process.getErrorStream()); if (!streamOutput.isEmpty()) { detailedException = new Exception(streamOutput); } } throw new DebugException(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Could not determine GDB version using command: " + StringUtil.join(args, " "), detailedException)); } return gdbVersion; } catch (IOException e) { throw new DebugException(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Error with command: " + StringUtil.join(args, " "), e)); } finally { if (timeoutJob != null) { timeoutJob.cancel(); } if (process != null) { process.destroy(); } } }
Source:
public static void main(String... args) throws IOException, ClassNotFoundException { try (Ignite ignite = Ignition.start("examples/config/example-ignite-ml.xml")) { System.out.println(">>> Ignite grid started."); ModelStorage storage = ModelStorageFactory.getModelStorage(ignite); ModelDescriptorStorage descStorage = ModelDescriptorStorageFactory.getModelDescriptorStorage(ignite); System.out.println("Saving model into model storage..."); byte[] mdl = serialize((IgniteFunction<byte[], byte[]>)i -> i); storage.mkdirs("/"); storage.putFile("/my_model", mdl); System.out.println("Saving model descriptor into model descriptor storage..."); ModelDescriptor desc = new ModelDescriptor( "MyModel", "My Cool Model", new ModelSignature("", "", ""), new ModelStorageInfModelReader("/my_model"), new IgniteFunctionInfModelParser<>() ); descStorage.put("my_model", desc); System.out.println("List saved models..."); for (IgniteBiTuple<String, ModelDescriptor> model : descStorage) System.out.println("-> {'" + model.getKey() + "' : " + model.getValue() + "}"); System.out.println("Load saved model descriptor..."); desc = descStorage.get("my_model"); System.out.println("Build inference model..."); SingleInfModelBuilder mdlBuilder = new SingleInfModelBuilder(); try (InfModel<byte[], byte[]> infMdl = mdlBuilder.build(desc.getReader(), desc.getParser())) { System.out.println("Make inference..."); for (int i = 0; i < 10; i++) { Integer res = deserialize(infMdl.predict(serialize(i))); System.out.println(i + " -> " + res); } } } }

Target:
public static void main(String... args) throws IOException, ClassNotFoundException { try (Ignite ignite = Ignition.start("examples/config/example-ignite-ml.xml")) { System.out.println(">>> Ignite grid started."); ModelStorage storage = new ModelStorageFactory().getModelStorage(ignite); ModelDescriptorStorage descStorage = new ModelDescriptorStorageFactory().getModelDescriptorStorage(ignite); System.out.println("Saving model into model storage..."); byte[] mdl = serialize((IgniteFunction<byte[], byte[]>)i -> i); storage.mkdirs("/"); storage.putFile("/my_model", mdl); System.out.println("Saving model descriptor into model descriptor storage..."); ModelDescriptor desc = new ModelDescriptor( "MyModel", "My Cool Model", new ModelSignature("", "", ""), new ModelStorageInfModelReader("/my_model"), new IgniteFunctionInfModelParser<>() ); descStorage.put("my_model", desc); System.out.println("List saved models..."); for (IgniteBiTuple<String, ModelDescriptor> model : descStorage) System.out.println("-> {'" + model.getKey() + "' : " + model.getValue() + "}"); System.out.println("Load saved model descriptor..."); desc = descStorage.get("my_model"); System.out.println("Build inference model..."); SingleInfModelBuilder mdlBuilder = new SingleInfModelBuilder(); try (InfModel<byte[], byte[]> infMdl = mdlBuilder.build(desc.getReader(), desc.getParser())) { System.out.println("Make inference..."); for (int i = 0; i < 10; i++) { Integer res = deserialize(infMdl.predict(serialize(i))); System.out.println(i + " -> " + res); } } } }
Source:
public boolean txnCommitContainsAll(List<Data> data) { for (Data datum : data) { if (getItemQueue().stream().noneMatch(item -> datum.equals(item.getData()))) { return false; } } return true; }

Target:
public boolean txnCommitContainsAll(List<Data> data) { for (Data datum : data) { if (itemQueueContains(datum)) { return false; } } return true; }
Source:
public void performAlign(int offset, int width) { int plotAreaOffset = fXYViewer.getPointAreaOffset(); int sashOffset = Math.max(1, offset - plotAreaOffset); int total = fSashForm.getBounds().width; int width1 = (int) (sashOffset / (float) total * 1000); int width2 = (int) ((total - sashOffset) / (float) total * 1000); fSashForm.setWeights(new int[] { width1, width2 }); fSashForm.layout(); }

Target:
public void performAlign(int offset, int width) { int plotAreaOffset = fXYViewer.getPointAreaOffset(); int sashOffset = Math.max(1, offset - plotAreaOffset); int total = fSashForm.getBounds().width; int width1 = (int) (sashOffset / (float) total * 1000); int width2 = (int) ((total - sashOffset) / (float) total * 1000); fSashForm.setWeights(new int[] { width1, width2 }); fSashForm.layout(); Composite composite = fXYViewerContainer; GridLayout layout = (GridLayout) composite.getLayout(); int timeAxisWidth = getAvailableWidth(offset); int marginSize = timeAxisWidth - width; layout.marginRight = Math.max(0, marginSize); composite.layout(); }
Source:
private static void questionableMethodsAllowedToBlock(BlockHound.Builder builder) { builder.allowBlockingCallsInside(BasicComponentRegistryImpl.class.getName(), "prepareWrapperChange"); builder.allowBlockingCallsInside(BasicComponentRegistryImpl.class.getName(), "awaitWrapperState"); builder.allowBlockingCallsInside(JGroupsTransport.class.getName(), "sendCommand"); builder.allowBlockingCallsInside(JGroupsTransport.class.getName(), "sendResponse"); builder.allowBlockingCallsInside(ClusterTopologyManagerImpl.class.getName(), "prepareJoin"); builder.allowBlockingCallsInside(ClusterTopologyManagerImpl.class.getName(), "updateClusterState"); }

Target:
private static void questionableMethodsAllowedToBlock(BlockHound.Builder builder) { builder.allowBlockingCallsInside(BasicComponentRegistryImpl.class.getName(), "prepareWrapperChange"); builder.allowBlockingCallsInside(BasicComponentRegistryImpl.class.getName(), "awaitWrapperState"); builder.allowBlockingCallsInside(ClusterTopologyManagerImpl.class.getName(), "prepareJoin"); builder.allowBlockingCallsInside(ClusterTopologyManagerImpl.class.getName(), "updateClusterState"); }
Source:
public Message<?> preSend(Message<?> message, MessageChannel channel) { Message<?> sentMessage = null; if (this.klazz.isAssignableFrom(message.getPayload().getClass())) { Object contentTypeFromMessage = message.getHeaders().get(MessageHeaders.CONTENT_TYPE); if (contentTypeFromMessage == null) { sentMessage = MessageConverterConfigurer.this.messageBuilderFactory .fromMessage(message) .setHeader(MessageHeaders.CONTENT_TYPE, this.contentType) .build(); } else { sentMessage = message; } } else { Object converted = this.input ? this.messageConverter.fromMessage(message, this.klazz) : this.messageConverter.toMessage(message.getPayload(), message.getHeaders(), null); if (converted != null) { Message<?> convertedMessage = (Message<?>) converted; Object contentType = convertedMessage.getHeaders().get(MessageHeaders.CONTENT_TYPE); if (contentType instanceof MimeType) { sentMessage = MessageConverterConfigurer.this.messageBuilderFactory .fromMessage(convertedMessage).setHeader( MessageHeaders.CONTENT_TYPE, contentType.toString()).build(); } else { sentMessage = convertedMessage; } } } if (sentMessage != null) { return sentMessage; } else { throw new MessageConversionException("Cannot convert " + message + " to " + this.contentType); } }

Target:
public Message<?> preSend(Message<?> message, MessageChannel channel) { Message<?> sentMessage = null; if (this.klazz.isAssignableFrom(message.getPayload().getClass())) { Object contentTypeFromMessage = message.getHeaders().get(MessageHeaders.CONTENT_TYPE); if (contentTypeFromMessage == null) { sentMessage = MessageConverterConfigurer.this.messageBuilderFactory .fromMessage(message) .setHeader(MessageHeaders.CONTENT_TYPE, this.contentType) .build(); } else { sentMessage = message; } } else { Object converted = this.input ? this.messageConverter.fromMessage(message, this.klazz) : this.messageConverter.toMessage(message.getPayload(), message.getHeaders()); if (converted instanceof Message) { sentMessage = (Message<?>) converted; } else { sentMessage = MessageConverterConfigurer.this.messageBuilderFactory.withPayload(converted) .copyHeaders(message.getHeaders()).setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, this.mimeType).build(); } } if (sentMessage == null) { throw new MessageConversionException("Cannot convert " + message + " to " + this.contentType); } return sentMessage; }
Source:
private void freezeVm() { if (!isLiveSnapshotApplicable() || !isCinderDisksExist()) { return; } VDSReturnValue returnValue; try { returnValue = runVdsCommand(VDSCommandType.Freeze, new VdsAndVmIDVDSParametersBase(getVds().getId(), getVmId())); } catch (EngineException e) { handleFreezeVmFailure(e); return; } if (!returnValue.getSucceeded()) { handleFreezeVmFailure(new EngineException(EngineError.freezeErr)); } }

Target:
private void freezeVm() { if (!shouldFreezeVm()) { return; } VDSReturnValue returnValue; try { returnValue = runVdsCommand(VDSCommandType.Freeze, new VdsAndVmIDVDSParametersBase(getVds().getId(), getVmId())); } catch (EngineException e) { handleFreezeVmFailure(e); return; } if (!returnValue.getSucceeded()) { handleFreezeVmFailure(new EngineException(EngineError.freezeErr)); } else { auditLogDirector.log(this, AuditLogType.FREEZE_VM_SUCCESS); } }
Source:
public static void main(String[] args) { new SpringApplicationBuilder().sources(SchedulerTaskLauncherApplication.class).bannerMode(Banner.Mode.OFF).run(args); }

Target:
public static void main(String[] args) { new SpringApplicationBuilder().sources(SchedulerTaskLauncherApplication.class).run(args); }
Source:
public CompletableFuture<Collection<LogInfo>> requestLogList(Time timeout) { return CompletableFuture.supplyAsync(() -> { final String logDir = taskManagerConfiguration.getTaskManagerLogDir(); if (logDir != null) { final File[] logFiles = new File(logDir).listFiles(); if (logFiles == null) { throw new CompletionException(new FlinkException(String.format("There isn't a log file in TaskExecutor’s log dir %s.", logDir))); } return Arrays.stream(logFiles) .filter(File::isFile) .map(logFile -> new LogInfo(logFile.getName(), logFile.length())) .collect(Collectors.toList()); } return Collections.emptyList(); }, taskExecutorServices.getIOExecutor()); }

Target:
public CompletableFuture<Collection<LogInfo>> requestLogList(Time timeout) { return CompletableFuture.supplyAsync(() -> { final String logDir = taskManagerConfiguration.getTaskManagerLogDir(); if (logDir != null) { final File[] logFiles = new File(logDir).listFiles(); if (logFiles == null) { throw new CompletionException(new FlinkException(String.format("There isn't a log file in TaskExecutor’s log dir %s.", logDir))); } return Arrays.stream(logFiles) .filter(File::isFile) .map(logFile -> new LogInfo(logFile.getName(), logFile.length())) .collect(Collectors.toList()); } return Collections.emptyList(); }, ioExecutor); }
Source:
public Map<String, String> retrieveKeycloakAttributes() throws ServerException { Map<String, String> keycloakUserAttributes; try { keycloakUserAttributes = requestFactory.fromUrl(keyclockCurrentUserInfoUrl).request().asProperties(); } catch (IOException | ApiException e) { LOG.warn("Exception during retrieval of the Keycloak user profile", e); throw new ServerException("Exception during retrieval of the Keycloak user profile", e); } return keycloakUserAttributes; }

Target:
public Map<String, String> retrieveKeycloakAttributes() throws ServerException { try { return requestFactory.fromUrl(keyclockCurrentUserInfoUrl).request().asProperties(); } catch (IOException | ApiException e) { LOG.warn("Exception during retrieval of the Keycloak user profile", e); throw new ServerException("Exception during retrieval of the Keycloak user profile", e); } }
Source:
public Message<?> receive(long timeout) { try { if (this.receiveTimeout < 0) { this.latch.await(); } else { if (!this.latch.await(this.receiveTimeout, TimeUnit.MILLISECONDS)) { this.clientTimedOut = true; } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } this.clientHasReceived = true; return this.message; }

Target:
public Message<?> receive(long timeout) { try { if (this.receiveTimeout < 0) { this.latch.await(); this.clientHasReceived = true; } else { if (this.latch.await(this.receiveTimeout, TimeUnit.MILLISECONDS)) { this.clientHasReceived = true; } else { this.clientTimedOut = true; } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return this.message; }
Source:
public void testRestartedRM() throws Exception { MiniYARNCluster cluster = new MiniYARNCluster( "testRestartedRMNegative", NODE_MANAGER_COUNT, 1, 1); YarnClient rmClient = YarnClient.createYarnClient(); try { cluster.init(conf); cluster.start(); final Configuration yarnConf = cluster.getConfig(); rmClient = YarnClient.createYarnClient(); rmClient.init(yarnConf); rmClient.start(); List<NodeReport> nodeReports = rmClient.getNodeReports(); Assert.assertEquals( "The proxy didn't get expected number of node reports", NODE_MANAGER_COUNT, nodeReports.size()); } finally { if (rmClient != null) { rmClient.stop(); } cluster.stop(); } }

Target:
public void testRestartedRM() throws Exception { MiniYARNCluster cluster = new MiniYARNCluster("testRestartedRMNegative", NUMNODEMANAGERS, 1, 1); YarnClient rmClient = YarnClient.createYarnClient(); try { cluster.init(conf); cluster.start(); final Configuration yarnConf = cluster.getConfig(); rmClient = YarnClient.createYarnClient(); rmClient.init(yarnConf); rmClient.start(); List <NodeReport> nodeReports = rmClient.getNodeReports(); assertEquals( "The proxy didn't get expected number of node reports", NUMNODEMANAGERS, nodeReports.size()); } finally { if (rmClient != null) { rmClient.stop(); } cluster.stop(); } }
Source:
public void reportAsHeaders(HttpServletResponse rsp) { rsp.addHeader("X-You-Are-Authenticated-As",authentication.getName()); GrantedAuthority[] authorities = authentication.getAuthorities(); for (int i = 0; i < authorities.length; i++) { if (i == MAX_REPORTED_AUTHORITIES) { rsp.addHeader("X-You-Are-In-Group", "<" + (authorities.length - i) + " more>"); break; } else { rsp.addHeader("X-You-Are-In-Group", authorities[i].getAuthority()); } } rsp.addHeader("X-Required-Permission", permission.getId()); for (Permission p=permission.impliedBy; p!=null; p=p.impliedBy) { rsp.addHeader("X-Permission-Implied-By", p.getId()); } }

Target:
public void reportAsHeaders(HttpServletResponse rsp) { rsp.addHeader("X-You-Are-Authenticated-As",authentication.getName()); if (REPORT_GROUP_HEADERS) { for (GrantedAuthority auth : authentication.getAuthorities()) { rsp.addHeader("X-You-Are-In-Group",auth.getAuthority()); } } else { rsp.addHeader("X-You-Are-In-Group-Disabled", "JENKINS-39402: use -Dhudson.security.AccessDeniedException2.REPORT_GROUP_HEADERS=true or use /whoAmI to diagnose"); } rsp.addHeader("X-Required-Permission", permission.getId()); for (Permission p=permission.impliedBy; p!=null; p=p.impliedBy) { rsp.addHeader("X-Permission-Implied-By", p.getId()); } }
Source:
public void shouldConvertToHashMap() { final Function<Integer, Integer> keyMapper = i -> AbstractMapTest.md5(Integer.toString(i) + " unique line value").hashCode(); final Value<Integer> value = of(9, 5, 1); Map<Integer, Integer> map = value.toMap(v -> Tuple.of(keyMapper.apply(v), v)); if (value.isSingleValued()) { map = map.put(keyMapper.apply(5), 5).put(keyMapper.apply(1), 1); } assertThat(map.mkString(", ")).isEqualTo( "(110427681, 5), " + "(663160547, 1), " + "(1571254982, 9)"); }

Target:
public void shouldConvertToHashMap() { final Value<Integer> value = of(9, 5, 1); final Map<Integer, Integer> map = value.toMap(i -> Tuple.of(i, i)); if (value.isSingleValued()) { assertThat(map).isEqualTo(HashMap.of(9, 9)); } else { assertThat(map).isEqualTo(HashMap.of(1, 1, 5, 5, 9, 9)); } }
Source:
public static Filter fromOldFormat( String includeDatabases, String excludeDatabases, String includeTables, String excludeTables, String blacklistDatabases, String blacklistTables, String includeValues ) throws InvalidFilterException { ArrayList<String> filterRules = new ArrayList<>(); if ( blacklistDatabases != null ) { for ( String s : blacklistDatabases.split(",") ) filterRules.add("blacklist: " + s + ".*"); } if ( blacklistTables != null ) { for (String s : blacklistTables.split(",")) filterRules.add("blacklist: *." + s); } if ( includeDatabases != null || includeTables != null ) { filterRules.add("exclude: *.*"); } if ( includeDatabases != null ) { for ( String s : includeDatabases.split(",") ) filterRules.add("include: " + s + ".*"); } if ( excludeDatabases != null ) { for (String s : includeDatabases.split(",")) filterRules.add("exclude: " + s + ".*"); } if ( includeTables != null ) { for ( String s : includeTables.split(",") ) filterRules.add("include: *." + s); } if ( excludeTables != null ) { for ( String s : excludeTables.split(",") ) filterRules.add("exclude: *." + s); } return new Filter(String.join(", ", filterRules), includeValues); }

Target:
public static Filter fromOldFormat( String includeDatabases, String excludeDatabases, String includeTables, String excludeTables, String blacklistDatabases, String blacklistTables, String includeValues ) throws InvalidFilterException { ArrayList<String> filterRules = new ArrayList<>(); if ( blacklistDatabases != null ) { for ( String s : blacklistDatabases.split(",") ) filterRules.add("blacklist: " + s + ".*"); } if ( blacklistTables != null ) { for (String s : blacklistTables.split(",")) filterRules.add("blacklist: *." + s); } if ( includeDatabases != null || includeTables != null ) { filterRules.add("exclude: *.*"); } if ( includeDatabases != null ) { for ( String s : includeDatabases.split(",") ) filterRules.add("include: " + s + ".*"); } if ( excludeDatabases != null ) { for (String s : excludeDatabases.split(",")) filterRules.add("exclude: " + s + ".*"); } if ( includeTables != null ) { for ( String s : includeTables.split(",") ) filterRules.add("include: *." + s); } if ( excludeTables != null ) { for ( String s : excludeTables.split(",") ) filterRules.add("exclude: *." + s); } if (includeValues != null && !"".equals(includeValues)) { for (String s : includeValues.split(",")) { String[] columnAndValue = s.split("="); filterRules.add("exclude: *.*." + columnAndValue[0] + "=*"); filterRules.add("include: *.*." + columnAndValue[0] + "=" + columnAndValue[1]); } } String filterRulesAsString = String.join(", ", filterRules); LOGGER.warn("using exclude/include/includeColumns is deprecated. Please update your configuration to use: "); LOGGER.warn("filter = \"" + filterRulesAsString + "\""); return new Filter(filterRulesAsString); }
Source:
private static String computeIntervalPattern(Map<String, String> prefsMap) { String ssecFmt = computeSubSecFormat(prefsMap); return "TTT." + ssecFmt; }

Target:
private static String computeIntervalPattern(Map<String, String> prefsMap) { String ssecFmt = computeSubSecFormat(prefsMap); return ITmfTimePreferencesConstants.TIME_ELAPSED_FMT + "." + ssecFmt; }
Source:
public List<Target> getTargets() { if (hasTargets()) { return targets; } else { return new ArrayList<>(); } }

Target:
public List<Target> getTargets() { if (hasTargets()) { return targets; } else { return null; } }
Source:
public void run() throws IOException { try { if (readyForRead()) { final int maxRead = m_handler.getMaxRead(); if (maxRead > 0) { fillReadStream(maxRead); } int read; while (true) { if (m_nextFrameLength == 0) { if (readStream().dataAvailable() >= 5) { read = readStream().getBytes(m_frameHeader); m_frameHeader.flip(); m_frameHeader.position(3); m_frameHeader.get(m_twoBytes); m_nextFrameLength = ((m_twoBytes[0] & 0xff) << 8) | (m_twoBytes[1] & 0xff); } else { break; } } if (readStream().dataAvailable() >= m_nextFrameLength) { DBBPool.BBContainer frameCont = DBBPool.allocateDirectAndPool(m_nextFrameLength + 5); ByteBuffer frame = frameCont.b(); frame.limit(m_nextFrameLength + 5); m_frameHeader.flip(); frame.put(m_frameHeader); m_frameHeader.clear(); readStream().getBytes(frame); m_callables.add(new DecryptionCallable(frameCont)); m_nextFrameLength = 0; } else { break; } } Callable c = m_callables.poll(); if (c != null) { Future<List<ByteBuffer>> f = SSLEncryptionService.instance().submit(c); List<ByteBuffer> messages; while (f != null) { try { messages = f.get(); c = m_callables.poll(); f = null; if (c != null) { f = SSLEncryptionService.instance().submit(c); } for (ByteBuffer message : messages) { m_handler.handleMessage(message, this); m_messagesRead++; } } catch (InterruptedException e) { return; } catch (ExecutionException e) { throw new IOException(e); } } } } drainWriteStream(); } finally { synchronized (m_lock) { assert (m_running == true); m_running = false; } } }

Target:
public void run() throws IOException { try { if (m_isShuttingDown) { unregistered(); return; } processReads(); handleDecryptedMessages(); processWrites(); handleEncryptedBuffers(); writeStream().checkBackpressureEnded(); cleanup(); } catch (IOException ioe) { networkLog.error("Exception in SSLVoltPort.run", ioe); throw ioe; } finally { synchronized (m_lock) { assert (m_running == true); m_running = false; } } }
Source:
private NetworkAttachment createAttachmentWhenAttachingTo(VdsNetworkInterface targetNic) { NetworkAttachment networkAttachment = new NetworkAttachment(targetNic, networkModel.getNetwork(), NetworkCommonUtils.createDefaultIpConfiguration()); NetworkParameters netParams = networkModel.getSetupModel().getNetworkToLastDetachParams().get(networkModel.getName()); if (netParams != null) { applyOnAttachmentParamsFrom(netParams, networkAttachment); } else { VdsNetworkInterface nicToTakeParamsFrom = null; if (networkModel.hasVlan()) { nicToTakeParamsFrom = getPotentialVlanDevice(targetNic); } else { nicToTakeParamsFrom = targetNic; } if (nicToTakeParamsFrom != null && nicToTakeParamsFrom.getId() != null) { applyOnAttachmentParamsFrom(new InterfacePropertiesAccessor.FromNic(nicToTakeParamsFrom), networkAttachment); } fixBootProtocolOfMgmtNetworkIfNeeded(networkAttachment); } return networkAttachment; }

Target:
private NetworkAttachment createAttachmentWhenAttachingTo(VdsNetworkInterface targetNic) { NetworkAttachment networkAttachment = new NetworkAttachment(targetNic, networkModel.getNetwork(), NetworkCommonUtils.createDefaultIpConfiguration()); NetworkParameters netParams = networkModel.getSetupModel().getNetworkToLastDetachParams().get(networkModel.getName()); if (netParams != null) { applyOnAttachmentParamsFrom(netParams, networkAttachment); } else { VdsNetworkInterface nicToTakeParamsFrom = null; if (networkModel.hasVlan()) { nicToTakeParamsFrom = getPotentialVlanDevice(targetNic); } else { nicToTakeParamsFrom = targetNic; } boolean newlyCreatedBond = nicToTakeParamsFrom != null && nicToTakeParamsFrom.getId() == null; if (nicToTakeParamsFrom != null && !newlyCreatedBond) { applyOnAttachmentParamsFrom(new InterfacePropertiesAccessor.FromNic(nicToTakeParamsFrom), networkAttachment); } fixBootProtocolOfMgmtNetworkIfNeeded(networkAttachment); } return networkAttachment; }
Source:
public BaseRuleTest(Plugin...plugins) { this.plugins = plugins; }

Target:
public BaseRuleTest(Plugin... plugins) { this.plugins = ImmutableList.copyOf(plugins); }
Source:
private static void writeBinaryCheckpoints(TreeMap<Integer, StoredBlock> checkpoints, File file) throws Exception { try (FileOutputStream fileOutputStream = new FileOutputStream(file, false)) { MessageDigest digest = Sha256Hash.newDigest(); try ( DigestOutputStream digestOutputStream = new DigestOutputStream(fileOutputStream, digest); DataOutputStream dataOutputStream = new DataOutputStream(digestOutputStream) ) { digestOutputStream.on(false); dataOutputStream.writeBytes("CHECKPOINTS 1"); dataOutputStream.writeInt(0); digestOutputStream.on(true); dataOutputStream.writeInt(checkpoints.size()); ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE); for (StoredBlock block : checkpoints.values()) { block.serializeCompact(buffer); dataOutputStream.write(buffer.array()); buffer.position(0); } Sha256Hash checkpointsHash = Sha256Hash.wrap(digest.digest()); System.out.println("Hash of checkpoints data is " + checkpointsHash); System.out.println("Checkpoints written to '" + file.getCanonicalPath() + "'."); } } }

Target:
private static void writeBinaryCheckpoints(TreeMap<Integer, StoredBlock> checkpoints, File file) throws Exception { MessageDigest digest = Sha256Hash.newDigest(); try ( FileOutputStream fileOutputStream = new FileOutputStream(file, false); DigestOutputStream digestOutputStream = new DigestOutputStream(fileOutputStream, digest); DataOutputStream dataOutputStream = new DataOutputStream(digestOutputStream) ) { digestOutputStream.on(false); dataOutputStream.writeBytes("CHECKPOINTS 1"); dataOutputStream.writeInt(0); digestOutputStream.on(true); dataOutputStream.writeInt(checkpoints.size()); ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE); for (StoredBlock block : checkpoints.values()) { block.serializeCompact(buffer); dataOutputStream.write(buffer.array()); buffer.position(0); } Sha256Hash checkpointsHash = Sha256Hash.wrap(digest.digest()); System.out.println("Hash of checkpoints data is " + checkpointsHash); System.out.println("Checkpoints written to '" + file.getCanonicalPath() + "'."); } }