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:edu.pdx.konstan2.PortlandLive.StopsFactory.java

public String[] listRoutes() {
    ArrayList<String> result = new ArrayList<>();
    for (Route r : routes) {
        result.add(r.description);/*from   w  w w.  j  av  a  2  s. com*/
    }
    return result.toArray(new String[result.size()]);
}

From source file:com.technophobia.substeps.model.Util.java

public static String[] getArgs(final String patternString, final String sourceString,
        final String[] keywordPrecedence) {

    log.debug("Util getArgs String[] with pattern: " + patternString + " and sourceStr: " + sourceString);

    String[] rtn = null;/*from  w  w w .j a v a  2s. c o m*/

    ArrayList<String> argsList = null;

    String patternCopy = new String(patternString);
    if (keywordPrecedence != null && StringUtils.startsWithAny(patternString, keywordPrecedence)) {
        //
        for (String s : keywordPrecedence) {

            patternCopy = StringUtils.removeStart(patternCopy, s);
        }

        patternCopy = "(?:" + StringUtils.join(keywordPrecedence, "|") + ")" + patternCopy;
    }

    final Pattern pattern = Pattern.compile(patternCopy);
    final Matcher matcher = pattern.matcher(sourceString);

    final int groupCount = matcher.groupCount();

    // TODO - this doesn't work if we're not doing strict matching
    if (matcher.find()) {

        for (int i = 1; i <= groupCount; i++) {
            final String arg = matcher.group(i);

            if (arg != null) {
                if (argsList == null) {
                    argsList = new ArrayList<String>();
                }
                argsList.add(arg);
            }
        }
    }

    if (argsList != null) {
        rtn = argsList.toArray(new String[argsList.size()]);

        if (log.isDebugEnabled()) {

            final StringBuilder buf = new StringBuilder();
            buf.append("returning args: ");

            for (final String s : argsList) {

                buf.append("[").append(s).append("] ");
            }

            log.debug(buf.toString());
        }

    }

    return rtn;
}

From source file:controller.FriendController.java

public void addFriendToList(String userID) {
    if (globalUserlist != null) {
        User reqUser = null;// w ww. j  a  v  a2 s.c  om
        for (User user : globalUserlist) {
            if (user.userID.equals(userID)) {
                reqUser = user;
            }
        }
        if (reqUser != null) {
            ArrayList<User> userList = new ArrayList<User>(Arrays.asList(personalFriendlist));
            userList.add(reqUser);
            shared.setPersonalFriendlist(userList.toArray(new User[userList.size()]));
        } else {
            System.out.println("ERROR: Could not find requesting user. - " + userID);
        }
    } else {
        System.out.println("ERROR: Global userlist not retrieved yet.");
    }
}

From source file:edu.pdx.konstan2.PortlandLive.StopsFactory.java

public String[] routesIDs() {
    ArrayList<String> result = new ArrayList<>();
    for (Route r : routes) {
        result.add(r.route.toString());//w ww  . j  av  a2 s .c o m
    }
    return result.toArray(new String[result.size()]);
}

From source file:be.ibridge.kettle.core.XMLHandler.java

public static String[] getNodeElements(Node node) {
    ArrayList elements = new ArrayList(); // List of String 

    NodeList nodeList = node.getChildNodes();
    if (nodeList == null)
        return null;

    for (int i = 0; i < nodeList.getLength(); i++) {
        String nodeName = nodeList.item(i).getNodeName();
        if (elements.indexOf(nodeName) < 0)
            elements.add(nodeName);//w w  w.  ja  v  a  2  s.  com
    }

    if (elements.size() == 0)
        return null;

    return (String[]) elements.toArray(new String[elements.size()]);
}

From source file:com.janrain.servlet.IPRangeFilter.java

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    String ipWhiteList = System.getProperty(BackplaneSystemProps.IP_WHITE_LIST);
    if (StringUtils.isNotBlank(ipWhiteList)) {
        List<String> items = Arrays.asList(ipWhiteList.split("\\s*,\\s*"));
        ArrayList<Pattern> patternArrayList = new ArrayList<Pattern>();
        for (String item : items) {
            patternArrayList.add(Pattern.compile(item));
        }/*from  ww w. j ava 2s .  c  o  m*/
        whiteListProxies = (Pattern[]) patternArrayList.toArray(new Pattern[0]);
        logger.info("white listed ips: " + ipWhiteList);
    }
}

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

public static String[] listResourcesByType(String jar$, String type$) {
    try {/*from  w w w  .j a  v a2 s.c  o m*/

        ArrayList<String> sl = new ArrayList<String>();
        ZipFile zf = new ZipFile(jar$);
        Enumeration<? extends ZipEntry> entries = zf.entries();
        ZipEntry ze;
        String[] sa;
        String resource$;
        while (entries.hasMoreElements()) {
            try {
                ze = entries.nextElement();
                sa = ze.getName().split("/");
                resource$ = sa[sa.length - 1];
                //     System.out.println("ExtensionHandler:loadIcon:zip entry="+sa[sa.length-1]);
                if (type$.equals(FileExpert.getExtension(resource$))) {
                    sl.add(resource$);
                }
            } catch (Exception e) {

            }
        }
        return sl.toArray(new String[0]);
    } catch (Exception e) {
        Logger.getLogger(ExtensionHandler.class.getName()).severe(e.toString());
        return null;
    }

}

From source file:hyperheuristics.algorithm.moeadfrrmab.UCBSelectorVariance.java

protected double calcVariance(String op) {
    ArrayList<String[]> slOp = slidingwindow.getWindowforOp(op);
    if (slOp.size() > 1) {
        ArrayList<Double> values = new ArrayList<>();
        for (int i = 0; i < slOp.size(); i++) {
            String[] data = slOp.get(i);
            double FIR = Double.valueOf(data[1]);
            values.add(FIR);/*  ww  w . j  a v  a 2 s  .c o  m*/
        }
        double[] arr = ArrayUtils.toPrimitive(values.toArray(new Double[0]));
        return this.calcVariance(arr);
    }
    return 1.0;
}

From source file:com.opencredo.portlet.MyBooksController.java

private void storeMyBooks(PortletPreferences prefs, SortedSet<Book> myBooks) {
    ArrayList<String> keys = new ArrayList<String>();
    for (Iterator<Book> i = myBooks.iterator(); i.hasNext();) {
        Book book = i.next();/*from w w  w  .j a  v  a  2 s.  c  om*/
        keys.add(book.getKey().toString());
    }
    String[] keysArr = keys.toArray(new String[] {});
    try {
        prefs.setValues("myBooks", keysArr);
        prefs.store();
    } catch (Exception e) {
        logger.warn("unable to set portlet preference", e);
    }
}

From source file:net.sf.taverna.t2.activities.biomoby.ExecuteAsyncCgiService.java

private static boolean pollAsyncCgiService(String msName, String url, EndpointReference epr, String[] queryIds,
        String[] result) throws MobyException {
    // Needed to remap results
    HashMap<String, Integer> queryMap = new HashMap<String, Integer>();
    for (int qi = 0; qi < queryIds.length; qi++) {
        String queryId = queryIds[qi];
        if (queryId != null)
            queryMap.put(queryId, new Integer(qi));
    }//from  ww w .  jav a2 s  .  c om

    if (queryMap.size() == 0)
        return false;

    // construct the GetMultipleResourceProperties XML
    StringBuffer xml = new StringBuffer();
    xml.append("<wsrf-rp:GetMultipleResourceProperties xmlns:wsrf-rp='" + RESOURCE_PROPERTIES_NS
            + "' xmlns:mobyws='http://biomoby.org/'>");
    for (String q : queryMap.keySet())
        xml.append("<wsrf-rp:ResourceProperty>mobyws:" + STATUS_PREFIX + q + "</wsrf-rp:ResourceProperty>");
    xml.append("</wsrf-rp:GetMultipleResourceProperties>");

    StringBuffer httpheader = new StringBuffer();
    httpheader.append("<moby-wsrf>");
    httpheader.append("<wsa:Action xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">"
            + GET_MULTIPLE_RESOURCE_PROPERTIES_ACTION + "</wsa:Action>");
    httpheader.append(
            "<wsa:To xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsu:Id=\"To\">"
                    + url + "</wsa:To>");
    httpheader.append(
            "<mobyws:ServiceInvocationId xmlns:mobyws=\"http://biomoby.org/\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsa:IsReferenceParameter=\"true\">"
                    + epr.getServiceInvocationId() + "</mobyws:ServiceInvocationId>");
    httpheader.append("</moby-wsrf>");

    AnalysisEvent[] l_ae = null;
    // First, status from queries
    String response = "";
    // construct the Httpclient
    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "jMoby/Taverna2");
    // create the post method
    PostMethod method = new PostMethod(url + "/status");
    // add the moby-wsrf header (with no newlines)
    method.addRequestHeader("moby-wsrf", httpheader.toString().replaceAll("\r\n", ""));

    // put our data in the request
    RequestEntity entity;
    try {
        entity = new StringRequestEntity(xml.toString(), "text/xml", null);
    } catch (UnsupportedEncodingException e) {
        throw new MobyException("Problem posting data to webservice", e);
    }
    method.setRequestEntity(entity);

    // retry up to 10 times
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(10, true));

    // call the method
    try {
        if (client.executeMethod(method) != HttpStatus.SC_OK)
            throw new MobyException("Async HTTP POST service returned code: " + method.getStatusCode() + "\n"
                    + method.getStatusLine() + "\nduring our polling request");
        response = stream2String(method.getResponseBodyAsStream());
    } catch (IOException e) {
        throw new MobyException("Problem reading response from webservice", e);
    } finally {
        // Release current connection to the connection pool once you
        // are
        // done
        method.releaseConnection();
    }

    if (response != null) {
        l_ae = AnalysisEvent.createFromXML(response);
    }

    if (l_ae == null || l_ae.length == 0) {
        new MobyException("Troubles while checking asynchronous MOBY job status from service " + msName);
    }

    ArrayList<String> finishedQueries = new ArrayList<String>();
    // Second, gather those finished queries
    for (int iae = 0; iae < l_ae.length; iae++) {
        AnalysisEvent ae = l_ae[iae];
        if (ae.isCompleted()) {
            String queryId = ae.getQueryId();
            if (!queryMap.containsKey(queryId)) {
                throw new MobyException(
                        "Invalid result queryId on asynchronous MOBY job status fetched from " + msName);
            }
            finishedQueries.add(queryId);
        }
    }

    // Third, let's fetch the results from the finished queries
    if (finishedQueries.size() > 0) {
        String[] resQueryIds = finishedQueries.toArray(new String[0]);
        for (int x = 0; x < resQueryIds.length; x++) {
            // construct the GetMultipleResourceProperties XML
            xml = new StringBuffer();
            xml.append("<wsrf-rp:GetMultipleResourceProperties xmlns:wsrf-rp='" + RESOURCE_PROPERTIES_NS
                    + "' xmlns:mobyws='http://biomoby.org/'>");
            for (String q : resQueryIds)
                xml.append("<wsrf-rp:ResourceProperty>mobyws:" + RESULT_PREFIX + q
                        + "</wsrf-rp:ResourceProperty>");
            xml.append("</wsrf-rp:GetMultipleResourceProperties>");

            httpheader = new StringBuffer();
            httpheader.append("<moby-wsrf>");
            httpheader.append("<wsa:Action xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">"
                    + GET_MULTIPLE_RESOURCE_PROPERTIES_ACTION + "</wsa:Action>");
            httpheader.append(
                    "<wsa:To xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsu:Id=\"To\">"
                            + url + "</wsa:To>");
            httpheader.append(
                    "<mobyws:ServiceInvocationId xmlns:mobyws=\"http://biomoby.org/\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsa:IsReferenceParameter=\"true\">"
                            + epr.getServiceInvocationId() + "</mobyws:ServiceInvocationId>");
            httpheader.append("</moby-wsrf>");
            client = new HttpClient();
            client.getParams().setParameter("http.useragent", "jMoby/Taverna2");
            // create the post method
            method = new PostMethod(url + "/results");
            // add the moby-wsrf header (with no newlines)
            method.addRequestHeader("moby-wsrf", httpheader.toString().replaceAll("\r\n", ""));

            // put our data in the request
            entity = null;
            try {
                entity = new StringRequestEntity(xml.toString(), "text/xml", null);
            } catch (UnsupportedEncodingException e) {
                throw new MobyException("Problem posting data to webservice", e);
            }
            method.setRequestEntity(entity);

            // retry up to 10 times
            client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(10, true));

            // call the method
            try {
                if (client.executeMethod(method) != HttpStatus.SC_OK)
                    throw new MobyException("Async HTTP POST service returned code: " + method.getStatusCode()
                            + "\n" + method.getStatusLine() + "\nduring our polling request");
                // place the result in the array
                result[x] = stream2String(method.getResponseBodyAsStream());
                // Marking as null
                queryIds[x] = null;
            } catch (IOException e) {
                logger.warn("Problem getting result from webservice\n" + e.getMessage());
            } finally {
                // Release current connection
                method.releaseConnection();
            }
        }

    }
    return finishedQueries.size() != queryMap.size();
}