Example usage for org.apache.commons.collections CollectionUtils addAll

List of usage examples for org.apache.commons.collections CollectionUtils addAll

Introduction

In this page you can find the example usage for org.apache.commons.collections CollectionUtils addAll.

Prototype

public static void addAll(Collection collection, Object[] elements) 

Source Link

Document

Adds all elements in the array to the given collection.

Usage

From source file:org.xenmaster.api.entity.VM.java

public List<Object> getDataSources() throws BadAPICallException {
    Object[] result = (Object[]) dispatch("get_data_sources");
    ArrayList<Object> arrr = new ArrayList<>();
    CollectionUtils.addAll(arrr, result);
    return arrr;/*from   w  w w. ja  v  a  2s  . co  m*/
}

From source file:org.xenmaster.controller.Dispatcher.java

public Object dispatch(String methodName, Object[] params, int connection) throws BadAPICallException {
    ArrayList list = new ArrayList();
    CollectionUtils.addAll(list, params);

    return execute(methodName, list, connection);
}

From source file:org.xenmaster.controller.Dispatcher.java

public Object dispatchWithSession(String methodName, Object[] params, int connection)
        throws BadAPICallException {
    if (conn.getSession().getReference() == null) {
        throw new Error("Session has not been initialized");
    }//from ww  w  .  ja v  a2  s  .  com
    ArrayList list = new ArrayList();
    list.add(conn.getSession().getReference());
    CollectionUtils.addAll(list, params);

    return execute(methodName, list, connection);
}

From source file:phex.download.DownloadEngine.java

public void exchangeHTTPHandshake(SWDownloadSegment aSegment)
        throws IOException, UnusableHostException, HTTPMessageException {
    NetworkManager networkMgr = NetworkManager.getInstance();
    isDownloadSuccessful = false;/* www  .  j av  a2 s  . com*/
    segment = aSegment;
    long downloadOffset = segment.getTransferStartPosition();

    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    // reset to default input stream
    inStream = connection.getInputStream();

    String requestUrl = candidate.getDownloadRequestUrl();

    HTTPRequest request = new HTTPRequest("GET", requestUrl, true);
    request.addHeader(new HTTPHeader(HTTPHeaderNames.HOST, candidate.getHostAddress().getFullHostName()));
    request.addHeader(
            new HTTPHeader(GnutellaHeaderNames.LISTEN_IP, networkMgr.getLocalAddress().getFullHostName()));
    long segmentEndOffset = segment.getEnd();
    if (segmentEndOffset == -1) {// create header with open end
        request.addHeader(new HTTPHeader(HTTPHeaderNames.RANGE, "bytes=" + downloadOffset + "-"));
    } else {
        request.addHeader(
                new HTTPHeader(HTTPHeaderNames.RANGE, "bytes=" + downloadOffset + "-" + segmentEndOffset));
    }
    request.addHeader(new HTTPHeader(GnutellaHeaderNames.X_QUEUE, "0.1"));
    // request a HTTP keep alive connection, needed for queuing to work.
    request.addHeader(new HTTPHeader(HTTPHeaderNames.CONNECTION, "Keep-Alive"));
    if (candidate.isG2FeatureAdded()) {
        request.addHeader(new HTTPHeader("X-Features", "g2/1.0"));
    }

    buildAltLocRequestHeader(request);

    if (ServiceManager.sCfg.isChatEnabled) {
        DestAddress ha = networkMgr.getLocalAddress();
        IpAddress myIp = ha.getIpAddress();
        if (myIp == null || !myIp.isSiteLocalIP()) {
            request.addHeader(new HTTPHeader("Chat", ha.getFullHostName()));
        }
    }

    String httpRequestStr = request.buildHTTPRequestString();

    NLogger.debug(NLoggerNames.Download_Engine,
            "HTTP Request to: " + candidate.getHostAddress() + "\n" + httpRequestStr);
    candidate.addToCandidateLog("HTTP Request:\n" + httpRequestStr);
    // write request...
    writer.write(httpRequestStr);
    writer.flush();

    HTTPResponse response = HTTPProcessor.parseHTTPResponse(connection);
    if (NLogger.isDebugEnabled(NLoggerNames.Download_Engine)) {
        NLogger.debug(NLoggerNames.Download_Engine, "HTTP Response from: " + candidate.getHostAddress() + "\n"
                + response.buildHTTPResponseString());
    }
    if (ServiceManager.sCfg.downloadCandidateLogBufferSize > 0) {
        candidate.addToCandidateLog("HTTP Response:\n" + response.buildHTTPResponseString());
    }

    HTTPHeader header = response.getHeader(HTTPHeaderNames.SERVER);
    if (header != null) {
        candidate.setVendor(header.getValue());
    }

    header = response.getHeader(HTTPHeaderNames.TRANSFER_ENCODING);
    if (header != null) {
        if (header.getValue().equals("chunked")) {
            inStream = new ChunkedInputStream(connection.getInputStream());
        }
    }

    replyContentRange = null;
    header = response.getHeader(HTTPHeaderNames.CONTENT_RANGE);
    if (header != null) {
        replyContentRange = parseContentRange(header.getValue());
        // startPos of -1 indicates '*' (free to choose)
        if (replyContentRange.startPos != -1 && replyContentRange.startPos != downloadOffset) {
            throw new IOException("Invalid 'CONTENT-RANGE' start offset.");
        }
    }

    replyContentLength = -1;
    header = response.getHeader(HTTPHeaderNames.CONTENT_LENGTH);
    if (header != null) {
        try {
            replyContentLength = header.longValue();
        } catch (NumberFormatException exp) { //unknown 
        }
    }

    URN downloadFileURN = downloadFile.getFileURN();
    ArrayList contentURNHeaders = new ArrayList();
    header = response.getHeader(GnutellaHeaderNames.X_GNUTELLA_CONTENT_URN);
    if (header != null) {
        contentURNHeaders.add(header);
    }
    // Shareaza 1.8.10.4 send also a bitprint urn in multiple X-Content-URN headers!
    HTTPHeader[] headers = response.getHeaders(GnutellaHeaderNames.X_CONTENT_URN);
    CollectionUtils.addAll(contentURNHeaders, headers);
    if (downloadFileURN != null) {
        Iterator contentURNIterator = contentURNHeaders.iterator();
        while (contentURNIterator.hasNext()) {
            header = (HTTPHeader) contentURNIterator.next();
            String contentURNStr = header.getValue();
            // check if I can understand urn.
            if (URN.isValidURN(contentURNStr)) {
                URN contentURN = new URN(contentURNStr);
                if (!downloadFileURN.equals(contentURN)) {
                    throw new IOException("Required URN and content URN do not match.");
                }
            }
        }
    }

    // check Limewire chat support header.
    header = response.getHeader(GnutellaHeaderNames.CHAT);
    if (header != null) {
        candidate.setChatSupported(true);
    }
    // read out REMOTE-IP header... to update my IP
    header = response.getHeader(GnutellaHeaderNames.REMOTE_IP);
    if (header != null) {
        byte[] remoteIP = AddressUtils.parseIP(header.getValue());
        if (remoteIP != null) {
            IpAddress ip = new IpAddress(remoteIP);
            DestAddress address = PresentationManager.getInstance().createHostAddress(ip, -1);
            networkMgr.updateLocalAddress(address);
        }
    }

    int httpCode = response.getStatusCode();

    // read available ranges
    header = response.getHeader(GnutellaHeaderNames.X_AVAILABLE_RANGES);
    if (header != null) {
        HTTPRangeSet availableRanges = HTTPRangeSet.parseHTTPRangeSet(header.getValue());
        if (availableRanges == null) {// failed to parse... give more detailed error report
            NLogger.error(NLoggerNames.Download_Engine, "Failed to parse X-Available-Ranges in "
                    + candidate.getVendor() + " request: " + response.buildHTTPResponseString());
        }
        candidate.setAvailableRangeSet(availableRanges);
    } else if (httpCode >= 200 && httpCode < 300
            && downloadFile.getTotalDataSize() != SWDownloadConstants.UNKNOWN_FILE_SIZE) {// OK header and no available range header.. we assume candidate
                                                                                                                                       // shares the whole file
        candidate.setAvailableRangeSet(new HTTPRangeSet(0, downloadFile.getTotalDataSize() - 1));
    }

    // collect alternate locations...
    List altLocList = new ArrayList();
    headers = response.getHeaders(GnutellaHeaderNames.ALT_LOC);
    List altLocTmpList = AlternateLocationContainer.parseUriResAltLocFromHTTPHeaders(headers);
    altLocList.addAll(altLocTmpList);

    headers = response.getHeaders(GnutellaHeaderNames.X_ALT_LOC);
    altLocTmpList = AlternateLocationContainer.parseUriResAltLocFromHTTPHeaders(headers);
    altLocList.addAll(altLocTmpList);

    headers = response.getHeaders(GnutellaHeaderNames.X_ALT);
    altLocTmpList = AlternateLocationContainer.parseCompactIpAltLocFromHTTPHeaders(headers, downloadFileURN);
    altLocList.addAll(altLocTmpList);

    // TODO1 huh?? dont we pare X-NALT???? 

    Iterator iterator = altLocList.iterator();
    while (iterator.hasNext()) {
        downloadFile.addDownloadCandidate((AlternateLocation) iterator.next());
    }

    // collect push proxies.
    // first the old headers..
    headers = response.getHeaders("X-Pushproxies");
    handlePushProxyHeaders(headers);
    headers = response.getHeaders("X-Push-Proxies");
    handlePushProxyHeaders(headers);
    // now the standard header
    headers = response.getHeaders(GnutellaHeaderNames.X_PUSH_PROXY);
    handlePushProxyHeaders(headers);

    updateKeepAliveSupport(response);

    if (httpCode >= 200 && httpCode < 300) {// code accepted

        // check if we can accept the urn...
        if (contentURNHeaders.size() == 0 && requestUrl.startsWith(GnutellaRequest.GNUTELLA_URI_RES_PREFIX)) {// we requested a download via /uri-res resource urn.
                                                                                                              // we expect that the result contains a x-gnutella-content-urn
                                                                                                              // or Shareaza X-Content-URN header.
            throw new IOException("Response to uri-res request without valid Content-URN header.");
        }

        // check if we need and can update our file and segment size.
        if (downloadFile.getTotalDataSize() == SWDownloadConstants.UNKNOWN_FILE_SIZE) {
            // we have a file with an unknown data size. For aditional check assert
            // certain parameters
            assert (segment.getTotalDataSize() == -1);
            // Now verify if we have the great chance to update our file data!
            if (replyContentRange != null
                    && replyContentRange.totalLength != SWDownloadConstants.UNKNOWN_FILE_SIZE) {
                downloadFile.setFileSize(replyContentRange.totalLength);
                // we learned the file size. To allow normal segment use 
                // interrupt the download!
                stopDownload();
                throw new ReconnectException();
            }
        }

        // connection successfully finished
        NLogger.debug(NLoggerNames.Download_Engine, "HTTP Handshake successfull.");
        return;
    }
    // check error type
    else if (httpCode == 503) {// 503 -> host is busy (this can also be returned when remotly queued)
        header = response.getHeader(GnutellaHeaderNames.X_QUEUE);
        XQueueParameters xQueueParameters = null;
        if (header != null) {
            xQueueParameters = XQueueParameters.parseHTTPRangeSet(header.getValue());
        }
        // check for persistent connection (gtk-gnutella uses queuing with 'Connection: close')
        if (xQueueParameters != null && isKeepAliveSupported) {
            throw new RemotelyQueuedException(xQueueParameters);
        } else {
            header = response.getHeader(HTTPHeaderNames.RETRY_AFTER);
            if (header != null) {
                int delta = HTTPRetryAfter.parseDeltaInSeconds(header);
                if (delta > 0) {
                    throw new HostBusyException(delta);
                }
            }
            throw new HostBusyException();
        }
    } else if (httpCode == HTTPCodes.HTTP_401_UNAUTHORIZED || httpCode == HTTPCodes.HTTP_403_FORBIDDEN) {
        if ("Network Disabled".equals(response.getStatusReason())) {
            if (candidate.isG2FeatureAdded()) {
                // already tried G2 but no success.. better give up and dont hammer..
                throw new UnusableHostException("Request Forbidden");
            } else {
                // we have not tried G2 but we could..
                candidate.setG2FeatureAdded(true);
                throw new HostBusyException(60 * 5);
            }
        } else {
            throw new UnusableHostException("Request Forbidden");
        }
    } else if (httpCode == 408) {
        // 408 -> Time out. Try later?
        throw new HostBusyException();
    } else if (httpCode == 404 || httpCode == 410) {// 404: File not found / 410: Host not sharing
        throw new FileNotAvailableException();
    } else if (httpCode == 416) {// 416: Requested Range Unavailable
        header = response.getHeader(HTTPHeaderNames.RETRY_AFTER);
        if (header != null) {
            int delta = HTTPRetryAfter.parseDeltaInSeconds(header);
            if (delta > 0) {
                throw new RangeUnavailableException(delta);
            }
        }
        throw new RangeUnavailableException();
    } else {
        throw new IOException("Unknown HTTP code: " + httpCode);
    }
}

From source file:se.streamsource.streamflow.client.ui.administration.forms.definition.VisibilityRuleValuesModel.java

/**
 * Fetches any possible rule values, especially if the target rule is a SelectionField.
 * The result is filtered by already set values. If the target rule is not a SelectionField
 * the EventList will be empty.//from  w w  w . j a v  a 2 s  .c  o m
 * @return An EventList containing possible rule values.
 */
public EventList<LinkValue> possiblePredefinedRuleValues() {
    EventList<LinkValue> possibleRuleValues = new BasicEventList<LinkValue>();
    LinksValue available = client.query("possiblerulevalues", LinksValue.class);

    List<LinkValue> linkValues = new ArrayList<LinkValue>();
    CollectionUtils.addAll(linkValues, filter(new Specification<LinkValue>() {
        public boolean satisfiedBy(LinkValue link) {
            return !elements.contains(link.text().get());
        }
    }, available.links().get()).iterator());

    EventListSynch.synchronize(linkValues, possibleRuleValues);

    return possibleRuleValues;
}

From source file:ubic.basecode.dataStructure.matrix.SparseRaggedDoubleMatrix.java

/**
 * @param matrix1D/*from   w ww . ja v a 2  s.c o m*/
 */
public void addRow(R name, DoubleMatrix1D matrix1D) {
    List<Double> row = new ArrayList<Double>();
    CollectionUtils.addAll(row, ArrayUtils.toObject(matrix1D.toArray()));
    matrix.add(row);
    this.setRowName(name, matrix.size() - 1);
    isDirty = true;
}

From source file:ubic.basecode.dataStructure.matrix.SparseRaggedDoubleMatrix.java

/**
 * @param name//from   w  w  w . ja  va2 s  . co m
 * @param indexes
 * @param values
 */
public void addRow(R name, IntArrayList indexes, DoubleArrayList values) {
    List<Double> row = new ArrayList<Double>();
    CollectionUtils.addAll(row, ArrayUtils.toObject(values.elements()));
    matrix.add(row);
    this.setRowName(name, matrix.size() - 1);
    isDirty = true;
}

From source file:uk.ac.ebi.spot.rdf.model.AssayGroups.java

public Set<String> getAssayAccessions() {
    Set<String> assayAccessions = Sets.newHashSet();

    for (AssayGroup assayGroup : assayGroupsById.values()) {
        CollectionUtils.addAll(assayAccessions, assayGroup.iterator());
    }//  www  .  j  a  v a  2  s.  co m

    return assayAccessions;
}