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:nosqltools.JSONUtilities.java

public String[] getFields() {
    //this array list will store the list of keys
    ArrayList<String> names = new ArrayList<>();

    if (json_array != null) {
        for (int i = 0; i < json_array.length(); i++) {
            //get the json object from the json array
            JSONObject jobj = json_array.getJSONObject(i);
            //store the array of field names from the json object. 
            String[] temp_names = getNames(jobj);

            //iterate over field names
            for (String temp_name : temp_names) {
                //if not already found in names add it 
                if (!names.contains(temp_name)) {
                    names.add(temp_name);
                }//w w w  . j  a v  a  2 s. co  m
            }
        }

        return names.toArray(new String[names.size()]);
    }
    //if json_obj return the field names from json_obj
    else if (json_obj != null) {
        return getNames(json_obj);
    } else {
        return new String[0];
    }

}

From source file:com.samsung.multiwindow.MultiWindow.java

/**
 * Get the MultiWindow enabled applications and activity names
 * //from  www  .jav a  2  s.  c  o  m
 * @param windowType
 *            The window type freestyle or splitstyle.
 * @param callbackContext
 *            The callback id used when calling back into JavaScript.
 * 
 */
private void getMultiWindowApps(final String windowType, final CallbackContext callbackContext)
        throws JSONException {

    if (Log.isLoggable(MULTIWINDOW, Log.DEBUG)) {
        Log.d(TAG, "Inside getMultiWindowApps");
    }
    cordova.getThreadPool().execute(new Runnable() {

        public void run() {

            JSONArray multiWindowApps = new JSONArray();
            Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
            List<ResolveInfo> resolveInfos = cordova.getActivity().getPackageManager().queryIntentActivities(
                    intent, PackageManager.GET_RESOLVED_FILTER | PackageManager.GET_META_DATA);

            try {
                // Get the multiwindow enabled applications

                int index = 0;
                for (ResolveInfo r : resolveInfos) {
                    if (r.activityInfo != null && r.activityInfo.applicationInfo.metaData != null) {
                        if (r.activityInfo.applicationInfo.metaData
                                .getBoolean("com.sec.android.support.multiwindow")
                                || r.activityInfo.applicationInfo.metaData
                                        .getBoolean("com.samsung.android.sdk.multiwindow.enable")) {
                            JSONObject appInfo = new JSONObject();
                            boolean bUnSupportedMultiWinodw = false;
                            if (windowType.equalsIgnoreCase("splitstyle")) {
                                if (r.activityInfo.metaData != null) {
                                    String activityWindowStyle = r.activityInfo.metaData
                                            .getString("com.sec.android.multiwindow.activity.STYLE");
                                    if (activityWindowStyle != null) {
                                        ArrayList<String> activityWindowStyles = new ArrayList<String>(
                                                Arrays.asList(activityWindowStyle.split("\\|")));
                                        if (!activityWindowStyles.isEmpty()) {
                                            if (activityWindowStyles.contains("fullscreenOnly")) {
                                                bUnSupportedMultiWinodw = true;
                                            }
                                        }
                                    }
                                }
                            }

                            if (!bUnSupportedMultiWinodw || !windowType.equalsIgnoreCase("splitstyle")) {
                                appInfo.put("packageName", r.activityInfo.applicationInfo.packageName);
                                appInfo.put("activity", r.activityInfo.name);
                                multiWindowApps.put(index++, appInfo);
                            }
                        }
                    }
                }
                callbackContext.success(multiWindowApps);
            } catch (Exception e) {

                callbackContext.error(e.getMessage());
            }

        }
    });
}

From source file:info.dc585.hpt.sa.SyncAdapter.java

private void syncTopHackers(ContentProviderClient provider, SyncResult syncResult) {

    try {/*  ww  w .ja  va 2 s  . com*/

        Log.d(TAG, "Calling something to sync up hackerpoint db");

        JSONArray hackers = NetworkUtilities.getTopHackers();
        if (hackers == null) {
            Log.e(TAG, "somehow got null hackers, explode please");
            syncResult.stats.numParseExceptions++;
        }
        if (hackers.length() == 0) {
            return;
        }

        Log.i(TAG, "Updateing content provider");
        Log.i(TAG, "hackers.length():" + hackers.length());
        for (int i = 0; i < hackers.length(); i++) {
            JSONObject jo = hackers.getJSONObject(i);
            String name = jo.getString("name");

            String selection = TopHackerTable.COLUMN_NAME + " like ?";
            String[] selectionArgs = { name };

            String[] projection = { TopHackerTable.COLUMN_ID, TopHackerTable.COLUMN_NAME };

            ContentValues values = new ContentValues();

            // FIXME:  Dear self, WTF would i trust network returned data without verifying limits ;)
            // TODO: See FIXME above.
            Cursor c = provider.query(HackerPointsContentProvider.HACKERS_URI, projection, selection,
                    selectionArgs, null);
            if (c.getCount() == 0) {
                Log.d(TAG, "performing insert for new name:" + name);

                int points = jo.getInt("points");
                values.put(TopHackerTable.COLUMN_POINTS, points);

                int pool = jo.getInt("pool");
                values.put(TopHackerTable.COLUMN_POOL, pool);

                int internets = jo.getInt("internets");
                values.put(TopHackerTable.COLUMN_INTERNETS, internets);

                String pictureURL = jo.getString("pictureURL");
                values.put(TopHackerTable.COLUMN_PICTUREURL, pictureURL);

                values.put(TopHackerTable.COLUMN_NAME, name);
                values.put(TopHackerTable.COLUMN_UPDATE, System.currentTimeMillis());
                provider.insert(HackerPointsContentProvider.HACKERS_URI, values);
                syncResult.stats.numInserts++;

            } else if (c.getCount() == 1) {
                Log.d(TAG, "performing update for name:" + name);
                if (name == null || name.isEmpty()) {
                    Log.e(TAG, "null or empty name");
                    continue;
                }

                int points = jo.getInt("points");
                values.put(TopHackerTable.COLUMN_POINTS, points);

                int pool = jo.getInt("pool");
                values.put(TopHackerTable.COLUMN_POOL, pool);

                int internets = jo.getInt("internets");
                values.put(TopHackerTable.COLUMN_INTERNETS, internets);

                String pictureURL = jo.getString("pictureURL");
                values.put(TopHackerTable.COLUMN_PICTUREURL, pictureURL);

                int rows = provider.update(HackerPointsContentProvider.HACKERS_URI, values, selection,
                        selectionArgs);

                Log.d(TAG, "Updated:" + rows + ": rows");
                syncResult.stats.numUpdates += rows;

            } else {
                Log.e(TAG, "Cursor count was not 0 or 1 was:" + c.getCount());
                continue;
            }
        }

        // Now run through both lists and figure out which one to delete.
        String[] projection = { TopHackerTable.COLUMN_NAME };
        Cursor c = provider.query(HackerPointsContentProvider.HACKERS_URI, projection, null, null, null);
        if (c.getCount() == 0) {
            return;
        }

        ArrayList<String> goodNames = new ArrayList<String>();
        ArrayList<String> rmNames = new ArrayList<String>();

        for (int i = 0; i < hackers.length(); i++) {
            JSONObject jo = hackers.getJSONObject(i);
            String name = jo.getString("name");
            goodNames.add(name);
        }

        while (c.moveToNext()) {
            int namec = c.getColumnIndex(TopHackerTable.COLUMN_NAME);
            String dbName = c.getString(namec);

            if (goodNames.contains(dbName) == false) {
                Log.d(TAG, "Adding name:" + dbName + ": to the delete list");
                rmNames.add(dbName);
            }
        }

        for (String nextName : rmNames) {
            Log.d(TAG, "deleting name:" + nextName + ":");
            // FIXME: use column name from Table class
            String where = " name = ? ";
            String[] whereArgs = { nextName };
            int rows = provider.delete(HackerPointsContentProvider.HACKERS_URI, where, whereArgs);
            syncResult.stats.numDeletes += rows;
        }

    } catch (final AuthenticationException e) {
        Log.e(TAG, "AuthenticationException", e);
    } catch (final JSONException e) {
        Log.e(TAG, "JSONException", e);
    } catch (final IOException e) {
        Log.e(TAG, "IOException", e);
    } catch (final ParseException e) {
        Log.e(TAG, "ParseException", e);
        syncResult.stats.numParseExceptions++;
    } catch (final RemoteException e) {
        Log.e(TAG, "RemoteException", e);
    }
}

From source file:com.celements.calendar.Event.java

void splitLanguageDependentFields(Set<String> confIndep, Set<String> confDep, List<String> propertyNames) {
    ArrayList<String> propNamesCleanList = new ArrayList<String>();
    propNamesCleanList.addAll(propertyNames);
    propNamesCleanList.remove("detaillink");
    if (propNamesCleanList.contains("date") || propNamesCleanList.contains("time")) {
        propNamesCleanList.remove("date");
        propNamesCleanList.remove("time");
        propNamesCleanList.add("eventDate");
    }// w  w w  .ja  v a2s.  co m
    if (propNamesCleanList.contains("date_end") || propNamesCleanList.contains("time_end")) {
        propNamesCleanList.remove("date_end");
        propNamesCleanList.remove("time_end");
        propNamesCleanList.add("eventDate_end");
    }
    LOGGER.debug("splitLanguageDepFields: " + propNamesCleanList.toString());
    for (String propName : propNamesCleanList) {
        if (propName.startsWith("l_")) {
            confDep.add(propName);
        } else {
            confIndep.add(propName);
        }
    }
}

From source file:org.sakaiproject.signup.tool.entityproviders.SignupEntityProducer.java

@Override
//this method is for merge data
public void transferCopyEntities(String fromContext, String toContext, List ids) {

    String currentUserId = getSakaiFacade().getCurrentUserId();
    List<SignupMeeting> allMeetings = getSignupMeetingService().getAllSignupMeetings(fromContext,
            currentUserId);//from  w w  w.  ja va2 s.co m
    List<SignupMeeting> newMeetings = new ArrayList<SignupMeeting>();
    SignupMeeting copiedMeeting = new SignupMeeting();
    SignupMeeting meetingTemp = new SignupMeeting();
    ArrayList<Long> recurIDs = new ArrayList<Long>();
    int skip = 0; //for when recurring meetings are removed

    if (!allMeetings.isEmpty()) {
        for (int i = 0; i < allMeetings.size(); i++) {
            meetingTemp = allMeetings.get(i); //holds each meeting

            if (meetingTemp.getRecurrenceId() != null && !recurIDs.contains(meetingTemp.getRecurrenceId())) {
                recurIDs.add(meetingTemp.getRecurrenceId()); //add recurID to the list
                copiedMeeting = createMeeting.prepareDeepCopy(meetingTemp, 0); //copies each meeting (meetingTemp)
                copiedMeeting.setCoordinatorIds(currentUserId); //changes organizer to currentUserId
                copiedMeeting.getSignupSites().get(0).setSiteId(toContext);
                copiedMeeting.setRepeatType(ONCE_ONLY);

                //copy attachments
                List<SignupAttachment> newOnes = new ArrayList<SignupAttachment>();
                List<SignupAttachment> olds = meetingTemp.getSignupAttachments();
                if (olds != null) {
                    for (SignupAttachment old : olds) {
                        SignupAttachment newOne = this.copyFileProcessor.copySignupAttachment(meetingTemp, true,
                                old, fromContext, toContext);
                        newOnes.add(newOne);
                    }
                }
                copiedMeeting.setSignupAttachments(newOnes);
                newMeetings.add((i - skip), copiedMeeting); //a list of copied signup meetings
            } else if (recurIDs.contains(meetingTemp.getRecurrenceId())) {
                skip++;
            } else {
                copiedMeeting = createMeeting.prepareDeepCopy(meetingTemp, 0); //copies each meeting (meetingTemp)
                copiedMeeting.setCoordinatorIds(currentUserId); //changes organizer to currentUserId
                copiedMeeting.getSignupSites().get(0).setSiteId(toContext);
                copiedMeeting.setRepeatType(ONCE_ONLY);

                List<SignupAttachment> newOnes = new ArrayList<SignupAttachment>();
                List<SignupAttachment> olds = meetingTemp.getSignupAttachments();
                if (olds != null) { //copied attachments with correct siteId
                    for (SignupAttachment old : olds) {
                        SignupAttachment newOne = this.copyFileProcessor.copySignupAttachment(meetingTemp, true,
                                old, fromContext, toContext);
                        newOnes.add(newOne);
                    }
                }
                copiedMeeting.setSignupAttachments(newOnes);
                newMeetings.add((i - skip), copiedMeeting); //a list of copied signup meetings
            }
        } //for end
        try {
            getSignupMeetingService().saveMeetings(newMeetings, currentUserId);
        } catch (PermissionException e) {
            log.warn("permission issue:" + e.getMessage());
        }
    } //if end
}

From source file:MSUmpire.LCMSPeakStructure.LCMSPeakBase.java

public ArrayList<PeakCluster> FindAllPeakClustersForPepByPSM(PepIonID pep) {
    ArrayList<PeakCluster> allclusterList = new ArrayList<>();
    for (PSM psm : pep.GetPSMList()) {
        ArrayList<PeakCluster> clusterList = FindPeakClustersByMassRTTol(psm.ObserPrecursorMass, psm.Charge,
                psm.RetentionTime, parameter.MaxCurveRTRange / 2);
        for (PeakCluster cluster : clusterList) {
            if (!allclusterList.contains(cluster)) {
                allclusterList.add(cluster);
            }//ww w  .ja  v a  2  s.  co m
        }
    }
    return allclusterList;
}

From source file:com.hygenics.parser.QualityAssurer.java

public void run() {
    this.checkTable();
    // CHECK THAT VARIABLES WHERE specified Correctly
    if (this.photoFolder != null || this.photoTable != null) {

        if (this.photoFolder != null ^ this.photoTable != null) {
            log.error("When specifiying a Photo Table or Photo Folder both variables must be present");
            throw new NullPointerException("Photo Table or Photo Folder is missing");
        } else {/*from   ww  w  .ja  va  2s .co  m*/
            int exists = 0;
            int nonexistant = 0;

            // check that the photos folder matches the photo database
            for (String f : new File(this.photoFolder).list()) {
                if (this.template.getJsonData("SELECT * FROM " + this.photoTable + " WHERE " + this.imageColumn
                        + " ILIKE '%" + f.replaceAll(this.imageReplace, "") + "%'").size() > 0) {
                    exists++;
                } else {
                    nonexistant++;
                }
            }

            if (exists == 0 || (imageCutoff > -1 && nonexistant > 0 && exists / nonexistant < imageCutoff)) {
                try {
                    throw new DataCountException(
                            "Photo Counts too Low!\nRation: " + Double.toString(exists / nonexistant));
                } catch (DataCountException e) {
                    e.printStackTrace();
                    System.exit(-1);
                }
            }
        }
    }

    java.sql.Timestamp date = new java.sql.Timestamp(Calendar.getInstance().getTimeInMillis());

    File[] files = new File(this.dropFolder).listFiles();
    //check that a file that at least one of the following is present
    if (oneMustMatch != null) {
        for (String r : oneMustMatch) {
            Pattern p = Pattern.compile(r);
            boolean found = false;
            for (File f : files) {
                Matcher m = p.matcher(f.getName());
                if (m.find()) {
                    found = true;
                }
            }
            if (!found) {
                try {
                    throw new FileNotFoundException("The file " + r + " Must Be Present!");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    System.exit(-1);
                }
            }
        }
    }

    // check file naming convention
    if (this.filenameRegex != null || this.dropFolder != null) {
        if (this.filenameRegex != null ^ this.dropFolder != null) {
            log.error(
                    "If Drop Folder is Specified or File Name Regex is specified, the other must also be specified.");
            throw new NullPointerException("Drop Folder or File Name Regex Not Specified");
        }

        if (files != null) {
            for (File f : files) {
                if (f.isFile() && !f.getName().contains(".zip")
                        && f.getName().replaceAll(filenameRegex, "").length() != 0) {
                    log.error("File Name Was Not Appropriately Specified");
                    try {
                        throw new InvalidPath("File Name Not Specified Properly. " + f + " must conform to "
                                + this.filenameRegex);
                    } catch (InvalidPath e) {
                        e.printStackTrace();
                        System.exit(-1);
                    }
                }
            }
        } else {
            try {
                throw new FileNotFoundException("No Directory %s found!".format(this.dropFolder));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.exit(255);
            }
        }
    }

    // Insert Column Counts into QA Table
    int recCount = 0;
    ArrayList<String> jsons = this.template.getJsonData(
            "SELECT table_schema as schema,table_name as table,column_name as column FROM information_schema.columns WHERE table_schema LIKE '"
                    + this.schema + "'");
    ArrayList<String> tables = new ArrayList<String>();

    if (jsons.size() > 0) {
        // get column count
        for (String json : jsons) {
            Map<String, Json> jmap = Json.read(json).asJsonMap();

            if (!tables.contains(jmap.get("table").asString())) {
                // get table counts and add to appropriate jsons
                String tquery = "SELECT count(*) FROM " + jmap.get("schema").asString() + "."
                        + jmap.get("table").asString();
                int tcount = Json.read(this.template.getJsonData(tquery).get(0)).asJsonMap().get("count")
                        .asInteger();
                recCount += tcount;
                this.template.execute("INSERT INTO " + this.countTable + "(schemaname,tablename,count) VALUES('"
                        + jmap.get("schema").asString() + "','" + jmap.get("table").asString() + "','" + tcount
                        + "')");
                tables.add(jmap.get("table").asString());
            }

            String query = "SELECT count(\"" + jmap.get("column").asString() + "\") FROM "
                    + jmap.get("schema").asString() + "." + jmap.get("table").asString() + " WHERE \""
                    + jmap.get("column").asString() + "\" IS NOT NULL AND length(trim(cast(\""
                    + jmap.get("column").asString() + "\" as text))) > 0";
            int count = Json.read(this.template.getJsonData(query).get(0)).asJsonMap().get("count").asInteger();
            this.template.execute(
                    "INSERT INTO " + this.columnCheckTable + "(schemaname,tablename,columnname,count) VALUES('"
                            + jmap.get("schema").asString() + "','" + jmap.get("table").asString() + "','"
                            + jmap.get("column").asString() + "','" + count + "')");
        }

        this.template.execute(
                "INSERT INTO " + this.sourceTable + " VALUES('" + this.schema.replaceAll("[0-9]+", "") + "')");

    }

    // if no records are discovered, error
    if (recCount == 0) {
        log.error("No Data Found in Tables. Terminating!");
        try {
            throw new MissingData("No Data Found In Tables");
        } catch (MissingData e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    // If all checks succeed, insert into the source table
    this.template.execute("INSERT INTO " + this.sourceTable + " VALUES('" + this.schema + "')");

}

From source file:com.workplacesystems.utilsj.ThreadDumperJdk16.java

@Override
void outputLockedSynchronizers(ThreadInfo info, ExtraLockInfo exLockInfo, StringBuffer buffer) {
    List<LockInfo> locked_synchronizers = Arrays.asList(info.getLockedSynchronizers());
    if (!locked_synchronizers.isEmpty() || (exLockInfo != null && exLockInfo.hasHeldLocks())) {
        buffer.append("   Locked Synchronizers:\n");
        ArrayList<String> reportedSyncs = new ArrayList<String>();
        for (LockInfo lockInfo : locked_synchronizers) {
            reportedSyncs.add(lockInfo.toString());
            formatLock(lockInfo, null, buffer);
            if (exLockInfo != null) {
                if (exLockInfo.heldWritesContains(lockInfo))
                    buffer.append(" for write");
                if (exLockInfo.heldReadsContains(lockInfo))
                    buffer.append(" for read");
            }/*w ww.j  ava2s  . c o  m*/
            buffer.append("\n");
        }

        if (exLockInfo != null) {
            for (LockInfo writeLock : exLockInfo.getHeldWriteLocks()) {
                if (!reportedSyncs.contains(writeLock.toString())) {
                    formatLock(writeLock, null, buffer);
                    buffer.append(" for write\n");
                }
            }
            for (LockInfo readLock : exLockInfo.getHeldReadLocks()) {
                if (!reportedSyncs.contains(readLock.toString())) {
                    formatLock(readLock, null, buffer);
                    buffer.append(" for read\n");
                }
            }
        }
        buffer.append("\n");
    }
}

From source file:eu.earthobservatory.testsuite.utils.Utils.java

public static void createdb() throws Exception {
    String url = "";
    ArrayList<String> databases = new ArrayList<String>();
    PreparedStatement pst = null;

    //Read properties
    Properties properties = new Properties();
    InputStream propertiesStream = Utils.class.getResourceAsStream(dbPropertiesFile);
    properties.load(propertiesStream);/*from w w w  .  ja  v a2 s.c o  m*/

    if ((databaseTemplateName = System.getProperty("postgis.databaseTemplateName")) == null) {
        databaseTemplateName = properties.getProperty("postgis.databaseTemplateName");
    }

    if ((serverName = System.getProperty("postgis.serverName")) == null) {
        serverName = properties.getProperty("postgis.serverName");
    }

    if ((username = System.getProperty("postgis.username")) == null) {
        username = properties.getProperty("postgis.username");
    }

    if ((password = System.getProperty("postgis.password")) == null) {
        password = properties.getProperty("postgis.password");
    }

    if ((port = System.getProperty("postgis.port")) == null) {
        port = properties.getProperty("postgis.port");
    }

    //Connect to server and create the temp database
    url = "jdbc:postgresql://" + serverName + ":" + port;
    conn = DriverManager.getConnection(url, username, password);

    pst = conn.prepareStatement("SELECT * FROM pg_catalog.pg_database");
    ResultSet rs = pst.executeQuery();

    while (rs.next()) {
        databases.add(rs.getString(1));
    }
    rs.close();
    pst.close();

    databaseName = "teststrabon" + (int) (Math.random() * 10000);
    while (databases.contains(databaseName)) {
        databaseName += "0";
    }

    pst = conn.prepareStatement("CREATE DATABASE " + databaseName + " TEMPLATE " + databaseTemplateName);
    pst.executeUpdate();
    pst.close();
    conn.close();

    url = "jdbc:postgresql://" + serverName + ":" + port + "/" + databaseName;
    conn = DriverManager.getConnection(url, username, password);

    strabon = new Strabon(databaseName, username, password, Integer.parseInt(port), serverName, true);
}

From source file:com.unicornlabs.kabouter.gui.power.PowerPanel.java

/**
 * Updates the list of devices//from   w  ww.j  a v a2s  .  co  m
 */
public void updateDeviceList() {
    deviceList.setEnabled(false);
    //Save the currently selected item
    List selectedValuesList = deviceList.getSelectedValuesList();

    deviceList.removeAll();

    //Get the device ids from the device manager
    ArrayList<String> deviceIds = theDeviceManager.getDeviceDisplayNames();

    //Sort them alphabetically
    Collections.sort(deviceIds);

    String[] deviceIdsAsStringArr = new String[deviceIds.size()];
    deviceIdsAsStringArr = deviceIds.toArray(deviceIdsAsStringArr);

    deviceList.setListData(deviceIdsAsStringArr);

    for (Object item : selectedValuesList) {
        if (deviceIds.contains((String) item)) {
            deviceList.setSelectedValue(item, true);
        }
    }

    deviceList.setEnabled(true);

}