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

Object[] toArray();

Source Link

Document

Returns an array containing all of the elements in this collection.

Usage

From source file:com.medvision360.medrecord.engine.ArchetypeBasedValidator.java

private String toString(Collection<?> allowedNodeIds) {
    return StringUtils.join(allowedNodeIds.toArray(), ", ");
}

From source file:es.gva.cit.gazetteer.idec.drivers.IDECGazetteerServiceDriver.java

public Feature[] getFeature(URI uri, GazetteerQuery query) {
    Collection nodes = new java.util.ArrayList();
    URL url = null;/*from   www .  j  a  v  a 2s . c om*/
    try {
        url = uri.toURL();
    } catch (MalformedURLException e) {
        setServerAnswerReady("errorServerNotFound");
        return null;
    }
    setQuery(query);
    System.out.println(getPOSTGetFeature(query));
    nodes = new HTTPPostProtocol().doQuery(url, getPOSTGetFeature(query), 0);
    if ((nodes != null) && (nodes.size() == 1)) {
        return IdecFeatureParser.parse((XMLNode) nodes.toArray()[0]);
    } else {
        return null;
    }
}

From source file:com.autentia.wuija.persistence.impl.hibernate.HibernateDao.java

public void persist(Collection<?> entities) {
    persist(entities.toArray());
}

From source file:com.xpn.xwiki.stats.impl.xwiki.XWikiStatsReader.java

/**
 * Return the statistics action stored.//from w w  w. jav a  2 s. co  m
 * 
 * @param action the action.
 * @param size the maximum size of the list to return.
 * @param context the XWiki context.
 * @return the list of recent statistics action stored.
 */
public Collection<Object> getRecentActions(String action, int size, XWikiContext context) {
    List<Object> list = new ArrayList<Object>();

    if ((action.equals(ViewAction.VIEW_ACTION) || (action.equals(SaveAction.ACTION_NAME)))) {
        Collection<?> actions = StatsUtil.getRecentActionFromSessions(context, action);

        if (actions != null) {
            Object[] actionsarray = actions.toArray();
            CollectionUtils.reverseArray(actionsarray);
            int nb = Math.min(actions.size(), size);
            for (int i = 0; i < nb; i++) {
                list.add(actionsarray[i]);
            }
        }
    }

    return list;
}

From source file:com.redhat.lightblue.rest.auth.jboss.CertLdapLoginModule.java

@Override
protected Group[] getRoleSets() throws LoginException {
    LOGGER.debug("staticRoleLoginModule getRoleSets()");

    String roleName = (String) options.get(AUTH_ROLE_NAME);

    SimpleGroup userRoles = new SimpleGroup("Roles");

    Principal p = null;//w  w  w .  j a v  a  2 s  . com

    String certPrincipal = getUsername();

    try {
        initializeLightblueLdapRoleProvider();

        LOGGER.debug("Certificate principal:" + certPrincipal);

        //first try getting search name from uid in certificate principle (new certificates)
        String searchName = getLDAPAttribute(certPrincipal, UID);
        if (StringUtils.isNotBlank(searchName)) {
            //only try to validate environment if it is a certificate that contains uid
            validateEnvironment(certPrincipal);
        } else {
            // fallback to getting search name from cn in certificate principle (legacy certificates)
            searchName = getLDAPAttribute(certPrincipal, CN);
        }

        Collection<String> groupNames = lbLdap.getUserRoles(searchName);

        p = super.createIdentity(roleName);

        userRoles.addMember(p);
        for (String groupName : groupNames) {
            Principal role = super.createIdentity(groupName);
            LOGGER.debug("Found role: " + groupName);
            userRoles.addMember(role);
        }

        if (ACCESS_LOGGER.isDebugEnabled()) {
            ACCESS_LOGGER.debug("Certificate principal: " + certPrincipal + ", roles: "
                    + Arrays.toString(groupNames.toArray()));
        }

        LOGGER.debug("Assign principal [" + p.getName() + "] to role [" + roleName + "]");
    } catch (Exception e) {
        String principalName = p == null ? certPrincipal : p.getName();
        LOGGER.error("Failed to assign principal [" + principalName + "] to role [" + roleName + "]", e);
    }
    Group[] roleSets = { userRoles };
    return roleSets;
}

From source file:ar.com.zauber.commons.gis.street.impl.SQLStreetsDAO.java

/** @see StreetsDAO#geocode(String, int) */
public final Collection<GeocodeResult> geocode_(final String streetParam, final int altura, final Integer id) {
    Validate.notEmpty(streetParam);/*from w w  w. ja va 2s  . com*/

    String streetFiltered = executeFilters(streetParam);

    final Collection<Object> args = new ArrayList<Object>();
    args.add(streetFiltered);
    args.add(altura);
    if (id != null) {
        args.add(id.intValue());
    }

    final Collection<GeocodeResult> ret = new ArrayList<GeocodeResult>();
    final String q = "select * from geocode_ba(?, ?)" + (id == null ? "" : " where id=?");
    template.query(q, args.toArray(), new ResultSetExtractor() {
        public final Object extractData(final ResultSet rs) throws SQLException, DataAccessException {

            while (rs.next()) {
                try {
                    ret.add(new GeocodeResult(rs.getInt("id"), rs.getString("nomoficial"), rs.getInt("altura"),
                            "AR", (Point) wktReader.read(rs.getString("astext"))));
                } catch (ParseException e) {
                    throw new DataRetrievalFailureException("parsing feature geom");
                }
            }

            return null;
        }
    });

    return ret;
}

From source file:com.scooter1556.sms.server.service.AdaptiveStreamingService.java

public void sendHLSPlaylist(UUID id, String type, Integer extra, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    // Get the request base URL so we can use it in our playlist
    String baseUrl = request.getRequestURL().toString().replaceFirst("/stream(.*)", "");

    List<String> playlist;

    // Get playlist as a string array
    if (type == null) {
        playlist = generateHLSVariantPlaylist(id, baseUrl);
    } else {/*  w  ww.  j a  v  a  2  s.co m*/
        playlist = generateHLSPlaylist(id, baseUrl, type, extra);
    }

    if (playlist == null) {
        LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME,
                "Unable to generate HLS playlist.", null);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to generate HLS playlist.");
        return;
    }

    // Write playlist to buffer so we can get the content length
    StringWriter playlistWriter = new StringWriter();
    for (String line : playlist) {
        playlistWriter.write(line + "\n");
    }

    // Set Header Parameters
    response.reset();
    response.setContentType("application/x-mpegurl");
    response.setContentLength(playlistWriter.toString().length());

    // Enable CORS
    response.setHeader(("Access-Control-Allow-Origin"), "*");
    response.setHeader("Access-Control-Allow-Methods", "GET");
    response.setIntHeader("Access-Control-Max-Age", 3600);

    // Write playlist out to the client
    response.getWriter().write(playlistWriter.toString());

    /*********************** DEBUG: Response Headers *********************************/
    String requestHeader = "\n***************\nResponse Header:\n***************\n";
    Collection<String> responseHeaderNames = response.getHeaderNames();

    for (int i = 0; i < responseHeaderNames.size(); i++) {
        String header = (String) responseHeaderNames.toArray()[i];
        String value = response.getHeader(header);
        requestHeader += header + ": " + value + "\n";
    }

    // Log Headers
    LogService.getInstance().addLogEntry(LogService.Level.INSANE, CLASS_NAME, requestHeader, null);

    /********************************************************************************/

    // Log playlist
    LogService.getInstance().addLogEntry(LogService.Level.INSANE, CLASS_NAME,
            "\n************\nHLS Playlist\n************\n" + playlistWriter.toString(), null);
}

From source file:com.googlecode.concurrentlinkedhashmap.ConcurrentMapTest.java

@Test(dataProvider = "warmedMap")
public void valuesToArray_whenPopulated(Map<Integer, Integer> map) {
    Collection<Integer> values = map.values();
    Object[] array1 = values.toArray();
    Object[] array2 = values.toArray(new Integer[map.size()]);
    Object[] expected = newHashMap(map).values().toArray();
    for (Object[] array : asList(array1, array2)) {
        assertThat(array.length, is(equalTo(values.size())));
        assertThat(asList(array), containsInAnyOrder(expected));
    }/*from  ww  w. jav a 2  s  .  com*/
}

From source file:org.semispace.semimeter.dao.SemiMeterDao.java

private void failed_rewrite_performInsertion(Collection<Item> items) {
    //log.debug("Performing batch insertion of "+items.size()+" items.");
    //List<Object[]> insertArgs = new ArrayList<Object[]>();
    //List<Object[]> updateArgs = new ArrayList<Object[]>();

    SqlParameterSource[] insertArgs = SqlParameterSourceUtils.createBatch(items.toArray());
    SqlParameterSource[] updateArgs = SqlParameterSourceUtils.createBatch(items.toArray());

    //for ( Item item : items ) {
    // Original just called insert
    //insertArgs.add( new Object[]{item.getWhen(), item.getPath(),item.getWhen(), item.getPath()});
    //updateArgs.add( new Object[] {item.getAccessNumber(), item.getPath(), item.getWhen()});
    //}/*from   w  w  w. j av  a  2 s.c  o m*/
    rwl.writeLock().lock();
    try {
        try {
            //log.debug("INSERT INTO meter(updated, count, path) SELECT DISTINCT ?, 0, ? FROM meter WHERE NOT EXISTS ( SELECT * FROM meter WHERE updated=? AND path=?)");
            jdbcTemplate.batchUpdate(
                    "INSERT INTO meter(updated, counted, path) SELECT DISTINCT :when, 0, :path FROM meter WHERE NOT EXISTS ( SELECT * FROM meter WHERE updated=:when AND path=:path)",
                    insertArgs);
        } catch (Exception e) {
            log.warn(
                    "Unlikely event occurred - failure whilst inserting priming elements. This is not overly critical. Masked exception: "
                            + e);
        }
        jdbcTemplate.batchUpdate(
                "update meter SET counted=counted+:accessNumber WHERE :path like :path and updated=:when",
                updateArgs);
    } catch (Exception e) {
        log.error("Could not update elements", e);
    } finally {
        rwl.writeLock().unlock();
    }
}

From source file:com.gst.infrastructure.dataqueries.domain.Report.java

private void validate(final Collection<String> reportTypes) {

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource("report");

    baseDataValidator.reset().parameter("reportName").value(this.reportName).notBlank()
            .notExceedingLengthOf(100);/*ww  w.  j  av a  2 s  . c  om*/

    baseDataValidator.reset().parameter("reportType").value(this.reportType).notBlank()
            .isOneOfTheseValues(reportTypes.toArray());

    baseDataValidator.reset().parameter("reportSubType").value(this.reportSubType).notExceedingLengthOf(20);

    if (StringUtils.isNotBlank(this.reportType)) {
        if (this.reportType.equals("Chart")) {
            baseDataValidator.reset().parameter("reportSubType").value(this.reportSubType)
                    .cantBeBlankWhenParameterProvidedIs("reportType", this.reportType)
                    .isOneOfTheseValues(new Object[] { "Bar", "Pie" });
        } else {
            baseDataValidator.reset().parameter("reportSubType").value(this.reportSubType)
                    .mustBeBlankWhenParameterProvidedIs("reportType", this.reportType);
        }
    }

    baseDataValidator.reset().parameter("reportCategory").value(this.reportCategory).notExceedingLengthOf(45);

    if (StringUtils.isNotBlank(this.reportType)) {
        if ((this.reportType.equals("Table")) || (this.reportType.equals("Chart"))) {
            baseDataValidator.reset().parameter("reportSql").value(this.reportSql)
                    .cantBeBlankWhenParameterProvidedIs("reportType", this.reportType);
        } else {
            baseDataValidator.reset().parameter("reportSql").value(this.reportSql)
                    .mustBeBlankWhenParameterProvidedIs("reportType", this.reportType);
        }
    }
    throwExceptionIfValidationWarningsExist(dataValidationErrors);
}