Example usage for org.apache.commons.lang ArrayUtils add

List of usage examples for org.apache.commons.lang ArrayUtils add

Introduction

In this page you can find the example usage for org.apache.commons.lang ArrayUtils add.

Prototype

public static short[] add(short[] array, short element) 

Source Link

Document

Copies the given array and adds the given element at the end of the new array.

Usage

From source file:org.exoplatform.social.core.storage.impl.ActivityStorageImpl.java

private String[] getNumberOfViewedOfActivities(Identity owner, ActivityFilterType type) {

    if (type.fromSinceTime() == type.toSinceTime()) {
        return ArrayUtils.EMPTY_STRING_ARRAY;
    }/*from  ww w .  ja  va 2 s .  c o  m*/

    List<Identity> identities = new ArrayList<Identity>();
    identities.add(owner);

    ActivityBuilderWhere where = ActivityBuilderWhere.viewedRange();

    switch (type) {
    case CONNECTIONS_ACTIVITIES:
        identities.addAll(relationshipStorage.getConnections(owner));
        break;
    case USER_ACTIVITIES:
        where.mentioner(owner);
        //identities.addAll(relationshipStorage.getConnections(owner));
        break;
    case USER_SPACE_ACTIVITIES:
        identities.addAll(getSpacesId(owner));
        break;
    case SPACE_ACTIVITIES:
        break;
    }

    //
    JCRFilterLiteral jcrfilter = ActivityFilter.ACTIVITY_VIEWED_RANGE_FILTER;
    jcrfilter.with(ActivityFilter.ACTIVITY_FROM_UPDATED_POINT_FIELD)
            .value(TimestampType.NEWER.from(type.oldFromSinceTime()));
    jcrfilter.with(ActivityFilter.ACTIVITY_TO_UPDATED_POINT_FIELD)
            .value(TimestampType.OLDER.from(type.toSinceTime()));

    //
    QueryResult<ActivityEntity> result = getActivitiesOfIdentitiesQuery(where.owners(identities), jcrfilter)
            .objects();
    String[] excludedActivities = new String[0];

    //
    while (result.hasNext()) {
        excludedActivities = (String[]) ArrayUtils.add(excludedActivities, result.next().getId());
    }

    return excludedActivities;
}

From source file:org.exoplatform.social.core.storage.impl.RelationshipStorageImpl.java

private String[] getRelationships(String id) {
    ThreadLocal<String[]> identityIdsLocal = new ThreadLocal<String[]>();

    String[] relationshipIds = new String[0];
    identityIdsLocal.set(relationshipIds);

    try {//w ww . j av  a  2  s.com

        IdentityEntity identityEntity = _findById(IdentityEntity.class, id);

        StringBuffer sb = new StringBuffer().append("SELECT * FROM soc:relationshipdefinition WHERE ");
        sb.append(JCRProperties.path.getName()).append(" LIKE '")
                .append(identityEntity.getPath() + StorageUtils.SLASH_STR + StorageUtils.PERCENT_STR)
                .append("'");
        //
        sb.append(" ORDER BY ").append(RelationshipEntity.createdTime.getName()).append(" DESC ");

        synchronized (lock) {

            NodeIterator it = nodes(sb.toString());

            while (it.hasNext()) {
                Node node = (Node) it.next();

                RelationshipEntity currentRelationshipEntity = _findById(RelationshipEntity.class,
                        node.getUUID());

                IdentityEntity gotIdentityEntity;
                if (currentRelationshipEntity.isReceiver()) {
                    gotIdentityEntity = currentRelationshipEntity.getFrom();
                } else {
                    gotIdentityEntity = currentRelationshipEntity.getTo();
                }
                identityIdsLocal
                        .set((String[]) ArrayUtils.add(identityIdsLocal.get(), gotIdentityEntity.getId()));
            }

        }
    } catch (Exception e) {
        throw new RelationshipStorageException(RelationshipStorageException.Type.FAILED_TO_GET_RELATIONSHIP,
                e.getMessage());
    }

    return identityIdsLocal.get();
}

From source file:org.exoplatform.social.core.storage.impl.RelationshipStorageImpl.java

private String[] getSuggestion(List<String> relationshipIds) {
    String[] suggestions = new String[0];

    try {/*  w ww . ja  v a  2  s  .c  om*/
        int startIndex = 0;
        int toIndex = 100;
        //
        List<String> excludeIdentities = StorageUtils.subList(relationshipIds, startIndex, toIndex);
        while (excludeIdentities.size() > 0) {

            StringBuffer sb = new StringBuffer().append("SELECT * FROM soc:identitydefinition WHERE ");
            sb.append(JCRProperties.path.getName()).append(" LIKE '")
                    .append(getProviderRoot().getProviders().get(OrganizationIdentityProvider.NAME).getPath()
                            + StorageUtils.SLASH_STR + StorageUtils.PERCENT_STR)
                    .append("'");

            for (String id : excludeIdentities) {
                sb.append(" AND NOT ").append(JCRProperties.id.getName()).append(" = '").append(id).append("'");
            }

            NodeIterator nodeIter = nodes(sb.toString());
            while (nodeIter.hasNext()) {
                Node node = (Node) nodeIter.next();
                String id = node.getUUID();
                //String remoteId = node.getProperty(IdentityEntity.remoteId.getName()).getString();
                if (relationshipIds.contains(id) == false && ArrayUtils.contains(suggestions, id) == false) {
                    suggestions = (String[]) ArrayUtils.add(suggestions, id);
                }
            }

            //
            startIndex = toIndex;
            toIndex += 100;

            excludeIdentities = StorageUtils.subList(relationshipIds, startIndex, toIndex);
        } //end filter identities

    } catch (Exception e) {
        throw new RelationshipStorageException(RelationshipStorageException.Type.FAILED_TO_GET_RELATIONSHIP,
                e.getMessage());
    }

    return suggestions;
}

From source file:org.exoplatform.social.core.test.AbstractCoreTest.java

/**
 * Creates new space with out init apps.
 *
 * @param space/*from  ww  w .ja  v  a  2  s  .  c om*/
 * @param creator
 * @param invitedGroupId
 * @return
 * @since 1.2.0-GA
 */
protected Space createSpaceNonInitApps(Space space, String creator, String invitedGroupId) {
    // Creates new space by creating new group
    String groupId = null;
    try {
        groupId = SpaceUtils.createGroup(space.getDisplayName(), creator);
    } catch (SpaceException e) {
        LOG.error("Error while creating group", e);
    }

    if (invitedGroupId != null) {
        // Invites user in group join to new created space.
        // Gets users in group and then invites user to join into space.
        OrganizationService org = (OrganizationService) ExoContainerContext.getCurrentContainer()
                .getComponentInstanceOfType(OrganizationService.class);
        try {
            PageList<User> groupMembersAccess = org.getUserHandler().findUsersByGroup(invitedGroupId);
            List<User> users = groupMembersAccess.getAll();

            for (User user : users) {
                String userId = user.getUserName();
                if (!userId.equals(creator)) {
                    String[] invitedUsers = space.getInvitedUsers();
                    if (!ArrayUtils.contains(invitedUsers, userId)) {
                        invitedUsers = (String[]) ArrayUtils.add(invitedUsers, userId);
                        space.setInvitedUsers(invitedUsers);
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("Failed to invite users from group " + invitedGroupId, e);
        }
    }
    String[] managers = new String[] { creator };
    space.setManagers(managers);
    space.setGroupId(groupId);
    space.setUrl(space.getPrettyName());
    try {
        spaceService.saveSpace(space, true);
    } catch (SpaceException e) {
        LOG.warn("Error while saving space", e);
    }
    return space;
}

From source file:org.hippoecm.frontend.plugins.standardworkflow.PermissionsFolderWorkflowPlugin.java

public PermissionsFolderWorkflowPlugin(IPluginContext context, final IPluginConfig config) {
    super(context, config);

    add(new StdWorkflow("queryModifier", new StringResourceModel("query-label", this, null), context,
            getModel()) {/*from ww w.j  a  v  a2 s . c o  m*/

        @Override
        protected Component getIcon(final String id) {
            return HippoIcon.inline(id, CmsIcon.FILE_UNLOCKED);
        }

        @Override
        protected IDialogService.Dialog createRequestDialog() {
            try {
                Node folder = getModel().getNode();
                PermissionsFolderWorkflowPlugin.this.name = ((HippoNode) folder).getDisplayName();
                try {
                    Value[] values = folder.getProperty("hippostd:foldertype").getValues();
                    for (Value value : values) {
                        folderTypesList.add(new DisplayModel(value.getString()));
                    }
                } catch (RepositoryException e) {
                    log.error("Couldn't get foldertypes from folder", e);
                }
            } catch (RepositoryException ex) {
                log.error("Couldn't get display name for folder", ex);
                PermissionsFolderWorkflowPlugin.this.name = "";
            }
            Session session = UserSession.get().getJcrSession();
            Query query = null;

            try {
                QueryManager qMgr = session.getWorkspace().getQueryManager();
                query = qMgr.createQuery(QUERY_STATEMENT_QUERIES, QUERY_LANGUAGE_QUERIES);
            } catch (RepositoryException ex) {
                log.error("Error retrieving all templatequeries: {}", ex);
            }

            return new PermissionsConfirmDialog(getModel(), this,
                    new PropertyModel(PermissionsFolderWorkflowPlugin.this, "name"), query);
        }

        @Override
        protected void execute(WorkflowDescriptorModel model) throws Exception {
            Session session = ((UserSession) getSession()).getJcrSession();
            Node folder = model.getNode();
            String[] store = new String[folderTypesList.size()];
            for (IModel propertyModel : folderTypesList) {
                store = (String[]) ArrayUtils.add(store, propertyModel.getObject());
            }
            folder.setProperty("hippostd:foldertype", store);
            session.save();
        }
    });
}

From source file:org.hoteia.qalingo.core.aop.cache.CacheManagementAspect.java

public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    Object returnObject = null;/*  w  ww  .j  av a 2s.  c o  m*/
    try {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class classReturnType = signature.getReturnType();
        Object[] args = joinPoint.getArgs();
        String cacheType = null;
        String cacheName = null;
        Cache cache = null;
        String key = null;

        logger.debug("Start Cache AOP. Call from : '" + joinPoint.getSignature().toShortString() + "'");

        // DEFINE THE CACHE TYPE
        try {
            CacheMethodInformation cacheMethodInformation = signature.getMethod()
                    .getAnnotation(CacheMethodInformation.class);
            cacheType = cacheMethodInformation.cacheType();
            logger.debug("CacheMethodInformation from annotation : cacheType= '" + cacheType + "'");
            cacheName = cacheMethodInformation.cacheName();
            logger.debug("CacheEntityInformation from annotation : cacheName= '" + cacheName + "'");

        } catch (Exception e) {
            // TODO: handle exception
        }
        if (DomainEntity.class.isAssignableFrom(classReturnType)) {
            cacheType = CacheType.CACHE_ENTITY;
            if (joinPoint.getSignature().toShortString().contains("ByCode")) {
                // FIRST ARG IS A STRING FOR THE GET METHOD : SO THIS A GET BY CODE
                cacheType = CacheType.CACHE_LINK_CODE_ID;
            }
        } else if (AbstractPojo.class.isAssignableFrom(classReturnType)) {
            cacheType = CacheType.CACHE_POJO;

        }
        logger.debug("Cache Type : '" + cacheType + "'");

        // TARGETED FETCH PLAN
        FetchPlan askedFetchPlan = null;
        FetchPlan loadedFetchPlan = null;
        for (Object arg : args) {
            if (arg instanceof Object[]) {
                Object[] objects = (Object[]) arg;
                for (Object object : objects) {
                    if (object instanceof FetchPlan) {
                        FetchPlan fetchPlan = (FetchPlan) object;
                        if (fetchPlan != null && !fetchPlan.getFetchModes().isEmpty()) {
                            askedFetchPlan = fetchPlan;
                            break;
                        }
                    }
                }
            }
        }

        if (StringUtils.isNotEmpty(cacheType)) {
            try {
                CacheEntityInformation cacheEntityInformation = (CacheEntityInformation) classReturnType
                        .getAnnotation(CacheEntityInformation.class);
                cacheName = cacheEntityInformation.cacheName();
                // CHECK THE NAME OF THE CACHE
                if (cacheType.equals(CacheType.CACHE_LINK_CODE_ID)) {
                    cacheName += "_link_code_id";
                }
                logger.debug("CacheEntityInformation from annotation : cacheName= '" + cacheName + "'");

            } catch (Exception e) {
                // TODO: handle exception
            }

            if (StringUtils.isNotEmpty(cacheName)) {
                // LOAD THE CACHE
                if (cacheType.equals(CacheType.CACHE_ENTITY)) {
                    String id = null;
                    if (args != null && args.length > 0) {
                        if (args[0] instanceof Long) {
                            id = ((Long) args[0]).toString();
                        }
                    }
                    key = cacheService.buildEntityKey(signature.getReturnType(), id);
                    if (id == null) {
                        // OVERRIDE THE KEY BY THE METHOD
                        key = signature.toShortString();
                    }
                    cache = cacheService.getCache(cacheName, String.class, AbstractEntity.class);

                } else if (cacheType.equals(CacheType.CACHE_LINK_CODE_ID)) {
                    String code = null;
                    if (args != null && args.length > 0) {
                        if (args[0] instanceof String) {
                            code = ((String) args[0]).toString();
                        }
                    }
                    key = cacheService.buildCodeIdKey(signature, code);
                    if (code == null) {
                        // OVERRIDE THE KEY BY THE METHOD
                        key = signature.toShortString();
                    }
                    cache = cacheService.getCache(cacheName, String.class, Long.class);

                } else if (cacheType.equals(CacheType.CACHE_POJO)) {
                    key = cacheService.buildCommonKey(signature, args);
                    cache = cacheService.getCache(cacheName, String.class, AbstractPojo.class);

                } else if (cacheType.equals(CacheType.CACHE_STRING)) {
                    key = cacheService.buildCommonKey(signature, args);
                    cache = cacheService.getCache(cacheName, String.class, String.class);
                }

                // TEST IF THE VALUE IS IN CACHE
                if (cache != null) {
                    logger.debug("Searching object in cache with : key= '" + key + "'");
                    if (cache.containsKey(key)) {
                        logger.debug("Object exist in cache with : key= '" + key + "'");
                        Object element = cache.get(key);
                        if (element != null) {
                            // WE TEST IF THE FETCH PLAN ARE EQUALS
                            returnObject = element;

                            if (cacheType.equals(CacheType.CACHE_ENTITY)) {
                                returnObject = checkFetchPlan(returnObject, askedFetchPlan, loadedFetchPlan);

                            } else if (cacheType.equals(CacheType.CACHE_LINK_CODE_ID)) {
                                String cacheNameEntity = cacheName.replace("_link_code_id", "");
                                Long id = (Long) returnObject;
                                returnObject = null;
                                Cache cacheEntity = cacheService.getCache(cacheNameEntity, String.class,
                                        AbstractEntity.class);
                                String keyEntity = cacheService.buildEntityKey(signature.getReturnType(),
                                        id.toString());
                                if (cacheEntity.containsKey(keyEntity)) {
                                    Object entity = cacheEntity.get(keyEntity);
                                    returnObject = entity;
                                    returnObject = checkFetchPlan(returnObject, askedFetchPlan,
                                            loadedFetchPlan);
                                }
                            }
                        }
                    } else {
                        logger.debug("Object doesn't exist in cache with : key= '" + key + "'");
                    }
                }
            }
        }

        // NOTHING IN CACHE - CALL THE TARGET METHOD
        if (returnObject == null) {
            if (loadedFetchPlan != null) {
                args = ArrayUtils.add(args, loadedFetchPlan);
                returnObject = joinPoint.proceed(args);
            } else {
                returnObject = joinPoint.proceed();
            }

            if (returnObject != null && cache != null) {
                // PUT IN CACHE
                if (cacheType.equals(CacheType.CACHE_ENTITY)) {
                    logger.debug("Put in cache '" + cacheName + "'. key : '" + key + "'. value: '"
                            + returnObject + "'");
                    cache.put(key, returnObject);

                    // PUT THE CODE/ID
                    String cacheNameCodeId = cacheName + "_link_code_id";
                    Cache cacheCodeId = cacheService.getCache(cacheNameCodeId, String.class, Long.class);
                    Long id = (Long) handleClassMethodGetValue(joinPoint, returnObject, classReturnType,
                            "getId");
                    String code = (String) handleClassMethodGetValue(joinPoint, returnObject, classReturnType,
                            "getCode");
                    String newKey = key = cacheService.buildCodeIdKey(signature, code);
                    logger.debug("Put in cache '" + cacheNameCodeId + "'. key : '" + newKey + "'. value: '" + id
                            + "'");
                    cacheCodeId.put(newKey, id);

                } else if (cacheType.equals(CacheType.CACHE_LINK_CODE_ID)) {
                    Long id = (Long) handleClassMethodGetValue(joinPoint, returnObject, classReturnType,
                            "getId");
                    logger.debug("Put in cache '" + cacheName + "'. key : '" + key + "'. value: '" + id + "'");
                    cache.put(key, id);

                    // PUT THE ENTITY
                    String cacheNameEntity = cacheName.replace("_link_code_id", "");
                    Cache cacheEntity = cacheService.getCache(cacheNameEntity, String.class,
                            AbstractEntity.class);
                    String newKey = cacheService.buildEntityKey(signature.getReturnType(), id.toString());
                    logger.debug("Put in cache '" + cacheName + "'. key : '" + newKey + "'. value: '"
                            + returnObject + "'");
                    cacheEntity.put(newKey, returnObject);

                } else if (cacheType.equals(CacheType.CACHE_POJO)) {
                    logger.debug("Put in cache '" + cacheName + "'. key : '" + key + "'. value: '"
                            + returnObject + "'");
                    cache.put(key, returnObject);

                } else if (cacheType.equals(CacheType.CACHE_STRING)) {
                    logger.debug("Put in cache '" + cacheName + "'. key : '" + key + "'. value: '"
                            + returnObject + "'");
                    cache.put(key, returnObject);
                }
            }
        }

    } catch (Exception e) {
        logger.error("Failed to load datas with Cache AOP! Call from : '"
                + joinPoint.getSignature().toShortString() + "'", e);
    }

    logger.debug("End Cache AOP. Call from : '" + joinPoint.getSignature().toShortString() + "'");
    logger.debug("---------------------------------------------------------------------------------");

    return returnObject;
}

From source file:org.intermine.api.search.SearchResults.java

/**
 * Get an object capable of searching over multiple directories.
 * @param target What type and scope we are looking for.
 * @param userDirectory The user's index.
 * @param globalDirectories All the globally available indices.
 * @return A searcher object./* ww  w. j a  v a 2  s  . c om*/
 * @throws CorruptIndexException If one of the indices cannot be used.
 * @throws IOException If there is a problem reading the indices.
 */
private static MultiSearcher prepareSearcher(SearchTarget target, Directory userDirectory,
        List<Directory> globalDirectories) throws CorruptIndexException, IOException {
    IndexSearcher userIndexSearcher = new IndexSearcher(userDirectory);
    IndexSearcher[] globalIndexSearchers = new IndexSearcher[globalDirectories.size()];
    for (int i = 0; i < globalDirectories.size(); i++) {
        globalIndexSearchers[i] = new IndexSearcher(globalDirectories.get(i));
    }
    Searchable[] searchables;
    if (target.isUserOnly()) {
        searchables = new Searchable[] { userIndexSearcher };
    } else if (target.isGlobalOnly()) {
        searchables = globalIndexSearchers;
    } else { // ALL
        searchables = (Searchable[]) ArrayUtils.add(globalIndexSearchers, userIndexSearcher);
    }
    MultiSearcher searcher = new MultiSearcher(searchables);

    return searcher;
}

From source file:org.jasig.portal.events.aggr.JpaBaseAggregationDao.java

@Override
public final List<T> getAggregations(DateTime start, DateTime end, K key,
        AggregatedGroupMapping... aggregatedGroupMappings) {
    if (!start.isBefore(end)) {
        throw new IllegalArgumentException("Start must be before End: " + start + " - " + end);
    }/*from ww w  .  j  a v a  2  s .c o  m*/
    final LocalDate startDate = start.toLocalDate();
    LocalDate endDate = end.toLocalDate();
    if (startDate.equals(endDate)) {
        endDate = endDate.plusDays(1);
    }

    final TypedQuery<T> query = this.createCachedQuery(findAggregationsByDateRangeQuery);

    query.setParameter(this.startDate, start.toLocalDate());
    query.setParameter(this.startTime, start.toLocalTime());

    query.setParameter(this.endDate, end.toLocalDate());
    query.setParameter(this.endTime, end.toLocalTime());
    query.setParameter(this.endMinusOneDate, end.minusDays(1).toLocalDate());

    query.setParameter(this.intervalParameter, key.getInterval());

    this.bindAggregationSpecificKeyParameters(query, key);

    aggregatedGroupMappings = (AggregatedGroupMapping[]) ArrayUtils.add(aggregatedGroupMappings,
            key.getAggregatedGroup());
    query.setParameter(this.aggregatedGroupsParameter, ImmutableSet.copyOf(aggregatedGroupMappings));

    return query.getResultList();
}

From source file:org.jboss.tools.openshift.internal.core.docker.ImageStreamTagMetaData.java

public ImageStreamTagMetaData(final String json) {
    this.node = ModelNode.fromJSONString(json);
    final ModelNode config = this.node.get(ROOT).get(CONTAINER_CONFIG);
    if (ModelType.OBJECT == config.getType() && config.has(EXPOSED_PORT)) {
        CONFIG_ROOT = (String[]) ArrayUtils.add(ROOT, CONTAINER_CONFIG);
    } else {//from  ww w  .java2 s . c  o m
        CONFIG_ROOT = (String[]) ArrayUtils.add(ROOT, CONFIG);
    }
    PORT_KEY = (String[]) ArrayUtils.add(CONFIG_ROOT, EXPOSED_PORT);
    VOLUMES_KEY = (String[]) ArrayUtils.add(CONFIG_ROOT, VOLUMES);
    ENV_KEY = (String[]) ArrayUtils.add(CONFIG_ROOT, ENV);
    LABELS_KEY = (String[]) ArrayUtils.add(CONFIG_ROOT, LABELS);
}

From source file:org.jboss.tools.openshift.internal.core.ImageStreamTagMetaData.java

public ImageStreamTagMetaData(final String json) {
    this.node = ModelNode.fromJSONString(json);
    final ModelNode config = this.node.get(ROOT).get(CONTAINER_CONFIG);
    if (ModelType.OBJECT == config.getType() && config.has(EXPOSED_PORT)) {
        CONFIG_ROOT = (String[]) ArrayUtils.add(ROOT, CONTAINER_CONFIG);
    } else {/* w w w  .  j a v a2 s .c om*/
        CONFIG_ROOT = (String[]) ArrayUtils.add(ROOT, CONFIG);
    }
    PORT_KEY = (String[]) ArrayUtils.add(CONFIG_ROOT, EXPOSED_PORT);
    VOLUMES_KEY = (String[]) ArrayUtils.add(CONFIG_ROOT, VOLUMES);
    ENV_KEY = (String[]) ArrayUtils.add(CONFIG_ROOT, ENV);
}