Example usage for java.util List retainAll

List of usage examples for java.util List retainAll

Introduction

In this page you can find the example usage for java.util List retainAll.

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this list that are contained in the specified collection (optional operation).

Usage

From source file:nl.amc.biolab.nsg.display.component.MainUI.java

private List<Application> _getApplicationIntersection(Set<DataElement> des) {
    ArrayList<Application> usable_apps = new ArrayList<Application>();

    for (DataElement de : des) {
        List<Application> these_apps = app.getUserDataService().getApplications(de);

        if (these_apps.size() == 0) {
            return null;
        }//w ww . jav  a  2 s. c o m

        if (usable_apps.size() == 0) {
            usable_apps.addAll(these_apps);

            continue;
        }

        these_apps.retainAll(usable_apps);

        if (these_apps.size() == 0) {
            return null;
        }
    }

    return usable_apps;
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractSubscriptionController.java

private String getResourceComponentsAndFilterData(Tenant tenant, String tenantParam, String serviceInstanceUUID,
        String subscriptionId, String resourceType, ModelMap map, HttpServletRequest request,
        String successView, String sourceChannelName) throws ConnectorManagementServiceException {

    User user = getCurrentUser();//  ww w. j a  v a 2s.  c o  m
    List<String> currentUserServiceCategoryList = userService.getAllAccessibleCloudServiceCategories(user);
    if ((Boolean) request.getAttribute("isSurrogatedTenant")) {
        map.addAttribute("showUserProfile", true); // if service provider
        user = tenant.getOwner();
    }
    ServiceInstance serviceInstance = null;
    List<String> serviceCategoryList = userService.getAllAccessibleCloudServiceCategories(user);
    serviceCategoryList.retainAll(currentUserServiceCategoryList);

    boolean isPayAsYouGoChosen = config.getBooleanValue(Names.com_citrix_cpbm_catalog_payAsYouGoMode);
    boolean noResourceType = false;
    if (ProductBundle.SERVICEBUNDLE.equalsIgnoreCase(resourceType) && isPayAsYouGoChosen) {
        // the case when you select drop down of service instance after hitting catalog first time - the default message
        // is shown again
        noResourceType = true;
    }
    map.addAttribute("noResourceType", noResourceType);
    map.addAttribute("isPayAsYouGoChosen", isPayAsYouGoChosen);
    map.addAttribute("userHasCloudServiceAccount", userService.isUserHasAnyActiveCloudService(user));
    map.addAttribute("tenant", tenant);
    map.addAttribute("serviceCategoryList", serviceCategoryList);
    map.addAttribute("chargeRecurrenceFrequencyList", productBundleService.getChargeRecurrenceFrequencyList());
    // If there is a subscription get the service instance directly from subscription
    if (StringUtils.isNotBlank(subscriptionId)) {
        Subscription subscription = subscriptionService.locateSubscriptionById(Long.parseLong(subscriptionId));
        resourceType = subscription.getResourceType().getResourceTypeName();
        serviceInstance = subscription.getServiceInstance();
        serviceInstanceUUID = subscription.getServiceInstance().getUuid();
        map.addAttribute("selectedCloudServiceInstance", serviceInstanceUUID);
        map.addAttribute("selectedCategory", serviceInstance.getService().getCategory());
    } else {
        // if service instance is null get the first cloud service instance
        if (serviceInstanceUUID == null) {
            for (String category : serviceCategoryList) {
                List<ServiceInstance> currentUserCloudTypeServiceInstances = userService
                        .getCloudServiceInstance(getCurrentUser(), category);
                List<ServiceInstance> cloudTypeServiceInstances = userService.getCloudServiceInstance(user,
                        category);
                cloudTypeServiceInstances.retainAll(currentUserCloudTypeServiceInstances);
                if (cloudTypeServiceInstances != null && cloudTypeServiceInstances.size() > 0) {
                    serviceInstance = cloudTypeServiceInstances.get(0);
                    serviceInstanceUUID = serviceInstance.getUuid();
                    break;
                }
            }
        } else {
            // get the service instance from service instance uuid
            serviceInstance = connectorConfigurationManager.getInstanceByUUID(serviceInstanceUUID);
            map.addAttribute("selectedCloudServiceInstance", serviceInstanceUUID);
            map.addAttribute("selectedCategory", serviceInstance.getService().getCategory());
        }
    }
    if (serviceInstance != null) {
        try {
            TenantHandle tenantHandle = tenantService.getTenantHandle(tenant.getUuid(), serviceInstanceUUID);
            UserHandle userHandle = userService.getUserHandleByServiceInstanceUuid(user.getUuid(),
                    serviceInstanceUUID);
            if (tenantHandle == null) {
                throw new ConnectorManagementServiceException(
                        "Tenant Handle is required to subscribe to a resource");
            }
            String tenantHandleString = tenantHandle.getHandle();
            String userHandleString = userHandle == null ? null : userHandle.getHandle();
            Service service = serviceInstance.getService();
            String requestedResourceType = resourceType;
            map.addAttribute("tenantDataJsonStr", tenantHandle.getData());
            map.addAttribute("service", service);
            map.addAttribute("serviceInstanceUuid", serviceInstanceUUID);
            map.addAttribute("serviceBundleResourceType", ProductBundle.SERVICEBUNDLE);
            if (StringUtils.isBlank(resourceType)) {
                resourceType = ProductBundle.SERVICEBUNDLE;
            }
            // If the connector is down by default resourceType is Service Bundle and their will not be any available
            // resource type
            map.addAttribute("resourceTypes", new ArrayList<String>());
            map.addAttribute("resourceType", resourceType);
            List<ServiceResourceType> resourceTypeNames = connectorConfigurationManager
                    .getAvailableResourceTypes(serviceInstanceUUID, tenantHandleString, userHandleString);
            List<ServiceResourceType> availableResourceTypes = new ArrayList<ServiceResourceType>();
            List<String> availableResourceTypeNames = new ArrayList<String>();
            if (CollectionUtils.isNotEmpty(resourceTypeNames)) {
                for (ServiceResourceType serviceResourceType : resourceTypeNames) {
                    if (StringUtils.isNotBlank(subscriptionId) || productBundleService
                            .validateBundleBusinessConstraints(null, tenant, user, serviceResourceType)) {
                        availableResourceTypes.add(serviceResourceType);
                        availableResourceTypeNames.add(serviceResourceType.getResourceTypeName());
                    }
                }
            }
            availableResourceTypeNames.add(ProductBundle.SERVICEBUNDLE);
            if (CollectionUtils.isNotEmpty(availableResourceTypes)) {
                if (!availableResourceTypeNames.contains(requestedResourceType)) {
                    // No resource type is given or given one is not available. Enable the first in the list.
                    resourceType = availableResourceTypeNames.get(0);
                }
            } else {
                // Initializing resource type as SERVICE when service has no resourceTypes
                resourceType = ProductBundle.SERVICEBUNDLE;
                noResourceType = true;
                map.addAttribute("noResourceType", noResourceType);
            }
            // Override resourceTypes and resourceType if connector returns the resource type and available resource types
            map.addAttribute("resourceTypes", availableResourceTypes);
            map.addAttribute("resourceType", resourceType);

            ServiceResourceType serviceResourceType = connectorConfigurationManager
                    .getServiceResourceType(serviceInstanceUUID, resourceType);
            List<String> uniqueResourceComponentNames = new ArrayList<String>();
            if (serviceResourceType != null) {
                uniqueResourceComponentNames = getUniqueResourceComponents(serviceInstanceUUID, resourceType);
                map.addAttribute("resourceComponents",
                        serviceResourceType.getServiceResourceGroupsComponents());
            }
            map.addAttribute("uniqueResourceComponentNames", uniqueResourceComponentNames);
            if (StringUtils.isNotBlank(subscriptionId)) {
                Subscription subscription = subscriptionService
                        .locateSubscriptionById(Long.parseLong(subscriptionId));
                JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(subscription.getConfigurationData());

                subscription = subscriptionService
                        .updateFilterAndResourceComponentNamesinConfigurationData(subscription);

                map.addAttribute("subscription", subscription);
                map.addAttribute("configurationData", jsonObject);
                com.citrix.cpbm.access.Subscription subscriptionProxy = (com.citrix.cpbm.access.Subscription) CustomProxy
                        .newInstance(subscription);
                SubscriptionForm subscriptionForm = new SubscriptionForm(subscriptionProxy);
                map.addAttribute("subscriptionForm", subscriptionForm);
            } else {
                com.citrix.cpbm.access.Subscription subscription = (com.citrix.cpbm.access.Subscription) CustomProxy
                        .newInstance(new Subscription());
                SubscriptionForm subscriptionForm = new SubscriptionForm(subscription);
                map.addAttribute("subscriptionForm", subscriptionForm);
            }
            addValuesForRenderingConnectorValues(map, serviceInstance, resourceType);
            boolean isAlive = ((CloudConnector) connectorManagementService
                    .getServiceInstance(serviceInstanceUUID)).getStatus();
            if (!isAlive) {
                throw new CloudServiceException(
                        messageSource.getMessage("cloud.service.down", null, user.getLocale()));
            }
        } catch (CloudServiceException cse) {
            map.addAttribute("cloudServiceException", true);
            map.addAttribute("cloudServiceExceptionStr", cse.getMessage());
        } catch (Exception e) {
            logger.error("Error in creating the Service Instance Map...", e);
            throw new ConnectorManagementServiceException("Error in creating the Service Instance Map...", e);
        }
        map.addAttribute("tnc", tncString);
        map.addAttribute("sourceChannelName", sourceChannelName);
        String result = subscribeBundleGet(request, tenant, tenantParam, successView, map, serviceInstance,
                resourceType);
        return result;
    } else {
        map.addAttribute("cloudServiceException", true);
        map.addAttribute("cloudServiceExceptionStr", "");
        return successView;
    }
}

From source file:pltag.parser.Chart.java

/**
 *
 * This method is used to find the n-best paths through the chart, and thereby build the n-best trees.
 * @param ce//from w w  w .  j a  v  a  2 s  .com
 * @param contList
 * @param nextPOStag
 * @param top
 * @param targetprob
 * @param train
 * @return 
 */
@SuppressWarnings("unchecked")
public ArrayList<StringTreeAnalysis> getAnalyses(ChartEntry ce, ArrayList<ArrayList<BuildBlock>>[] contList,
        String nextPOStag, boolean top, double targetprob, boolean train) {
    //        if (ParserModel.useTimeOut && System.currentTimeMillis() - startTime > 600000)
    if (ParserModel.useTimeOut && System.currentTimeMillis() - startTime > opts.timeOutStage2) {//1000 = 1sec, 60 000 = 1 min, 300 000 = 5 min
        //            LogInfo.logs("Time out at stage 2 (10min).");
        if (!opts.silentMode)
            LogInfo.logs("Time out at stage 2 - analyses reconstruction ( "
                    + (((double) opts.timeOutStage2 / 1000.0) / 60.0) + " min).");
        //            ParserRunner.printConsole("Time out at stage 2 (10min).\t");
        return new ArrayList<StringTreeAnalysis>(); //null;
    }
    /*if ( Runtime.getRuntime().freeMemory()/(1024*1024) < 20){//1000 = 1sec, 60 000 = 1 min, 300 000 = 5 min
    System.out.print("-");//Time out at stage 2 (1min).");
    ParserRunner.printConsole("less than 20MB free mem left-A-.\t");
    return null;
    }//*/
    ArrayList<StringTreeAnalysis> derivations = new ArrayList<StringTreeAnalysis>();
    if (ce == null) {
        return new ArrayList<StringTreeAnalysis>(); //null;
    }
    //System.out.print("["+ce.getTreeState().getWordCover()[1]+", ");
    //System.out.print(treestatelistarray.get(ce.getTreeState().getWordCover()[1]).indexOf(ce)+"]");

    /*
     * in the following block of code, the goal is to identify a list of buildBlocks which were used for
     * generating the best analyses, based on the determined top probability analysis (basically, I am
     * trying to recover it by checking whether the determined best log-probability is equal to the sum of the
     * log-probs of the buildblocks used to create the analysis.
     * In a first step, we make sure to exclude any inconsistent analyses (that's what the restrictlist is used for).
     * In a second step, the buildblocks for analyses with matching probability are calculated.
     * There could be several analyses with same probability; all of these are calculated,
     *  we therefore might have several buildblocks.
     */
    ArrayList<ArrayList<BuildBlock>> restrictList = contList[ce.getTreeState().getWordCover()[1]];
    StringBuilder bbidbuilder = new StringBuilder();
    int max = ce.getTreeState().getWordCover()[1];
    //if (max >= contList.length) max = contList.length-1;
    for (int z = max; z >= 0; z--) {
        if (contList[z] != null && !contList[z].isEmpty()) {
            bbidbuilder.append(contList[z].hashCode());
        }
    }
    //        List<BuildBlock> buildBlocks;
    List<Pair<BuildBlock, Integer>> buildBlocks;
    if (restrictList != null && !restrictList.isEmpty()) {
        //            buildBlocks = (ArrayList<BuildBlock>) ce.getBuildBlocks().clone();
        buildBlocks = newBuildBlockList((ArrayList<BuildBlock>) ce.getBuildBlocks().clone());
        for (ArrayList<BuildBlock> restriction : restrictList) {
            List<Pair<BuildBlock, Integer>> restrictionPair = newBuildBlockList(restriction);
            //                ArrayList<BuildBlock> intersection = (ArrayList<BuildBlock>) ce.getBuildBlocks().clone();
            List<Pair<BuildBlock, Integer>> intersection = newBuildBlockList(
                    (ArrayList<BuildBlock>) ce.getBuildBlocks().clone());
            //                intersection.retainAll(restriction);
            intersection.retainAll(restrictionPair);
            if (intersection.isEmpty()) {
                if (ce.getBuildBlocks().get(0).getOperation().name().endsWith("S")) {
                    continue;
                }
            } else {
                buildBlocks.retainAll(intersection);
            }
        }
        if (buildBlocks.isEmpty()) {
            //                buildBlocks = ce.getBuildBlocks();
            buildBlocks = newBuildBlockList(ce.getBuildBlocks());
        }
    } else {
        //            buildBlocks = ce.getBuildBlocks();
        buildBlocks = newBuildBlockList(ce.getBuildBlocks());
    } /*just for baseline.
      BuildBlock single = buildBlocks.get(0);
      buildBlocks.clear();
      buidBlocks.add(single);*/
    if (top && ce.getTreeState().getWordCover()[1] > 0) {// && buildBlocks.size()>1){
                                                         //double maxProb = Double.NEGATIVE_INFINITY;
        ArrayList<Pair<BuildBlock, Integer>> altlist = new ArrayList<Pair<BuildBlock, Integer>>();
        for (int i = buildBlocks.size() - 1; i >= 0; i--) {
            //                BuildBlock bb = buildBlocks.get(i);
            Pair<BuildBlock, Integer> bbPair = buildBlocks.get(i);
            BuildBlock bb = bbPair.getFirst();
            for (double d : bb.getPrevChartEntry().getNBestProbs()) {
                if (d == Double.NEGATIVE_INFINITY) {
                    continue;
                }
                double bbprobdiff = bb.getProbability() + d - targetprob;// bb.getPrevChartEntry().getNBestProb()//.getBestProbability();
                /*if (bbprob > maxProb){
                     maxProb = bbprob;
                     altlist.clear();altlist.add(bb);
                     }
                     else*/
                //                    if (Math.abs(bbprobdiff) < 0.00000001 && !altlist.contains(bb))
                if (Math.abs(bbprobdiff) < 0.00000001 && !altlist.contains(bbPair)) {
                    altlist.add(new Pair(bb, i));
                    //   System.out.print("->");
                }
            }
        }
        buildBlocks.clear();
        buildBlocks.addAll(altlist);
        //if (buildBlocks.isEmpty()) System.out.println("Failed to find path back at word +"+ce.getTreeState().getWordCover()[1]);
    }

    bbidbuilder.append(treeStateListArray.get(ce.getTreeState().getWordCover()[1]).indexOf(ce));
    String bbid = bbidbuilder.toString();
    /*
     * Now we loop over all buildblocks (these should all yield the analysis with target probability)
     */
    int bbi = 0;
    //        for (BuildBlock bb : buildBlocks)
    for (Pair<BuildBlock, Integer> bbPair : buildBlocks) {
        BuildBlock bb = bbPair.getFirst();
        //if (bbi>0) System.out.print("\t");
        double res = targetprob - bb.getProbability();
        //double rem = res - bb.getPrevChartEntry().getBestProbability();
        //System.out.println(ce.getTreeState().getWordCover()[1]+" "+bbi+"\t"+ bb.getProbability() + "\t"+ bb.getPrevChartEntry().getBestProbability() +"\t"+ bb);//.getProbability()+"\t"+res + "\t"+ bb.getPrevChartEntry().getBestProbability()+"\t"+rem);
        //System.out.print("\n"+ce.getTreeState().getWordCover()[1]+" "+bbi+"\t"+ bb.getProbability() + "\t"+ bb.getOperation());         
        //            bbi++;
        if (bb.getOperation() == ParserOperation.initial) {
            if (!top || Math.abs(res) < 0.00000001)// in the end it has to sum to zero, otherwise something went wrong.
            {
                Fringe f = ce.getTreeState().getFringe();
                f.setClusterNumberCount(true);
                StringTreeAnalysis sta = new StringTreeAnalysis(opts, bb, f);
                //if (ParserModel.train) 
                // here we start building the proper tree.
                // the following lines with buildTrace are for keeping track of the events that occur in the analysis
                // which are needed for training, where we want to count the events that lead to the correct analysis.

                // changed "-" to Integer.MAX_VALUE. "-" is an illegal value, that is never used in the 
                // called method, otherwise it would throw an exception, as it refers to an array index.
                if (train)
                    sta.setTrace(bb.getFreqCounter().getWordProbs().get(0), bb.getFreqCounter().getTreeProbs(),
                            Integer.MAX_VALUE, ParserOperation.initial, sta.getStringTree(), null, "-");
                //                    sta.setTrace(bb.getFreqCounter().getWordProbs().get(0), bb.getFreqCounter().getTreeProbs(), "-", ParserOperation.initial, sta.getStringTree(), null, "-");
                sta.getStringTree().setProbability(bb.getProbability());
                //so here our analysis, which we are building up, is added to the set of trees that are constructed.
                derivations.add(sta);
                bb.addAnalysis(buildBlocks.toString(), sta);
                sta.addToBuiltTrace("[" + ce.getTreeState().getWordCover()[1] + ", ");
                //                    sta.addToBuiltTrace(treeStateListArray.get(ce.getTreeState().getWordCover()[1]).indexOf(ce) + "]");
                //                    sta.addToBuiltTrace(treeStateListArray.get(ce.getTreeState().getWordCover()[1]).indexOf(ce) + " " + bbPair.getSecond()  +  " " + (bb.getAnalyses(buildBlocks.toString()).size() - 1) + "]");
                sta.addToBuiltTrace(treeStateListArray.get(ce.getTreeState().getWordCover()[1]).indexOf(ce)
                        + " " + bbPair.getSecond() + " " + targetprob + "]");

            }
            //   System.out.println("");
        } else // for all other parser operations beside "initial"
        {
            // we don't want to do the same work over and over if calculating more than
            // one analysis. (In particular, it often happens that several final analysis start out the same.)
            // Therefore, we just re-use those trees that we've already built.
            if (!top && bb.hasAnalysis(bbid)) {
                derivations.addAll(bb.getAnalyses(bbid));
                //System.out.println("has analysis");
                //      System.out.println("");
            } else {
                /*
                 * if we haven't done the tree that we need yet, still need to do the proper building work...
                 * again, we first need to make sure that everything is consistent, and we use the history of
                 * buildblocks for that (they are here put into contListNew). Basically, the idea is that the
                 * buildblock we're working on now gives us some restrictions on what other buildblocks are
                 * consistent with it.
                 */
                FringeAndProb fap = bb.getPrevChartEntry().getTreeState().getFutureFringe();
                ArrayList<BuildBlock>[] contListNew = new ArrayList[contList.length];
                int wind = 0;
                if (fap.getBBHist() != null) {
                    for (LinkedList<BuildBlock> lb : fap.getBBHist()) {
                        for (BuildBlock b : lb) {
                            if (b.getPrevChartEntry() == null) {
                                continue;
                            }
                            if (contListNew[wind] == null) {
                                contListNew[wind] = new ArrayList<BuildBlock>();
                            }
                            if (!contListNew[wind].contains(b)) {
                                contListNew[wind].add(b);
                            }
                        }
                        wind++;
                    }
                }
                ArrayList<ArrayList<BuildBlock>>[] contListRes = new ArrayList[contList.length];//contList.clone();// new ArrayList[contList.length];//
                for (int i = 0; i < contListNew.length; i++) {
                    ArrayList<BuildBlock> bblist = contListNew[i];
                    if (bblist != null && !bblist.isEmpty()) {
                        if (contList[i] == null) {
                            contListRes[i] = new ArrayList<ArrayList<BuildBlock>>();
                        } else {
                            contListRes[i] = (ArrayList<ArrayList<BuildBlock>>) contList[i].clone();
                        }
                        contListRes[i].add(bblist);
                    } else {
                        contListRes[i] = contList[i];//.clone();
                    }
                }

                String nextPos = bb.getElemTreeString();
                int anchorind = nextPos.indexOf("+<>");
                if (anchorind == -1) {
                    if (nextPos.contains("^null_1")) {
                        anchorind = nextPos.indexOf("+^1_1)");
                    }
                    if (anchorind == -1 && nextPos.contains("^null_2")) {
                        anchorind = nextPos.indexOf("+^2_2)");
                        if (anchorind == -1) {
                            anchorind = nextPos.indexOf("_2)") - 3;
                        }
                    }
                    if (anchorind == -1 && nextPos.contains("^null_3")) {
                        anchorind = nextPos.indexOf("+^3_3)");
                        if (anchorind == -1) {
                            anchorind = nextPos.indexOf("_3)") - 3;
                        }
                    }
                    if (anchorind == -1 && nextPos.contains("^null_4")) {
                        anchorind = nextPos.indexOf("+^4_4)");
                        if (anchorind == -1) {
                            anchorind = nextPos.indexOf("_4)") - 3;
                        }
                    }
                    if (anchorind == -1 && nextPos.contains("^null_5")) {
                        anchorind = nextPos.indexOf("+^5_5)");
                        if (anchorind == -1) {
                            anchorind = nextPos.indexOf("_5)") - 3;
                        }
                    }
                    if (anchorind == -1 && nextPos.contains("^null_6")) {
                        anchorind = nextPos.indexOf("+^6_6)");
                        if (anchorind == -1) {
                            anchorind = nextPos.indexOf("_6)") - 3;
                        }
                    }

                    nextPos = nextPos.substring(0, anchorind);
                    nextPos = nextPos.substring(nextPos.lastIndexOf(" ") + 1);
                } else {
                    nextPos = nextPos.substring(0, anchorind);
                    nextPos = nextPos.substring(nextPos.lastIndexOf("( ") + 2);
                    nextPos = nextPos.substring(0, nextPos.indexOf("^") - 1);
                }
                /*
                 * here is now the recursive call which will give us the analysis built up to this point.
                 */
                ArrayList<StringTreeAnalysis> prevDerivations = getAnalyses(bb.getPrevChartEntry(), contListRes,
                        nextPos, top, targetprob - bb.getProbability(), train);

                if (prevDerivations != null) {
                    /*
                     * for all derivations up to the current point, we need to now integrate the current buildblock
                     * (or more correctly, the elementary tree that buildblock tells us to, using the operation and integration
                     * site saved in buildblock).
                     */
                    for (StringTreeAnalysis deriv : prevDerivations) {
                        if (deriv == null) {
                            System.out.println("prevderiv empty.");
                            continue;
                        }
                        if (opts.verbose)//just some trace to see what's going on.
                        {
                            System.out.println("Chart:getAnalyses: " + deriv.getStringTree() + "\n + "
                                    + bb.getElemTreeString());
                            System.out.println(ce.getTreeState());
                            FringeAndProb futureFringe = ce.getTreeState().getFutureFringe();
                            //if (ce.getTreeState().getFringe()!=null && !ce.getTreeState().getFringe().isEmpty())
                            //System.out.println(futureFringe.getFringe());
                            if (futureFringe != null && futureFringe.hasNext()) {
                                System.out.println(futureFringe.getNext());
                            }
                            System.out.println();
                        }
                        /*
                         * So here is the real meat: the prefix tree gets integrated with the new elementary tree.
                         */
                        StringTreeAnalysis result = deriv.integrate(bb, bb.getPrevChartEntry().getTreeState(),
                                ce.getTreeState(), nextPOStag, train);
                        // after that we just deal with what went wrong, and store the analysis and return it
                        //                            if (opts.timeProfile)
                        //                            {
                        //                                System.out.println(result);
                        //                                System.err.println(ce.getTreeState());
                        //                            }
                        if (result == null) {
                            //                            System.out.print("."); // COMMENTED OUT
                            //System.out.println("incorrect analysis."+bb+"\n("+deriv+")\n");
                            if (ParserModel.useTimeOut
                                    && System.currentTimeMillis() - startTime > opts.timeOutStage2) {//1000 = 1sec, 60 000 = 1 min, 300 000 = 5 min
                                //            LogInfo.logs("Time out at stage 2 (10min).");
                                if (!opts.silentMode)
                                    LogInfo.logs("Time out at stage 2 - analyses reconstruction ( "
                                            + (((double) opts.timeOutStage2 / 1000.0) / 60.0) + " min).");
                                //                                        System.currentTimeMillis() - startTime > 1800000)
                                //                                ParserRunner.printConsole("Time out at stage 2 (30min).\t");
                                return null;
                            }
                            deriv.integrate(bb, bb.getPrevChartEntry().getTreeState(), ce.getTreeState(),
                                    nextPOStag, train);
                            continue;
                        }
                        derivations.add(result);
                        bb.addAnalysis(bbid, result);
                        result.addToBuiltTrace("[" + ce.getTreeState().getWordCover()[1] + ", ");
                        //                            result.addToBuiltTrace(treeStateListArray.get(ce.getTreeState().getWordCover()[1]).indexOf(ce) + " " + bbPair.getSecond()  +  " " + (bb.getAnalyses(bbid).size() - 1) + "]");
                        result.addToBuiltTrace(
                                treeStateListArray.get(ce.getTreeState().getWordCover()[1]).indexOf(ce) + " "
                                        + bbPair.getSecond() + " " + targetprob + "]");
                        if (ParserModel.useTimeOut
                                && System.currentTimeMillis() - startTime > opts.timeOutStage2) {//1000 = 1sec, 60 000 = 1 min, 300 000 = 5 min
                            //            LogInfo.logs("Time out at stage 2 (10min).");
                            if (!opts.silentMode)
                                LogInfo.logs("Time out at stage 2 - analyses reconstruction ( "
                                        + (((double) opts.timeOutStage2 / 1000.0) / 60.0) + " min).");
                            //                            ParserRunner.printConsole("Time out at stage 2 (10min).\t");
                            return derivations;
                        } //if ( Runtime.getRuntime().freeMemory()/(1024*1024) < 100){//1000 = 1sec, 60 000 = 1 min, 300 000 = 5 min
                          //System.out.print("o");//Time out at stage 2 (1min).");
                          //StatsRunner.printConsole("less than 20MB free mem left.\t");
                          //return derivations;
                          //}//*/                  
                    } // for prevDerivations
                }
            } // else
        } // else
        bbi++;
    } // for
      //if (!derivations.isEmpty())
      //   System.out.print("!"+derivations.get(0).getBuiltTrace());
      //   System.out.println("empty deriv.");

    return derivations;
}

From source file:edu.duke.cabig.c3pr.web.ajax.StudyAjaxFacade.java

/**
 * Gets the site personnel. Used by study_personnel jsp.
 * Note: we only load the study scoped staff who are not already assigned to the study.
 *
 * @param hcsId the hcs id/*from   w  ww. j  av  a  2  s  .c o  m*/
 * @param studyId the study id
 * @return the site personnel
 * @throws Exception the exception
 */
public List<PersonUser> getAllStaffAssociatedToStudyAndStudyOrganizations(String text, String studyId)
        throws Exception {

    //copy elements of notified list into another list to be used for search results
    List<PersonUser> eligbleStudyStaff = new ArrayList<PersonUser>();
    for (int i = 0; i < notifiedPersonUsers.size(); i++) {
        eligbleStudyStaff.add(notifiedPersonUsers.get(i));
    }
    if (eligbleStudyStaff.size() > 0) {

        // find all the research staff who meet the criteria
        List<PersonUser> searchedPersonUsers = personUserDao.getBySubNameAndSubEmail(extractSubnames(text));
        Set<PersonUser> searchedPersonUsersSet = new HashSet<PersonUser>();
        searchedPersonUsersSet.addAll(searchedPersonUsers);
        eligbleStudyStaff.retainAll(searchedPersonUsersSet);
    }
    // construct the reduced person users list for sending to the front end
    List<PersonUser> reducedPersonUsers = new ArrayList<PersonUser>(eligbleStudyStaff.size());

    Iterator<PersonUser> personUserIterator = eligbleStudyStaff.iterator();
    while (personUserIterator.hasNext()) {
        reducedPersonUsers.add(buildReduced(personUserIterator.next(),
                Arrays.asList("id", "firstName", "lastName", "assignedIdentifier")));
    }
    return reducedPersonUsers;
}

From source file:org.impalaframework.service.registry.internal.ServiceEntryRegistryDelegate.java

/**
 * Returns named service, which has to implement all of implementation types specified
 *///from   w w  w  .  j a v a  2s .  co  m
@SuppressWarnings("unchecked")
private List<ServiceRegistryEntry> getServicesInternal(String beanName, Class<?>[] exportTypes) {

    final boolean useBeanLookup;
    final boolean exportTypesSet;

    if (ArrayUtils.isNullOrEmpty(exportTypes)) {
        Assert.notNull(beanName, "Either bean name must be not null, or export types must be non-empty");
        useBeanLookup = true;
        exportTypesSet = false;
    } else {
        exportTypesSet = true;

        if (beanName == null) {
            Assert.notEmpty(exportTypes,
                    "Either bean name must be not null, or export types must be non-empty");
            useBeanLookup = false;
        } else {
            //bean lookup and export types are available - use bean lookup
            useBeanLookup = true;
        }
    }

    List<ServiceRegistryEntry> references;

    //use read lock protected section to get services
    try {
        registryReadLock.lock();

        final List<ServiceRegistryEntry> list;

        if (useBeanLookup) {
            list = beanNameToService.get(beanName);

            //if we have explicit types and list is not empty, we get the exported list use this to filter the 
            //list to be returned
            if (exportTypesSet && list != null && !list.isEmpty()) {

                final List<ServiceRegistryEntry> exportList = classNameToServices.get(exportTypes[0].getName());
                if (exportList == null) {
                    return Collections.EMPTY_LIST;
                } else {
                    list.retainAll(exportList);
                }
            }
        } else {
            //get list from export types
            list = classNameToServices.get(exportTypes[0].getName());
        }
        references = (list == null ? Collections.EMPTY_LIST : new ArrayList<ServiceRegistryEntry>(list));

    } finally {
        registryReadLock.unlock();
    }

    //no need to sort here, as it is already sorted
    return references;
}

From source file:ddf.test.itests.platform.TestSecurity.java

@Test(expected = SSLHandshakeException.class)
public void testDisallowedCipherSuites() throws Exception {
    String[] disallowedCipherSuites = new String[] {
            // We can't test any cipher suite with > 128 encryption. 256 requires the unlimited strength policy to be installed
            //                "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", "TLS_RSA_WITH_AES_256_CBC_SHA256",
            //                "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384",
            //                "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256",
            //                "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
            //                "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",
            //                "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
            //                "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
            //                "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_256_GCM_SHA384",
            //                "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384",
            //                "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384",
            "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
            "TLS_RSA_WITH_AES_128_CBC_SHA256", "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256",
            "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256",
            "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
            "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA",
            "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA",
            "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", "TLS_ECDHE_RSA_WITH_RC4_128_SHA", "SSL_RSA_WITH_RC4_128_SHA",
            "TLS_ECDH_ECDSA_WITH_RC4_128_SHA", "TLS_ECDH_RSA_WITH_RC4_128_SHA",
            "TLS_RSA_WITH_AES_128_GCM_SHA256", "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256",
            "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256",
            "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA", "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
            "SSL_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA",
            "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA", "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA",
            "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA", "SSL_RSA_WITH_RC4_128_MD5",
            "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" };

    List<String> systemCipherSuites = Arrays.asList(System.getProperty("https.cipherSuites").split(","));
    List<String> intersection = new ArrayList<>(Arrays.asList(disallowedCipherSuites));
    intersection.retainAll(systemCipherSuites);
    assertThat("Supported cipher suite in disallowed ciphers", intersection, emptyCollectionOf(String.class));

    String url = SERVICE_ROOT.getUrl() + "/catalog/query?q=*&src=local";
    CredentialsProvider credentialsProvider = createBasicAuth("admin", "admin");
    HttpClient client = createHttpClient("TLSv1.2", disallowedCipherSuites, credentialsProvider);

    HttpGet get = new HttpGet(url);
    client.execute(get);/*from  w  w w  .  j  a v  a2  s. c o  m*/
}

From source file:org.wso2.iot.agent.services.operation.OperationManager.java

/**
 * Check the app restriction policy (black list or white list) for compliance
 *
 * @param operation - Operation object//from w  w w. j  a  v a2s  .  co  m
 * @return - Compliance feature object
 * @throws AndroidAgentException
 */
public ComplianceFeature checkAppRestrictionPolicy(Operation operation, ComplianceFeature policy)
        throws AndroidAgentException {

    AppRestriction appRestriction = CommonUtils.getAppRestrictionTypeAndList(operation, null, null);
    List<String> installedAppPackages = CommonUtils.getInstalledAppPackages(getContext());

    if (Constants.AppRestriction.BLACK_LIST.equals(appRestriction.getRestrictionType())) {
        List<String> commonApps = new ArrayList<>(installedAppPackages);
        if (commonApps.retainAll(appRestriction.getRestrictedList())) {
            if (commonApps.size() > 0) {
                policy.setCompliance(false);
                return policy;
            }
        }
    } else if (Constants.AppRestriction.WHITE_LIST.equals(appRestriction.getRestrictionType())) {
        List<String> remainApps = new ArrayList<>(CommonUtils.getInstalledAppPackagesByUser(getContext()));
        String permittedPackageName;
        JSONObject permittedApp;
        String whiteListAppsPref;
        for (String packageName : remainApps) {
            whiteListAppsPref = Preference.getString(context, Constants.AppRestriction.WHITE_LIST_APPS);
            if (whiteListAppsPref != null) {
                try {
                    JSONArray whiteListApps = new JSONArray(whiteListAppsPref);
                    for (int i = 0; i < whiteListApps.length(); i++) {
                        permittedApp = new JSONObject(whiteListApps.getString(i));
                        permittedPackageName = permittedApp.getString(Constants.AppRestriction.PACKAGE_NAME);
                        if (!permittedPackageName.equals(packageName)) {
                            policy.setCompliance(false);
                            return policy;
                        }
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Invalid JSON format..");
                }
            }
        }
    }
    policy.setCompliance(true);
    return policy;
}

From source file:org.ebayopensource.turmeric.eclipse.mavenapi.test.internal.collections.TestListUtil.java

/**
 * Test method for {@link org.ebayopensource.turmeric.eclipse.mavenapi.internal.collections.ListUtil#transformed(org.ebayopensource.turmeric.eclipse.mavenapi.internal.collections.Transformer, java.util.List)}.
 *///from www. j a  v a  2  s.  c o m
@Test
public void testTransformedTransformerOfTListOfQ() {
    List<String> collection = new ArrayList<String>();
    collection.add("S3");
    collection.add("Nvidia");
    collection.add("ATI");
    final Transformer<String> transformer = new Transformer<String>() {
        private static final long serialVersionUID = 1631027078150099602L;

        @Override
        public String transform(final Object input) {
            return ObjectUtils.toString(input).toLowerCase();
        }
    };
    List<String> list = ListUtil.transformed(transformer, collection);
    for (int i = 0; i < collection.size(); i++) {
        String expected = collection.get(i);
        String actual = list.get(i);
        Assert.assertNotSame(expected, actual);
        Assert.assertTrue(expected.equalsIgnoreCase(actual));
    }
    String item = "3dfx";
    list.add(item);
    Assert.assertTrue(list.contains(item));
    list.remove(item);
    Assert.assertFalse(list.contains(item));
    list.add(0, item);
    Assert.assertTrue(list.indexOf(item) == 0);
    Assert.assertTrue(list.lastIndexOf(item) == 0);
    list.remove(0);
    list.set(0, item);
    Assert.assertTrue(list.indexOf(item) == 0);

    Collection<String> data = new ArrayList<String>(2);
    data.add("Voodoo");
    data.add("Radeon");
    list.addAll(data);
    Assert.assertTrue(list.containsAll(data));
    list.removeAll(data);
    Assert.assertFalse(list.containsAll(data));
    list.addAll(0, data);
    list.retainAll(data);
}

From source file:org.phenotips.groups.internal.DefaultGroupManager.java

@Override
public Set<Group> getGroupsForUser(User user) {
    if (user == null || user.getProfileDocument() == null) {
        return Collections.emptySet();
    }//from  w w  w .ja  v  a2  s  .c o  m

    DocumentReference profile = user.getProfileDocument();

    Set<Group> result = new LinkedHashSet<>();
    try {
        Query q = this.qm.createQuery("from doc.object(XWiki.XWikiGroups) grp where grp.member in (:u, :su)",
                Query.XWQL);
        q.bindValue("u", profile.toString());
        q.bindValue("su", this.compactSerializer.serialize(profile));
        List<Object> groups = q.execute();
        List<Object> nestedGroups = new ArrayList<>(groups);
        while (!nestedGroups.isEmpty()) {
            StringBuilder qs = new StringBuilder(
                    "from doc.object(XWiki.XWikiGroups) grp where grp.member in (");
            for (int i = 0; i < nestedGroups.size(); ++i) {
                if (i > 0) {
                    qs.append(',');
                }
                qs.append('?').append(i + 1);
            }
            qs.append(')');
            q = this.qm.createQuery(qs.toString(), Query.XWQL);
            for (int i = 0; i < nestedGroups.size(); ++i) {
                String formalGroupName = this.resolver.resolve(String.valueOf(nestedGroups.get(i)), GROUP_SPACE)
                        .toString();
                q.bindValue(i + 1, formalGroupName);
            }
            nestedGroups = q.execute();
            nestedGroups.removeAll(groups);
            groups.addAll(nestedGroups);
        }
        q = this.qm.createQuery(
                "from doc.object(XWiki.XWikiGroups) grp, doc.object(PhenoTips.PhenoTipsGroupClass) phgrp",
                Query.XWQL);
        groups.retainAll(q.execute());
        for (Object groupName : groups) {
            result.add(getGroup(String.valueOf(groupName)));
        }
    } catch (QueryException ex) {
        this.logger.warn("Failed to search for user's groups: {}", ex.getMessage());
    }

    return Collections.unmodifiableSet(result);
}

From source file:org.jahia.services.usermanager.ldap.LDAPUserGroupProvider.java

/**
 * Construct a list that contain only the elements also contains from the other list
 *
 * @param first//from  ww w  .ja  v a2 s  .  c  o  m
 * @param second
 * @return
 */
private List<String> getCommonAttributesSize(List<String> first, List<String> second) {
    List<String> commons = new ArrayList<String>(first);
    commons.retainAll(second);
    return commons;
}