Example usage for java.util ArrayList contains

List of usage examples for java.util ArrayList contains

Introduction

In this page you can find the example usage for java.util ArrayList contains.

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this list contains the specified element.

Usage

From source file:com.xpn.xwiki.plugin.collection.CollectionPlugin.java

/**
 * Retrieve the breadcrumb path by looking up parents
 *
 * @param docName page from which to start the breadcrumb
 * @param pageList list of pages already traversed to avoid infinite loops
 * @param context XWiki Context/*from  www .  ja  v  a2  s  .  c om*/
 */
public List<String> getBreadcrumbFromParents(String docName, ArrayList<String> pageList, XWikiContext context) {
    try {
        XWikiDocument doc = context.getWiki().getDocument(docName, context);
        String page = doc.getParent();
        if ((page != null) & !page.equals("") && !pageList.contains(page) && !page.equals("XWiki.XWikiGuest")
                && !page.equals("XWiki.XWikiUsers")) {
            pageList.add(page);
            return getBreadcrumbFromParents(page, pageList, context);
        } else {
            return pageList;
        }
    } catch (XWikiException e1) {
        // could not read document ignore it
        return pageList;
    }
}

From source file:org.dklisiaris.downtown.helper.XMLParser.java

public ArrayList<String> getAllSubTagItems(Document doc, String elemTag, String itemTag, boolean isMulti) {
    ArrayList<String> items = new ArrayList<String>();
    //Document doc = getDomElement(xml); // getting DOM element
    NodeList nl = doc.getElementsByTagName(elemTag);
    // looping through all item nodes <category>
    for (int k = 0; k < nl.getLength(); k++) {
        Element e = (Element) nl.item(k);
        if (isMulti) {
            NodeList subItems = e.getElementsByTagName(itemTag);
            for (int j = 0; j < subItems.getLength(); j++) {
                Element subItem = (Element) subItems.item(j);
                String value = getElementValue(subItem);
                if (!items.contains(value)) {
                    items.add(value);//from   ww  w. j a v  a2 s  . co  m
                    //Log.d("Item added:",value);
                }
                //Log.d("Subcat",parser.getElementValue(subcat));
            }
        } else {
            String value = getValue(e, itemTag);
            if (!items.contains(value)) {
                items.add(value);
                //Log.d("Item added:",value);
            }
        }
    }

    return items;
}

From source file:com.aware.Aware.java

/**
 * Insert / Update settings of the framework
 * @param key/*ww w . j  a  v  a2  s . c  om*/
 * @param value
 */
public static void setSetting(Context context, String key, Object value) {

    boolean is_restricted_package = true;

    ArrayList<String> global_settings = new ArrayList<String>();
    global_settings.add("debug_flag");
    global_settings.add("debug_tag");
    global_settings.add("study_id");
    global_settings.add("study_start");

    if (global_settings.contains(key)) {
        is_restricted_package = false;
    }

    //Only AWARE client can change the device ID if needed
    if (key.equals("device_id") && !context.getPackageName().equals("com.aware")) {
        return;
    }

    ContentValues setting = new ContentValues();
    setting.put(Aware_Settings.SETTING_KEY, key);
    setting.put(Aware_Settings.SETTING_VALUE, value.toString());
    setting.put(Aware_Settings.SETTING_PACKAGE_NAME, context.getPackageName());

    Cursor qry = context.getContentResolver().query(Aware_Settings.CONTENT_URI, null, Aware_Settings.SETTING_KEY
            + " LIKE '" + key + "'"
            + (is_restricted_package
                    ? " AND " + Aware_Settings.SETTING_PACKAGE_NAME + " LIKE '" + context.getPackageName() + "'"
                    : ""),
            null, null);
    //update
    if (qry != null && qry.moveToFirst()) {
        try {
            if (!qry.getString(qry.getColumnIndex(Aware_Settings.SETTING_VALUE)).equals(value.toString())) {
                context.getContentResolver().update(Aware_Settings.CONTENT_URI, setting,
                        Aware_Settings.SETTING_ID + "="
                                + qry.getInt(qry.getColumnIndex(Aware_Settings.SETTING_ID)),
                        null);
                if (Aware.DEBUG)
                    Log.d(Aware.TAG, "Updated: " + key + "=" + value);
            }
        } catch (SQLiteException e) {
            if (Aware.DEBUG)
                Log.d(TAG, e.getMessage());
        } catch (SQLException e) {
            if (Aware.DEBUG)
                Log.d(TAG, e.getMessage());
        }
        //insert
    } else {
        try {
            context.getContentResolver().insert(Aware_Settings.CONTENT_URI, setting);
            if (Aware.DEBUG)
                Log.d(Aware.TAG, "Added: " + key + "=" + value);
        } catch (SQLiteException e) {
            if (Aware.DEBUG)
                Log.d(TAG, e.getMessage());
        } catch (SQLException e) {
            if (Aware.DEBUG)
                Log.d(TAG, e.getMessage());
        }
    }
    if (qry != null && !qry.isClosed())
        qry.close();
}

From source file:eu.freme.broker.eservices.FremeNER.java

@RequestMapping(value = "/e-entity/freme-ner/documents", method = { RequestMethod.POST, RequestMethod.GET })
public ResponseEntity<String> execute(
        /*@RequestParam(value = "input", required = false) String input,
        @RequestParam(value = "i", required = false) String i,
        @RequestParam(value = "informat", required = false) String informat,
        @RequestParam(value = "f", required = false) String f,
        @RequestParam(value = "outformat", required = false) String outformat,
        @RequestParam(value = "o", required = false) String o,
        @RequestParam(value = "prefix", required = false) String prefix,
        @RequestParam(value = "p", required = false) String p,
        *//*  w ww .  j  a  va  2  s  .  c o m*/
        @RequestHeader(value = "Accept", required = false) String acceptHeader,
        @RequestHeader(value = "Content-Type", required = false) String contentTypeHeader,
        @RequestParam(value = "language", required = true) String language,
        @RequestParam(value = "dataset", required = true) String dataset,
        @RequestParam(value = "numLinks", required = false) String numLinksParam,
        @RequestParam(value = "enrichement", required = false) String enrichementType,
        @RequestParam(value = "mode", required = false) String mode,
        @RequestParam(value = "domain", required = false) String domain,
        @RequestParam(value = "types", required = false) String types,
        @RequestParam(value = "datasetKey", required = false) String datasetKey,
        @RequestParam Map<String, String> allParams, @RequestBody(required = false) String postBody) {
    try {

        //            System.out.println(domain);
        //            System.out.println(types);

        // Check the language parameter.
        if (!SUPPORTED_LANGUAGES.contains(language)) {
            // The language specified with the langauge parameter is not supported.
            throw new eu.freme.broker.exception.BadRequestException("Unsupported language.");
        }

        if (dataset.equals("wand")) {
            if (datasetKey != null) {
                if (datasetKey.equals(wandKey)) {
                    // The user has access right to the dataset.
                } else {
                    throw new eu.freme.broker.exception.AccessDeniedException(
                            "You dont have access right for this dataset" + wandKey);
                }
            } else {
                throw new eu.freme.broker.exception.AccessDeniedException(
                        "You dont have access right for this dataset");
            }
        }

        ArrayList<String> rMode = new ArrayList<>();

        // Check the MODE parameter.
        if (mode != null) {
            String[] modes = mode.split(",");
            for (String m : modes) {
                if (m.equals("spot") || m.equals("classify") || m.equals("link") || m.equals("all")) {
                    // OK, the mode is supported.
                    rMode.add(m);
                } else {
                    // The mode specified is not supported.
                    throw new eu.freme.broker.exception.BadRequestException("Unsupported mode: " + m);
                }
            }

            if (rMode.contains("classify") && !rMode.contains("spot")) {
                throw new eu.freme.broker.exception.BadRequestException(
                        "Unsupported mode combination: classification must be performed in combination with spotting.");
            }

            if (rMode.contains("all")) {
                rMode.clear();
                rMode.add("all");
            }

        } else {
            // OK, perform all.
            rMode.add("all");
        }

        int numLinks = 1;
        // Check the dataset parameter.
        if (numLinksParam != null) {
            numLinks = Integer.parseInt(numLinksParam);
            if (numLinks > 5) {
                numLinks = 1;
            }
        }

        //NIFParameterSet parameters = this.normalizeNif(input, informat, outformat, postBody, acceptHeader, contentTypeHeader, prefix);
        NIFParameterSet nifParameters = this.normalizeNif(postBody, acceptHeader, contentTypeHeader, allParams,
                false);

        Model inModel = ModelFactory.createDefaultModel();
        Model outModel = ModelFactory.createDefaultModel();
        outModel.setNsPrefix("dbpedia", "http://dbpedia.org/resource/");
        outModel.setNsPrefix("dbpedia-de", "http://de.dbpedia.org/resource/");
        outModel.setNsPrefix("dbpedia-nl", "http://nl.dbpedia.org/resource/");
        outModel.setNsPrefix("dbpedia-es", "http://es.dbpedia.org/resource/");
        outModel.setNsPrefix("dbpedia-it", "http://it.dbpedia.org/resource/");
        outModel.setNsPrefix("dbpedia-fr", "http://fr.dbpedia.org/resource/");
        outModel.setNsPrefix("dbpedia-ru", "http://ru.dbpedia.org/resource/");
        outModel.setNsPrefix("dbc", "http://dbpedia.org/resource/Category:");
        outModel.setNsPrefix("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
        outModel.setNsPrefix("dcterms", "http://purl.org/dc/terms/");
        outModel.setNsPrefix("freme-onto", "http://freme-project.eu/ns#");

        String docForProcessing = null;

        if (nifParameters.getInformat().equals(RDFConstants.RDFSerialization.PLAINTEXT)) {
            // input is sent as value of the input parameter
            docForProcessing = nifParameters.getInput();

            //                if(rMode.size() == 1 && rMode.contains("link")) {
            //                    throw new eu.freme.broker.exception.BadRequestException("Unsupported mode combination: you must provide NIF in order to perform only linking.");
            //                }

        } else {
            // input is sent as body of the request

            if (rMode.size() == 1 && rMode.contains("link")) {
                docForProcessing = postBody;
            } else {
                inModel = rdfConversionService.unserializeRDF(nifParameters.getInput(),
                        nifParameters.getInformat());

                StmtIterator iter = inModel.listStatements(null, RDF.type, inModel
                        .getResource("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#Context"));

                boolean textFound = false;
                String tmpPrefix = "http://freme-project.eu/#";
                // The first nif:Context with assigned nif:isString will be processed.
                while (!textFound) {
                    Resource contextRes = iter.nextStatement().getSubject();
                    tmpPrefix = contextRes.getURI().split("#")[0];
                    nifParameters.setPrefix(tmpPrefix);
                    Statement isStringStm = contextRes.getProperty(inModel.getProperty(
                            "http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#isString"));
                    if (isStringStm != null) {
                        docForProcessing = isStringStm.getObject().asLiteral().getString();
                        textFound = true;
                    }
                }
            }

            if (docForProcessing == null) {
                throw new eu.freme.broker.exception.BadRequestException("No content to process.");
            }
        }

        String fremeNERRes = entityAPI.callFremeNER(docForProcessing, language, nifParameters.getPrefix(),
                dataset, numLinks, rMode, nifParameters.getInformat().contentType(), domain, types);
        outModel.read(new ByteArrayInputStream(fremeNERRes.getBytes()), null, "TTL");
        outModel.add(inModel);
        HashMap<String, String> templateParams = new HashMap<>();
        if (enrichementType != null) {
            if (enrichementType.equals("dbpedia-categories")) {
                Template template = templateDAO.findOneById(300);
                outModel = dataEnricher.enrichWithTemplate(outModel, template, templateParams);
            }
        }

        return createSuccessResponse(outModel, nifParameters.getOutformat());
    } catch (BadRequestException e) {
        logger.error(e.getMessage(), e);
        throw new eu.freme.broker.exception.BadRequestException(e.getMessage());
    } catch (eu.freme.eservices.eentity.exceptions.ExternalServiceFailedException e) {
        logger.error(e.getMessage(), e);
        throw new ExternalServiceFailedException();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new eu.freme.broker.exception.BadRequestException(e.getMessage());
    }
}

From source file:com.aware.Aware.java

/**
 * Retrieve setting value given key./*from   w  ww.ja  v a  2s.c  om*/
 * @param key
 * @return value
 */
public static String getSetting(Context context, String key) {

    boolean is_restricted_package = true;

    ArrayList<String> global_settings = new ArrayList<String>();
    global_settings.add("debug_flag");
    global_settings.add("debug_tag");
    global_settings.add("device_id");
    global_settings.add("study_id");
    global_settings.add("study_start");

    if (global_settings.contains(key)) {
        is_restricted_package = false;
    }

    String value = "";
    Cursor qry = context.getContentResolver().query(Aware_Settings.CONTENT_URI, null, Aware_Settings.SETTING_KEY
            + " LIKE '" + key + "'"
            + (is_restricted_package
                    ? " AND " + Aware_Settings.SETTING_PACKAGE_NAME + " LIKE '" + context.getPackageName() + "'"
                    : ""),
            null, null);
    if (qry != null && qry.moveToFirst()) {
        value = qry.getString(qry.getColumnIndex(Aware_Settings.SETTING_VALUE));
    }
    if (qry != null && !qry.isClosed())
        qry.close();
    return value;
}

From source file:com.mirth.connect.server.controllers.DefaultChannelController.java

@Override
public synchronized boolean updateChannel(Channel channel, ServerEventContext context, boolean override)
        throws ControllerException {
    // Never include code template libraries in the channel stored in the database
    channel.getCodeTemplateLibraries().clear();
    channel.clearDependencies();/*from w ww  . j a v a 2  s  .  c  om*/

    /*
     * Methods that update the channel must be synchronized to ensure the channel cache and
     * database never contain different versions of a channel.
     */

    int newRevision = channel.getRevision();
    int currentRevision = 0;

    Channel matchingChannel = getChannelById(channel.getId());

    // If the channel exists, set the currentRevision
    if (matchingChannel != null) {
        /*
         * If the channel in the database is the same as what's being passed in, don't bother
         * saving it.
         * 
         * Ignore the channel revision and last modified date when comparing the channel being
         * passed in to the existing channel in the database. This will prevent the channel from
         * being saved if the only thing that changed was the revision and/or the last modified
         * date. The client/CLI take care of this by passing in the proper revision number, but
         * the API alone does not.
         */
        if (EqualsBuilder.reflectionEquals(channel, matchingChannel,
                new String[] { "lastModified", "revision" })) {
            return true;
        }

        currentRevision = matchingChannel.getRevision();

        // Use the larger nextMetaDataId to ensure a metadata ID will never be reused if an older version of a channel is imported or saved.
        channel.setNextMetaDataId(Math.max(matchingChannel.getNextMetaDataId(), channel.getNextMetaDataId()));
    }

    /*
     * If it's not a new channel, and its version is different from the one in the database (in
     * case it has been changed on the server since the client started modifying it), and
     * override is not enabled
     */
    if ((currentRevision > 0) && (currentRevision != newRevision) && !override) {
        return false;
    } else {
        channel.setRevision(currentRevision + 1);
    }

    ArrayList<String> destConnectorNames = new ArrayList<String>(channel.getDestinationConnectors().size());

    for (Connector connector : channel.getDestinationConnectors()) {
        if (destConnectorNames.contains(connector.getName())) {
            throw new ControllerException("Destination connectors must have unique names");
        }
        destConnectorNames.add(connector.getName());
    }

    try {
        // If we are adding, then make sure the name isn't being used
        matchingChannel = getChannelByName(channel.getName());

        if (matchingChannel != null) {
            if (!channel.getId().equals(matchingChannel.getId())) {
                logger.error("There is already a channel with the name " + channel.getName());
                throw new ControllerException("A channel with that name already exists");
            }
        }

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("id", channel.getId());
        params.put("name", channel.getName());
        params.put("revision", channel.getRevision());
        params.put("channel", channel);

        // Put the new channel in the database
        if (getChannelById(channel.getId()) == null) {
            logger.debug("adding channel");
            SqlConfig.getSqlSessionManager().insert("Channel.insertChannel", params);
        } else {
            logger.debug("updating channel");
            SqlConfig.getSqlSessionManager().update("Channel.updateChannel", params);
        }

        // invoke the channel plugins
        for (ChannelPlugin channelPlugin : extensionController.getChannelPlugins().values()) {
            channelPlugin.save(channel, context);
        }

        return true;
    } catch (Exception e) {
        throw new ControllerException(e);
    }
}

From source file:com.tremolosecurity.provisioning.core.providers.AlfrescoProviderREST.java

@Override
public void syncUser(User user, boolean addOnly, Set<String> attributes, Map<String, Object> request)
        throws ProvisioningException {

    int approvalID = 0;

    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }/*from w  w w . java 2 s  .  c  o m*/

    Workflow workflow = (Workflow) request.get("WORKFLOW");

    String token = "";

    try {
        token = this.login();
    } catch (Exception e) {
        throw new ProvisioningException("Could not initialize Alfresco Web Services Client", e);
    }

    AlfrescoUser userDetails;
    try {
        userDetails = userLookup(user.getUserID(), token);
    } catch (Exception e) {
        this.createUser(user, attributes, request);
        return;
    }

    for (String attrName : user.getAttribs().keySet()) {
        Attribute attr = user.getAttribs().get(attrName);

        if (!attributes.contains(attr.getName())) {
            continue;
        }

        StringBuffer b = new StringBuffer();
        b.append("set").append(attrName.toUpperCase().charAt(0)).append(attrName.substring(1));
        String methodName = b.toString();

        try {
            Method method = AlfrescoUser.class.getMethod(methodName, String.class);
            method.invoke(userDetails, attr.getValues().get(0));
        } catch (Exception e) {
            throw new ProvisioningException("Could not create user", e);
        }

    }

    Gson gson = new Gson();
    String json = gson.toJson(userDetails, AlfrescoUser.class);

    StringBuffer b = new StringBuffer();
    b.append(this.endpoint).append("/people/").append(user.getUserID()).append("?alf_ticket=").append(token);

    HttpPut httpput = new HttpPut(b.toString());
    try {
        LastMileUtil.addLastMile(cfg, loginId, HEADER_NAME, httpput, lastMileKeyAlias, useLastMile);
    } catch (Exception e) {
        throw new ProvisioningException("Error generating provisioning last mile", e);
    }
    //httpput.addHeader("X-Alfresco-Remote-User", this.loginId);

    try {
        StringEntity data = new StringEntity(json);
        data.setContentType("application/json");
        httpput.setEntity(data);

        try {
            CloseableHttpResponse response = httpclient.execute(httpput);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new Exception("error");
            }

            response.close();
        } finally {

            httpput.releaseConnection();
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not sync user", e);
    }

    for (String attrName : user.getAttribs().keySet()) {
        Attribute attr = user.getAttribs().get(attrName);
        if (!attributes.contains(attr.getName())) {
            continue;
        }

        this.cfg.getProvisioningEngine().logAction(this.name, false, ActionType.Replace, approvalID, workflow,
                attrName, user.getAttribs().get(attrName).getValues().get(0));

    }

    ArrayList<String> tmpgroups = new ArrayList<String>();
    tmpgroups.addAll(user.getGroups());
    List<String> groups = null;
    try {
        groups = this.groupUserGroups(user.getUserID(), token);
    } catch (Exception e1) {
        throw new ProvisioningException("Could not load groups", e1);
    }

    if (groups != null) {
        for (String group : groups) {

            if (tmpgroups.contains(group)) {
                tmpgroups.remove(group);
            } else {
                if (!addOnly) {
                    this.deleteUserFromGroup(token, user.getUserID(), group, approvalID, workflow);
                }
            }
        }

        for (String group : tmpgroups) {
            this.addUsertoGroup(token, user.getUserID(), group, approvalID, workflow);
        }
    }

}

From source file:net.phase.wallet.Currency.java

private static ArrayList<Key> parseFromReader(BufferedReader bin) throws IOException, ParseException {
    ArrayList<Key> keysArray = new ArrayList<Key>();
    String keyHash;/*from  w w  w . ja va 2  s. c  o m*/
    boolean foundKey = false;

    while ((keyHash = bin.readLine()) != null) {
        // add a space at the start to make the regex work more easily
        keyHash = " " + keyHash + " ";

        Pattern p = Pattern.compile("\\W(1[1-9A-HJ-NP-Za-km-z]{27,34})\\W");
        Matcher m = p.matcher(keyHash);

        if (m.find()) {
            Log.d("balance", "Key " + m.group(1) + " found");
            Key newKey = new Key(m.group(1));

            if (!keysArray.contains(newKey)) {
                keysArray.add(newKey);
                foundKey = true;
            }
        }
    }

    if (foundKey) {
        return keysArray;
    } else {
        return null;
    }
}

From source file:com.twinsoft.convertigo.engine.ContextManager.java

public void remove(Context context) {
    if (context == null) {
        // Silently ignore
        Engine.logContextManager.warn("The context cannot be removed because it does not exist any more!");
        return;//w w  w  .j a  va  2  s .c om
    }

    // To prevent from deadlock, we must synchronize on the context itself (see #3048)
    // to avoid another request thread to try to use the context simultaneously.
    // This lock must occur BEFORE acquiring lock the the contexts table.
    synchronized (context) {
        String contextID = context.contextID;
        Engine.logContextManager.info("Removing context " + contextID);

        synchronized (contexts) {
            contexts.remove(contextID);
        }

        context.isDestroying = true;

        if ((context.requestedObject != null) && (context.requestedObject.runningThread != null)) {
            Engine.logContextManager.debug("Stopping requestable thread for context " + contextID);
            //context.requestedObject.runningThread.bContinue = false;
            context.abortRequestable();
        }

        // Trying to execute the end transaction (only in the engine mode)
        if ((Engine.isEngineMode()) && (context.getConnector() != null)) {
            // Execute the end transaction
            String endTransactionName = "n/a";
            try {
                endTransactionName = context.getConnector().getEndTransactionName();
                if ((endTransactionName != null) && (!endTransactionName.equals(""))) {
                    Engine.logContextManager
                            .debug("Trying to execute the end transaction: \"" + endTransactionName + "\"");
                    context.transactionName = endTransactionName;
                    DefaultRequester defaultRequester = new DefaultRequester();
                    // #4910 - prevent loop for destroying context renew
                    context.isDestroying = false;
                    defaultRequester.processRequest(context);
                    Engine.logContextManager.debug("End transaction successfull");
                }
            } catch (Throwable e) {
                Engine.logContextManager.error("Unable to execute the end transaction; " + "context: "
                        + context.contextID + ", " + "project: " + context.projectName + ", " + "connector: "
                        + context.connectorName + ", " + "end transaction: " + endTransactionName, e);
            } finally {
                context.isDestroying = true;
            }
            // Unlocks device if any
            // WARNING: removing the device pool MUST BE DONE AFTER the end transaction!!!
            String connectorQName = context.getConnector().getQName();
            DevicePool devicePool = getDevicePool(connectorQName);
            if (devicePool != null) {
                long contextNum = (Long.valueOf(Integer.toString(context.contextNum, 10))).longValue();
                Engine.logContextManager.trace("DevicePool for '" + connectorQName
                        + "' exist: unlocking device for context number " + contextNum + ".");
                devicePool.unlockDevice(contextNum);
            }
        }
        if (Engine.isEngineMode()) {
            for (final Connector connector : context.getOpenedConnectors()) {
                Engine.logContextManager.trace("Releasing " + connector.getName() + " connector ("
                        + connector.getClass().getName() + ") for context id " + context.contextID);
                Thread th = new Thread(new Runnable() {
                    public void run() {
                        connector.release();
                    }
                });
                th.setDaemon(true);
                th.start();
            }
        }

        context.clearConnectors();

        // Set TwsCachedXPathAPI to null
        context.cleanXpathApi();

        Engine.theApp.sessionManager.removeSession(contextID);
        String projectName = (String) context.projectName;

        /* Fix: #1754 - Slower transaction execution with many session */
        // HTTP session maintain its own context list in order to
        // improve context removal on session unbound process
        // See also #4198 which fix a regression
        String sessionID = context.httpSession != null ? context.httpSession.getId()
                : context.contextID.substring(0, context.contextID.indexOf("_"));
        HttpSession httpSession = HttpSessionListener.getHttpSession(sessionID);
        if (httpSession != null) {
            synchronized (httpSession) {
                try {
                    ArrayList<Context> contextList = GenericUtils.cast(httpSession.getAttribute("contexts"));
                    if ((contextList != null) && contextList.contains(context)) {
                        contextList.remove(context);
                        Engine.logContextManager.debug("(ContextManager) context " + contextID
                                + " has been removed from http session's context list");
                    }
                    httpSession.setAttribute("contexts", contextList);
                } catch (Exception e) {
                    // Ignore: HTTP session may have already been invalidated
                }
            }
        }

        Engine.logContextManager.debug("Context " + contextID + " has been removed");
        Engine.logContext.debug("[" + contextID + "] Context removed, project: " + projectName);
        Engine.logContextManager.info("Current in-use contexts: " + contexts.size());
        Engine.logUsageMonitor.info("[Contexts] Current in-use contexts: " + contexts.size());
    }
}

From source file:com.andersson.minesweeper.util.IabHelper.java

private int querySkuDetails(String itemType, Inventory inv, List<String> moreSkus)
        throws RemoteException, JSONException {
    logDebug("Querying SKU details.");
    ArrayList<String> skuList = new ArrayList<String>();
    skuList.addAll(inv.getAllOwnedSkus(itemType));
    if (moreSkus != null) {
        for (String sku : moreSkus) {
            if (!skuList.contains(sku)) {
                skuList.add(sku);// w  w  w. j a v  a2  s . com
            }
        }
    }

    if (skuList.size() == 0) {
        logDebug("queryPrices: nothing to do because there are no SKUs.");
        return BILLING_RESPONSE_RESULT_OK;
    }

    // Split the sku list in blocks of no more than 20 elements.
    ArrayList<ArrayList<String>> packs = new ArrayList<ArrayList<String>>();
    ArrayList<String> tempList;
    int n = skuList.size() / 20;
    int mod = skuList.size() % 20;
    for (int i = 0; i < n; i++) {
        tempList = new ArrayList<String>();
        for (String s : skuList.subList(i * 20, i * 20 + 20)) {
            tempList.add(s);
        }
        packs.add(tempList);
    }
    if (mod != 0) {
        tempList = new ArrayList<String>();
        for (String s : skuList.subList(n * 20, n * 20 + mod)) {
            tempList.add(s);
        }
        packs.add(tempList);
    }

    for (ArrayList<String> skuPartList : packs) {
        Bundle querySkus = new Bundle();
        querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuPartList);
        Bundle skuDetails = mService.getSkuDetails(3, mPackageName, itemType, querySkus);

        if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) {
            int response = getResponseCodeFromBundle(skuDetails);
            if (response != BILLING_RESPONSE_RESULT_OK) {
                logDebug("getSkuDetails() failed: " + getResponseDesc(response));
                return response;
            } else {
                logError("getSkuDetails() returned a bundle with neither an error nor a detail list.");
                return IABHELPER_BAD_RESPONSE;
            }
        }

        ArrayList<String> responseList = skuDetails.getStringArrayList(RESPONSE_GET_SKU_DETAILS_LIST);

        for (String thisResponse : responseList) {
            SkuDetails d = new SkuDetails(itemType, thisResponse);
            logDebug("Got sku details: " + d);
            inv.addSkuDetails(d);
        }
    }

    return BILLING_RESPONSE_RESULT_OK;
}