Example usage for java.util ArrayList toArray

List of usage examples for java.util ArrayList toArray

Introduction

In this page you can find the example usage for java.util ArrayList toArray.

Prototype

@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) 

Source Link

Document

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

Usage

From source file:com.espertech.esper.support.util.ArrayAssertionUtil.java

public static Object[] iteratorToArrayObject(Iterator iterator) {
    if (iterator == null) {
        Assert.fail("Null iterator");
    }/*ww  w  .jav a2s.c o m*/
    ArrayList<Object> items = new ArrayList<Object>();
    for (; iterator.hasNext();) {
        items.add(iterator.next());
    }
    return items.toArray(new Object[items.size()]);
}

From source file:gdt.data.entity.facet.ExtensionHandler.java

/**
 * Get the handler instance.  /*w  w  w  .  ja v a2 s . c  o  m*/
 *  @param entigrator entigrator instance
 *  @param extension$ extension key
 *  @param handlerClass$ class name
 * @return handler instance.
 */

public static Object loadHandlerInstance(Entigrator entigrator, String extension$, String handlerClass$) {
    try {
        System.out.println(
                "ExtensionHandler:loadHandlerInstance:extension=" + extension$ + " handler=" + handlerClass$);

        Object obj = null;
        Class<?> cls = entigrator.getClass(handlerClass$);
        if (cls == null) {
            System.out.println("ExtensionHandler:loadHandlerInstance:1");
            Sack extension = entigrator.getEntityAtKey(extension$);
            String lib$ = extension.getElementItemAt("field", "lib");
            String jar$ = "jar:file:" + entigrator.getEntihome() + "/" + extension$ + "/" + lib$ + "!/";
            ArrayList<URL> urll = new ArrayList<URL>();
            urll.add(new URL(jar$));

            String[] sa = extension.elementListNoSorted("external");
            if (sa != null) {
                File file;
                for (String s : sa) {
                    file = new File(entigrator.getEntihome() + "/" + extension$ + "/" + s);
                    if (file.exists())
                        urll.add(new URL("jar:file:" + file.getPath() + "!/"));
                }
            }
            URL[] urls = urll.toArray(new URL[0]);
            URLClassLoader cl = URLClassLoader.newInstance(urls);

            //   Class<?>cls=entigrator.getClass(handlerClass$);

            cls = cl.loadClass(handlerClass$);

            if (cls == null) {
                System.out.println("ExtensionHandler:loadHandlerInstance:cannot load class =" + handlerClass$);
                return null;
            } else {
                //   System.out.println("ExtensionHandler:loadHandlerInstance:found class ="+handlerClass$);
                entigrator.putClass(handlerClass$, cls);
            }

        }

        try {

            Constructor[] ctors = cls.getDeclaredConstructors();
            System.out.println("ExtensionHandler:loadHandlerInstance:ctors=" + ctors.length);
            Constructor ctor = null;
            for (int i = 0; i < ctors.length; i++) {
                ctor = ctors[i];
                if (ctor.getGenericParameterTypes().length == 0)
                    break;
            }
            ctor.setAccessible(true);
            obj = ctor.newInstance();

        } catch (java.lang.NoClassDefFoundError ee) {
            System.out.println("ExtensionHandler:loadHandlerInstance:" + ee.toString());
            return null;
        }
        //if(obj!=null)
        System.out.println("ExtensionHandler:loadHandlerInstance:obj=" + obj.getClass().getName());
        return obj;
    } catch (Exception e) {
        Logger.getLogger(ExtensionHandler.class.getName()).severe(e.toString());
        return null;
    }

}

From source file:com.espertech.esper.support.util.ArrayAssertionUtil.java

public static EventBean[] iteratorToArray(Iterator<EventBean> iterator) {
    if (iterator == null) {
        Assert.fail("Null iterator");
    }/*from w w w . j  a v  a2 s  .  c o m*/
    ArrayList<EventBean> events = new ArrayList<EventBean>();
    for (; iterator.hasNext();) {
        events.add(iterator.next());
    }
    return events.toArray(new EventBean[0]);
}

From source file:com.yahoo.glimmer.indexing.VerticalDocumentFactory.java

public static void setupConf(Configuration conf, boolean withContexts, String resourcesHash,
        String hashValuePrefix, String predicates) throws IOException {
    InputStream predicatesInputStream = CompressionCodecHelper.openInputStream(conf, new Path(predicates));
    ArrayList<String> predicatesToUseAsFields = new ArrayList<String>();

    BufferedReader reader = new BufferedReader(new InputStreamReader(predicatesInputStream));
    String nextLine = "";

    while ((nextLine = reader.readLine()) != null) {
        nextLine = nextLine.trim();// w  w w .  java  2  s  . c  om
        if (!nextLine.isEmpty()) {
            // Take the first column
            String predicate = nextLine.split("\\s+")[0];
            // if no match, returns the whole string

            // Only include if it's in the namespaces table and not
            // blacklisted
            if (predicate != null && !isOnPredicateBlacklist(predicate)) {
                predicatesToUseAsFields.add(predicate);
                LOG.info("Indexing predicate:" + predicate);
            }
        }
    }
    reader.close();

    LOG.info("Loaded " + predicatesToUseAsFields.size() + " fields.");
    setupConf(conf, IndexType.VERTICAL, withContexts, resourcesHash, hashValuePrefix,
            predicatesToUseAsFields.toArray(new String[0]));
}

From source file:com.ricemap.spateDB.operations.Sampler.java

/**
 * Reads a sample of the given file and returns the number of items read.
 * /*  ww  w .j a  v a  2 s  . c  o m*/
 * @param fs
 * @param file
 * @param count
 * @return
 * @throws IOException
 */
public static <T extends TextSerializable, O extends TextSerializable> int sampleLocalByCount(FileSystem fs,
        Path[] files, int count, long seed, ResultCollector<O> output, T inObj, O outObj) throws IOException {
    ArrayList<Path> data_files = new ArrayList<Path>();
    for (Path file : files) {
        if (fs.getFileStatus(file).isDir()) {
            // Directory, process all data files in this directory (visible files)
            FileStatus[] fileStatus = fs.listStatus(file, hiddenFileFilter);
            for (FileStatus f : fileStatus) {
                data_files.add(f.getPath());
            }
        } else {
            // File, process this file
            data_files.add(file);
        }
    }

    files = data_files.toArray(new Path[data_files.size()]);

    ResultCollector<T> converter = createConverter(output, inObj, outObj);
    long[] files_start_offset = new long[files.length + 1]; // Prefix sum of files sizes
    long total_length = 0;
    for (int i_file = 0; i_file < files.length; i_file++) {
        files_start_offset[i_file] = total_length;
        total_length += fs.getFileStatus(files[i_file]).getLen();
    }
    files_start_offset[files.length] = total_length;

    // Generate offsets to read from and make sure they are ordered to minimize
    // seeks between different HDFS blocks
    Random random = new Random(seed);
    long[] offsets = new long[count];
    for (int i = 0; i < offsets.length; i++) {
        if (total_length == 0)
            offsets[i] = 0;
        else
            offsets[i] = Math.abs(random.nextLong()) % total_length;
    }
    Arrays.sort(offsets);

    int record_i = 0; // Number of records read so far
    int records_returned = 0;

    int file_i = 0; // Index of the current file being sampled
    while (record_i < count) {
        // Skip to the file that contains the next sample
        while (offsets[record_i] > files_start_offset[file_i + 1])
            file_i++;

        // Open a stream to the current file and use it to read all samples
        // in this file
        FSDataInputStream current_file_in = fs.open(files[file_i]);
        long current_file_size = files_start_offset[file_i + 1] - files_start_offset[file_i];

        // The start and end offsets of data within this block
        // offsets are calculated relative to file start
        long data_start_offset = 0;
        if (current_file_in.readLong() == SpatialSite.RTreeFileMarker) {
            // This file is an RTree file. Update the start offset to point
            // to the first byte after the header
            data_start_offset = 8 + RTree.getHeaderSize(current_file_in);
        }
        // Get the end offset of data by searching for the beginning of the
        // last line
        long data_end_offset = current_file_size;
        // Skip the last line too to ensure to ensure that the mapped position
        // will be before some line in the block
        current_file_in.seek(data_end_offset);
        data_end_offset = Tail.tail(current_file_in, 1, null, null);
        long file_data_size = data_end_offset - data_start_offset;

        // Keep sampling as long as records offsets are within this file
        while (record_i < count && (offsets[record_i] - files_start_offset[file_i]) < current_file_size) {
            offsets[record_i] -= files_start_offset[file_i];
            // Map file position to element index in this tree assuming fixed
            // size records
            long element_offset_in_file = offsets[record_i] * file_data_size / current_file_size
                    + data_start_offset;
            current_file_in.seek(element_offset_in_file);
            LineReader reader = new LineReader(current_file_in, 4096);
            // Read the first line after that offset
            Text line = new Text();
            reader.readLine(line); // Skip the rest of the current line
            reader.readLine(line); // Read next line

            // Report this element to output
            if (converter != null) {
                inObj.fromText(line);
                converter.collect(inObj);
            }
            record_i++;
            records_returned++;
        }
        current_file_in.close();
    }
    return records_returned;
}

From source file:com.neutti.webframe.util.StringUtil.java

/**
 * Splits template name to get identifier, field name and locale
 * @param templateName String in form <code>identifier_field_locale</code>
 * @return Array containing identifier, field and locale or empty array if string format is incorrect
 *//* www .  j  av a  2 s.  c om*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String[] splitTemplateName(String templateName) {
    ArrayList result = new ArrayList();
    int k = templateName.lastIndexOf("_");
    if (k != -1) {
        String locale = templateName.substring(k + 1);
        templateName = templateName.substring(0, k);
        k = templateName.lastIndexOf("_");
        if (k != -1) {
            String field = templateName.substring(k + 1);
            templateName = templateName.substring(0, k);
            result.add(templateName);
            result.add(field);
            result.add(locale);
        }
    }
    return (String[]) result.toArray(new String[0]);
}

From source file:com.github.chenxiaolong.dualbootpatcher.patcher.PatcherUtils.java

public static InstallLocation[] getNamedInstallLocations(Context context) {
    ThreadUtils.enforceExecutionOnNonMainThread();

    Log.d(TAG, "Looking for named ROMs");

    File dir = new File(Environment.getExternalStorageDirectory() + File.separator + "MultiBoot");

    ArrayList<InstallLocation> locations = new ArrayList<>();

    File[] files = dir.listFiles();
    if (files != null) {
        for (File f : files) {
            String name = f.getName();

            if (name.startsWith("data-slot-") && !name.equals("data-slot-")) {
                Log.d(TAG, "- Found data-slot: " + name.substring(10));
                locations.add(getDataSlotInstallLocation(context, name.substring(10)));
            } else if (name.startsWith("extsd-slot-") && !name.equals("extsd-slot-")) {
                Log.d(TAG, "- Found extsd-slot: " + name.substring(11));
                locations.add(getExtsdSlotInstallLocation(context, name.substring(11)));
            }/*from w w w .  j a  v a2 s  . c o  m*/
        }
    } else {
        Log.e(TAG, "Failed to list files in: " + dir);
    }

    return locations.toArray(new InstallLocation[locations.size()]);
}

From source file:net.javacoding.xsearch.config.ServerConfiguration.java

public static DatasetConfiguration[] getDatasetConfigurations(String[] indexNames)
        throws ConfigurationException {
    if (indexNames == null || indexNames.length <= 0) {
        ArrayList<DatasetConfiguration> al = getDatasetConfigurations();
        for (int i = 0; i < al.size();) {
            DatasetConfiguration dc = (DatasetConfiguration) al.get(i);
            if (dc.getDisplayOrder() >= 0) {
                i++;//from  ww  w .ja  v a  2 s .  c  om
            } else {
                al.remove(i);
            }
        }
        return (DatasetConfiguration[]) al.toArray(new DatasetConfiguration[al.size()]);
    }
    ServerConfiguration sc = ServerConfiguration.getServerConfiguration();
    sc.syncDatasets();
    ArrayList<DatasetConfiguration> dcs = new ArrayList<DatasetConfiguration>();
    for (int i = 0; i < indexNames.length; i++) {
        DatasetConfiguration dc = ServerConfiguration.getDatasetConfiguration(indexNames[i]);
        if (dc != null)
            dcs.add(dc);
    }
    DatasetConfiguration[] cs = (DatasetConfiguration[]) dcs.toArray(new DatasetConfiguration[dcs.size()]);
    Arrays.sort(cs, new Comparator<DatasetConfiguration>() { // sort the array
        public int compare(DatasetConfiguration o1, DatasetConfiguration o2) {
            return o1.getDisplayOrder() - o2.getDisplayOrder();
        }
    });
    return cs;
}

From source file:com.amalto.webapp.core.util.Util.java

public static WSWhereItem buildWhereItem(String criteria) {
    WSWhereItem wi;/*from ww  w .  j a v  a  2s .com*/
    String[] filters = criteria.split(" "); //$NON-NLS-1$
    String filterXpaths, filterOperators, filterValues;
    filterXpaths = filters[0];
    filterOperators = filters[1];
    if (filters.length <= 2) {
        filterValues = " "; //$NON-NLS-1$
    } else if (filters.length == 3) {
        filterValues = filters[2];
    } else {// more than 3 mean filterValues contains whitespace
        StringBuilder sb = new StringBuilder();
        for (int i = 2; i < filters.length; i++) {
            sb.append(filters[i]);
            if (i < filters.length - 1) {
                sb.append(" ");//$NON-NLS-1$
            }
        }
        filterValues = sb.toString();
    }
    if (filterXpaths == null || filterXpaths.trim().isEmpty()) {
        return null;
    }
    WSWhereCondition wc = new WSWhereCondition(filterXpaths, Util.getOperator(filterOperators), filterValues,
            WSStringPredicate.NONE, false);
    ArrayList<WSWhereItem> conditions = new ArrayList<WSWhereItem>();
    WSWhereItem item = new WSWhereItem(wc, null, null);
    conditions.add(item);
    if (conditions.size() == 0) {
        wi = null;
    } else {
        WSWhereAnd and = new WSWhereAnd(conditions.toArray(new WSWhereItem[conditions.size()]));
        wi = new WSWhereItem(null, and, null);
    }
    return wi;
}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

/**
 * Order the supplied array of X.509 certificates in issued to issuer order.
 *
 * @param certs/* w ww  . ja v  a2s . c o  m*/
 *            X.509 certificates
 * @return The ordered X.509 certificates
 */
public static X509Certificate[] orderX509CertChain(X509Certificate certs[]) {

    if (certs == null) {
        return new X509Certificate[0];
    }

    if (certs.length <= 1) {
        return certs;
    }

    // Put together each possible certificate path...
    ArrayList<ArrayList<X509Certificate>> paths = new ArrayList<ArrayList<X509Certificate>>();

    // For each possible path...
    for (int i = 0; i < certs.length; i++) {
        // Each possible path assumes a different certificate is the root issuer
        ArrayList<X509Certificate> path = new ArrayList<X509Certificate>();
        X509Certificate issuerCert = certs[i];
        path.add(issuerCert);

        X509Certificate newIssuer = null;

        // Recursively build that path by finding the next issued certificate
        while ((newIssuer = findIssuedCert(issuerCert, certs)) != null) {
            // Found an issued cert, now attempt to find its issued certificate
            issuerCert = newIssuer;
            path.add(0, newIssuer);
        }

        // Path complete
        paths.add(path);
    }

    // Get longest path - this will be the ordered path
    ArrayList<X509Certificate> longestPath = paths.get(0);
    for (int i = 1; i < paths.size(); i++) {
        ArrayList<X509Certificate> path = paths.get(i);
        if (path.size() > longestPath.size()) {
            longestPath = path;
        }
    }

    // Return longest path
    return longestPath.toArray(new X509Certificate[longestPath.size()]);
}