Example usage for java.util Collection toArray

List of usage examples for java.util Collection toArray

Introduction

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

Prototype

default <T> T[] toArray(IntFunction<T[]> generator) 

Source Link

Document

Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.

Usage

From source file:com.laxser.blitz.lama.provider.jdbc.JdbcDataAccessProvider.java

/**
 * findPlugin<br>//from  w w w. ja  v  a2  s  .co  m
 * 
 * @return
 * 
 * @author tai.wang@opi-corp.com May 26, 2010 - 4:30:09 PM
 */
protected JdbcWrapper[] findJdbcWrappers() {
    // JdbcWrapperscoreprototype
    @SuppressWarnings("unchecked")
    Collection<JdbcWrapper> jdbcWrappers = this.applicationContext.getBeansOfType(JdbcWrapper.class).values();
    JdbcWrapper[] arrayJdbcWrappers = jdbcWrappers.toArray(new JdbcWrapper[0]);
    for (JdbcWrapper jdbcWrapper : arrayJdbcWrappers) {
        Assert.isNull(jdbcWrapper.getJdbc());// jdbc should be null here
    }
    Arrays.sort(arrayJdbcWrappers, new Comparator<JdbcWrapper>() {

        @Override
        public int compare(JdbcWrapper thees, JdbcWrapper that) {
            Order thessOrder = thees.getClass().getAnnotation(Order.class);
            Order thatOrder = that.getClass().getAnnotation(Order.class);
            int thessValue = thessOrder == null ? 0 : thessOrder.value();
            int thatValue = thatOrder == null ? 0 : thatOrder.value();
            return thessValue - thatValue;
        }

    });
    return arrayJdbcWrappers;
}

From source file:com.github.haixing_hu.criteria.CombinedCriterion.java

/**
 * Constructs a {@link CombinedCriterion}.
 *
 * @param operator// www  . j  av a 2 s.c om
 *          the logic operator.
 * @param criteria
 *          an array of sub-criteria involved in the logic combination.
 * @throws NullPointerException
 *           if {@code operator} or {@code criteria} is {@code null}.
 * @throws IllegalArgumentException
 *           if {@code criteria} has less than 2 elements.
 */
public CombinedCriterion(final LogicOperator operator, final Collection<Criterion> criteria) {
    super(CriterionType.COMBINED);
    this.operator = requireNonNull("operator", operator);
    requireSizeAtLeast("criteria", criteria, 2);
    this.criteria = criteria.toArray(new Criterion[0]);
}

From source file:com.liferay.ide.alloy.core.webresources.PortalResourcesProvider.java

@Override
public File[] getResources(IWebResourcesContext context) {
    File[] retval = null;/*  w  w w . j  a v  a2s .  com*/
    final IFile htmlFile = context.getHtmlFile();
    final ILiferayProject project = LiferayCore.create(htmlFile.getProject());

    if (htmlFile != null && project != null) {
        final ILiferayPortal portal = project.adapt(ILiferayPortal.class);

        if (portal != null && ProjectUtil.isPortletProject(htmlFile.getProject())) {
            final IPath portalDir = portal.getAppServerPortalDir();

            if (portalDir != null) {
                final IPath cssPath = portalDir.append("html/themes/_unstyled/css");

                if (cssPath.toFile().exists()) {
                    synchronized (fileCache) {
                        final Collection<File> cachedFiles = fileCache.get(cssPath);

                        if (cachedFiles != null) {
                            retval = cachedFiles.toArray(new File[0]);
                        } else {
                            final Collection<File> files = FileUtils.listFiles(cssPath.toFile(),
                                    new String[] { "css", "scss" }, true);

                            final Collection<File> cached = new HashSet<File>();

                            for (File file : files) {
                                if (file.getName().endsWith("scss")) {
                                    final File cachedFile = new File(file.getParent(),
                                            ".sass-cache/" + file.getName().replaceAll("scss$", "css"));

                                    if (cachedFile.exists()) {
                                        cached.add(file);
                                    }
                                }
                            }

                            files.removeAll(cached);

                            if (files != null) {
                                retval = files.toArray(new File[0]);
                            }

                            fileCache.put(cssPath, files);
                        }
                    }
                }
            }
        } else if (portal != null && ProjectUtil.isLayoutTplProject(htmlFile.getProject())) {
            // return the static css resource for layout template names based on the version

            final String version = portal.getVersion();

            try {
                if (version != null && (version.startsWith("6.0") || version.startsWith("6.1"))) {
                    retval = createLayoutHelperFiles("resources/layouttpl-6.1.css");
                } else if (version != null) {
                    retval = createLayoutHelperFiles("resources/layouttpl-6.2.css");
                }
            } catch (IOException e) {
                AlloyCore.logError("Unable to load layout template helper css files", e);
            }
        }
    }

    return retval;
}

From source file:de.cismet.lagis.cidsmigtest.CustomBeanToStringTester.java

/**
 * DOCUMENT ME!/*w w w  . ja va2 s.com*/
 *
 * @param   object  DOCUMENT ME!
 *
 * @return  DOCUMENT ME!
 */
public static String getStringOf(final Collection<? extends CidsBean> object) {
    final StringBuilder sb = new StringBuilder("\n" + tab() + "[Collection |");
    if (object != null) {
        final List<CidsBean> sortedList = new ArrayList<CidsBean>();
        Collections.addAll(sortedList, object.toArray(new CidsBean[0]));
        Collections.sort(sortedList, new Comparator<CidsBean>() {

            @Override
            public int compare(final CidsBean o1, final CidsBean o2) {
                return o1.getMetaObject().getId() - o2.getMetaObject().getId();
            }
        });
        for (final CidsBean item : sortedList) {
            sb.append(getStringOf(item)).append("\n");
        }
    }
    sb.append("\n").append(untab()).append("]");
    return sb.toString();
}

From source file:com.googlecode.android_scripting.rpc.MethodDescriptorTest.java

@SuppressWarnings("unused")
public void testCollectFromClass() {
    class A extends RpcReceiver {
        public A() {
            super(null);
        }/* www.  j a  v  a 2  s  .  c o m*/

        public void notRpc() {
        }

        @Rpc(description = "rpc", returns = "nothing")
        public void rpc() {
        }

        @Override
        public void shutdown() {
        }
    }

    Collection<MethodDescriptor> methods = MethodDescriptor.collectFrom(A.class);

    assertEquals(1, methods.size());
    assertEquals("rpc", methods.toArray(new MethodDescriptor[0])[0].getName());
}

From source file:br.com.caelum.vraptor.interceptor.multipart.CommonsUploadMultipartInterceptor.java

public void intercept(InterceptorStack stack, ResourceMethod method, Object instance)
        throws InterceptionException {
    logger.info("Request contains multipart data. Try to parse with commons-upload.");

    FileItemFactory factory = createFactoryForDiskBasedFileItems(config.getDirectory());

    ServletFileUpload uploader = fileUploadCreator.create(factory);
    uploader.setSizeMax(config.getSizeLimit());

    try {/*from   ww  w  .j a  v a 2 s . co m*/
        final List<FileItem> items = uploader.parseRequest(request);
        logger.debug("Found {} attributes in the multipart form submission. Parsing them.", items.size());

        final Multimap<String, String> params = LinkedListMultimap.create();

        for (FileItem item : items) {
            String name = item.getFieldName();
            name = fixIndexedParameters(name);

            if (item.isFormField()) {
                logger.debug("{} is a field", name);
                params.put(name, getValue(item));

            } else if (isNotEmpty(item)) {
                logger.debug("{} is a file", name);
                processFile(item, name);

            } else {
                logger.debug("A file field was empty: {}", item.getFieldName());
            }
        }

        for (String paramName : params.keySet()) {
            Collection<String> paramValues = params.get(paramName);
            parameters.setParameter(paramName, paramValues.toArray(new String[paramValues.size()]));
        }

    } catch (final SizeLimitExceededException e) {
        reportSizeLimitExceeded(e);

    } catch (FileUploadException e) {
        logger.warn("There was some problem parsing this multipart request, "
                + "or someone is not sending a RFC1867 compatible multipart request.", e);
    }

    stack.next(method, instance);
}

From source file:net.dv8tion.jda.core.entities.impl.MemberImpl.java

@Override
public boolean hasPermission(Channel channel, Collection<Permission> permissions) {
    Args.notNull(permissions, "Permission Collection");

    return hasPermission(channel, permissions.toArray(new Permission[permissions.size()]));
}

From source file:ch.there.gson.GsonInvokerServiceExporter.java

@Override
public void handle(HttpExchange exchange) throws IOException {
    Gson gson = GsonFactory.getGson();//from w w  w  . ja v a  2s  . co  m

    try {
        Integer rpcVersion = Integer.valueOf(exchange.getRequestHeaders().getFirst("rpc-version"));
        CallerRemoteApiVersion.setVersion(rpcVersion);
        InputStreamReader reader = new InputStreamReader(exchange.getRequestBody());
        JsonParser parser = new JsonParser();
        JsonObject remote = parser.parse(reader).getAsJsonObject();
        String methodName = remote.get("methodName").getAsString();

        Type collectionType = new TypeToken<Collection<Class<?>>>() {
        }.getType();
        Collection<Class<?>> parameterTypes = gson.fromJson(remote.get("parameterTypes"), collectionType);

        JsonArray args = remote.get("arguments").getAsJsonArray();
        Class<?>[] params = parameterTypes.toArray(new Class[parameterTypes.size()]);

        Object[] arguments = new Object[params.length];

        for (int i = 0; i < params.length; i++) {
            Class<?> clazz = params[i];
            Object argument = gson.fromJson(args.get(i), clazz);
            arguments[i] = argument;
        }

        RemoteInvocation remoteInvocation = new RemoteInvocation(methodName, params, arguments);
        RemoteInvocationResult result = invokeAndCreateResult(remoteInvocation, getProxy());
        writeRemoteInvocationResult(exchange, result);
        exchange.close();
    } catch (Throwable e) {
        e.printStackTrace();
    }

}

From source file:org.apache.batchee.cli.lifecycle.impl.SpringLifecycle.java

@Override
public AbstractApplicationContext start() {
    final Map<String, Object> config = configuration("spring");

    final AbstractApplicationContext ctx;
    if (config.containsKey("locations")) {
        final Collection<String> locations = new LinkedList<String>();
        locations.addAll(asList(config.get("locations").toString().split(",")));
        ctx = new ClassPathXmlApplicationContext(locations.toArray(new String[locations.size()]));
    } else if (config.containsKey("classes")) {
        final Collection<Class<?>> classes = new LinkedList<Class<?>>();
        final ClassLoader loader = currentThread().getContextClassLoader();
        for (final String clazz : config.get("classes").toString().split(",")) {
            try {
                classes.add(loader.loadClass(clazz));
            } catch (final ClassNotFoundException e) {
                throw new BatchContainerRuntimeException(e);
            }/*w  w w .j av  a2s . c  om*/
        }
        ctx = new AnnotationConfigApplicationContext(classes.toArray(new Class<?>[classes.size()]));
    } else {
        throw new IllegalArgumentException(
                LIFECYCLE_PROPERTIES_FILE + " should contain 'classes' or 'locations' key");
    }

    final Properties p = new Properties();
    p.put(BatchArtifactFactory.class.getName(), new SpringArtifactFactory(ctx));

    final ServicesManager mgr = new ServicesManager();
    mgr.init(p);

    ServicesManager.setServicesManagerLocator(new ServicesManagerLocator() {
        @Override
        public ServicesManager find() {
            return mgr;
        }
    });

    return ctx;
}

From source file:com.google.enterprise.connector.persist.MigrateStore.java

/**
 * Prints a menu from a Collection of choices, asks the user to pick one.
 *
 * @param header Text to display above the list of choices.
 * @param prompt Text to display on the prompt line.
 * @param choices Available choices./*from w w  w. ja va2 s.co m*/
 * @return item chosen from the choices, or null if none was selected.
 */
private String pickMenu(String header, String prompt, Collection<String> choices) {
    try {
        String[] items = choices.toArray(new String[0]);
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        do {
            System.out.println("");
            System.out.println(header);
            for (int i = 0; i < items.length; i++) {
                System.out.println("  " + (i + 1) + ")  " + items[i]);
            }
            System.out.print(prompt);

            String answer = in.readLine();
            if (answer == null || answer.trim().length() == 0) {
                return null;
            }
            int choiceNum;
            try {
                choiceNum = Integer.parseInt(answer) - 1;
            } catch (NumberFormatException nfe) {
                choiceNum = -1; // Force chose again.
            }
            if (choiceNum >= 0 && choiceNum < items.length) {
                return items[choiceNum];
            }
            System.err.println("Invalid choice.\n");
        } while (true);
    } catch (IOException e) {
        System.err.println("Failed to read from input: " + e.getMessage());
    }
    return null;
}