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.espertech.esper.epl.expression.core.ExprNodeUtility.java

public static ExprNode[] toArray(Collection<ExprNode> expressions) {
    if (expressions.isEmpty()) {
        return EMPTY_EXPR_ARRAY;
    }// w ww . j  av a2 s.  com
    return expressions.toArray(new ExprNode[expressions.size()]);
}

From source file:lu.softec.xwiki.macro.internal.ClassRunnerMacro.java

private ClassLoader getClassLoader(Collection<URL> pkgUrls, Collection<URL> dpkgUrls) {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (!dpkgUrls.isEmpty()) {
        pkgUrls.addAll(dpkgUrls);//from  w ww  .jav a 2 s.c  o  m
    }
    if (!pkgUrls.isEmpty()) {
        loader = loaderf.getURLClassLoader(pkgUrls.toArray(new URL[0]), loader, !dpkgUrls.isEmpty());
    }
    return loader;
}

From source file:com.espertech.esper.core.start.EPPreparedExecuteMethodQuery.java

/**
 * Executes the prepared query./*w  ww .  j  a  v  a2s.  co m*/
 * @return query results
 */
public EPPreparedQueryResult execute(ContextPartitionSelector[] contextPartitionSelectors) {
    int numStreams = processors.length;

    if (contextPartitionSelectors != null && contextPartitionSelectors.length != numStreams) {
        throw new IllegalArgumentException(
                "Number of context partition selectors does not match the number of named windows in the from-clause");
    }

    // handle non-context case
    if (statementSpec.getOptionalContextName() == null) {

        Collection<EventBean>[] snapshots = new Collection[numStreams];
        for (int i = 0; i < numStreams; i++) {

            ContextPartitionSelector selector = contextPartitionSelectors == null ? null
                    : contextPartitionSelectors[i];
            snapshots[i] = getStreamFilterSnapshot(i, selector);
        }

        resultSetProcessor.clear();
        return process(snapshots);
    }

    List<ContextPartitionResult> contextPartitionResults = new ArrayList<ContextPartitionResult>();
    ContextPartitionSelector singleSelector = contextPartitionSelectors != null
            && contextPartitionSelectors.length > 0 ? contextPartitionSelectors[0] : null;

    // context partition runtime query
    Collection<Integer> agentInstanceIds = EPPreparedExecuteMethodHelper.getAgentInstanceIds(processors[0],
            singleSelector, services.getContextManagementService(), statementSpec.getOptionalContextName());

    // collect events and agent instances
    for (int agentInstanceId : agentInstanceIds) {
        NamedWindowProcessorInstance processorInstance = processors[0].getProcessorInstance(agentInstanceId);
        if (processorInstance != null) {
            Collection<EventBean> coll = processorInstance.getTailViewInstance().snapshot(filters[0],
                    statementSpec.getAnnotations());
            contextPartitionResults.add(new ContextPartitionResult(coll,
                    processorInstance.getTailViewInstance().getAgentInstanceContext()));
        }
    }

    // process context partitions
    ArrayDeque<EventBean[]> events = new ArrayDeque<EventBean[]>();
    for (ContextPartitionResult contextPartitionResult : contextPartitionResults) {
        Collection<EventBean> snapshot = contextPartitionResult.getEvents();
        if (statementSpec.getFilterRootNode() != null) {
            snapshot = getFiltered(snapshot, Collections.singletonList(statementSpec.getFilterRootNode()));
        }
        EventBean[] rows = snapshot.toArray(new EventBean[snapshot.size()]);
        resultSetProcessor.setAgentInstanceContext(contextPartitionResult.getContext());
        UniformPair<EventBean[]> results = resultSetProcessor.processViewResult(rows, null, true);
        if (results != null && results.getFirst() != null && results.getFirst().length > 0) {
            events.add(results.getFirst());
        }
    }
    return new EPPreparedQueryResult(resultSetProcessor.getResultEventType(), EventBeanUtility.flatten(events));
}

From source file:com.nextep.designer.dbgm.ui.editors.ForeignKeyFormEditor.java

/**
 * Prompts the user for a new remote table and defines this selection in the current foreign
 * key./*from  w  w  w  . j av a2  s . co  m*/
 */
private void changeRemoteTable(Shell shell) {
    final ICommonUIService uiService = CorePlugin.getService(ICommonUIService.class);
    final IBasicTable remoteTable = (IBasicTable) uiService.findElement(shell,
            DBGMUIMessages.getString("changeRemoteTableTitle"), //$NON-NLS-1$
            IElementType.getInstance(IBasicTable.TYPE_ID));
    if (remoteTable != null) {
        final Collection<IKeyConstraint> constraints = remoteTable.getConstraints();
        updateRemoteConstraint(constraints.toArray(new IKeyConstraint[constraints.size()]));
    } else {
        getModel().setRemoteConstraintRef(null);
        changeRemoteConstraintButton.setEnabled(false);
    }
}

From source file:com.sec.ose.osi.thread.job.identify.IdentifyThread.java

private boolean performReset(IdentifyData tmpIdentifiedData) {
    String projectName = tmpIdentifiedData.getProjectName();
    String projectID = ProjectAPIWrapper.getProjectID(projectName);
    if (projectID == null) {
        projectID = UISDKInterfaceManager.getSDKInterface().getProjectID(projectName);
    }//w ww  .j av  a  2  s  .  co  m
    log.debug("### performReset Start - " + projectName);

    /** Data Processing **/
    String currentComponentName = tmpIdentifiedData.getCurrentComponentName();
    String currentVersionName = tmpIdentifiedData.getCurrentVersionName();
    log.debug("currentComponentName : " + currentComponentName);
    log.debug("currentVersionName : " + currentVersionName);

    String currentComponentID = null;
    String currentVersionID = "";

    int type = tmpIdentifiedData.getCompositeType();
    boolean bFile = true;

    CommonIdentify identification = null;
    if ((type & IdentificationConstantValue.STRING_MATCH_TYPE) != 0) {
        identification = new StringSearchIdentify(tmpIdentifiedData, projectName, projectID, bFile,
                currentComponentName, currentComponentID, currentVersionID, "", null);
    } else if ((type & IdentificationConstantValue.CODE_MATCH_TYPE) != 0) {
        identification = new CodeMatchIdentify(tmpIdentifiedData, projectName, projectID, bFile, false,
                currentComponentName, currentComponentID, currentVersionID, "", null);
    } else if ((type & IdentificationConstantValue.PATTERN_MATCH_TYPE) != 0) {
        identification = new PatternMatchIdentify(tmpIdentifiedData, projectName, projectID, bFile,
                currentComponentName, currentComponentID, currentVersionID, "", null);
    } else {
        log.warn("[ERROR] Unknown identify type : " + type);
        return false;
    }

    log.debug("reset type : " + identification.getInfo());

    /** action **/
    try {
        Collection<String> filePath = tmpIdentifiedData.getFilePath();
        String[] filePathList = filePath.toArray(new String[filePath.size()]);

        for (int i = 0; i < filePathList.length; i++) {
            String curFilePath = filePathList[i];
            log.info("reset filepath : " + curFilePath);
            identification.setPath(curFilePath);

            if ((currentComponentName == null) || (currentComponentName.equals("null"))
                    || (currentComponentName.length() == 0)) {
                log.debug("currentComponentName is null~~~");
            }
            if ((currentVersionName.length() <= 0)
                    || (currentVersionName.toLowerCase().equals("unspecified"))) {
                currentComponentID = ComponentAPIWrapper.getComponentId(projectID, currentComponentName);
            } else {
                //ComponentVersion componentVersion = ComponentAPIWrapper.getComponentVersionByName(currentComponentName, currentVersionName, projectID, curFilePath);
                ComponentVersion componentVersion = ComponentAPIWrapper
                        .getComponentVersionByName(currentComponentName, currentVersionName);
                if (componentVersion != null) {
                    currentComponentID = componentVersion.getComponentId();
                    currentVersionID = componentVersion.getVersionId();
                } else {
                    currentComponentID = ComponentAPIWrapper.getComponentId(projectID, currentComponentName);
                }
            }
            log.info("currentComponentID : " + currentComponentID);
            log.info("currentVersionID : " + currentVersionID);
            identification.setCurrentComponentID(currentComponentID);
            identification.setCurrentVersionID(currentVersionID);
            identification.setNewComponent();

            List<CodeTreeIdentificationInfo> identifiedNodes = identification.getIdentifications();

            for (CodeTreeIdentificationInfo identificationInfo : identifiedNodes) {
                log.debug("List<CodeTreeIdentificationInfo> : " + identificationInfo.getName());
                List<Identification> identifications = identificationInfo.getIdentifications();
                if (identifications.size() <= 0) {
                    log.warn("List<Identification> size is 0.. can't reset..");
                }
                for (Identification id : identifications) {
                    log.debug("List<Identification> : " + id.getIdentifiedComponentId());
                    identification.reset(id);
                }
            }
        }
        log.info("### Reset Complete");
    } catch (SdkFault e1) {
        log.error("performIdentification is fail...");
        log.error(e1);
        return false;
    }
    return true;
}

From source file:com.devicehive.service.helpers.HazelcastHelper.java

private Predicate prepareFilters(Long id, String guid, Collection<String> devices,
        Collection<String> notifications, Collection<String> commands, Date timestampSt, Date timestampEnd,
        String status) {//ww  w .  j  a v  a2 s.  c o  m
    final List<Predicate> predicates = new ArrayList<>();
    if (id != null) {
        predicates.add(Predicates.equal(ID.getField(), id));
    }

    if (StringUtils.isNotEmpty(guid)) {
        predicates.add(Predicates.equal(GUID.getField(), guid));
    }

    if (devices != null && !devices.isEmpty()) {
        predicates.add(Predicates.in(DEVICE_GUID.getField(), devices.toArray(new String[devices.size()])));
    }

    if (notifications != null && !notifications.isEmpty()) {
        predicates.add(Predicates.in(NOTIFICATION.getField(),
                notifications.toArray(new String[notifications.size()])));
    } else if (commands != null && !commands.isEmpty()) {
        predicates.add(Predicates.in(COMMAND.getField(), commands.toArray(new String[commands.size()])));
    }

    if (timestampSt != null) {
        predicates.add(Predicates.greaterThan(TIMESTAMP.getField(), timestampSt));
    }

    if (timestampEnd != null) {
        predicates.add(Predicates.lessThan(TIMESTAMP.getField(), timestampEnd));
    }

    if (StringUtils.isNotEmpty(status)) {
        predicates.add(Predicates.equal(STATUS.getField(), status));
    }

    final Predicate[] predicatesArray = new Predicate[predicates.size()];
    for (int i = 0; i < predicates.size(); i++) {
        predicatesArray[i] = predicates.get(i);
    }

    return Predicates.and(predicatesArray);
}

From source file:org.openvpms.component.business.service.archetype.ArchetypeServiceQueryTestCase.java

/**
 * Tests the NodeSet get method. This verifies that subcollections are
 * loaded correctly, avoiding LazyInitializationExceptionnException.
 *//* w  w w.  j av  a  2  s. c  o m*/
@Test
public void testGetNodeSet() {
    // set up a party with a single contact and contact purpose
    Contact contact = (Contact) create("contact.phoneNumber");
    contact.getDetails().put("areaCode", "03");
    contact.getDetails().put("telephoneNumber", "0123456789");
    Lookup purpose = LookupUtil.createLookup(getArchetypeService(), "lookup.contactPurpose", "Home", "Home");
    save(purpose);

    contact.addClassification(purpose);

    Party person = createPerson();
    person.addContact(contact);
    save(person);

    // query the firstName, lastName and contacts nodes of the person
    ArchetypeQuery query = new ArchetypeQuery(person.getObjectReference());
    List<String> names = Arrays.asList("firstName", "lastName", "contacts");
    IPage<NodeSet> page = getArchetypeService().getNodes(query, names);
    assertNotNull(page);

    // verify that the page only has a single element, and that the node
    // set has the expected nodes
    assertEquals(1, page.getResults().size());
    NodeSet nodes = page.getResults().get(0);
    assertEquals(3, nodes.getNames().size());
    assertTrue(nodes.getNames().contains("firstName"));
    assertTrue(nodes.getNames().contains("lastName"));
    assertTrue(nodes.getNames().contains("contacts"));

    // verify the values of the simple nodes
    assertEquals(person.getObjectReference(), nodes.getObjectReference());
    assertEquals("Tim", nodes.get("firstName"));
    assertEquals("Anderson", nodes.get("lastName"));

    // verify the values of the contact node. If the classification hasn't
    // been loaded, a LazyInitializationException will be raised by
    // hibernate
    @SuppressWarnings("unchecked")
    Collection<Contact> contacts = (Collection<Contact>) nodes.get("contacts");
    assertEquals(1, contacts.size());
    contact = contacts.toArray(new Contact[contacts.size()])[0];
    assertEquals("03", contact.getDetails().get("areaCode"));
    assertEquals("0123456789", contact.getDetails().get("telephoneNumber"));
    assertEquals(1, contact.getClassificationsAsArray().length);
    purpose = contact.getClassificationsAsArray()[0];
    assertEquals("Home", purpose.getName());
}

From source file:net.ontopia.topicmaps.query.impl.basic.DynamicAssociationPredicate.java

public QueryMatches satisfy(QueryMatches matches, Object[] arguments) throws InvalidQueryException {

    // check whether to use a faster implementation
    int argix = -1;
    for (int i = 0; i < arguments.length; i++) {
        Pair pair = (Pair) arguments[i];
        int colno = matches.getIndex(pair.getFirst());
        if (matches.bound(colno)) {
            argix = i;/*from   w  w  w  .  j  a v a  2 s.  c  o  m*/
            break;
        }
    }
    if (argix != -1)
        return satisfyWhenBound(matches, arguments, argix);

    // initialize
    QueryMatches result = new QueryMatches(matches);
    AssociationRoleIF[] seed2 = new AssociationRoleIF[2]; // most assocs are binary
    ArgumentPair[] bound = getBoundArguments(matches, arguments, -1);
    ArgumentPair[] unbound = getUnboundArguments(matches, arguments);
    int colcount = matches.colcount; // time-saving shortcut
    Object[][] data = matches.data; // ditto

    // loop over associations
    AssociationIF[] assocs = index.getAssociations(type).toArray(new AssociationIF[0]);

    // prefetch roles
    Prefetcher.prefetch(topicmap, assocs, Prefetcher.AssociationIF, Prefetcher.AssociationIF_roles, false);

    int bound_length = bound.length;
    int unbound_length = unbound.length;
    boolean[] roleused = new boolean[10];

    for (AssociationIF assoc : assocs) {
        Collection<AssociationRoleIF> rolecoll = assoc.getRoles();
        AssociationRoleIF[] roles = rolecoll.toArray(seed2);
        int roles_length = rolecoll.size();
        if (roles_length > roleused.length)
            roleused = new boolean[roles_length];

        // loop over existing matches
        for (int row = 0; row <= matches.last; row++) {
            // blank out array of used roles
            for (int roleix = 0; roleix < roles_length; roleix++)
                roleused[roleix] = false;

            // check bound columns against association
            boolean ok = true;
            for (int colix = 0; colix < bound_length; colix++) {
                TopicIF roleType = bound[colix].roleType;
                int col = bound[colix].ix;

                // find corresponding role
                ok = false;
                for (int roleix = 0; roleix < roles_length; roleix++) {
                    if (!roleused[roleix] && roleType.equals(roles[roleix].getType())
                            && data[row][col].equals(roles[roleix].getPlayer())) {
                        ok = true;
                        roleused[roleix] = true;
                        break;
                    }
                }

                if (!ok) // no matching role, so don't bother checking more columns
                    break;
            }

            if (!ok) // match failed, so try next row
                continue;

            // produce all possible combinations of role bindings
            while (true) {
                boolean one_unused_role = false; // it's ok so long as *one* role was unused

                // produce match by binding unbound columns
                for (int colix = 0; colix < unbound_length; colix++) {
                    TopicIF roleType = unbound[colix].roleType;

                    // find corresponding role
                    int role = -1;
                    for (int roleix = 0; roleix < roles_length; roleix++) {
                        if (roleType.equals(roles[roleix].getType())) {
                            if (roles[roleix].getPlayer() == null) {
                                roleused[roleix] = true; // don't touch this again
                                continue; // keep looking
                            }

                            role = roleix; // this role is a candidate for use

                            if (!roleused[roleix]) {
                                one_unused_role = true;
                                break; // this role was unused, so let's use it;
                                       // otherwise keep looking
                            }
                        }
                    }
                    if (role == -1) {
                        one_unused_role = false; // this makes sure no match is produced
                        break; // no role found, so give up
                    }

                    // ok, there is an association role matching this unbound column
                    roleused[role] = true;
                    unbound[colix].boundTo = roles[role].getPlayer();
                }

                if (!one_unused_role)
                    break; // no combos where one role unused

                // ok, the row/assoc combo is fine; now make a match for it
                if (result.last + 1 == result.size)
                    result.increaseCapacity();
                result.last++;

                System.arraycopy(data[row], 0, result.data[result.last], 0, colcount);
                for (int colix = 0; colix < unbound_length; colix++) {
                    // we may have had multiple arguments for the same unbound
                    // column, so have to check whether they matched up
                    Object value = result.data[result.last][unbound[colix].ix];
                    if ((value == null || value.equals(unbound[colix].boundTo))
                            && unbound[colix].boundTo != null)
                        result.data[result.last][unbound[colix].ix] = unbound[colix].boundTo;
                    else {
                        // this match is bad. we need to retract it
                        result.last--; // all cols reset when new matches made, anyway
                    }
                }
            } // while(true)

        } // for each row in existing matches
    } // for each association

    // check if we have a symmetrical query, and if so, mirror the
    // symmetrical values
    mirrorIfSymmetrical(result, arguments);

    return result;
}

From source file:net.ontopia.topicmaps.query.impl.basic.DynamicAssociationPredicate.java

/**
 * INTERNAL: Faster version of satisfy for use when one variable has
 * already been bound, because it is much faster in that case. It is
 * faster because it does not need to do the full all associations x
 * all matches comparison. It is used instead of the naive one when
 * heuristics indicate that this is the best approach.
 *
 * @param matches The query matches passed in to us.
 * @param arguments The arguments passed to the predicate.
 * @param argix The argument to start from.
 *///from   w w  w. jav  a  2  s  .c o  m
private QueryMatches satisfyWhenBound(QueryMatches matches, Object[] arguments, int argix)
        throws InvalidQueryException {

    // initialize
    // boundcol: column in matches where start argument is bound
    int boundcol = matches.getIndex(((Pair) arguments[argix]).getFirst());
    QueryMatches result = new QueryMatches(matches);
    AssociationRoleIF[] seed2 = new AssociationRoleIF[2]; // most assocs are binary
    ArgumentPair[] bound = getBoundArguments(matches, arguments, argix);
    ArgumentPair[] unbound = getUnboundArguments(matches, arguments);
    int colcount = matches.colcount; // time-saving shortcut
    Object[][] data = matches.data; // ditto

    int bound_length = bound.length;
    int unbound_length = unbound.length;
    TopicIF rtype = (TopicIF) ((Pair) arguments[argix]).getSecond();

    // pre-allocating this to save time
    boolean[] roleused = new boolean[25];

    Prefetcher.prefetchRolesByType(topicmap, matches, boundcol, rtype, type, Prefetcher_RBT_fields,
            Prefetcher_RBT_traverse);

    //     // in the in-memory implementation the getRolesByType() call often consumes
    //     // much of the time needed to run a query. we solve this by implementing a
    //     // simple role cache. using an LRUMap to avoid making a cache that grows
    //     // beyond all reasonable bounds.
    //     java.util.Map rolecache =
    //       new org.apache.commons.collections.map.LRUMap(100);

    // loop over existing matches
    for (int row = 0; row <= matches.last; row++) {

        // verify that we're looking at a topic
        if (!(data[row][boundcol] instanceof TopicIF))
            continue; // this can't be a valid row

        // now, test if this row is really valid
        TopicIF topic = (TopicIF) data[row][boundcol];

        // first, look for roles in assocs of the type we're supposed to have
        for (AssociationRoleIF arole : topic.getRolesByType(rtype, type)) {

            // ok, we've found the role; now let's see if the association
            // can produce a match
            // --------------------------------------------------------------
            Collection<AssociationRoleIF> rolecoll = arole.getAssociation().getRoles();
            AssociationRoleIF[] roles = rolecoll.toArray(seed2);
            int roles_length = rolecoll.size();

            // check bound arguments against association
            boolean ok = true;
            for (int arg = 0; arg < bound_length; arg++) {
                TopicIF roleType = bound[arg].roleType;
                int col = bound[arg].ix;

                // find corresponding role
                int role = -1;
                for (int roleix = 0; roleix < roles_length; roleix++) {
                    if (roleType.equals(roles[roleix].getType()) && data[row][col] != null && // bug #2001
                            data[row][col].equals(roles[roleix].getPlayer())) {
                        role = roleix;
                        break;
                    }
                }

                if (role == -1) { // no matching role found
                    ok = false;
                    break;
                }
            }
            if (!ok)
                continue; // this assoc didn't match

            // produce match by binding unbound columns
            if (roles_length > roleused.length)
                roleused = new boolean[roles_length];
            for (int roleix = 0; roleix < roles_length; roleix++)
                roleused[roleix] =
                        // if this is the start role then that's already used
                        topic.equals(roles[roleix].getPlayer()) && rtype.equals(roles[roleix].getType());

            for (int arg = 0; arg < unbound_length; arg++) {
                TopicIF roleType = unbound[arg].roleType;

                // find corresponding role
                int role = -1;
                for (int roleix = 0; roleix < roles_length; roleix++) {
                    if (roleType.equals(roles[roleix].getType()) && !roleused[roleix]) {
                        role = roleix;
                        break;
                    }
                }
                if (role == -1) {
                    ok = false;
                    break;
                }

                // won't accept null players
                if (roles[role].getPlayer() == null) {
                    ok = false;
                    break;
                }

                // ok, there is an association role matching this unbound column
                unbound[arg].boundTo = roles[role].getPlayer();
                roleused[role] = true;
            }

            if (ok) {
                // ok, the row/assoc combo is fine; now make a match for it
                if (result.last + 1 == result.size)
                    result.increaseCapacity();
                result.last++;

                System.arraycopy(data[row], 0, result.data[result.last], 0, colcount);
                for (int arg = 0; arg < unbound_length && ok; arg++) {
                    result.data[result.last][unbound[arg].ix] = unbound[arg].boundTo;
                    unbound[arg].boundTo = null;
                }
            }
            // ----------------------------------------------------------------------
        }
    }

    QueryTracer.trace("  results: " + result.last);
    return result;
}

From source file:com.gc.iotools.fmt.detect.droid.DroidDetectorImpl.java

/**
 * {@inheritDoc}/*  w ww.  j  a  va 2  s  .com*/
 */
public FormatEnum[] getDetectedFormats() {
    final FFSignatureFile fsigfile = CONF_MAP.get(this.configFile);
    final Collection<FormatEnum> result = new ArrayList<FormatEnum>();
    for (int i = 0; i < fsigfile.getNumFileFormats(); i++) {
        final FileFormat fformat = fsigfile.getFileFormat(i);
        final FormatId fid = getFormatEnum(fformat);
        final FormatEnum fenum = fid.format;
        if (!FormatEnum.UNLISTED.equals(fenum) && !FormatEnum.UNKNOWN.equals(fenum)) {
            result.add(fenum);
        }
    }
    return result.toArray(new FormatEnum[result.size()]);
}