auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void synchronizeGroups() { ParkingPositionPlugin plugin = OsmandPlugin.getEnabledPlugin(ParkingPositionPlugin.class); boolean parkingPluginEnable = plugin != null; favoriteGroups.clear(); groups.clear(); List<FavoriteGroup> disablesGroups = new ArrayList<>(); List<FavoriteGroup> gs = helper.getFavoriteGroups(); Set<?> flt = filter; for (FavoriteGroup key : gs) { boolean empty = true; if (flt == null || flt.contains(key)) { if (key.name.equals(PersonalFavouritePoint.PERSONAL)) { ArrayList<FavouritePoint> list = new ArrayList<>(); for (FavouritePoint p : key.points) { if (p.getName().equals(PersonalFavouritePoint.PointType.PARKING.name())) { if (parkingPluginEnable) { list.add(p); empty = false; } } else { list.add(p); empty = false; } } favoriteGroups.put(key, list); } else { empty = false; favoriteGroups.put(key, new ArrayList<>(key.points)); } } else { ArrayList<FavouritePoint> list = new ArrayList<>(); for (FavouritePoint p : key.points) { if (flt.contains(p)) { if (p.getName().equals(PersonalFavouritePoint.PointType.PARKING.name())) { if (parkingPluginEnable) { list.add(p); empty = false; } } else { list.add(p); empty = false; } } } favoriteGroups.put(key, list); } if (!empty) { if (key.visible) { groups.add(key); } else { disablesGroups.add(key); } } } groups.addAll(disablesGroups); notifyDataSetChanged(); }

Target:
void synchronizeGroups() { favoriteGroups.clear(); groups.clear(); List<FavoriteGroup> disablesGroups = new ArrayList<>(); List<FavoriteGroup> gs = helper.getFavoriteGroups(); Set<?> flt = filter; for (FavoriteGroup key : gs) { boolean empty = true; if (flt == null || flt.contains(key)) { empty = false; favoriteGroups.put(key, new ArrayList<>(key.points)); } else { ArrayList<FavouritePoint> list = new ArrayList<>(); for (FavouritePoint p : key.points) { if (flt.contains(p)) { list.add(p); empty = false; } } favoriteGroups.put(key, list); } if (!empty) { if (key.visible) { groups.add(key); } else { disablesGroups.add(key); } } } groups.addAll(disablesGroups); notifyDataSetChanged(); }
Source:
public static void deleteRecursive(@NonNull File fileOrDirectory, @NonNull List<String> exceptions) { if (exceptions.size() > 0 && exceptions.contains(fileOrDirectory.getName())) return; if (fileOrDirectory.isDirectory()) { File[] filesList = fileOrDirectory.listFiles(); if (filesList != null) { for (File child : filesList) { deleteRecursive(child, exceptions); } } } fileOrDirectory.delete(); }

Target:
public static void deleteRecursive(@NonNull File fileOrDirectory, @NonNull List<String> exceptions) { if (exceptions.contains(fileOrDirectory.getName())) return; if (fileOrDirectory.isDirectory()) { File[] filesList = fileOrDirectory.listFiles(); if (filesList != null) { for (File child : filesList) { deleteRecursive(child, exceptions); } } } fileOrDirectory.delete(); }
Source:
private void layoutPageTitle(final int fontSizeSp, final OnLeadImageLayoutListener listener, final int sequence) { if (!isFragmentAdded()) { return; } pageTitleText.setLayoutDirection(isLangRTL(parentFragment.getTitle().getSite().getLanguageCode()) ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR); pageTitleText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp); if (pageTitleText.getHeight() == 0) { final int postDelay = 50; pageTitleText.postDelayed(new Runnable() { @Override public void run() { layoutPageTitle(fontSizeSp, listener, sequence); } }, postDelay); } else { pageTitleText.post(new Runnable() { @Override public void run() { if (!isFragmentAdded()) { return; } if (((int) (pageTitleText.getHeight() / displayDensity) > TITLE_MAX_HEIGHT_DP) && (fontSizeSp > TITLE_MIN_TEXT_SIZE_SP)) { int newSize = fontSizeSp - TITLE_TEXT_SIZE_DECREMENT_SP; if (newSize < TITLE_MIN_TEXT_SIZE_SP) { newSize = TITLE_MIN_TEXT_SIZE_SP; } layoutPageTitle(newSize, listener, sequence); } else { layoutViews(listener, sequence); } } }); } }

Target:
private void layoutPageTitle(final int fontSizeSp, final OnLeadImageLayoutListener listener, final int sequence) { if (!isFragmentAdded()) { return; } setLayoutDirection(pageTitleText, parentFragment.getTitle().getSite().getLanguageCode()); pageTitleText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp); if (pageTitleText.getHeight() == 0) { final int postDelay = 50; pageTitleText.postDelayed(new Runnable() { @Override public void run() { layoutPageTitle(fontSizeSp, listener, sequence); } }, postDelay); } else { pageTitleText.post(new Runnable() { @Override public void run() { if (!isFragmentAdded()) { return; } if (((int) (pageTitleText.getHeight() / displayDensity) > TITLE_MAX_HEIGHT_DP) && (fontSizeSp > TITLE_MIN_TEXT_SIZE_SP)) { int newSize = fontSizeSp - TITLE_TEXT_SIZE_DECREMENT_SP; if (newSize < TITLE_MIN_TEXT_SIZE_SP) { newSize = TITLE_MIN_TEXT_SIZE_SP; } layoutPageTitle(newSize, listener, sequence); } else { layoutViews(listener, sequence); } } }); } }
Source:
public void onLocationPermissionsGranted() { googleMap.setMyLocationEnabled(myLocationEnabled); }

Target:
@Override public void onLocationPermissionsGranted() { googleMap.setMyLocationEnabled(myLocationEnabled); }
Source:
protected void doTest(Location loc) throws Exception { RedisStore redis = app.createAndManageChild(EntitySpec.create(RedisStore.class)); app.start(ImmutableList.of(loc)); EntityTestUtils.assertAttributeEqualsEventually(redis, RedisStore.SERVICE_UP, true); JedisSupport support = new JedisSupport(redis); try { support.redisTest(); } finally { redis.stop(); } EntityTestUtils.assertPredicateEventuallyTrue(redis, new Predicate<RedisStore>() { @Override public boolean apply(@Nullable RedisStore input) { return input != null && input.getAttribute(RedisStore.UPTIME) > 0; } }); }

Target:
protected void doTest(Location loc) throws Exception { RedisStore redis = app.createAndManageChild(EntitySpec.create(RedisStore.class)); app.start(ImmutableList.of(loc)); EntityTestUtils.assertAttributeEqualsEventually(redis, RedisStore.SERVICE_UP, true); JedisSupport support = new JedisSupport(redis); support.redisTest(); EntityTestUtils.assertPredicateEventuallyTrue(redis, new Predicate<RedisStore>() { @Override public boolean apply(@Nullable RedisStore input) { return input != null && input.getAttribute(RedisStore.UPTIME) > 0 && input.getAttribute(RedisStore.TOTAL_COMMANDS_PROCESSED) >= 0 && input.getAttribute(RedisStore.TOTAL_CONNECTIONS_RECEIVED) >= 0 && input.getAttribute(RedisStore.EXPIRED_KEYS) >= 0 && input.getAttribute(RedisStore.EVICTED_KEYS) >= 0 && input.getAttribute(RedisStore.KEYSPACE_HITS) >= 0 && input.getAttribute(RedisStore.KEYSPACE_MISSES) >= 0; } }); }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("jtx{").append(propagationBehavior.toString()).append(',') .append(readOnlyMode ? "readonly" : "readwrite").append(',') .append(isolationLevel.toString()).append(',').append(timeout) .append('}'); return sb.toString(); }

Target:
public String toString() { return new StringBuilder().append("jtx{").append(propagationBehavior) .append(',').append(readOnlyMode ? "readonly" : "readwrite") .append(',').append(isolationLevel.toString()).append(',') .append(timeout).append('}').toString(); }
Source:
public int getUserIdOrThrow() { Preconditions.checkState( !userRole.equals(UserRole.ANONYMOUS), "Anonymous user is expected to have a null user id, " + "it is the only case expected where user id would be null"); return Optional.ofNullable(userId) .orElseThrow(() -> new AssertionError("Expected to have a non-null user id")); }

Target:
public int getUserIdOrThrow() { Preconditions.checkState( !userRole.equals(UserRole.ANONYMOUS), "Anonymous users always have a null user id"); return Optional.ofNullable(userId) .orElseThrow(() -> new AssertionError("Error, expected to have a non-null user id")); }
Source:
private void deleteConflictBatch(DeleteConflictList theDcl, IFhirResourceDao<IBaseResource> theDao) { DeleteConflictList newBatch = new DeleteConflictList(); for (DeleteConflict next : theDcl) { IdDt nextSource = next.getSourceId(); ourLog.info("Have delete conflict - Cascading delete", next); theDao.delete(nextSource.toVersionless(), newBatch, null, null); } theDcl.removeIf(x -> true); theDcl.addAll(newBatch); }

Target:
private void deleteConflictBatch(DeleteConflictList theDcl, IFhirResourceDao<IBaseResource> theDao) { DeleteConflictList newBatch = new DeleteConflictList(); for (DeleteConflict next : theDcl) { IdDt nextSource = next.getSourceId(); ourLog.info("Have delete conflict - Cascading delete", nextSource); theDao.delete(nextSource.toVersionless(), newBatch, null, null); } theDcl.removeAll(); theDcl.addAll(newBatch); }
Source:
private void initItems() { listModelCollection = new ObservableCollection<SearchableListModel>(); dataCenterList = new DataCenterListModel(); listModelCollection.add(dataCenterList); clusterList = new ClusterListModel(); listModelCollection.add(clusterList); hostList = new HostListModel(); listModelCollection.add(hostList); storageList = new StorageListModel(); listModelCollection.add(storageList); vmList = new VmListModel(); listModelCollection.add(vmList); poolList = new PoolListModel(); listModelCollection.add(poolList); templateList = new TemplateListModel(); listModelCollection.add(templateList); eventList = new EventListModel(); listModelCollection.add(eventList); quotaList = new QuotaListModel(); listModelCollection.add(quotaList); volumeList = new VolumeListModel(); listModelCollection.add(volumeList); diskList = new DiskListModel(); listModelCollection.add(diskList); userList = new UserListModel(); listModelCollection.add(userList); reportsList = new ReportsListModel(ReportInit.getInstance().getReportBaseUrl()); listModelCollection.add(reportsList); reportsList.setIsAvailable(false); networkList = new NetworkListModel(); listModelCollection.add(networkList); providerList = new ProviderListModel(); listModelCollection.add(providerList); profileList = new VnicProfileListModel(); listModelCollection.add(profileList); setItems(listModelCollection); roleListModel = new RoleListModel(); systemPermissionListModel = new SystemPermissionListModel(); clusterPolicyListModel = new ClusterPolicyListModel(); setSelectedItem(getDefaultItem()); }

Target:
private void initItems() { ObservableCollection<SearchableListModel> listModelCollection = new ObservableCollection<SearchableListModel>(); dataCenterList = new DataCenterListModel(); listModelCollection.add(dataCenterList); clusterList = new ClusterListModel(); listModelCollection.add(clusterList); hostList = new HostListModel(); listModelCollection.add(hostList); storageList = new StorageListModel(); listModelCollection.add(storageList); vmList = new VmListModel(); listModelCollection.add(vmList); poolList = new PoolListModel(); listModelCollection.add(poolList); templateList = new TemplateListModel(); listModelCollection.add(templateList); eventList = new EventListModel(); listModelCollection.add(eventList); quotaList = new QuotaListModel(); listModelCollection.add(quotaList); volumeList = new VolumeListModel(); listModelCollection.add(volumeList); diskList = new DiskListModel(); listModelCollection.add(diskList); userList = new UserListModel(); listModelCollection.add(userList); reportsList = new ReportsListModel(ReportInit.getInstance().getReportBaseUrl()); listModelCollection.add(reportsList); reportsList.setIsAvailable(false); networkList = new NetworkListModel(); listModelCollection.add(networkList); providerList = new ProviderListModel(); listModelCollection.add(providerList); profileList = new VnicProfileListModel(); listModelCollection.add(profileList); setItems(listModelCollection); roleListModel = new RoleListModel(); systemPermissionListModel = new SystemPermissionListModel(); clusterPolicyListModel = new ClusterPolicyListModel(); setSelectedItem(getDefaultItem()); }
Source:
public int compareValueTo( ZonedTimeSchemaKey other ) { int compare = Long.compare( nanosOfDayUTC, other.nanosOfDayUTC ); if ( compare == 0 ) { compare = Integer.compare( zoneOffsetSeconds, other.zoneOffsetSeconds ); } return compare; }

Target:
public int compareValueTo( ZonedTimeSchemaKey other ) { int compare = Long.compare( nanosOfDayUTC, other.nanosOfDayUTC ); if ( compare == 0 && differentValidZoneOffset( other ) ) { compare = Values.COMPARATOR.compare( asValue(), other.asValue() ); } return compare; }
Source:
public Iterable<Directive> process(final XML xml) throws IOException { final XML req = xml.nodes("/talk/request").get(0); final Issue.Smart issue = new TalkIssues(this.github, xml).get(); final boolean success = Boolean.parseBoolean( req.xpath("success/text()").get(0) ); final URI home = new Home(xml).uri(); final String pattern; if (success) { pattern = "Reports.success"; } else { pattern = "Reports.failure"; } final StringBuilder msg = new StringBuilder( Logger.format( Reports.PHRASES.getString(pattern), home.toASCIIString(), Long.parseLong(req.xpath("msec/text()").get(0)) ) ).append(Reports.highlights(req)); if (!success) { msg.append(Reports.tail(req)); } final int number = Integer.parseInt(req.xpath("@id").get(0)); final Comment.Smart comment = Reports.origin(issue, number); final String message; if (comment.body().contains("stop")) { message = String.format( Reports.PHRASES.getString("Reports.stop-fails"), msg.toString() ); } else { message = msg.toString(); } new Answer(comment).post(success, message); Logger.info(this, "issue #%d reported: %B", issue.number(), success); return new Directives() .xpath("/talk/request[success]") .strict(1).remove(); }

Target:
public Iterable<Directive> process(final XML xml) throws IOException { final XML req = xml.nodes("/talk/request").get(0); final Issue.Smart issue = new TalkIssues(this.github, xml).get(); final boolean success = Boolean.parseBoolean( req.xpath("success/text()").get(0) ); final URI home = new Home(xml).uri(); final String pattern; if (success) { pattern = "Reports.success"; } else { pattern = "Reports.failure"; } final int number = Integer.parseInt(req.xpath("@id").get(0)); final Comment.Smart comment = Reports.origin(issue, number); final StringBuilder message = new StringBuilder(); if (comment.body().contains("stop")) { message.append(Reports.PHRASES.getString("Reports.stop-fails")) .append(' '); } message.append( Logger.format( Reports.PHRASES.getString(pattern), home.toASCIIString(), Long.parseLong(req.xpath("msec/text()").get(0)) ) ).append(Reports.highlights(req)); if (!success) { message.append(Reports.tail(req)); } new Answer(comment).post(success, message.toString()); Logger.info(this, "issue #%d reported: %B", issue.number(), success); return new Directives() .xpath("/talk/request[success]") .strict(1).remove(); }
Source:
public SearchLatencyListener(Settings settings) { super(settings); statBuckets = new HashMap<>(); lock = new ReentrantReadWriteLock(); scheduledProcedure = new ScheduledProcedure(this::rotate, Scheduler.newFixedDelaySchedule(ROTATION_DELAY.millis(), ROTATION_DELAY.millis(), TimeUnit.MILLISECONDS)); }

Target:
public SearchLatencyListener(Settings settings) { super(settings); statBuckets = new ConcurrentHashMap<>(); scheduledProcedure = new ScheduledProcedure(this::rotate, Scheduler.newFixedRateSchedule(ROTATION_DELAY.millis(), ROTATION_DELAY.millis(), TimeUnit.MILLISECONDS)); }
Source:
public Tags tags() { return new RtTags(this.entry, this.entry, this.owner); }

Target:
public Tags tags() { return new RtTags(this.entry, this.owner); }
Source:
private Map mapAttributes(Map<String, Object> persistentItem) { Object srcs = persistentItem.getOrDefault("src_txt", Collections.emptySet()); if (srcs instanceof String) { srcs = ImmutableSet.of((String) srcs); } Object metacardIds = persistentItem.getOrDefault("metacardIds_txt", Collections.emptySet()); if (metacardIds instanceof String) { metacardIds = ImmutableSet.of((String) metacardIds); } return new ImmutableMap.Builder<String, Object>() .put("id", persistentItem.get("id_txt")) .put("src", srcs) .put("metacardIds", metacardIds) .put("queryId", persistentItem.getOrDefault("queryId_txt", "")) .put("serverGenerated", persistentItem.getOrDefault("serverGenerated_txt", "true")) .put( "when", persistentItem.getOrDefault("when_lng", DateTime.now().toInstant().getMillis())) .build(); }

Target:
private Map<String, Object> mapAttributes(Map<String, Object> persistentItem) { persistentItem = PersistentItem.stripSuffixes(persistentItem); Object srcs = persistentItem.getOrDefault("src", Collections.emptySet()); if (srcs instanceof String) { srcs = ImmutableSet.of((String) srcs); } Object metacardIds = persistentItem.getOrDefault("metacardIds", Collections.emptySet()); if (metacardIds instanceof String) { metacardIds = ImmutableSet.of((String) metacardIds); } return new ImmutableMap.Builder<String, Object>() .put("id", persistentItem.get("id")) .put("src", srcs) .put("metacardIds", metacardIds) .put("queryId", persistentItem.getOrDefault("queryId", "")) .put("serverGenerated", persistentItem.getOrDefault("serverGenerated", "true")) .put("when", persistentItem.getOrDefault("when", DateTime.now().toInstant().getMillis())) .build(); }
Source:
boolean equals(Binary other) { if (value.hasArray()) { return other.equals(value.array(), value.arrayOffset() + offset, length); } byte[] bytes = getBytes(); return other.equals(bytes, 0, bytes.length); }

Target:
boolean equals(Binary other) { if (value.hasArray()) { return other.equals(value.array(), value.arrayOffset() + offset, length); } else { return other.equals(value, offset, length); } }
Source:
public void setSeconds(double seconds) { String str = String.format(Locale.ROOT,"%.6f",seconds); int decimal = str.indexOf('.'); microSeconds = Integer.parseInt(str.substring(decimal + 1)); wholeSeconds = Integer.parseInt(str.substring(0,decimal)); if ( seconds < 0 ) { microSeconds = -microSeconds; } }

Target:
public void setSeconds(double seconds) { wholeSeconds = (int) seconds; microSeconds = (int) Math.round((seconds - wholeSeconds) * MICROS_IN_SECOND); }
Source:
private OMNode readNonXML (URL url) throws IOException { Properties metadata = getMetadata(url.getPath()); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); try (InputStream inputStream = urlConnection.getInputStream()) { if (inputStream == null) { return null; } String mediaType = metadata.getProperty(METADATA_KEY_MEDIA_TYPE, ESBRegistryConstants.DEFAULT_MEDIA_TYPE); if (ESBRegistryConstants.DEFAULT_MEDIA_TYPE.equals(mediaType)) { StringBuilder strBuilder = new StringBuilder(); try (BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = bReader.readLine()) != null) { strBuilder.append(line); } } return OMAbstractFactory.getOMFactory().createOMText(strBuilder.toString()); } else { return OMAbstractFactory.getOMFactory().createOMText( new DataHandler(new SynapseBinaryDataSource(inputStream, mediaType)), true); } } }

Target:
private OMNode readNonXML (URL url) throws IOException { URLConnection urlConnection = url.openConnection(); urlConnection.connect(); try (InputStream inputStream = urlConnection.getInputStream()) { if (inputStream == null) { return null; } Properties metadata = getMetadata(url.getPath()); String mediaType = metadata.getProperty(METADATA_KEY_MEDIA_TYPE, ESBRegistryConstants.DEFAULT_MEDIA_TYPE); if (ESBRegistryConstants.DEFAULT_MEDIA_TYPE.equals(mediaType)) { StringBuilder strBuilder = new StringBuilder(); try (BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = bReader.readLine()) != null) { strBuilder.append(line); } } return OMAbstractFactory.getOMFactory().createOMText(strBuilder.toString()); } else { return OMAbstractFactory.getOMFactory().createOMText( new DataHandler(new SynapseBinaryDataSource(inputStream, mediaType)), true); } } }
Source:
private void beforeActions() { Properties properties = PropertiesUtil.getJttpBuildProperties(); issueCollectorSrc = properties.getProperty(PropertiesUtil.ISSUE_COLLECTOR_SRC); userSettings = settingsHelper.loadUserSettings(); globalSettings = settingsHelper.loadGlobalSettings(); parseDateParam(); boolean dayBack = getHttpRequest().getParameter(Parameter.DAY_BACK) != null; boolean dayNext = getHttpRequest().getParameter(Parameter.DAY_NEXT) != null; boolean today = getHttpRequest().getParameter(Parameter.TODAY) != null; if (dayBack || dayNext || today) { parseDateParamAfterDateSwitcher(dayBack, dayNext, today); } String actionWorklogIdValue = getHttpRequest().getParameter(Parameter.ACTION_WORKLOG_ID); if ((actionWorklogIdValue != null) && !"".equals(actionWorklogIdValue) && !"$actionWorklogId".equals(actionWorklogIdValue)) { actionWorklogId = Long.valueOf(actionWorklogIdValue); } String actionFlagValue = getHttpRequest().getParameter(Parameter.ACTION_FLAG); if (actionFlagValue != null) { actionFlag = actionFlagValue; } parseMessageParam(); showMoveAllNoPermission = Boolean.valueOf(getHttpRequest().getParameter("showMoveAllNoPermission")); }

Target:
private void beforeActions() { Properties properties = PropertiesUtil.getJttpBuildProperties(); issueCollectorSrc = properties.getProperty(PropertiesUtil.ISSUE_COLLECTOR_SRC); userSettings = settingsHelper.loadUserSettings(); globalSettings = settingsHelper.loadGlobalSettings(); parseDateParam(); boolean dayBack = getHttpRequest().getParameter(Parameter.DAY_BACK) != null; boolean dayNext = getHttpRequest().getParameter(Parameter.DAY_NEXT) != null; boolean today = getHttpRequest().getParameter(Parameter.TODAY) != null; if (dayBack || dayNext || today) { parseDateParamAfterDateSwitcher(dayBack, dayNext, today); } String actionWorklogIdValue = getHttpRequest().getParameter(Parameter.ACTION_WORKLOG_ID); if ((actionWorklogIdValue != null) && !"".equals(actionWorklogIdValue) && !"$actionWorklogId".equals(actionWorklogIdValue)) { actionWorklogId = Long.valueOf(actionWorklogIdValue); } String actionFlagValue = getHttpRequest().getParameter(Parameter.ACTION_FLAG); if (actionFlagValue != null) { actionFlag = actionFlagValue; } parseMessageParam(); showMoveAllNoPermission = Boolean.valueOf(getHttpRequest().getParameter(Parameter.IS_SHOW_MOVE_ALL_NO_PERMISSION)); }
Source:
public HashSet<T> addAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); if (isEmpty() && elements instanceof HashSet) { @SuppressWarnings("unchecked") final HashSet<T> set = (HashSet<T>) elements; return set; } if (Collections.isEmpty(elements) || this.equals(elements)){ return this; } else { return new HashSet<>(addAll(tree, elements)); } }

Target:
public HashSet<T> addAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); if (isEmpty() && elements instanceof HashSet) { @SuppressWarnings("unchecked") final HashSet<T> set = (HashSet<T>) elements; return set; } final HashArrayMappedTrie<T, T> that = addAll(tree, elements); if (that.size() == tree.size()) { return this; } else { return new HashSet<>(that); } }
Source:
protected int getSize() { return queue.size(); }

Target:
int getSize() { return queue.size(); }
Source:
void moreSettings() { popup.setOnMenuItemClickListener(item -> { switch (item.getItemId()) { case R.id.toggleBeep: editor = sp.edit(); if (mRing) { mRing = false; item.setChecked(false); editor.putBoolean("ring", false); } else { mRing = true; item.setChecked(true); editor.putBoolean("ring", true); } editor.apply(); break; case R.id.toggleAutofocus: if (barcodeView.getBarcodeView().isPreviewActive()) { barcodeView.pause(); } editor = sp.edit(); CameraSettings settings = barcodeView.getBarcodeView().getCameraSettings(); if (mAutofocus) { mAutofocus = false; settings.setAutoFocusEnabled(false); item.setChecked(false); editor.putBoolean("focus", false); } else { mAutofocus = true; settings.setAutoFocusEnabled(true); item.setChecked(true); editor.putBoolean("focus", true); } barcodeView.getBarcodeView().setCameraSettings(settings); barcodeView.resume(); editor.apply(); break; case R.id.troubleScanning: hideAllViews(); handler.removeCallbacks(runnable); quickView.setOnClickListener(null); searchByBarcode.setText(null); searchByBarcode.setVisibility(View.VISIBLE); quickView.setVisibility(View.INVISIBLE); bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); new Handler().postDelayed(new Runnable() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { quickView.setVisibility(View.VISIBLE); } }); } }, 500); searchByBarcode.requestFocus(); break; case R.id.toggleCamera: toggleCamera(); break; } return true; }); popup.show(); }

Target:
void moreSettings() { popup.setOnMenuItemClickListener(item -> { switch (item.getItemId()) { case R.id.toggleBeep: editor = sp.edit(); if (mRing) { mRing = false; item.setChecked(false); editor.putBoolean("ring", false); } else { mRing = true; item.setChecked(true); editor.putBoolean("ring", true); } editor.apply(); break; case R.id.toggleAutofocus: if (barcodeView.getBarcodeView().isPreviewActive()) { barcodeView.pause(); } editor = sp.edit(); CameraSettings settings = barcodeView.getBarcodeView().getCameraSettings(); if (mAutofocus) { mAutofocus = false; settings.setAutoFocusEnabled(false); item.setChecked(false); editor.putBoolean("focus", false); } else { mAutofocus = true; settings.setAutoFocusEnabled(true); item.setChecked(true); editor.putBoolean("focus", true); } barcodeView.getBarcodeView().setCameraSettings(settings); barcodeView.resume(); editor.apply(); break; case R.id.troubleScanning: hideAllViews(); handler.removeCallbacks(runnable); quickView.setOnClickListener(null); searchByBarcode.setText(null); searchByBarcode.setVisibility(View.VISIBLE); quickView.setVisibility(View.INVISIBLE); bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); new Handler().postDelayed(new Runnable() { @Override public void run() { quickView.setVisibility(View.VISIBLE); } }, 500); searchByBarcode.requestFocus(); break; case R.id.toggleCamera: toggleCamera(); break; } return true; }); popup.show(); }
Source:
public MapEnvironment getEnv() { return env; }

Target:
protected MapEnvironment getEnv() { return env; }
Source:
public Collection<PluginMeta> get(Map<String, String> attributes) throws InfrastructureException { String pluginsAttribute = attributes.getOrDefault(Constants.WORKSPACE_TOOLING_PLUGINS_ATTRIBUTE, null); String editorAttribute = attributes.getOrDefault(Constants.WORKSPACE_TOOLING_EDITOR_ATTRIBUTE, null); if (pluginRegistry == null && (!Strings.isNullOrEmpty(pluginsAttribute) || !Strings.isNullOrEmpty(editorAttribute))) { throw new InfrastructureException(CHE_REGISTRY_MISSING_ERROR); } if (Strings.isNullOrEmpty(editorAttribute) && Strings.isNullOrEmpty(pluginsAttribute)) { return emptyList(); } ArrayList<Pair<String, String>> metasIdsVersions = new ArrayList<>(); if (!isNullOrEmpty(pluginsAttribute)) { String[] plugins = pluginsAttribute.split(" *, *"); if (plugins.length != 0) { Collection<Pair<String, String>> pluginsIdsVersions = parseIdsVersions(plugins); metasIdsVersions.addAll(pluginsIdsVersions); } } if (!isNullOrEmpty(editorAttribute)) { Collection<Pair<String, String>> editorIdVersionCollection = parseIdsVersions(editorAttribute); if (editorIdVersionCollection.size() > 1) { throw new InfrastructureException( "Multiple editors found in workspace config attributes. " + "It is not supported. Please, use one editor only."); } metasIdsVersions.addAll(editorIdVersionCollection); } return getMetas(metasIdsVersions); }

Target:
public Collection<PluginMeta> get(Map<String, String> attributes) throws InfrastructureException { if (attributes == null) { return emptyList(); } String pluginsAttribute = attributes.getOrDefault(Constants.WORKSPACE_TOOLING_PLUGINS_ATTRIBUTE, null); String editorAttribute = attributes.getOrDefault(Constants.WORKSPACE_TOOLING_EDITOR_ATTRIBUTE, null); if (Strings.isNullOrEmpty(editorAttribute) && Strings.isNullOrEmpty(pluginsAttribute)) { return emptyList(); } if (pluginRegistry == null) { throw new InfrastructureException(CHE_REGISTRY_MISSING_ERROR); } ArrayList<Pair<String, String>> metasIdsVersions = new ArrayList<>(); if (!isNullOrEmpty(pluginsAttribute)) { String[] plugins = pluginsAttribute.split(" *, *"); if (plugins.length != 0) { Collection<Pair<String, String>> pluginsIdsVersions = parseIdsVersions(plugins); metasIdsVersions.addAll(pluginsIdsVersions); } } if (!isNullOrEmpty(editorAttribute)) { Collection<Pair<String, String>> editorIdVersionCollection = parseIdsVersions(editorAttribute); if (editorIdVersionCollection.size() > 1) { throw new InfrastructureException( "Multiple editors found in workspace config attributes. " + "It is not supported. Please, use one editor only."); } metasIdsVersions.addAll(editorIdVersionCollection); } return getMetas(metasIdsVersions); }
Source:
public static List<File> getTestInputFilesNoPartial(FilenameFilter filter) { File[] testFiles = getPackagePath().toFile().listFiles(filter); return Lists.newArrayList(testFiles); }

Target:
public static List<File> getTestInputFilesNoPartial(FilenameFilter filter) { File[] testFiles = getPackagePath().toFile().listFiles(filter); return Arrays.asList(testFiles); }
Source:
public @NonNull List<E> subList(int fromIndex, int toIndex) { throw new UnsupportedOperationException("No subList(fromIndex, toIndex) in " + this.getClass().getName()); }

Target:
public @NonNull List<E> subList(int fromIndex, int toIndex) { throw new UnsupportedOperationException("No subList(int, int) in " + this.getClass().getName()); }
Source:
private Diamond3iIterable(Vector3ic origin, int startDistance, int maxDistance) { Preconditions.checkArgument(startDistance < maxDistance, "startDistance must be < maxDistance"); Preconditions.checkArgument(maxDistance >= 0, "maxDistance must be >= 0"); Preconditions.checkArgument(startDistance >= 0, "maxDistance must be >= 0"); this.origin.set(origin); this.endDistance = maxDistance; this.startDistance = startDistance; }

Target:
private Diamond3iIterable(Vector3ic origin, int startDistance, int maxDistance) { Preconditions.checkArgument(startDistance < maxDistance, "startDistance must be < maxDistance"); Preconditions.checkArgument(maxDistance >= 0, "maxDistance must be >= 0"); Preconditions.checkArgument(startDistance >= 0, "startDistance must be >= 0"); this.origin.set(origin); this.endDistance = maxDistance; this.startDistance = startDistance; }
Source:
private boolean isEditorsClean() { for (EditorPartPresenter editorPartPresenter : editorAgentProvider.get().getOpenedEditors()) { if (editorPartPresenter.isDirty()) { return false; } } return true; }

Target:
private boolean isEditorsClean() { return editorAgentProvider .get() .getOpenedEditors() .stream() .noneMatch(EditorPartPresenter::isDirty); }
Source:
public InstructorCourseEditPageData(AccountAttributes account, CourseAttributes course, List<InstructorAttributes> instructorList, InstructorAttributes currentInstructor, int instructorToShowIndex, List<String> sectionNames, List<String> feedbackNames) { super(account); instructorPanelList = new ArrayList<CourseEditInstructorPanel>(); this.course = course; this.instructorToShowIndex = instructorToShowIndex; this.currentInstructor = currentInstructor; createButtons(); createInstructorPanelList(instructorList, sectionNames, feedbackNames); addInstructorPanel = createInstructorPanel(instructorPanelList.size() + 1, null, sectionNames, feedbackNames); }

Target:
public InstructorCourseEditPageData(AccountAttributes account, CourseAttributes course, List<InstructorAttributes> instructorList, InstructorAttributes currentInstructor, int instructorToShowIndex, List<String> sectionNames, List<String> feedbackNames) { super(account); this.course = course; this.instructorToShowIndex = instructorToShowIndex; createButtons(currentInstructor); instructorPanelList = createInstructorPanelList(currentInstructor, instructorList, sectionNames, feedbackNames); addInstructorPanel = createInstructorPanel(currentInstructor, instructorPanelList.size() + 1, null, sectionNames, feedbackNames); }
Source:
private static String getMimeType(String path) { if (path.endsWith(".png")) { return "image/png"; } else if (path.endsWith(".gif")) { return "image/gif"; } else if (path.endsWith(".jpg") || path.endsWith(".jpeg")) { return "image/jpeg"; } return null; }

Target:
private static String getMimeType(String path) { int d = path.lastIndexOf('.'); if (d == -1) { return null; } String ext = path.substring(d + 1); return TYPES.get(ext.toLowerCase()); }
Source:
protected EC2Cloud(String id, boolean useInstanceProfileForCredentials, String credentialsId, String privateKey, String sshKeysCredentialsId, String instanceCapStr, List<? extends SlaveTemplate> templates, String roleArn, String roleSessionName) { super(id); this.useInstanceProfileForCredentials = useInstanceProfileForCredentials; this.roleArn = roleArn; this.roleSessionName = roleSessionName; this.credentialsId = credentialsId; this.sshKeysCredentialsId = sshKeysCredentialsId; if (this.sshKeysCredentialsId == null && privateKey != null){ migratePrivateSshKeyToCredential(privateKey); } if (templates == null) { this.templates = Collections.emptyList(); } else { this.templates = templates; } if (instanceCapStr == null || instanceCapStr.isEmpty()) { this.instanceCap = Integer.MAX_VALUE; } else { this.instanceCap = Integer.parseInt(instanceCapStr); } readResolve(); }

Target:
protected EC2Cloud(String id, boolean useInstanceProfileForCredentials, String credentialsId, String privateKey, String sshKeysCredentialsId, String instanceCapStr, List<? extends SlaveTemplate> templates, String roleArn, String roleSessionName) { super(id); this.useInstanceProfileForCredentials = useInstanceProfileForCredentials; this.roleArn = roleArn; this.roleSessionName = roleSessionName; this.credentialsId = credentialsId; this.sshKeysCredentialsId = sshKeysCredentialsId; if (this.sshKeysCredentialsId == null && ( this.privateKey != null || privateKey != null)){ migratePrivateSshKeyToCredential(this.privateKey != null ? this.privateKey.getPrivateKey() : privateKey); } this.privateKey = null; if (templates == null) { this.templates = Collections.emptyList(); } else { this.templates = templates; } if (instanceCapStr == null || instanceCapStr.isEmpty()) { this.instanceCap = Integer.MAX_VALUE; } else { this.instanceCap = Integer.parseInt(instanceCapStr); } readResolve(); }
Source:
public JsonWebToken currentPrincipal() { Objects.requireNonNull(httpServletRequest, "HTTP Servlet Request is required to produce a JSonWebToken principal."); final Object tokenAttribute = httpServletRequest.getAttribute(JsonWebToken.class.getName()); if (tokenAttribute != null && Function.class.isInstance(tokenAttribute)) { return (JsonWebToken) Function.class.cast(tokenAttribute).apply(httpServletRequest); } return null; }

Target:
public JsonWebToken currentPrincipal() { Objects.requireNonNull(httpServletRequest, "HTTP Servlet Request is required to produce a JSonWebToken principal."); final Object tokenAttribute = httpServletRequest.getAttribute(JsonWebToken.class.getName()); if (Function.class.isInstance(tokenAttribute)) { return (JsonWebToken) Function.class.cast(tokenAttribute).apply(httpServletRequest); } return null; }
Source:
public void currentPlaylistIndexEvent(PlayerEvent event) { percentChangeEvent(event.getPlayerId(), CommandType.CURRTRACK, event.getPlayer().getCurrentPlaylistIndex()); }

Target:
public void currentPlaylistIndexEvent(PlayerEvent event) { numberChangeEvent(event.getPlayerId(), CommandType.CURRTRACK, event.getPlayer().getCurrentPlaylistIndex()); }
Source:
private void goThroughShop() { mainMenu(MAIN_SHOP); shopScreen(SHOP_BACK); }

Target:
private void goThroughShop() { mainMenu(MAIN_SHOP); assertEquals(State.getSkin(), Style.getNoob()); shopScreen(SHOP_LIST); shopScreen(SHOP_LIST); assertNotEquals(State.getSkin(), Style.getNoob()); shopScreen(SHOP_BACK); }
Source:
private Status parseStatusFromResult(String result) { try { JAXBContext context = JAXBContext.newInstance("com.youview.refdata.schemas.youviewstatusreport._2010_12_07"); Unmarshaller unmarshaller = context.createUnmarshaller(); StatusReport report = (StatusReport) unmarshaller.unmarshal(new ByteArrayInputStream(result.getBytes(StandardCharsets.UTF_8))); TransactionReportType txnReport = report.getTransactionReport().get(0); switch (txnReport.getState()) { case ACCEPTED: return Status.ACCEPTED; case COMMITTED: return Status.COMMITTED; case COMMITTING: return Status.COMMITTING; case FAILED: return Status.FAILED; case PUBLISHED: return Status.PUBLISHED; case PUBLISHING: return Status.PUBLISHING; case QUARANTINED: return Status.QUARANTINED; case VALIDATING: return Status.VALIDATING; default: return Status.UNKNOWN; } } catch (JAXBException e) { throw Throwables.propagate(e); } }

Target:
private Status parseStatusFromResult(String result) { try { JAXBContext context = JAXBContext.newInstance("com.youview.refdata.schemas.youviewstatusreport._2010_12_07"); Unmarshaller unmarshaller = context.createUnmarshaller(); StatusReport report = (StatusReport) unmarshaller.unmarshal(new ByteArrayInputStream(result.getBytes(StandardCharsets.UTF_8))); TransactionReportType txnReport = Iterables.getOnlyElement(report.getTransactionReport()); switch (txnReport.getState()) { case ACCEPTED: return Status.ACCEPTED; case COMMITTED: return Status.COMMITTED; case COMMITTING: return Status.COMMITTING; case FAILED: return Status.FAILED; case PUBLISHED: return Status.PUBLISHED; case PUBLISHING: return Status.PUBLISHING; case QUARANTINED: return Status.QUARANTINED; case VALIDATING: return Status.VALIDATING; default: return Status.UNKNOWN; } } catch (JAXBException e) { throw Throwables.propagate(e); } }
Source:
private static void checkTerminateFailures() { synchronized (fTestFailedToTerminate) { while (fTerminateThreadsRunning > 0) { try { fTestFailedToTerminate.wait(500); } catch (InterruptedException e) { } } if (fTestFailedToTerminate.isEmpty() == false) { StringBuffer buffer = new StringBuffer(); for (String failedName : fTestFailedToTerminate) { buffer.append("\nTermination failed for test " + failedName); } fTestFailedToTerminate.clear(); Assert.assertTrue(buffer.toString(), false); } } }

Target:
private static void checkTerminateFailures() { synchronized (fTestFailedToTerminate) { while (fTerminateThreadsRunning > 0) { try { fTestFailedToTerminate.wait(500); } catch (InterruptedException e) { } } if (fTestFailedToTerminate.isEmpty() == false) { StringBuilder buffer = new StringBuilder(); for (String failedName : fTestFailedToTerminate) { buffer.append("\nTermination failed for test " + failedName); } fTestFailedToTerminate.clear(); Assert.assertTrue(buffer.toString(), false); } } }
Source:
public Collection<Object> getAttributeValues(IAtsWorkItem workItem, IAttributeType attributeType) throws OseeCoreException { Set<Object> results = new HashSet<Object>(); Artifact artifact = WorkItemUtil.get(workItem); if (artifact == null) { throw new OseeArgumentException("Can't Find Artifact matching " + workItem.toStringWithId()); } IAttributeType attrType = AttributeTypeManager.getType(attributeType); if (attrType == null) { throw new OseeArgumentException(String.format("Can't resolve Attribute Type [%s]", attributeType)); } else { results.addAll(artifact.getAttributeValues(attributeType)); } return results; }

Target:
public Collection<Object> getAttributeValues(IAtsWorkItem workItem, IAttributeType attributeType) throws OseeCoreException { Artifact artifact = WorkItemUtil.get(workItem); Conditions.checkNotNull(artifact, "workItem", "Can't Find Artifact matching " + workItem.toStringWithId()); IAttributeType attrType = AttributeTypeManager.getType(attributeType); if (attrType == null) { throw new OseeArgumentException(String.format("Can't resolve Attribute Type [%s]", attributeType)); } return artifact.getAttributeValues(attributeType); }
Source:
public void fireEvents(TaskType taskType, long delay, Object entity) throws InterruptedException { final String WaitForLaunch = "WaitForLaunch".intern(); final String PoweringUp = "Powering up".intern(); final String Up = "Up".intern(); final String PoweredDown = "Powering down".intern(); final String Down = "Down".intern(); VM vm = null; Host host = null; StorageDomain storageDomain = null; if (entity instanceof VM){ vm = (VM) entity; } else if (entity instanceof Host){ host = (Host) entity; } else if (entity instanceof StorageDomain){ storageDomain = (StorageDomain) entity; } else { log.error("{} unsupported entity type for events", entity); } switch (taskType){ case START_VM: vmUpdateStatus(vm, VM.VMStatus.WaitForLaunch, delay / 2, WaitForLaunch, false); vmUpdateStatus(vm, VM.VMStatus.PoweringUp, delay / 2, PoweringUp, false); break; case START_VM_AS_UP: vmUpdateStatus(vm, VM.VMStatus.Up, delay, Up, true); break; case SHUTDOWN_VM: vmUpdateStatus(vm, VM.VMStatus.PoweredDown, delay, PoweredDown, false); if (vm != null) { vm.getHost().getRunningVMs().remove(vm.getId()); } vmUpdateStatus(vm, VM.VMStatus.Down, 0, Down, true); break; default: log.error("Unhandled status detected."); break; } }

Target:
public void fireEvents(TaskType taskType, long delay, Object entity) throws InterruptedException { final String WaitForLaunch = "WaitForLaunch".intern(); final String PoweringUp = "Powering up".intern(); final String Up = "Up".intern(); final String PoweredDown = "Powering down".intern(); final String Down = "Down".intern(); VM vm = (VM) entity; switch (taskType){ case START_VM: ExecutorService srv_preUp = getNewService(); vmUpdateStatus(vm, VM.VMStatus.WaitForLaunch, delay, WaitForLaunch, srv_preUp); vmUpdateStatus(vm, VM.VMStatus.PoweringUp, delay, PoweringUp, srv_preUp); break; case START_VM_AS_UP: ExecutorService srv_up = getNewService(); vmUpdateStatus(vm, VM.VMStatus.Up, delay, Up, srv_up); break; case SHUTDOWN_VM: ExecutorService srv_down = getNewService(); vmUpdateStatus(vm, VM.VMStatus.PoweredDown, delay, PoweredDown, srv_down); if (vm != null) { vm.getHost().getRunningVMs().remove(vm.getId()); } vmUpdateStatus(vm, VM.VMStatus.Down, 0, Down, srv_down); break; default: log.error("Unhandled status detected."); break; } }
Source:
public Cursor convert(final NakadiCursor nakadiCursor) { final boolean zeroPaddedOffsets = featureToggleService.isFeatureEnabled(FeatureToggleService.Feature.ZERO_PADDED_OFFSETS); final String offset; if (nakadiCursor.getOffset().equals("-1")) { offset = Cursor.BEFORE_OLDEST_OFFSET; } else { if (zeroPaddedOffsets) { offset = StringUtils.leftPad(nakadiCursor.getOffset(), 18, '0'); } else { offset = nakadiCursor.getOffset(); } } return new Cursor( nakadiCursor.getPartition(), offset); }

Target:
public Cursor convert(final NakadiCursor nakadiCursor) { final boolean zeroPaddedOffsets = featureToggleService.isFeatureEnabled(FeatureToggleService.Feature.ZERO_PADDED_OFFSETS); final String offset; if (nakadiCursor.getOffset().equals("-1")) { offset = Cursor.BEFORE_OLDEST_OFFSET; } else { if (zeroPaddedOffsets) { offset = StringUtils.leftPad(nakadiCursor.getOffset(), CURSOR_OFFSET_LENGTH, '0'); } else { offset = nakadiCursor.getOffset(); } } return new Cursor( nakadiCursor.getPartition(), offset); }
Source:
public long getTimeInMillisSinceEpoch() { return SystemClock.currentThreadTimeMillis(); }

Target:
public long getTimeInMillisSinceEpoch() { Calendar currentTime = Calendar.getInstance(); long offset = currentTime.get(Calendar.ZONE_OFFSET) + currentTime.get(Calendar.DST_OFFSET); return currentTime.getTimeInMillis() + offset; }
Source:
public void testAddItem() { Category category = new Category(new NamespacedKey(plugin, "items_test"), new CustomItem(Material.DIAMOND_AXE, "&6Testing")); SlimefunItem item = SlimefunMocks.mockSlimefunItem(plugin, "CATEGORY_ITEMS_TEST_ITEM", new CustomItem(Material.BAMBOO, "&6Test Bamboo")); item.setCategory(category); item.register(plugin); item.load(); Assertions.assertEquals(1, category.getItems().size()); item.setCategory(category); item.setCategory(category); Assertions.assertEquals(1, category.getItems().size()); Assertions.assertThrows(IllegalArgumentException.class, () -> category.add(null)); Assertions.assertTrue(category.getItems().contains(item)); }

Target:
public void testAddItem() { Category category = new Category(new NamespacedKey(plugin, "items_test"), new CustomItem(Material.DIAMOND_AXE, "&6Testing")); SlimefunItem item = TestUtilities.mockSlimefunItem(plugin, "CATEGORY_ITEMS_TEST_ITEM", new CustomItem(Material.BAMBOO, "&6Test Bamboo")); item.setCategory(category); item.register(plugin); item.load(); Assertions.assertTrue(category.getItems().contains(item)); Assertions.assertEquals(1, category.getItems().size()); item.setCategory(category); Assertions.assertEquals(1, category.getItems().size()); Assertions.assertThrows(IllegalArgumentException.class, () -> category.add(null)); }
Source:
public void testWhenAnyResultFirstError() { final Exception error = new RuntimeException("This task failed."); runTaskTest(new Callable<Task<?>>() { @Override public Task<?> call() throws Exception { final ArrayList<Task<Void>> tasks = new ArrayList<Task<Void>>(); final Task<Void> firstToCompleteError = Task.callInBackground(new Callable<Void>() { @Override public Void call() throws Exception { Thread.sleep(50); throw error; } }); tasks.addAll(launchTasksWithRandomCompletions(10)); tasks.add(firstToCompleteError); return Task.whenAnyResult(tasks).continueWith(new Continuation<Task<Void>, Object>() { @Override public Object then(Task<Task<Void>> task) throws Exception { assertTrue(task.isCompleted()); assertFalse(task.isFaulted()); assertFalse(task.isCancelled()); assertEquals(task.getResult(), firstToCompleteError); assertTrue(task.getResult().isCompleted()); assertFalse(task.getResult().isCancelled()); assertTrue(task.getResult().isFaulted()); return null; } }); } }); }

Target:
public void testWhenAnyResultFirstError() { final Exception error = new RuntimeException("This task failed."); runTaskTest(new Callable<Task<?>>() { @Override public Task<?> call() throws Exception { final ArrayList<Task<Integer>> tasks = new ArrayList<>(); final Task<Integer> firstToCompleteError = Task.callInBackground(new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(50); throw error; } }); tasks.addAll(launchTasksWithRandomCompletions(5)); tasks.add(firstToCompleteError); tasks.addAll(launchTasksWithRandomCompletions(5)); return Task.whenAnyResult(tasks).continueWith(new Continuation<Task<Integer>, Object>() { @Override public Object then(Task<Task<Integer>> task) throws Exception { assertTrue(task.isCompleted()); assertFalse(task.isFaulted()); assertFalse(task.isCancelled()); assertEquals(firstToCompleteError, task.getResult()); assertTrue(task.getResult().isCompleted()); assertFalse(task.getResult().isCancelled()); assertTrue(task.getResult().isFaulted()); assertEquals(error, task.getResult().getError()); return null; } }); } }); }
Source:
public void addsMultipleCookies() throws IOException { final String setcookie = "Set-Cookie: xoo=value?;Path=/;"; final String xoo = "xoo"; final String bar = "bar"; final String value = "value?"; MatcherAssert.assertThat( new RsPrint( new RsWithCookie( new RsWithCookie( new RsEmpty(), xoo, value, RsWithCookieTest.PATH ), bar, "worksToo?", "Path=/2nd/path/" ) ).print(), Matchers.equalTo( Joiner.on(RsWithCookieTest.CRLF).join( RsWithCookieTest.HTTP_OK, setcookie, "Set-Cookie: bar=worksToo?;Path=/2nd/path/;", "", "" ) ) ); }

Target:
public void addsMultipleCookies() throws IOException { final String qux = "qux"; final String bar = "bar"; final String value = "value?"; final String path = "Path=/qux"; MatcherAssert.assertThat( new RsPrint( new RsWithCookie( new RsWithCookie( new RsEmpty(), qux, value, path ), bar, "worksToo?", "Path=/2nd/path/" ) ).print(), Matchers.equalTo( RsWithCookieTest.cookies( RsWithCookieTest.formatCookie(qux, value, path), "bar=worksToo?;Path=/2nd/path/" ) ) ); }