List of usage examples for java.util Collections reverse
@SuppressWarnings({ "rawtypes", "unchecked" }) public static void reverse(List<?> list)
This method runs in linear time.
From source file:com.zhengmo.data.transaction.ChainedTransactionManager.java
/** * ?List.//from ww w. ja v a 2s . com * @param collection ? * @param <T> ? * @return list */ private <T> Iterable<T> reverse(Collection<T> collection) { List<T> list = new ArrayList<T>(collection); Collections.reverse(list); return list; }
From source file:com.twitter.distributedlog.logsegment.TestLogSegmentCache.java
@Test(timeout = 60000) public void testSameLogSegment() throws Exception { LogSegmentCache cache = new LogSegmentCache("test-same-log-segment"); List<LogSegmentMetadata> expectedList = Lists.newArrayListWithExpectedSize(2); LogSegmentMetadata inprogress = DLMTestUtil.inprogressLogSegment("/inprogress-1", 1L, 1L, 1L); expectedList.add(inprogress);//w ww. ja v a 2s. c o m cache.add(DLMTestUtil.inprogressZNodeName(1L), inprogress); LogSegmentMetadata completed = DLMTestUtil.completedLogSegment("/segment-1", 1L, 1L, 100L, 100, 1L, 99L, 0L); expectedList.add(completed); cache.add(DLMTestUtil.completedLedgerZNodeNameWithLogSegmentSequenceNumber(1L), completed); List<LogSegmentMetadata> retrievedList = cache.getLogSegments(LogSegmentMetadata.COMPARATOR); assertEquals("Should get both log segments in ascending order", expectedList.size(), retrievedList.size()); for (int i = 0; i < expectedList.size(); i++) { assertEqualsWithoutSequenceId(expectedList.get(i), retrievedList.get(i)); } assertEquals("inprogress log segment should see start sequence id : 0", 0L, retrievedList.get(0).getStartSequenceId()); Collections.reverse(expectedList); retrievedList = cache.getLogSegments(LogSegmentMetadata.DESC_COMPARATOR); assertEquals("Should get both log segments in descending order", expectedList.size(), retrievedList.size()); for (int i = 0; i < expectedList.size(); i++) { assertEqualsWithoutSequenceId(expectedList.get(i), retrievedList.get(i)); } assertEquals("inprogress log segment should see start sequence id : 0", 0L, retrievedList.get(1).getStartSequenceId()); }
From source file:com.netflix.curator.x.discovery.TestServiceCache.java
@Test public void testCache() throws Exception { List<Closeable> closeables = Lists.newArrayList(); TestingServer server = new TestingServer(); closeables.add(server);// www . j av a2 s . c o m try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class) .basePath("/discovery").client(client).build(); closeables.add(discovery); discovery.start(); ServiceCache<String> cache = discovery.serviceCacheBuilder().name("test").build(); closeables.add(cache); cache.start(); final Semaphore semaphore = new Semaphore(0); ServiceCacheListener listener = new ServiceCacheListener() { @Override public void cacheChanged() { semaphore.release(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; cache.addListener(listener); ServiceInstance<String> instance1 = ServiceInstance.<String>builder().payload("thing").name("test") .port(10064).build(); ServiceInstance<String> instance2 = ServiceInstance.<String>builder().payload("thing").name("test") .port(10065).build(); discovery.registerService(instance1); Assert.assertTrue(semaphore.tryAcquire(10, TimeUnit.SECONDS)); discovery.registerService(instance2); Assert.assertTrue(semaphore.tryAcquire(3, TimeUnit.SECONDS)); ServiceInstance<String> instance3 = ServiceInstance.<String>builder().payload("thing").name("another") .port(10064).build(); discovery.registerService(instance3); Assert.assertFalse(semaphore.tryAcquire(3, TimeUnit.SECONDS)); // should not get called for a different service } finally { Collections.reverse(closeables); for (Closeable c : closeables) { IOUtils.closeQuietly(c); } } }
From source file:com.epam.training.facades.converters.populator.AbstractProductBundleTabsPopulator.java
@Override public void populate(final SOURCEPRODUCT productModel, final TARGETPRODUCT productData) throws ConversionException { // iterate over all components, which represent the package tabs in the frontend final Map<String, BundleTabData> bundleTabsMap = new HashMap<String, BundleTabData>(); for (final SOURCETEMPLATE sourceComponent : getComponents(productModel)) { final SOURCETEMPLATE parentBundleTemplate = (SOURCETEMPLATE) sourceComponent.getParentTemplate(); final SOURCETEMPLATE targetComponent = getTargetComponent(sourceComponent); final BundleTabData bundleTabData; if (bundleTabsMap.containsKey(parentBundleTemplate.getId())) { bundleTabData = bundleTabsMap.get(parentBundleTemplate.getId()); } else {// ww w. j av a 2 s . c o m bundleTabData = new BundleTabData(); bundleTabsMap.put(parentBundleTemplate.getId(), bundleTabData); } bundleTabData.setParentBundleTemplate(getBundleTemplateConverter().convert(parentBundleTemplate)); bundleTabData.setSourceComponent(getBundleTemplateConverter().convert(sourceComponent)); bundleTabData.setTargetComponent(getBundleTemplateConverter().convert(targetComponent)); final Map<String, FrequencyTabData> frequencyTabsMap = new HashMap<String, FrequencyTabData>(); final List<FrequencyTabData> frequencyTabList = bundleTabData.getFrequencyTabs(); if (CollectionUtils.isNotEmpty(frequencyTabList)) { for (final FrequencyTabData frequencyTabData : frequencyTabList) { frequencyTabsMap.put(frequencyTabData.getTermOfServiceFrequency().getCode() + ":" + frequencyTabData.getTermOfServiceNumber(), frequencyTabData); } } // iterate over all products per bundle tab for (final ProductModel targetProductModel : getProducts(productModel, sourceComponent, targetComponent)) { if (targetProductModel instanceof SubscriptionProductModel) { final SubscriptionProductModel subscriptionProductModel = (SubscriptionProductModel) targetProductModel; final TermOfServiceFrequencyData termOfServiceFrequency = getTermOfServiceFrequencyConverter() .convert(subscriptionProductModel.getSubscriptionTerm().getTermOfServiceFrequency()); final int termOfServiceNumber = subscriptionProductModel.getSubscriptionTerm() .getTermOfServiceNumber() == null ? 0 : subscriptionProductModel.getSubscriptionTerm().getTermOfServiceNumber() .intValue(); // The list of Plans is split by its terms and conditions number and frequency, which lead to the frequency tabs in the frontend FrequencyTabData frequencyTab; final String frequencyString = termOfServiceFrequency.getCode() + ":" + termOfServiceNumber; if (frequencyTabsMap.containsKey(frequencyString)) { frequencyTab = frequencyTabsMap.get(frequencyString); } else { frequencyTab = buildFrequencyTab(termOfServiceFrequency, termOfServiceNumber); frequencyTabsMap.put(frequencyString, frequencyTab); } // the related product is populated with specific information final ProductData subscriptionProductData = getProductConverter() .convert(subscriptionProductModel); getSubscriptionProductBasicPopulator().populate(subscriptionProductModel, subscriptionProductData); getSubscriptionProductEntitlementPopulator().populate(subscriptionProductModel, subscriptionProductData); getProductStockPopulator().populate(subscriptionProductModel, subscriptionProductData); callPopulators(sourceComponent, targetComponent, productModel, productData, subscriptionProductModel, subscriptionProductData); frequencyTab.getProducts().add(subscriptionProductData); } else { LOG.error("Product '" + targetProductModel.getCode() + "' is not a SubscriptionProduct. Ignoring it."); } } final List<FrequencyTabData> sortedFrequencies = new ArrayList<FrequencyTabData>( frequencyTabsMap.values()); Collections.sort(sortedFrequencies, new FrequencyTabDataComparator()); Collections.reverse(sortedFrequencies); bundleTabData.setFrequencyTabs(sortedFrequencies); } final List<BundleTabData> bundleTabs = new ArrayList<BundleTabData>(bundleTabsMap.values()); if (productModel instanceof DeviceModel) { productData.setSoldIndividually(BooleanUtils.toBoolean(productModel.getSoldIndividually())); productData.setBundleTabs(bundleTabs); } else if (productModel instanceof SubscriptionProductModel) { productData.setBundleTabs(bundleTabs); } // populate the information about pre-selected tabs changePreselectedFlags(bundleTabs, productModel.getCode()); }
From source file:me.childintime.childintime.InitialSetup.java
/** * Show the confirmation dialog./*from w w w . ja va2 s .co m*/ * * @return True if the user agree'd, false if not. */ private boolean showConfirmationDialog() { // Create a list with the buttons to show in the option dialog List<String> buttons = new ArrayList<>(); buttons.add("Continue"); buttons.add("Quit"); // Reverse the button list if we're on a Mac OS X system if (Platform.isMacOsX()) Collections.reverse(buttons); // Show the option dialog final int option = JOptionPane.showOptionDialog(this.progressDialog, "This is the first time you're using " + App.APP_NAME + " on this system.\n" + "Some application files are required to be installed.\n" + "Please Continue and allow us to set things up for you.", App.APP_NAME + " - Initial setup", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, buttons.toArray(), buttons.get(!Platform.isMacOsX() ? 0 : 1)); // Determine, set and return the result this.confirmDialogAgree = (option == (!Platform.isMacOsX() ? 0 : 1)); return this.confirmDialogAgree; }
From source file:com.netflix.curator.x.discovery.TestServiceDiscovery.java
@Test public void testMultipleInstances() throws Exception { final String SERVICE_ONE = "one"; final String SERVICE_TWO = "two"; List<Closeable> closeables = Lists.newArrayList(); TestingServer server = new TestingServer(); closeables.add(server);/*from w w w.ja va2 s .c om*/ try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceInstance<Void> s1_i1 = ServiceInstance.<Void>builder().name(SERVICE_ONE).build(); ServiceInstance<Void> s1_i2 = ServiceInstance.<Void>builder().name(SERVICE_ONE).build(); ServiceInstance<Void> s2_i1 = ServiceInstance.<Void>builder().name(SERVICE_TWO).build(); ServiceInstance<Void> s2_i2 = ServiceInstance.<Void>builder().name(SERVICE_TWO).build(); ServiceDiscovery<Void> discovery = ServiceDiscoveryBuilder.builder(Void.class).client(client) .basePath("/test").build(); closeables.add(discovery); discovery.start(); discovery.registerService(s1_i1); discovery.registerService(s1_i2); discovery.registerService(s2_i1); discovery.registerService(s2_i2); Assert.assertEquals(Sets.newHashSet(discovery.queryForNames()), Sets.newHashSet(SERVICE_ONE, SERVICE_TWO)); List<ServiceInstance<Void>> list = Lists.newArrayList(); list.add(s1_i1); list.add(s1_i2); Collections.sort(list, comparator); List<ServiceInstance<Void>> queriedInstances = Lists .newArrayList(discovery.queryForInstances(SERVICE_ONE)); Collections.sort(queriedInstances, comparator); Assert.assertEquals(queriedInstances, list, String.format("Not equal l: %s - d: %s", list, queriedInstances)); list.clear(); list.add(s2_i1); list.add(s2_i2); Collections.sort(list, comparator); queriedInstances = Lists.newArrayList(discovery.queryForInstances(SERVICE_TWO)); Collections.sort(queriedInstances, comparator); Assert.assertEquals(queriedInstances, list, String.format("Not equal 2: %s - d: %s", list, queriedInstances)); } finally { Collections.reverse(closeables); for (Closeable c : closeables) { IOUtils.closeQuietly(c); } } }
From source file:be.fedict.trust.service.bean.TrustServiceBean.java
@TransactionAttribute(TransactionAttributeType.REQUIRED) @SNMP(oid = SnmpConstants.VALIDATE_TSA)/*from ww w. java2 s . c o m*/ public ValidationResult validateTimestamp(String trustDomainName, byte[] encodedTimestampToken, boolean returnRevocationData) throws TSPException, IOException, CMSException, NoSuchAlgorithmException, NoSuchProviderException, CertStoreException, TrustDomainNotFoundException { LOG.debug("validate timestamp token"); /* * Parse embedded certificate chain */ List<X509Certificate> certificateChain = new LinkedList<X509Certificate>(); TimeStampToken timestampToken = new TimeStampToken(new CMSSignedData(encodedTimestampToken)); CertStore certStore = timestampToken.getCertificatesAndCRLs("Collection", "BC"); Collection<? extends Certificate> certificates = certStore.getCertificates(null); for (Certificate certificate : certificates) { certificateChain.add((X509Certificate) certificate); } if (TrustValidator.isSelfSigned(certificateChain.get(0))) { Collections.reverse(certificateChain); } /* * Validate */ TrustLinkerResult lastResult = null; RevocationData lastRevocationData = null; for (TrustDomainEntity trustDomain : getTrustDomains(trustDomainName)) { TrustValidator trustValidator = getTrustValidator(trustDomain, returnRevocationData); try { trustValidator.isTrusted(certificateChain); } catch (CertPathValidatorException ignored) { } if (trustValidator.getResult().isValid()) { LOG.debug("valid for trust domain: " + trustDomain.getName()); harvest(trustDomain, certificateChain); return new ValidationResult(trustValidator.getResult(), trustValidator.getRevocationData()); } lastResult = trustValidator.getResult(); lastRevocationData = trustValidator.getRevocationData(); } return new ValidationResult(lastResult, lastRevocationData); }
From source file:edu.depaul.armada.dao.ContainerLogDaoHibernate.java
/** * Returns a List<Metric> from all of the containers with data within a specified * amount of time./*from ww w. ja v a 2 s .c o m*/ * @param periodInHours int * @return List<Metric> */ @Override public List<Metric> getContainerCounts(int periodInHours) { List<Metric> metrics = new ArrayList<Metric>(periodInHours); Calendar cal = Calendar.getInstance(); for (int i = 0; i < periodInHours; i++) { Date end = cal.getTime(); int hour = cal.get(Calendar.HOUR_OF_DAY); cal.add(Calendar.HOUR_OF_DAY, -1); Date start = cal.getTime(); Criteria criteria = newCriteria(); criteria.add(Restrictions.le("timestamp", end)); criteria.add(Restrictions.gt("timestamp", start)); // we don't want overlap here criteria.setProjection(Projections.countDistinct("container")); int count = ((Long) criteria.uniqueResult()).intValue(); Metric temp = new Metric(); temp.setHour(hour); temp.setValue(count); metrics.add(temp); } Collections.reverse(metrics); // we want the current time to be the last hour return metrics; }
From source file:me.calebjones.blogsite.network.PostDownloader.java
private void getPostAll() { //Setup the URLS that I will need String firstUrl = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/" + "?pretty=true&number=100&fields=ID,title&order_by=ID"; String nextPage = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/" + "?pretty=true&number=100&fields=ID,title&order_by=ID&page_handle="; Request request = new Request.Builder().url(firstUrl).build(); int count = 0; try {//from w w w .j av a 2 s .c o m //First make a call to see how many total posts there are and save to 'found' final Response response = BlogsiteApplication.getInstance().client.newCall(request).execute(); if (!response.isSuccessful()) { mBuilder.setContentText("Download failed.").setProgress(0, 0, false).setAutoCancel(true) .setOngoing(false); mNotifyManager.notify(NOTIF_ID, mBuilder.build()); throw new IOException(); } else { //Take the response and parse the JSON JSONObject JObject = new JSONObject(response.body().string()); JSONArray posts = JObject.optJSONArray("posts"); //Store the data into the two objects, meta gets the next page later on. // Found is total post count. String meta = JObject.optString("meta"); int found = JObject.optInt("found"); postID = new ArrayList<>(); //If there are more then 100, which there always will unless something // catastrophic happens then set up the newURL. if (found > 100) { JSONObject metaLink = new JSONObject(meta); String nextValue = metaLink.optString("next_page"); newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8"); Log.d("The Jones Theory", newURL); } // Loop through the posts and add the post ID to the array. // The posts is still from the original call. for (int i = 0; i < posts.length(); i++) { JSONObject post = posts.optJSONObject(i); postID.add(post.optString("ID")); count++; } //Now this logic is in charge of loading the next pages // until all posts are loaded into the array. while (count != found) { Request newRequest = new Request.Builder().url(newURL).build(); Response newResponse = BlogsiteApplication.getInstance().client.newCall(newRequest).execute(); if (!newResponse.isSuccessful()) throw new IOException(); JSONObject nJObject = new JSONObject(newResponse.body().string()); JSONArray nPosts = nJObject.optJSONArray("posts"); String nMeta = nJObject.optString("meta"); int newFound = nJObject.optInt("found"); if (newFound > 100) { JSONObject metaLink = new JSONObject(nMeta); String nextValue = metaLink.optString("next_page"); newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8"); } for (int i = 0; i < nPosts.length(); i++) { JSONObject post = nPosts.optJSONObject(i); postID.add(post.optString("ID")); count++; } } Collections.reverse(postID); download(postID); Log.d("The Jones Theory", "getPostAll - Downloading = " + SharedPrefs.getInstance().isDownloading()); } } catch (IOException | JSONException e) { if (SharedPrefs.getInstance().isFirstDownload()) { SharedPrefs.getInstance().setFirstDownload(false); } SharedPrefs.getInstance().setDownloading(false); e.printStackTrace(); } }
From source file:ch.sourcepond.maven.release.scm.git.GitRepository.java
@Override public List<ProposedTag> tagsForVersion(final String module, final String versionWithoutBuildNumber) throws SCMException { final List<ProposedTag> results = new ArrayList<>(); List<Ref> tags;/*from w ww . java 2 s . c o m*/ try { tags = getGit().tagList().call(); } catch (final GitAPIException e) { throw new SCMException(e, "Error while getting a list of tags in the local repo"); } Collections.reverse(tags); final String tagWithoutBuildNumber = module + "-" + versionWithoutBuildNumber; for (final Ref tag : tags) { if (isPotentiallySameVersionIgnoringBuildNumber(tagWithoutBuildNumber, tag.getName())) { results.add(fromRef(tag)); } } return results; }