List of usage examples for java.util Collection iterator
Iterator<E> iterator();
From source file:Main.java
/** * Splits a collection in <tt>n</tt> new collections. The last collection may contain more elements than the others * if {@code set.size() % n != 0}./* w w w .jav a 2 s .c o m*/ * * @param set the input collection * @param n the number of new collections * @param <T> the element type * @return a list containing the new collections */ public static <T> List<T>[] split(Collection<T> set, int n) { if (set.size() >= n) { @SuppressWarnings("unchecked") List<T>[] arrays = new List[n]; int minSegmentSize = (int) Math.floor(set.size() / (double) n); int start = 0; int stop = minSegmentSize; Iterator<T> it = set.iterator(); for (int i = 0; i < n - 1; i++) { int segmentSize = stop - start; List<T> segment = new ArrayList<T>(segmentSize); for (int k = 0; k < segmentSize; k++) { segment.add(it.next()); } arrays[i] = segment; start = stop; stop += segmentSize; } int segmentSize = set.size() - start; List<T> segment = new ArrayList<T>(segmentSize); for (int k = 0; k < segmentSize; k++) { segment.add(it.next()); } arrays[n - 1] = segment; return arrays; } else { throw new IllegalArgumentException("n must not be smaller set size!"); } }
From source file:mitm.test.TestUtils.java
public static X509Certificate loadCertificate(File file) throws CertificateException, NoSuchProviderException, FileNotFoundException { Collection<? extends Certificate> certificates = CertificateUtils.readCertificates(file); if (certificates != null && certificates.size() > 0) { return (X509Certificate) certificates.iterator().next(); }//from w ww .j a v a 2 s . c om return null; }
From source file:eu.medsea.util.EncodingGuesser.java
/** * Utility method to get all of the current encoding names, in canonical format, supported by your JVM * at the time this is called./*from w w w . j av a 2 s .com*/ * @return current Collection of canonical encoding names */ public static Collection getCanonicalEncodingNamesSupportedByJVM() { Collection encodings = new TreeSet(); SortedMap charSets = Charset.availableCharsets(); Collection charSetNames = charSets.keySet(); for (Iterator it = charSetNames.iterator(); it.hasNext();) { encodings.add((String) it.next()); } if (log.isDebugEnabled()) { log.debug("The following [" + encodings.size() + "] encodings will be used: " + encodings); } return encodings; }
From source file:it.cnr.icar.eric.common.security.X509Parser.java
/** * Parses a X509Certificate from a DER formatted input stream. Uses the * BouncyCastle provider if available./*w ww .ja va2s . co m*/ * * @param inStream The DER InputStream with the certificate. * @return X509Certificate parsed from stream. * @throws JAXRException in case of IOException or CertificateException * while parsing the stream. */ public static X509Certificate parseX509Certificate(InputStream inStream) throws JAXRException { try { //possible options // - der x509 generated by keytool -export // - der x509 generated by openssh x509 (might require BC provider) // Get the CertificateFactory to parse the stream // if BouncyCastle provider available, use it CertificateFactory cf; try { Class<?> clazz = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider"); Constructor<?> constructor = clazz.getConstructor(new Class[] {}); Provider bcProvider = (Provider) constructor.newInstance(new Object[] {}); Security.addProvider(bcProvider); cf = CertificateFactory.getInstance("X.509", "BC"); } catch (Exception e) { // log error if bc present but failed to instanciate/add provider if (!(e instanceof ClassNotFoundException)) { log.error(CommonResourceBundle.getInstance() .getString("message.FailedToInstantiateBouncyCastleProvider")); } // fall back to default provider cf = CertificateFactory.getInstance("X.509"); } // Read the stream to a local variable DataInputStream dis = new DataInputStream(inStream); byte[] bytes = new byte[dis.available()]; dis.readFully(bytes); ByteArrayInputStream certStream = new ByteArrayInputStream(bytes); // Parse the cert stream int i = 0; Collection<? extends Certificate> c = cf.generateCertificates(certStream); X509Certificate[] certs = new X509Certificate[c.toArray().length]; for (Iterator<? extends Certificate> it = c.iterator(); it.hasNext();) { certs[i++] = (X509Certificate) it.next(); } // Some logging.. if (log.isDebugEnabled()) { if (c.size() == 1) { log.debug("One certificate, no chain."); } else { log.debug("Certificate chain length: " + c.size()); } log.debug("Subject DN: " + certs[0].getSubjectDN().getName()); log.debug("Issuer DN: " + certs[0].getIssuerDN().getName()); } // Do we need to return the chain? // do we need to verify if cert is self signed / valid? return certs[0]; } catch (CertificateException e) { String msg = CommonResourceBundle.getInstance().getString("message.parseX509CertificateStreamFailed", new Object[] { e.getClass().getName(), e.getMessage() }); throw new JAXRException(msg, e); } catch (IOException e) { String msg = CommonResourceBundle.getInstance().getString("message.parseX509CertificateStreamFailed", new Object[] { e.getClass().getName(), e.getMessage() }); throw new JAXRException(msg, e); } finally { try { inStream.close(); } catch (IOException e) { inStream = null; } } }
From source file:mitm.test.TestUtils.java
public static X509Certificate loadCertificate(String filename) throws CertificateException, NoSuchProviderException, FileNotFoundException { File file = new File(filename); Collection<? extends Certificate> certificates = CertificateUtils.readCertificates(file); if (certificates != null && certificates.size() > 0) { return (X509Certificate) certificates.iterator().next(); }//from w w w .ja v a2s .c o m return null; }
From source file:com.ebay.logstorm.server.utils.LogStormServerDebug.java
private static File findAssemblyJarFile() { String projectRootDir = System.getProperty("user.dir"); String assemblyModuleTargeDirPath = projectRootDir + "/assembly/target/"; File assemblyTargeDirFile = new File(assemblyModuleTargeDirPath); if (!assemblyTargeDirFile.exists()) { throw new IllegalStateException( assemblyModuleTargeDirPath + " not found, please execute 'mvn install -DskipTests' under " + projectRootDir + " to build the project firstly and retry"); }/*from w w w .j a v a2 s.com*/ String jarFileNameWildCard = "logstorm-assembly-*.jar"; Collection<File> jarFiles = FileUtils.listFiles(assemblyTargeDirFile, new WildcardFileFilter(jarFileNameWildCard), TrueFileFilter.INSTANCE); if (jarFiles.size() == 0) { throw new IllegalStateException( "jar is not found, please execute 'mvn install -DskipTests' from project root firstly and retry"); } File jarFile = jarFiles.iterator().next(); LOG.debug("Found pipeline.jar: {}", jarFile.getAbsolutePath()); return jarFile; }
From source file:com.liangc.hq.base.utils.MonitorUtils.java
/** * Sometimes, it's useful to just get a dump of all of the metrics * returned by the backend./*from w w w .j ava2 s .com*/ * * @param log * @param metrics a Map keyed on the category (String), values are * List's of MetricDisplaySummary beans */ public static void traceMetricDisplaySummaryMap(Log logger, Map metrics) { logger.trace("Dumping metric map (from " + MonitorUtils.class.getName() + "):"); for (Iterator categoryIter = metrics.keySet().iterator(); categoryIter.hasNext();) { String categoryName = (String) categoryIter.next(); logger.trace("Category: " + categoryName); int i = 0; Collection metricList = (Collection) metrics.get(categoryName); for (Iterator iter = metricList.iterator(); iter.hasNext();) { MetricDisplaySummary summaryBean = (MetricDisplaySummary) iter.next(); ++i; logger.trace("\t " + i + ": " + summaryBean); } } }
From source file:grails.plugin.searchable.internal.util.GrailsDomainClassUtils.java
/** * Get the actual (user-defined) Classes for the given GrailsDomainClass Collection. * Equivalent to collecting the results of <code>grailsDomainClass.getClazz()</code> on * each element/*from ww w .jav a2 s .c o m*/ * * @param grailsDomainClasses * @return A collection of User-defined classes, which may be empty */ public static Collection getClazzes(Collection grailsDomainClasses) { if (grailsDomainClasses == null || grailsDomainClasses.isEmpty()) { return Collections.EMPTY_SET; } Set clazzes = new HashSet(); for (Iterator iter = grailsDomainClasses.iterator(); iter.hasNext();) { clazzes.add(((GrailsDomainClass) iter.next()).getClazz()); } return clazzes; }
From source file:org.codehaus.groovy.grails.plugins.searchable.compass.mapping.CompassMappingUtils.java
/** * Resolve aliases between mappings/*w ww . j a v a2 s. c o m*/ * Note this method is destructive in the sense that it modifies the passed in mappings */ public static void resolveAliases(List classMappings, Collection grailsDomainClasses) { // set defaults for those classes without explicit aliases and collect aliases Map mappingByClass = new HashMap(); Map mappingsByAlias = new HashMap(); for (Iterator iter = classMappings.iterator(); iter.hasNext();) { CompassClassMapping classMapping = (CompassClassMapping) iter.next(); if (classMapping.getAlias() == null) { classMapping.setAlias(getDefaultAlias(classMapping.getMappedClass())); } mappingByClass.put(classMapping.getMappedClass(), classMapping); List mappings = (List) mappingsByAlias.get(classMapping.getAlias()); if (mappings == null) { mappings = new ArrayList(); mappingsByAlias.put(classMapping.getAlias(), mappings); } mappings.add(classMapping); } // override duplicate inherited aliases for (Iterator iter = mappingsByAlias.keySet().iterator(); iter.hasNext();) { List mappings = (List) mappingsByAlias.get(iter.next()); if (mappings.size() == 1) { continue; } CompassClassMapping parentMapping = null; for (Iterator miter = mappings.iterator(); miter.hasNext();) { CompassClassMapping classMapping = (CompassClassMapping) miter.next(); if (classMapping.getMappedClassSuperClass() == null) { parentMapping = classMapping; break; } } mappings.remove(parentMapping); for (Iterator miter = mappings.iterator(); miter.hasNext();) { CompassClassMapping classMapping = (CompassClassMapping) miter.next(); LOG.debug("Overriding duplicated alias [" + classMapping.getAlias() + "] for class [" + classMapping.getMappedClass().getName() + "] with default alias. (Aliases must be unique - maybe this was inherited from a superclass?)"); classMapping.setAlias(getDefaultAlias(classMapping.getMappedClass())); } } // resolve property ref aliases for (Iterator iter = classMappings.iterator(); iter.hasNext();) { CompassClassMapping classMapping = (CompassClassMapping) iter.next(); Class mappedClass = classMapping.getMappedClass(); for (Iterator piter = classMapping.getPropertyMappings().iterator(); piter.hasNext();) { CompassClassPropertyMapping propertyMapping = (CompassClassPropertyMapping) piter.next(); if ((propertyMapping.isComponent() || propertyMapping.isReference()) && !propertyMapping.hasAttribute("refAlias")) { Set aliases = new HashSet(); Class clazz = propertyMapping.getPropertyType(); aliases.add(((CompassClassMapping) mappingByClass.get(clazz)).getAlias()); GrailsDomainClassProperty domainClassProperty = GrailsDomainClassUtils .getGrailsDomainClassProperty(grailsDomainClasses, mappedClass, propertyMapping.getPropertyName()); Collection clazzes = GrailsDomainClassUtils .getClazzes(domainClassProperty.getReferencedDomainClass().getSubClasses()); for (Iterator citer = clazzes.iterator(); citer.hasNext();) { CompassClassMapping mapping = (CompassClassMapping) mappingByClass.get(citer.next()); if (mapping != null) { aliases.add(mapping.getAlias()); } } propertyMapping.setAttrbute("refAlias", DefaultGroovyMethods.join(aliases, ", ")); } } } // resolve extend aliases for (Iterator iter = classMappings.iterator(); iter.hasNext();) { CompassClassMapping classMapping = (CompassClassMapping) iter.next(); Class mappedClassSuperClass = classMapping.getMappedClassSuperClass(); if (mappedClassSuperClass != null && classMapping.getExtend() == null) { CompassClassMapping mapping = (CompassClassMapping) mappingByClass.get(mappedClassSuperClass); classMapping.setExtend(mapping.getAlias()); } } }
From source file:com.centeractive.ws.builder.DefinitionSaveTest.java
public static File findFile(File folder, String name) { final boolean RECURSIVE = true; String[] extensions = new String[] { FilenameUtils.getExtension(name) }; Collection<File> files = FileUtils.listFiles(folder, extensions, RECURSIVE); if (files.isEmpty() == false) { return files.iterator().next(); }/*from ww w.j av a 2s . c om*/ throw new RuntimeException("File not found " + name); }