auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void main(String[] args) throws Exception { BriefLogFormatter.init(); System.out.println("USAGE: [--net={MAIN/TEST/REGTEST}] host"); final String net = args.length > 1 ? args[0] : ""; NetworkParameters params; switch(net) { case "--net=REGTEST": default: params = RegTestParams.get(); break; case "--net=TEST": params = TestNet3Params.get(); break; case "--net=MAIN": params = MainNetParams.get(); break; } new ExamplePaymentChannelClient().run(args.length > 1 ? args[1] : args[0], params); }

Target:
public static void main(String[] args) throws Exception { BriefLogFormatter.init(); OptionParser parser = new OptionParser(); OptionSpec<NetworkEnum> net = parser.accepts("net", "The network to run the examples on").withRequiredArg().ofType(NetworkEnum.class).defaultsTo(NetworkEnum.TEST); OptionSpec<Integer> version = parser.accepts("version", "The payment channel protocol to use").withRequiredArg().ofType(Integer.class); parser.accepts("help", "Displays program options"); OptionSet opts = parser.parse(args); if (opts.has("help") || !opts.has(net) || opts.nonOptionArguments().size() != 1) { System.err.println("usage: ExamplePaymentChannelClient --net=MAIN/TEST/REGTEST --version=1/2 host"); parser.printHelpOn(System.err); return; } PaymentChannelClient.VersionSelector versionSelector = PaymentChannelClient.VersionSelector.VERSION_1; if (opts.has("version")) { switch (version.value(opts)) { case 1: versionSelector = PaymentChannelClient.VersionSelector.VERSION_1; break; case 2: versionSelector = PaymentChannelClient.VersionSelector.VERSION_2; break; default: System.err.println("Invalid version - valid versions are 1, 2"); return; } } NetworkParameters params = net.value(opts).get(); new ExamplePaymentChannelClient().run(opts.nonOptionArguments().get(0), versionSelector, params); }
Source:
public void testRequestedMappingIsStoredInFS() throws Exception { Ignite srv1 = startGrid(0); Organization org = new Organization(1, "Microsoft", "One Microsoft Way Redmond, WA 98052-6399, USA"); srv1.cache(DEFAULT_CACHE_NAME).put(1, org); clientMode = true; Ignite cl1 = startClientGrid(1); cl1.cache(DEFAULT_CACHE_NAME).get(1); String clsName = Organization.class.getName(); stopGrid(1); File[] files = Paths.get(TMP_DIR, "marshaller").toFile().listFiles(); assertNotNull(TMP_DIR + "/marshaller directory should contain at least one file", files); boolean orgClsMarshalled = false; for (File f : files) { if (clsName.equals(new String(Files.readAllBytes(f.toPath())))) { orgClsMarshalled = true; break; } } assertTrue(clsName + " should be marshalled and stored to disk", orgClsMarshalled); }

Target:
public void testRequestedMappingIsStoredInFS() throws Exception { Ignite srv1 = startGrid(0); Organization org = new Organization(1, "Microsoft", "One Microsoft Way Redmond, WA 98052-6399, USA"); srv1.cache(DEFAULT_CACHE_NAME).put(1, org); Ignite cl1 = startClientGrid(1); cl1.cache(DEFAULT_CACHE_NAME).get(1); String clsName = Organization.class.getName(); stopGrid(1); File[] files = Paths.get(TMP_DIR, "marshaller").toFile().listFiles(); assertNotNull(TMP_DIR + "/marshaller directory should contain at least one file", files); boolean orgClsMarshalled = false; for (File f : files) { if (clsName.equals(new String(Files.readAllBytes(f.toPath())))) { orgClsMarshalled = true; break; } } assertTrue(clsName + " should be marshalled and stored to disk", orgClsMarshalled); }
Source:
public Set<ConnectorPlanOptimizer> getConnectorPlanOptimizers() { return new HashSet<>(); }

Target:
public Set<ConnectorPlanOptimizer> getConnectorPlanOptimizers() { return ImmutableSet.of(); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); ImageButton one = (ImageButton) findViewById(R.id.facebookButton); one.setOnClickListener(this); ImageButton two = (ImageButton) findViewById(R.id.twitterButton); two.setOnClickListener(this); ImageButton three = (ImageButton) findViewById(R.id.youtubeButton); three.setOnClickListener(this); Button website = (Button) findViewById(R.id.websiteButton); website.setOnClickListener(this); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); initialize(); }
Source:
public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("provisioned"); action .setDescription( "Get the list of provisioned projects.<br /> " + "Require 'Create Projects' permission.") .setSince("5.2") .setResponseExample(Resources.getResource(getClass(), "projects-example-provisioned.json")) .setHandler(this) .addPagingParams(100, MAX_LIMIT) .addSearchQuery("sonar", "names", "keys") .addFieldsParam(POSSIBLE_FIELDS); action.setChangelog( new Change("6.4", "The 'uuid' field is deprecated in the response"), new Change("6.4", "The fields 'total', 'p' and 'ps' are now named 'total', 'pageIndex' and 'pageSize' in the response " + "and are nested inside an attribute 'paging'")); support.addOrganizationParam(action); }

Target:
public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("provisioned"); action .setDescription( "Get the list of provisioned projects.<br /> " + "Require 'Create Projects' permission.") .setSince("5.2") .setResponseExample(Resources.getResource(getClass(), "projects-example-provisioned.json")) .setHandler(this) .addPagingParams(100, MAX_LIMIT) .addSearchQuery("sonar", "names", "keys") .addFieldsParam(POSSIBLE_FIELDS); action.setChangelog( new Change("6.4", "The 'uuid' field is deprecated in the response"), new Change("6.4", "Paging response fields is now in a Paging object")); support.addOrganizationParam(action); }
Source:
protected void buildTree(LayoutModel<N> layoutModel) { alreadyDone = Sets.newHashSet(); this.currentX = 0; this.currentY = 0; Set<N> roots = TreeUtils.roots(layoutModel.getGraph()); Preconditions.checkArgument(roots.size() > 0); int overallWidth = calculateDimensionX(layoutModel, roots); overallWidth += (roots.size() + 1) * distX; int overallHeight = calculateDimensionY(layoutModel, roots); overallHeight += 2 * distY; layoutModel.setSize( Math.max(layoutModel.getWidth(), overallWidth), Math.max(layoutModel.getHeight(), overallHeight)); for (N node : roots) { calculateDimensionX(layoutModel, node); currentX += (this.basePositions.get(node) / 2 + this.distX); buildTree(layoutModel, node, (int) currentX); } }

Target:
protected void buildTree(LayoutModel<N> layoutModel) { alreadyDone = Sets.newHashSet(); this.currentX = 0; this.currentY = 0; Set<N> roots = TreeUtils.roots(layoutModel.getGraph()); Preconditions.checkArgument(roots.size() > 0); int overallWidth = calculateWidth(layoutModel, roots); overallWidth += (roots.size() + 1) * horizontalNodeSpacing; int overallHeight = calculateHeight(layoutModel, roots); overallHeight += 2 * verticalNodeSpacing; layoutModel.setSize( Math.max(layoutModel.getWidth(), overallWidth), Math.max(layoutModel.getHeight(), overallHeight)); for (N node : roots) { calculateWidth(layoutModel, node); currentX += (this.basePositions.get(node) / 2 + this.horizontalNodeSpacing); buildTree(layoutModel, node, (int) currentX); } }
Source:
public void goToNewsDetail(final News news) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity()); if (pref.getBoolean(Constants.CONFIG_EXTERNAL_BROWSER, false)) { Intent intent = new Intent(getActivity(), NewsCommentsActivity.class); intent.putExtra(Constants.NEWS, Parcels.wrap(news)); startActivity(intent); if (news.getUrl() != null && !news.getUrl().isEmpty()) { new Handler().postDelayed(new Runnable() { @Override public void run() { Uri uri = Uri.parse(news.getUrl()); startActivity(new Intent(Intent.ACTION_VIEW, uri)); } }, 300); } } else { Intent intent = new Intent(getActivity(), NewsDetailActivity.class); intent.putExtra(Constants.NEWS, Parcels.wrap(news)); startActivity(intent); } }

Target:
public void goToNewsDetail(final News news) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity()); Intent intent; if (pref.getBoolean(Constants.CONFIG_EXTERNAL_BROWSER, false)) { intent = new Intent(getActivity(), NewsCommentsActivity.class); if (news.getUrl() != null && !news.getUrl().isEmpty()) { new Handler().postDelayed(new Runnable() { @Override public void run() { Uri uri = Uri.parse(news.getUrl()); startActivity(new Intent(Intent.ACTION_VIEW, uri)); } }, 300); } } else { intent = new Intent(getActivity(), NewsDetailActivity.class); } intent.putExtra(Constants.NEWS, Parcels.wrap(news)); startActivity(intent); }
Source:
public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException { pm.beginTask("", 2); RefactoringStatus result; try { result= new RefactoringStatus(); IJavaElement element= (IJavaElement) getModifiedElement(); result.merge(super.isValid(new SubProgressMonitor(pm, 1))); if (result.hasFatalError()) return result; if (element != null && element.exists() && element instanceof IPackageFragment) { IPackageFragment pack= (IPackageFragment) element; if (fRenameSubpackages) { IPackageFragment[] allPackages= JavaElementUtil.getPackageAndSubpackages(pack); SubProgressMonitor subPm= new SubProgressMonitor(pm, 1); subPm.beginTask("", allPackages.length); for (IPackageFragment fragmentpackage : allPackages) { checkIfModifiable(result, fragmentpackage.getResource(), VALIDATE_NOT_DIRTY); if (result.hasFatalError()) return result; isValid(result, fragmentpackage, new SubProgressMonitor(subPm, 1)); } } else { isValid(result, pack, new SubProgressMonitor(pm, 1)); } } } finally { pm.done(); } return result; }

Target:
public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException { pm.beginTask("", 2); RefactoringStatus result; try { result= new RefactoringStatus(); IJavaElement element= (IJavaElement) getModifiedElement(); result.merge(super.isValid(new SubProgressMonitor(pm, 1))); if (result.hasFatalError()) return result; if (element != null && element.exists() && element instanceof IPackageFragment) { IPackageFragment pack= (IPackageFragment) element; if (fRenameSubpackages) { IPackageFragment[] allPackages= JavaElementUtil.getPackageAndSubpackages(pack); SubProgressMonitor subPm= new SubProgressMonitor(pm, 1); subPm.beginTask("", allPackages.length); for (IPackageFragment pckg : allPackages) { checkIfModifiable(result, pckg.getResource(), VALIDATE_NOT_DIRTY); if (result.hasFatalError()) return result; isValid(result, pckg, new SubProgressMonitor(subPm, 1)); } } else { isValid(result, pack, new SubProgressMonitor(pm, 1)); } } } finally { pm.done(); } return result; }
Source:
void sendCommand(Address target, ReplicableCommand command, long requestId, DeliverOrder deliverOrder, boolean rsvp, boolean noRelay, boolean checkView) { Message message = new Message(toJGroupsAddress(target)); marshallRequest(message, command, requestId); setMessageFlags(message, deliverOrder, rsvp, noRelay); if (checkView && !clusterView.contains(target)) return; send(message); }

Target:
void sendCommand(Address target, ReplicableCommand command, long requestId, DeliverOrder deliverOrder, boolean rsvp, boolean noRelay, boolean checkView) { if (checkView && !clusterView.contains(target)) return; Message message = new Message(toJGroupsAddress(target)); marshallRequest(message, command, requestId); setMessageFlags(message, deliverOrder, rsvp, noRelay); send(message); }
Source:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(WordPress.SITE, mSite); outState.putString(KEY_PLUGIN_SLUG, mSlug); outState.putBoolean(KEY_IS_CONFIGURING_PLUGIN, mIsConfiguringPlugin); outState.putBoolean(KEY_IS_INSTALLING_PLUGIN, mIsInstallingPlugin); outState.putBoolean(KEY_IS_UPDATING_PLUGIN, mIsUpdatingPlugin); outState.putBoolean(KEY_IS_REMOVING_PLUGIN, mIsRemovingPlugin); outState.putBoolean(KEY_IS_ACTIVE, mIsActive); outState.putBoolean(KEY_IS_AUTO_UPDATE_ENABLED, mIsAutoUpdateEnabled); outState.putBoolean(KEY_IS_SHOWING_REMOVE_PLUGIN_CONFIRMATION_DIALOG, mIsShowingRemovePluginConfirmationDialog); outState.putBoolean(KEY_IS_SHOWING_INSTALL_FIRST_PLUGIN_CONFIRMATION_DIALOG, mIsShowingInstallFirstPluginConfirmationDialog); outState.putBoolean(KEY_IS_SHOWING_AUTOMATED_TRANSFER_PROGRESS, mIsShowingAutomatedTransferProgress); outState.putBoolean(KEY_IS_SHOWING_DOMAIN_CREDIT_CHECK_PROGRESS, mIsShowingDomainCreditCheckProgress); }

Target:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(WordPress.SITE, mSite); outState.putString(KEY_PLUGIN_SLUG, mSlug); outState.putBoolean(KEY_IS_CONFIGURING_PLUGIN, mIsConfiguringPlugin); outState.putBoolean(KEY_IS_INSTALLING_PLUGIN, mIsInstallingPlugin); outState.putBoolean(KEY_IS_UPDATING_PLUGIN, mIsUpdatingPlugin); outState.putBoolean(KEY_IS_REMOVING_PLUGIN, mIsRemovingPlugin); outState.putBoolean(KEY_IS_ACTIVE, mIsActive); outState.putBoolean(KEY_IS_AUTO_UPDATE_ENABLED, mIsAutoUpdateEnabled); outState.putBoolean(KEY_IS_SHOWING_REMOVE_PLUGIN_CONFIRMATION_DIALOG, mIsShowingRemovePluginConfirmationDialog); outState.putBoolean(KEY_IS_SHOWING_INSTALL_FIRST_PLUGIN_CONFIRMATION_DIALOG, mIsShowingInstallFirstPluginConfirmationDialog); outState.putBoolean(KEY_IS_SHOWING_AUTOMATED_TRANSFER_PROGRESS, mIsShowingAutomatedTransferProgress); outState.putBoolean(KEY_IS_SHOWING_DOMAIN_CREDIT_CHECK_PROGRESS, mCheckingDomainCreditsProgressDialog != null && mCheckingDomainCreditsProgressDialog.isShowing()); }
Source:
public RelRoot plan(String query) { try { Planner planner = getPlanner(); SqlNode sql = planner.parse(query); SqlNode validatedSql = planner.validate(sql); RelRoot relRoot = planner.rel(validatedSql); LOG.info("query plan without optimization:\n" + RelOptUtil.toString(relRoot.rel, SqlExplainLevel.EXPPLAN_ATTRIBUTES)); if (!isQueryPlanOptimizerEnabled) { return relRoot; } return optimize(relRoot); } catch (Exception e) { String errorMsg = SamzaSqlValidator.formatErrorString(query, e); LOG.error(errorMsg, e); throw new SamzaException(errorMsg, e); } }

Target:
public RelRoot plan(String query) { try (Planner planner = getPlanner()) { SqlNode sql = planner.parse(query); SqlNode validatedSql = planner.validate(sql); RelRoot relRoot = planner.rel(validatedSql); LOG.info( "query plan without optimization:\n" + RelOptUtil.toString(relRoot.rel, SqlExplainLevel.EXPPLAN_ATTRIBUTES)); if (!isQueryPlanOptimizerEnabled) { LOG.info("Skipping query optimization as it is disabled."); return relRoot; } return optimize(planner, relRoot); } catch (Exception e) { String errorMsg = SamzaSqlValidator.formatErrorString(query, e); LOG.error(errorMsg, e); throw new SamzaException(errorMsg, e); } }
Source:
public void writeLac(final BookieSocketAddress addr, final long ledgerId, final byte[] masterKey, final long lac, final ByteBufList toSend, final WriteLacCallback cb, final Object ctx) { final PerChannelBookieClientPool client = lookupClient(addr); if (client == null) { cb.writeLacComplete(getRc(BKException.Code.BookieHandleNotAvailableException), ledgerId, addr, ctx); return; } toSend.retain(); client.obtain((rc, pcbc) -> { if (rc != BKException.Code.OK) { try { executor.executeOrdered(ledgerId, safeRun(() -> { cb.writeLacComplete(rc, ledgerId, addr, ctx); })); } catch (RejectedExecutionException re) { cb.writeLacComplete(getRc(BKException.Code.InterruptedException), ledgerId, addr, ctx); } } else { pcbc.writeLac(ledgerId, masterKey, lac, toSend, cb, ctx); } toSend.release(); }, ledgerId, conf.getUseV2WireProtocol()); }

Target:
public void writeLac(final BookieSocketAddress addr, final long ledgerId, final byte[] masterKey, final long lac, final ByteBufList toSend, final WriteLacCallback cb, final Object ctx) { final PerChannelBookieClientPool client = lookupClient(addr); if (client == null) { cb.writeLacComplete(getRc(BKException.Code.BookieHandleNotAvailableException), ledgerId, addr, ctx); return; } toSend.retain(); client.obtain((rc, pcbc) -> { if (rc != BKException.Code.OK) { try { executor.executeOrdered(ledgerId, safeRun(() -> { cb.writeLacComplete(rc, ledgerId, addr, ctx); })); } catch (RejectedExecutionException re) { cb.writeLacComplete(getRc(BKException.Code.InterruptedException), ledgerId, addr, ctx); } } else { pcbc.writeLac(ledgerId, masterKey, lac, toSend, cb, ctx); } toSend.release(); }, ledgerId, useV3Enforced); }
Source:
public static <M, K> Window<M, K, Collection<M>> keyedTumblingWindow(Function<M, K> keyFn, Duration interval) { BiFunction<M, Collection<M>, Collection<M>> aggregator = (m, c) -> { if (c == null) { return new ArrayList<>(Arrays.asList(m)); } c.add(m); return c; }; return keyedTumblingWindow(keyFn, interval, aggregator); }

Target:
public static <M, K> Window<M, K, Collection<M>> keyedTumblingWindow(Function<M, K> keyFn, Duration interval) { FoldLeftFunction<M, Collection<M>> aggregator = createAggregator(); Supplier<Collection<M>> initialValue = () -> new ArrayList<>(); return keyedTumblingWindow(keyFn, interval, initialValue, aggregator); }
Source:
public void canDeserializeAdminConfig() throws IOException { PrivilegesConfiguration configuration = deserialize(getConfigFile(ADMIN_PRIVILEGES_CONFIG)); assertThat(configuration).isInstanceOf(AdminPrivilegesConfiguration.class); assertThat(configuration.id()).isEqualTo(ADMIN_ID); assertThat(configuration.privileges()).isEqualTo(Privileges.ADMIN); }

Target:
public void canDeserializeAdminConfig() throws IOException { PrivilegesConfiguration deserializedConfiguration = deserialize(getConfigFile(ADMIN_PRIVILEGES_CONFIG)); AdminPrivilegesConfiguration expectedConfiguration = ImmutableAdminPrivilegesConfiguration.builder() .clientId(ADMIN_ID) .build(); assertThat(deserializedConfiguration).isEqualTo(expectedConfiguration); }
Source:
public Pair<Boolean, AuditLogType> disconnectHostFromStoragePoolServersCommandCompleted(HostStoragePoolParametersBase parameters) { if (FeatureSupported.cinderProviderSupported(parameters.getStoragePool().getCompatibilityVersion())) { VDSReturnValue returnValue = Backend.getInstance().getResourceManager().RunVdsCommand( VDSCommandType.RegisterLibvirtSecrets, new RegisterLibvirtSecretsVDSParameters(parameters.getVds().getId(), Collections.<LibvirtSecret>emptyList(), true)); if (!returnValue.getSucceeded()) { log.error("Failed to register libvirt secret on vds {}.", parameters.getVds().getName()); return new Pair<Boolean, AuditLogType>(false, AuditLogType.FAILED_TO_REGISTER_LIBVIRT_SECRET_ON_VDS); } } return new Pair<Boolean, AuditLogType>(true, null); }

Target:
public Pair<Boolean, AuditLogType> disconnectHostFromStoragePoolServersCommandCompleted(HostStoragePoolParametersBase parameters) { if (FeatureSupported.cinderProviderSupported(parameters.getStoragePool().getCompatibilityVersion())) { VDSReturnValue returnValue = Backend.getInstance().getResourceManager().RunVdsCommand( VDSCommandType.RegisterLibvirtSecrets, new RegisterLibvirtSecretsVDSParameters(parameters.getVds().getId(), Collections.<LibvirtSecret>emptyList(), true)); if (!returnValue.getSucceeded()) { log.error("Failed to unregister libvirt secret on vds {}.", parameters.getVds().getName()); return new Pair<Boolean, AuditLogType>(false, AuditLogType.FAILED_TO_REGISTER_LIBVIRT_SECRET_ON_VDS); } } return new Pair<Boolean, AuditLogType>(true, null); }
Source:
private void initMetricsInvoker() { metricsInvoker = new Invoker<MetricsService>() { @Override public Class<MetricsService> getInterface() { return MetricsService.class; } @Override public Result invoke(Invocation invocation) throws RpcException { String group = invocation.getArguments()[0].toString(); MetricRegistry registry = MetricManager.getIMetricManager().getMetricRegistryByGroup(group); SortedMap<MetricName, FastCompass> fastCompasses = registry.getFastCompasses(); long timestamp = System.currentTimeMillis(); double rateFactor = TimeUnit.SECONDS.toSeconds(1); double durationFactor = 1.0 / TimeUnit.MILLISECONDS.toNanos(1); MetricsCollector collector = MetricsCollectorFactory.createNew( CollectLevel.NORMAL, Collections.EMPTY_MAP, rateFactor, durationFactor, null); for (Map.Entry<MetricName, FastCompass> entry : fastCompasses.entrySet()) { collector.collect(entry.getKey(), entry.getValue(), timestamp); } RpcResult result = new RpcResult(); List res = collector.build(); res.addAll(getThreadPoolMessage()); result.setValue(JSON.toJSONString(res)); return result; } @Override public URL getUrl() { return URL.valueOf(protocolName + "://" + NetUtils.getLocalAddress().getHostName() + ":" + port + "/" + MetricsService.class.getName()); } @Override public boolean isAvailable() { return false; } @Override public void destroy() { } }; }

Target:
private Invoker<MetricsService> initMetricsInvoker() { Invoker<MetricsService> metricsInvoker = new Invoker<MetricsService>() { @Override public Class<MetricsService> getInterface() { return MetricsService.class; } @Override public Result invoke(Invocation invocation) throws RpcException { String group = invocation.getArguments()[0].toString(); MetricRegistry registry = MetricManager.getIMetricManager().getMetricRegistryByGroup(group); SortedMap<MetricName, FastCompass> fastCompasses = registry.getFastCompasses(); long timestamp = System.currentTimeMillis(); double rateFactor = TimeUnit.SECONDS.toSeconds(1); double durationFactor = 1.0 / TimeUnit.MILLISECONDS.toNanos(1); MetricsCollector collector = MetricsCollectorFactory.createNew( CollectLevel.NORMAL, Collections.EMPTY_MAP, rateFactor, durationFactor, null); for (Map.Entry<MetricName, FastCompass> entry : fastCompasses.entrySet()) { collector.collect(entry.getKey(), entry.getValue(), timestamp); } RpcResult result = new RpcResult(); List res = collector.build(); res.addAll(getThreadPoolMessage()); result.setValue(JSON.toJSONString(res)); return result; } @Override public URL getUrl() { return URL.valueOf(protocolName + "://" + NetUtils.getIpByConfig() + ":" + port + "/" + MetricsService.class.getName()); } @Override public boolean isAvailable() { return false; } @Override public void destroy() { } }; return metricsInvoker; }
Source:
public void testPostingsNonExistings() throws Exception { Directory dir = FSDirectory.open(tempDir1); IndexReader reader = DirectoryReader.open(dir); assertEquals(null, IndexReaderUtils.getPostingsList(reader, "asxe")); }

Target:
public void testPostingsNonExistings() throws Exception { Directory dir = FSDirectory.open(tempDir1); IndexReader reader = DirectoryReader.open(dir); assertNull(IndexReaderUtils.getPostingsList(reader, "asxe")); }
Source:
public void virtLimitFromFirstVirtLimitEntBatch() { stackedEnts.clear(); Entitlement e1 = createEntFromPool(pool1); e1.setQuantity(4); stackedEnts.add(e1); Entitlement e2 = createEntFromPool(pool4); e2.setQuantity(16); stackedEnts.add(e2); Class<Set<String>> listClass = (Class<Set<String>>) (Class) HashSet.class; ArgumentCaptor<Set<String>> arg = ArgumentCaptor.forClass(listClass); when(entCurMock.findByStackIds(eq(consumer), arg.capture())).thenReturn(stackedEnts); List<PoolUpdate> updates = poolRules.updatePoolsFromStack(consumer, Arrays.asList(stackDerivedPool, stackDerivedPool2), false); Set<String> stackIds = arg.getValue(); assertEquals(2, stackIds.size()); assertTrue(stackIds.contains(STACK)); assertTrue(stackIds.contains(STACK + "3")); for (PoolUpdate update : updates) { assertTrue(update.changed()); assertTrue(update.getQuantityChanged()); } assertEquals((Long) 2L, stackDerivedPool.getQuantity()); assertEquals((Long) 9L, stackDerivedPool2.getQuantity()); }

Target:
public void virtLimitFromFirstVirtLimitEntBatch() { stackedEnts.clear(); Entitlement e1 = createEntFromPool(pool1); e1.setQuantity(4); stackedEnts.add(e1); Entitlement e2 = createEntFromPool(pool4); e2.setQuantity(16); stackedEnts.add(e2); Class<Set<String>> listClass = (Class<Set<String>>) (Class) HashSet.class; ArgumentCaptor<Set<String>> arg = ArgumentCaptor.forClass(listClass); when(entCurMock.findByStackIds(eq(consumer), arg.capture())).thenReturn(stackedEnts); List<PoolUpdate> updates = poolRules.updatePoolsFromStack(consumer, Arrays.asList(stackDerivedPool, stackDerivedPool2), false); Set<String> stackIds = arg.getValue(); assertEquals(2, stackIds.size()); assertThat(stackIds, hasItems(STACK, STACK + "3")); for (PoolUpdate update : updates) { assertTrue(update.changed()); assertTrue(update.getQuantityChanged()); } assertEquals((Long) 2L, stackDerivedPool.getQuantity()); assertEquals((Long) 9L, stackDerivedPool2.getQuantity()); }
Source:
private SshClient getClient() { if (sshClient == null) { sshClient = SshClient.setUpDefaultClient(); sshClient.getProperties().putIfAbsent(FactoryManager.IDLE_TIMEOUT, idleTimeoutMillis); sshClient.getProperties().putIfAbsent(FactoryManager.NIO2_READ_TIMEOUT, readTimeoutMillis); sshClient.setHostConfigEntryResolver(new HostConfigEntryResolver() { @Override public HostConfigEntry resolveEffectiveHost(String host, int port, SocketAddress socketAddress, String username, AttributeRepository attributeRepository) throws IOException { return new HostConfigEntry(host, host, port, username); } }); sshClient.start(); } return sshClient; }

Target:
private SshClient getClient() { if (sshClient == null) { sshClient = SshClient.setUpDefaultClient(); sshClient.getProperties().put(FactoryManager.IDLE_TIMEOUT, idleTimeoutMillis); sshClient.getProperties().put(FactoryManager.NIO2_READ_TIMEOUT, readTimeoutMillis); sshClient.setHostConfigEntryResolver(new HostConfigEntryResolver() { @Override public HostConfigEntry resolveEffectiveHost(String host, int port, SocketAddress socketAddress, String username, AttributeRepository attributeRepository) throws IOException { return new HostConfigEntry(host, host, port, username); } }); sshClient.start(); } return sshClient; }
Source:
protected ActionResult execute() { String thisCourseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertPostParamNotNull(Const.ParamsNames.COURSE_ID, thisCourseId); InstructorAttributes thisInstructor = logic.getInstructorForGoogleId(thisCourseId, account.googleId); gateKeeper.verifyAccessible(thisInstructor, logic.getCourse(thisCourseId), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_INSTRUCTOR); List<InstructorAttributes> copiableInstructors = new ArrayList(); List<CourseAttributes> coursesOfThisInstructor = logic.getCoursesForInstructor(account.googleId); List<InstructorAttributes> existingInstructors = logic.getInstructorsForCourse(thisCourseId); for (CourseAttributes course : coursesOfThisInstructor) { String courseId = course.getId(); if (!courseId.equals(thisCourseId)) { List<InstructorAttributes> instructors = logic.getInstructorsForCourse(courseId); for (InstructorAttributes instructor : instructors) { if (!instructorInThisCourse(instructor, existingInstructors)) { copiableInstructors.add(instructor); } } } } InstructorCourseInstructorCopyPageData data = new InstructorCourseInstructorCopyPageData(account, sessionToken, copiableInstructors); return createShowPageResult(Const.ViewURIs.INSTRUCTOR_COURSE_INSTRUCTOR_COPY_MODAL, data); }

Target:
protected ActionResult execute() { String thisCourseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertPostParamNotNull(Const.ParamsNames.COURSE_ID, thisCourseId); InstructorAttributes thisInstructor = logic.getInstructorForGoogleId(thisCourseId, account.googleId); gateKeeper.verifyAccessible(thisInstructor, logic.getCourse(thisCourseId), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_INSTRUCTOR); List<InstructorAttributes> copiableInstructors = new ArrayList(); List<CourseAttributes> coursesOfThisInstructor = logic.getCoursesForInstructor(account.googleId); List<InstructorAttributes> existingInstructors = logic.getInstructorsForCourse(thisCourseId); for (CourseAttributes course : coursesOfThisInstructor) { String courseId = course.getId(); if (!courseId.equals(thisCourseId)) { List<InstructorAttributes> instructors = logic.getInstructorsForCourse(courseId); instructors.forEach(instructor -> { if (!instructorInThisCourse(instructor, existingInstructors)) { copiableInstructors.add(instructor); } }); } } InstructorCourseInstructorCopyPageData data = new InstructorCourseInstructorCopyPageData(account, sessionToken, copiableInstructors); return createShowPageResult(Const.ViewURIs.INSTRUCTOR_COURSE_INSTRUCTOR_COPY_MODAL, data); }
Source:
protected Warning createWarning(Matcher matcher) { String fileName = matcher.group(2); String lineNumber = matcher.group(3); String category = matcher.group(4); String message = matcher.group(5); return createWarning(fileName, getLineNumber(lineNumber), category, message); }

Target:
protected Warning createWarning(Matcher matcher) { Priority p = matcher.group(1).equals("[ERROR]") ? Priority.HIGH : Priority.NORMAL; String fileName = matcher.group(2); String lineNumber = matcher.group(3); String category = matcher.group(4); String message = matcher.group(5); return createWarning(fileName, getLineNumber(lineNumber), category, message, p); }
Source:
public ODatabaseSession getSession() { orientDB.createIfNotExists(databaseName, ODatabaseType.PLOCAL); if (session == null) { session = orientDB.open(databaseName, username, password); scriptPath.ifPresent(path -> loadScript(path, session)); } return session; }

Target:
public ODatabaseSession getSession() { return getSession(DEFAULT_USERNAME, DEFAULT_PASSWORD); }
Source:
public ProtobufMessages.Timers.Timer serialize(JobContext jobCtx, MarshallerWriteContext outputCtx) { ExpireJobContext ejobCtx = ( ExpireJobContext ) jobCtx; WorkingMemoryReteExpireAction expireAction = ejobCtx.getExpireAction(); DefaultJobHandle jobHandle = ( DefaultJobHandle ) ejobCtx.getJobHandle(); PointInTimeTrigger trigger = ( PointInTimeTrigger ) jobHandle.getTimerJobInstance().getTrigger(); final ExpireTimer.Builder expireTimerBuilder = ProtobufMessages.Timers.ExpireTimer.newBuilder() .setHandleId( expireAction.getFactHandle().getId() ); if (trigger.hasNextFireTime() != null) { expireTimerBuilder.setNextFireTimestamp(trigger.hasNextFireTime().getTime()); } return ProtobufMessages.Timers.Timer.newBuilder() .setType(ProtobufMessages.Timers.TimerType.EXPIRE) .setExpire(expireTimerBuilder.build()) .build(); }

Target:
public ProtobufMessages.Timers.Timer serialize(JobContext jobCtx, MarshallerWriteContext outputCtx) { ExpireJobContext ejobCtx = (ExpireJobContext) jobCtx; WorkingMemoryReteExpireAction expireAction = ejobCtx.getExpireAction(); DefaultJobHandle jobHandle = (DefaultJobHandle) ejobCtx.getJobHandle(); PointInTimeTrigger trigger = (PointInTimeTrigger) jobHandle.getTimerJobInstance().getTrigger(); Date nextFireTime = trigger.hasNextFireTime(); if (nextFireTime != null) { return ProtobufMessages.Timers.Timer.newBuilder() .setType(ProtobufMessages.Timers.TimerType.EXPIRE) .setExpire(ProtobufMessages.Timers.ExpireTimer.newBuilder() .setHandleId(expireAction.getFactHandle().getId()) .setNextFireTimestamp(nextFireTime.getTime()) .build()) .build(); } else { return null; } }
Source:
private boolean loadNewTask(String command) { try { ZNRecord taskConfig = _manager.getHelixDataAccessor().getBaseDataAccessor() .get("/" + _manager.getClusterName() + "/TASK_DEFINITION", null, 0); File taskJar = new File(taskConfig.getSimpleField("JAR_FILE")); URL taskJarUrl = taskJar.toURI().toURL(); URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{taskJarUrl}); for(String taskClass : taskConfig.getListField("TASK_CLASSES")) { classLoader.loadClass(taskClass); } Class cl = classLoader.loadClass(taskConfig.getSimpleField("TASKFACTORY")); _taskFactoryRegistry.put(command, (TaskFactory) cl.newInstance()); } catch (MalformedURLException | ClassNotFoundException | InstantiationException | IllegalAccessException e) { LOG.info("Loading new task " + command + " for instance " + _manager.getInstanceName() + " in cluster " + _manager.getClusterName() + " failed."); return false; } return true; }

Target:
private void loadNewTask(String command) { if (!_manager.getHelixDataAccessor().getBaseDataAccessor() .exists(TaskConstants.DYNAMICALLY_LOADED_TASK_PATH, 0)) { String errorMessage = "Path for dynamic tasks doesn't exist!"; LOG.error(errorMessage); throw new IllegalStateException(errorMessage); } DynamicTaskConfig taskConfig = new DynamicTaskConfig( _manager.getHelixDataAccessor().getBaseDataAccessor() .get(TaskConstants.DYNAMICALLY_LOADED_TASK_PATH + "/" + command, null, ~AccessOption.THROW_EXCEPTION_IFNOTEXIST)); if (taskConfig.getTaskConfigZNRecord() == null) { String errorMessage = "Failed to read ZNRecord for task " + command + " for instance " + _manager .getInstanceName() + " in cluster " + _manager.getClusterName() + "."; LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage); } JarLoader jarLoader = new LocalJarLoader(); URL taskJarUrl = jarLoader.loadJar(taskConfig.getJarFilePath()); URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{taskJarUrl}); for (String taskClass : taskConfig.getTaskClassesFqns()) { loadClass(classLoader, taskClass); } TaskFactory taskFactory; try { taskFactory = (TaskFactory) loadClass(classLoader, taskConfig.getTaskFactoryFqn()).newInstance(); } catch (InstantiationException | IllegalAccessException e) { String errorMessage = "Failed to instantiate TaskFactory class for new task in instance " + _manager .getInstanceName() + " in cluster " + _manager.getClusterName() + "."; LOG.error(errorMessage); throw new IllegalStateException(errorMessage); } _taskFactoryRegistry.put(command, taskFactory); }
Source:
public List<Pool> createPools(Subscription sub) { return createPools(sub, new ArrayList<Pool>()); }

Target:
public List<Pool> createPools(Subscription sub) { return createPools(sub, new LinkedList<Pool>()); }
Source:
protected Comparator getItemsComparator() { return (Comparator<RepositoryCommit>) (RepositoryCommit o1, RepositoryCommit o2) -> { int compare = o1.getRepositoryName().compareToIgnoreCase( o2.getRepositoryName()); if (compare == 0) compare = o1.getRevCommit().compareTo(o2.getRevCommit()); return compare; }; }

Target:
protected Comparator getItemsComparator() { return new Comparator<RepositoryCommit>() { @Override public int compare(RepositoryCommit o1, RepositoryCommit o2) { int compare = o1.getRepositoryName().compareToIgnoreCase( o2.getRepositoryName()); if (compare == 0) compare = o1.getRevCommit().compareTo(o2.getRevCommit()); return compare; } }; }
Source:
public void healtCheckRequestTest() throws ExecutionException, InterruptedException, JSONException, IOException { FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/healthCheck", Unpooled.buffer(0)); Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get(); HttpResponse response = (HttpResponse) responseParts.poll(); assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus()); assertEquals("Unexpected no of parts ", 1, responseParts.size()); HttpContent actualLastContent = (HttpContent) responseParts.poll(); assertTrue("Last Http Content expected", actualLastContent instanceof LastHttpContent); assertEquals("GET content does not match original content", "GOOD", RestTestUtils.getContentString(actualLastContent)); }

Target:
public void healtCheckRequestTest() throws ExecutionException, InterruptedException, IOException { FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/healthCheck", Unpooled.buffer(0)); Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get(); HttpResponse response = (HttpResponse) responseParts.poll(); assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus()); ByteBuffer content = getContent(response, responseParts); assertEquals("GET content does not match original content", "GOOD", new String(content.array())); }
Source:
public void parse() { final File destination = new File(Directories.getCachePath() + File.separator + fileName); final URL overrideDownload = Context.getInstance().getServerProviderInfo().getRandoms(); if (overrideDownload == null) { throw new NullPointerException("randoms() URL is null - expected to default to BDN URL!"); } Core.verbose(String.format("[%s] Destination: %s | dl: %s", getClass().getName(), destination, overrideDownload)); if (!destination.exists() || !destination.canRead()) { Core.verbose(String.format("[%s] Missing %s - downloading from %s...", PublicRandoms.class.getSimpleName(), destination.getAbsolutePath(), overrideDownload)); download(destination, overrideDownload); } try { URL url = destination.toURI().toURL(); URL[] urls = new URL[]{ url }; String server = Context.getInstance().getServerProviderInfo().getServerName(); URLClassLoader child = new URLClassLoader(urls, this.getClass().getClassLoader()); Class<?> classToLoad = Class.forName("org.parabot.randoms.Core", true, child); Method method = classToLoad.getDeclaredMethod("init", String.class); Object instance = classToLoad.newInstance(); Core.verbose(String.format("[%s] %s %s", PublicRandoms.class.getSimpleName(), "Initing core Randoms for", server)); method.invoke(instance, server); Core.verbose("Successfully parsed public random!"); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | MalformedURLException e) { e.printStackTrace(); Core.verbose("Failed to parse random..."); } }

Target:
public void parse() { final File destination = new File(Directories.getCachePath() + File.separator + fileName); final URL overrideDownload = Context.getInstance().getServerProviderInfo().getRandoms(); if (overrideDownload == null) { throw new NullPointerException("Unable to grab URL for Randoms jar. Default URL for BDN randoms must have changed!"); } Core.verbose(String.format("[%s] Destination: %s | dl: %s", getClass().getSimpleName(), destination, overrideDownload)); if (!destination.exists() || !destination.canRead()) { Core.verbose(String.format("[%s] Missing %s - downloading from %s...", getClass().getSimpleName(), destination.getAbsolutePath(), overrideDownload)); download(destination, overrideDownload); } try { URL url = destination.toURI().toURL(); URL[] urls = new URL[]{ url }; String server = Context.getInstance().getServerProviderInfo().getServerName(); URLClassLoader child = new URLClassLoader(urls, this.getClass().getClassLoader()); Class<?> classToLoad = Class.forName("org.parabot.randoms.Core", true, child); Method method = classToLoad.getDeclaredMethod("init", String.class); Object instance = classToLoad.newInstance(); Core.verbose(String.format("[%s] %s %s", getClass().getSimpleName(), "Initing core Randoms for", server)); method.invoke(instance, server); Core.verbose("Successfully parsed public random!"); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | MalformedURLException e) { e.printStackTrace(); Core.verbose("Failed to parse random..."); } }
Source:
protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperation operation = null; operation = new GetRemoteSharesForFileOperation(mPath, false, false); RemoteOperationResult result = ((GetRemoteSharesForFileOperation)operation).execute(client); if (result.isSuccess()) { if (result.getData().size() > 0) { OCShare share = (OCShare) result.getData().get(0); share.setShareLink(client.getBaseUri() + SHARING_LINK_TOKEN + share.getToken()); Log_OC.d(TAG, "Build Share link= " + share.getShareLink()); updateData(share); } else { operation = new CreateRemoteShareOperation(mPath, mShareType, mShareWith, mPublicUpload, mPassword, mPermissions); result = ((CreateRemoteShareOperation)operation).execute(client); if (result.isSuccess()) { if (result.getData().size() > 0) { OCShare share = (OCShare) result.getData().get(0); updateData(share); } } } } return result; }

Target:
protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperation operation = null; operation = new GetRemoteSharesForFileOperation(mPath, false, false); RemoteOperationResult result = ((GetRemoteSharesForFileOperation)operation).execute(client); if (!result.isSuccess() || result.getData().size() <= 0) { operation = new CreateRemoteShareOperation(mPath, mShareType, mShareWith, mPublicUpload, mPassword, mPermissions); result = ((CreateRemoteShareOperation)operation).execute(client); } if (result.isSuccess()) { if (result.getData().size() > 0) { OCShare share = (OCShare) result.getData().get(0); updateData(share); } } return result; }
Source:
public void setOpenStackAgentProperties(OpenstackNetworkProviderProperties properties) { _openStackAgentProperties = properties; if (_openStackAgentProperties != null) { _customizationConditions.add(CustomizationCondition.NEUTRON_SETUP); if (OpenstackNetworkPluginType.LINUX_BRIDGE.name().equals(_openStackAgentProperties.getPluginType())) { _customizationConditions.add(CustomizationCondition.NEUTRON_LINUX_BRIDGE_SETUP); } else if (OpenstackNetworkPluginType.OPEN_VSWITCH.name().equals(_openStackAgentProperties.getPluginType())) { _customizationConditions.add(CustomizationCondition.NEUTRON_OPEN_VSWITCH_SETUP); } } }

Target:
public void setOpenStackAgentProperties(OpenstackNetworkProviderProperties properties) { _openStackAgentProperties = properties; if (_openStackAgentProperties != null) { _customizationConditions.add(CustomizationCondition.NEUTRON_SETUP); if (_openStackAgentProperties.isLinuxBridge()) { _customizationConditions.add(CustomizationCondition.NEUTRON_LINUX_BRIDGE_SETUP); } else if (_openStackAgentProperties.isOpenVSwitch()) { _customizationConditions.add(CustomizationCondition.NEUTRON_OPEN_VSWITCH_SETUP); } } }
Source:
private static boolean isWeakCipherSuite(final String cipherSuite) { for (final String weakAlgorithm : WEAK_ALGORITHMS) { if (cipherSuite.contains(weakAlgorithm)) { return true; } } return false; }

Target:
static boolean isWeakCipherSuite(final String cipherSuite) { for (final Pattern pattern : WEAK_CIPHER_SUITE_PATTERNS) { if (pattern.matcher(cipherSuite).matches()) { return true; } } return false; }
Source:
public boolean isArray() { return descriptor.endsWith("[]"); }

Target:
public boolean isArray() { return isArray; }
Source:
private void rehash() { int newCapacity = capacity * 2; long[] newKeys = new long[newCapacity]; V[] newValues = (V[]) new Object[newCapacity]; for (int i = 0; i < keys.length; i++) { long storedKey = keys[i]; V storedValue = values[i]; if (storedValue != EmptyValue && storedValue != DeletedValue) { insertKeyValueNoLock(newKeys, newValues, storedKey, storedValue); } } keys = newKeys; values = newValues; usedBuckets = size; capacity = newCapacity; resizeThreshold = (int) (capacity * MapFillFactor); }

Target:
private void rehash() { int newCapacity = capacity * 2; long[] newKeys = new long[newCapacity]; V[] newValues = (V[]) new Object[newCapacity]; for (int i = 0; i < keys.length; i++) { long storedKey = keys[i]; V storedValue = values[i]; if (storedValue != EmptyValue && storedValue != DeletedValue) { insertKeyValueNoLock(newKeys, newValues, storedKey, storedValue); } } keys = newKeys; values = newValues; usedBuckets = size; capacityUpdater.lazySet(this, newCapacity); resizeThreshold = (int) (newCapacity * MapFillFactor); }
Source:
public Flux<Aggregation> aggregate(HttpHeaders headers, SearchRequest searchRequest) { return sendRequest(searchRequest, requestCreator.search(), SearchResponse.class, headers) .map(SearchResponse::getAggregations) .flatMap(Flux::fromIterable); }

Target:
public Flux<Aggregation> aggregate(HttpHeaders headers, SearchRequest searchRequest) { Assert.notNull(headers, "headers must not be null"); Assert.notNull(searchRequest, "searchRequest must not be null"); searchRequest.source().size(0); return sendRequest(searchRequest, requestCreator.search(), SearchResponse.class, headers) .map(SearchResponse::getAggregations) .flatMap(Flux::fromIterable); }
Source:
public void startPlugins() { for (PluginWrapper pluginWrapper : resolvedPlugins) { PluginState pluginState = pluginWrapper.getPluginState(); if ((PluginState.DISABLED != pluginState) && (PluginState.STARTED != pluginState)) { try { log.info("Start plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor())); pluginWrapper.getPlugin().start(); pluginWrapper.setPluginState(PluginState.STARTED); startedPlugins.add(pluginWrapper); firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState)); } catch (Exception e) { pluginWrapper.setPluginState(PluginState.FAILED); log.error(e.getMessage(), e); } } } }

Target:
public void startPlugins() { for (PluginWrapper pluginWrapper : resolvedPlugins) { PluginState pluginState = pluginWrapper.getPluginState(); if ((PluginState.DISABLED != pluginState) && (PluginState.STARTED != pluginState)) { try { log.info("Start plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor())); pluginWrapper.getPlugin().start(); pluginWrapper.setPluginState(PluginState.STARTED); pluginWrapper.setFailedException(null); startedPlugins.add(pluginWrapper); } catch (Exception e) { pluginWrapper.setPluginState(PluginState.FAILED); pluginWrapper.setFailedException(e); log.error(e.getMessage(), e); } finally { firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState)); } } } }
Source:
public void constructorValidValues() { final List<BinaryData> binaryDataList = Collections.singletonList(DATA_BYTES); AmqpDataBody actual = new AmqpDataBody(binaryDataList); assertEquals(AmqpBodyType.DATA, actual.getBodyType()); List<BinaryData> dataList = actual.getData().stream().collect(Collectors.toList()); assertEquals(binaryDataList.size(), dataList.size()); byte[] actualData = dataList.get(0).getData(); assertArrayEquals(CONTENTS_BYTES, actualData); }

Target:
public void constructorValidValues() { final List<BinaryData> expectedDataList = new ArrayList<>(); expectedDataList.add(new BinaryData("some data 1".getBytes())); expectedDataList.add(new BinaryData("some data 2".getBytes())); final AmqpDataBody actual = new AmqpDataBody(expectedDataList); assertEquals(AmqpBodyType.DATA, actual.getBodyType()); final List<BinaryData> dataList = actual.getData().stream().collect(Collectors.toList()); assertEquals(expectedDataList.size(), dataList.size()); assertArrayEquals(expectedDataList.toArray(), dataList.toArray()); }
Source:
public void persistContent() { try { String stringContent = getStringContent(); stringContent = stringContent.replaceAll("\n", ""); Matcher topInstructions = orderListPattern.matcher(stringContent); if (topInstructions.find()) { stringContent = stringContent.substring(topInstructions.start()); } else { results.error("OrderList tag no longer exists and instructions cannot be removed"); } Matcher editMatch = editPattern.matcher(stringContent); while (editMatch.find()) { String editedList = stringContent.substring(editMatch.start() + 1, editMatch.end() - 1); String guidList = getGuidList(editedList); stringContent = stringContent.replaceAll(editedList, guidList); editMatch = editPattern.matcher(stringContent); } checkValidXML(stringContent); if (results.isErrors()) { throw new OseeCoreException(results.toString()); } else { attributeConflict.setAttributeValue(stringContent); } } catch (OseeCoreException ex) { OseeLog.log(RelationOrderCompareItem.class, OseeLevel.SEVERE_POPUP, ex); } }

Target:
public void persistContent() { try { String stringContent = getStringContent(); stringContent = stringContent.replaceAll("\n", ""); Matcher topInstructions = orderListPattern.matcher(stringContent); if (topInstructions.find()) { stringContent = stringContent.substring(topInstructions.start()); } else { results.errorf("OrderList tag no longer exists and instructions cannot be removed"); } Matcher editMatch = editPattern.matcher(stringContent); while (editMatch.find()) { String editedList = stringContent.substring(editMatch.start() + 1, editMatch.end() - 1); String guidList = getGuidList(editedList); stringContent = stringContent.replaceAll(editedList, guidList); editMatch = editPattern.matcher(stringContent); } checkValidXML(stringContent); if (results.isErrors()) { XResultDataUI.report(results, "Relation Order Errors"); } else { attributeConflict.setAttributeValue(stringContent); } } catch (OseeCoreException ex) { OseeLog.log(RelationOrderCompareItem.class, OseeLevel.SEVERE_POPUP, ex); } }