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:net.duckling.falcon.api.boostrap.BootstrapDao.java

public boolean isDatabaseExisted() {
    Connection conn = getConnection();
    String sql = "show databases";
    Statement stmt = null;//from   w  w w  . jav a  2s  . c o  m
    ResultSet rs = null;
    ArrayList<String> results = new ArrayList<String>();
    try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery(sql);
        while (rs.next()) {
            results.add(rs.getString(1));
        }
    } catch (SQLException e) {
        throw new WrongSQLException(e.getMessage());
    } finally {
        try {
            closeAll(conn, stmt, rs);
        } catch (SQLException e) {
            throw new WrongSQLException(e.getMessage());
        }
    }
    return results.contains(database);
}

From source file:at.itbh.bev.rest.client.BevRestClient.java

/**
 * Query the ReST endpoint using the command line arguments
 * //from www.j  a  v a2 s  .  c o  m
 * @param args
 *            the command line arguments
 */
public void query(String[] args) {
    BevQueryExecutor executor = null;
    ResteasyClientBuilder clientBuilder = new ResteasyClientBuilder();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        int threadPoolSize = 1;
        if (line.hasOption("t")) {
            threadPoolSize = Integer.parseInt(line.getOptionValue("t"));
        }

        String postalCode = null;
        String place = null;
        String addressLine = null;
        String houseId = null;
        String radius = null;
        String longitude = null;
        String latitude = null;
        String separator = ";";
        boolean enforceUnique = false;
        if (line.hasOption("z")) {
            postalCode = line.getOptionValue("z");
        }
        if (line.hasOption("p")) {
            place = line.getOptionValue("p");
        }
        if (line.hasOption("a")) {
            addressLine = line.getOptionValue("a");
        }
        if (line.hasOption("i")) {
            houseId = line.getOptionValue("i");
        }
        if (line.hasOption("radius")) {
            radius = line.getOptionValue("radius");
        }
        if (line.hasOption("longitude")) {
            longitude = line.getOptionValue("longitude");
        }
        if (line.hasOption("latitude")) {
            latitude = line.getOptionValue("latitude");
        }
        if (line.hasOption("s")) {
            separator = line.getOptionValue("s");
        }
        if (line.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar BevRestClient.jar", options, true);
            System.exit(0);
        }
        if (line.hasOption("u")) {
            enforceUnique = true;
        }

        if (line.hasOption("disable-certificate-validation")) {
            clientBuilder.disableTrustManager();
        }

        if (!line.hasOption("proxy-port") && line.hasOption("proxy-host")) {
            throw new ParseException(
                    "The option --proxy-host is only allowed in combination with the option --proxy-port.");
        }
        if (line.hasOption("proxy-port") && !line.hasOption("proxy-host")) {
            throw new ParseException(
                    "The option --proxy-port is only allowed in combination with the option --proxy-host.");
        }
        if (line.hasOption("proxy-host") && line.hasOption("proxy-port")) {
            clientBuilder.defaultProxy(line.getOptionValue("proxy-host"),
                    Integer.parseInt(line.getOptionValue("proxy-port")));
        }

        OutputStreamWriter output;
        if (line.hasOption("o")) {
            output = new OutputStreamWriter(new FileOutputStream(line.getOptionValue("o")));
        } else {
            output = new OutputStreamWriter(System.out);
        }

        // avoid concurrent access exceptions in the Apache http client
        clientBuilder.connectionPoolSize(threadPoolSize);
        executor = new BevQueryExecutor(clientBuilder.build(), line.getOptionValue("r"), threadPoolSize);

        CsvPreference csvPreference = new CsvPreference.Builder('"',
                Objects.toString(line.getOptionValue("s"), ";").toCharArray()[0],
                System.getProperty("line.separator")).build();
        csvWriter = new CsvMapWriter(output, csvPreference, true);

        if (line.hasOption("b")) {
            ICsvMapReader mapReader = null;
            try {
                FileReader fileReader = new FileReader(line.getOptionValue("b"));
                mapReader = new CsvMapReader(fileReader, csvPreference);

                // calculate the output header (field names)
                final String[] header = mapReader.getHeader(true);
                ArrayList<String> tempFields = new ArrayList<>(Arrays.asList(defaultFieldNames));
                for (int i = 0; i < header.length; i++) {
                    if (!tempFields.contains(header[i])) {
                        tempFields.add(header[i]);
                    }
                }
                fieldNames = tempFields.toArray(new String[] {});

                Map<String, String> inputData;
                List<Future<List<BevQueryResult>>> queryResults = new ArrayList<>();
                while ((inputData = mapReader.read(header)) != null) {
                    queryResults
                            .add(executor.query(inputData.get(INPUT_POSTAL_CODE), inputData.get(INPUT_PLACE),
                                    inputData.get(INPUT_ADDRESS_LINE), inputData.get(INPUT_HOUSE_ID),
                                    inputData.get(INPUT_LONGITUDE), inputData.get(INPUT_LATITUDE),
                                    inputData.get(INPUT_RADIUS),
                                    inputData.get(INPUT_ENFORCE_UNIQUE) == null ? false
                                            : Boolean.parseBoolean(inputData.get(INPUT_ENFORCE_UNIQUE)),
                                    inputData));
                }
                csvWriter.writeHeader(fieldNames);
                for (Future<List<BevQueryResult>> queryResult : queryResults) {
                    List<BevQueryResult> results = queryResult.get();
                    outputResults(separator, results);
                }
            } finally {
                if (mapReader != null) {
                    mapReader.close();
                }
            }
        } else {
            fieldNames = defaultFieldNames;
            Map<String, String> inputData = new HashMap<String, String>();
            Future<List<BevQueryResult>> queryResult = executor.query(postalCode, place, addressLine, houseId,
                    longitude, latitude, radius, enforceUnique, inputData);
            try {
                List<BevQueryResult> results = queryResult.get();
                if (enforceUnique && results.size() == 1) {
                    if (!results.get(0).getFoundMatch())
                        throw new Exception("No unique result found.");
                }
                outputResults(separator, results);
            } catch (ExecutionException e) {
                throw e.getCause();
            }
        }
    } catch (ParseException exp) {
        System.out.println(exp.getMessage());
        System.out.println();
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar BevRestClient.jar", options, true);
        System.exit(-2);
    } catch (BevRestException e) {
        System.err.println(e.toString());
        System.exit(e.getErrorCode());
    } catch (JsonProcessingException e) {
        System.err.println(e.toString());
        System.exit(-3);
    } catch (IOException e) {
        System.err.println(e.toString());
        System.exit(-4);
    } catch (Throwable t) {
        System.err.println(t.toString());
        t.printStackTrace();
        System.exit(-1);
    } finally {
        if (csvWriter != null) {
            try {
                csvWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(-1);
            }
        }
        if (executor != null) {
            executor.dispose();
        }
    }
}

From source file:com.evolveum.midpoint.common.policy.PasswordPolicyUtils.java

/**
 * Check provided password against provided policy
 * //from   w  w w  .j ava 2s.  com
 * @param password
 *            - password to check
 * @param pp
 *            - Password policy used
 * @return - Operation result of this validation
 */
public static OperationResult validatePassword(String password, ValuePolicyType pp) {

    Validate.notNull(pp, "Password policy must not be null.");

    OperationResult ret = new OperationResult(OPERATION_PASSWORD_VALIDATION);
    ret.addParam("policyName", pp.getName());
    normalize(pp);

    if (password == null && pp.getMinOccurs() != null
            && XsdTypeMapper.multiplicityToInteger(pp.getMinOccurs()) == 0) {
        // No password is allowed
        ret.recordSuccess();
        return ret;
    }

    if (password == null) {
        password = "";
    }

    LimitationsType lims = pp.getStringPolicy().getLimitations();

    StringBuilder message = new StringBuilder();

    // Test minimal length
    if (lims.getMinLength() == null) {
        lims.setMinLength(0);
    }
    if (lims.getMinLength() > password.length()) {
        String msg = "Required minimal size (" + lims.getMinLength()
                + ") of password is not met (password length: " + password.length() + ")";
        ret.addSubresult(
                new OperationResult("Check global minimal length", OperationResultStatus.FATAL_ERROR, msg));
        message.append(msg);
        message.append("\n");
    }
    //      else {
    //         ret.addSubresult(new OperationResult("Check global minimal length. Minimal length of password OK.",
    //               OperationResultStatus.SUCCESS, "PASSED"));
    //      }

    // Test maximal length
    if (lims.getMaxLength() != null) {
        if (lims.getMaxLength() < password.length()) {
            String msg = "Required maximal size (" + lims.getMaxLength()
                    + ") of password was exceeded (password length: " + password.length() + ").";
            ret.addSubresult(
                    new OperationResult("Check global maximal length", OperationResultStatus.FATAL_ERROR, msg));
            message.append(msg);
            message.append("\n");
        }
        //         else {
        //            ret.addSubresult(new OperationResult("Check global maximal length. Maximal length of password OK.",
        //                  OperationResultStatus.SUCCESS, "PASSED"));
        //         }
    }
    // Test uniqueness criteria
    HashSet<String> tmp = new HashSet<String>(StringPolicyUtils.stringTokenizer(password));
    if (lims.getMinUniqueChars() != null) {
        if (lims.getMinUniqueChars() > tmp.size()) {
            String msg = "Required minimal count of unique characters (" + lims.getMinUniqueChars()
                    + ") in password are not met (unique characters in password " + tmp.size() + ")";
            ret.addSubresult(new OperationResult("Check minimal count of unique chars",
                    OperationResultStatus.FATAL_ERROR, msg));
            message.append(msg);
            message.append("\n");
        }
        //         else {
        //            ret.addSubresult(new OperationResult(
        //                  "Check minimal count of unique chars. Password satisfies minimal required unique characters.",
        //                  OperationResultStatus.SUCCESS, "PASSED"));
        //         }
    }

    // check limitation
    HashSet<String> allValidChars = new HashSet<String>(128);
    ArrayList<String> validChars = null;
    ArrayList<String> passwd = StringPolicyUtils.stringTokenizer(password);

    if (lims.getLimit() == null || lims.getLimit().isEmpty()) {
        if (message.toString() == null || message.toString().isEmpty()) {
            ret.computeStatus();
        } else {
            ret.computeStatus(message.toString());

        }

        return ret;
    }
    for (StringLimitType l : lims.getLimit()) {
        OperationResult limitResult = new OperationResult("Tested limitation: " + l.getDescription());
        if (null != l.getCharacterClass().getValue()) {
            validChars = StringPolicyUtils.stringTokenizer(l.getCharacterClass().getValue());
        } else {
            validChars = StringPolicyUtils.stringTokenizer(StringPolicyUtils.collectCharacterClass(
                    pp.getStringPolicy().getCharacterClass(), l.getCharacterClass().getRef()));
        }
        // memorize validChars
        allValidChars.addAll(validChars);

        // Count how many character for this limitation are there
        int count = 0;
        for (String s : passwd) {
            if (validChars.contains(s)) {
                count++;
            }
        }

        // Test minimal occurrence
        if (l.getMinOccurs() == null) {
            l.setMinOccurs(0);
        }
        if (l.getMinOccurs() > count) {
            String msg = "Required minimal occurrence (" + l.getMinOccurs() + ") of characters ("
                    + l.getDescription() + ") in password is not met (occurrence of characters in password "
                    + count + ").";
            limitResult.addSubresult(new OperationResult("Check minimal occurrence of characters",
                    OperationResultStatus.FATAL_ERROR, msg));
            message.append(msg);
            message.append("\n");
        }
        //         else {
        //            limitResult.addSubresult(new OperationResult("Check minimal occurrence of characters in password OK.",
        //                  OperationResultStatus.SUCCESS, "PASSED"));
        //         }

        // Test maximal occurrence
        if (l.getMaxOccurs() != null) {

            if (l.getMaxOccurs() < count) {
                String msg = "Required maximal occurrence (" + l.getMaxOccurs() + ") of characters ("
                        + l.getDescription()
                        + ") in password was exceeded (occurrence of characters in password " + count + ").";
                limitResult.addSubresult(new OperationResult("Check maximal occurrence of characters",
                        OperationResultStatus.FATAL_ERROR, msg));
                message.append(msg);
                message.append("\n");
            }
            //            else {
            //               limitResult.addSubresult(new OperationResult(
            //                     "Check maximal occurrence of characters in password OK.", OperationResultStatus.SUCCESS,
            //                     "PASSED"));
            //            }
        }
        // test if first character is valid
        if (l.isMustBeFirst() == null) {
            l.setMustBeFirst(false);
        }
        // we check mustBeFirst only for non-empty passwords
        if (StringUtils.isNotEmpty(password) && l.isMustBeFirst()
                && !validChars.contains(password.substring(0, 1))) {
            String msg = "First character is not from allowed set. Allowed set: " + validChars.toString();
            limitResult.addSubresult(
                    new OperationResult("Check valid first char", OperationResultStatus.FATAL_ERROR, msg));
            message.append(msg);
            message.append("\n");
        }
        //         else {
        //            limitResult.addSubresult(new OperationResult("Check valid first char in password OK.",
        //                  OperationResultStatus.SUCCESS, "PASSED"));
        //         }
        limitResult.computeStatus();
        ret.addSubresult(limitResult);
    }

    // Check if there is no invalid character
    StringBuilder sb = new StringBuilder();
    for (String s : passwd) {
        if (!allValidChars.contains(s)) {
            // memorize all invalid characters
            sb.append(s);
        }
    }
    if (sb.length() > 0) {
        String msg = "Characters [ " + sb + " ] are not allowed in password";
        ret.addSubresult(new OperationResult("Check if password does not contain invalid characters",
                OperationResultStatus.FATAL_ERROR, msg));
        message.append(msg);
        message.append("\n");
    }
    //      else {
    //         ret.addSubresult(new OperationResult("Check if password does not contain invalid characters OK.",
    //               OperationResultStatus.SUCCESS, "PASSED"));
    //      }

    if (message.toString() == null || message.toString().isEmpty()) {
        ret.computeStatus();
    } else {
        ret.computeStatus(message.toString());

    }

    return ret;
}

From source file:com.hichinaschool.flashcards.libanki.Card.java

public boolean isEmpty() {
    ArrayList<Integer> ords = mCol.getModels().availOrds(model(), Utils.joinFields(note().getFields()));
    if (ords.contains(mOrd)) {
        return true;
    }/*from  ww  w  . j a va2s. co  m*/
    return false;
}

From source file:de.fhg.fokus.odp.middleware.unittest.xTestCKANGateway.java

/**
 * Test the CKANDataset Constructor and getMap method.
 *//*from  w  w w  .  j  ava 2 s  .  c o m*/
@Test
@SuppressWarnings({ "unchecked" })
public void testCKANDatasetGetMap() {
    CKANDataset set = new CKANDataset();
    log.fine("########### DATASET CLASS TEST ###########");
    // System.out.println("state: " + state);

    set.setAuthor("123");
    set.setAuthorEmail("123@abc.de");
    // set.setComments(comments);
    set.setDateReleased("1.1.1");
    set.setDateUpdated("2.1.1");
    set.setGeographicalCoverage("von bis");
    set.setGeographicalGranularity("fein");

    set.setGroups(new ArrayList(Arrays.asList("group1", "group2", "group3")));

    set.setLicense("CC-BY");
    set.setMaintainer("abc");
    set.setMaintainerEmail("abc@123.de");
    set.setName("123");
    set.setNotes("dsfjlksjdfsd");

    set.setRatings(new ArrayList(Arrays.asList(new ArrayList(Arrays.asList("rating1", "user", "timestamp")))));
    set.setResources((new ArrayList(Arrays.asList(new ArrayList(Arrays.asList("res1", "user", "timestamp")),
            new ArrayList(Arrays.asList("res1", "user", "timestamp"))))));

    set.setState("active");

    set.setTags(new ArrayList(Arrays.asList("ich", "du", "er")));

    set.setTemporalCoverageFrom("jetz");
    set.setTemporalCoverageTo("gleich");
    set.setTemporalGranularity(2);
    set.setTitel("123");
    set.setUrl("www.123abc.de");
    set.setVersion("1.2");

    CKANDataset set2 = new CKANDataset(set.getMap());

    assertEquals(true, set2.getAuthor().equals("123"));
    ArrayList<String> tmp = (ArrayList<String>) set2.getResources().get(0);
    assertEquals(true, tmp.contains("res1"));
    log.fine("set2: " + set2.getTags().size());
}

From source file:com.sourcesense.alfresco.opensso.AlfrescoOpenSSOFilterTest.java

@Test
public void shouldSynchronizeGroups() throws Exception {
    ArrayList<String> groups = new ArrayList<String>();
    groups.add("group1");

    alfrescoFilter.setOpenSSOClient(new MockOpenSSOClient(USERNAME, groups));

    authenticate();//from   w  w  w. jav  a2 s .co m

    doRequest(ALFRESCO_URL);

    HttpTester response = doRequest(ALFRESCO_URL);

    ArrayList<String> currentGroups = alfrescoFilter.getAlfrescoFacade().getUserGroups("user1");

    assertEquals(HTTP_CODE_OK, response.getStatus());
    assertEquals(1, currentGroups.size());
    assertTrue(groups.contains("group1"));
    assertTrue(!groups.contains("marketing"));
}

From source file:edu.uci.ics.hyracks.algebricks.core.algebra.operators.logical.visitors.SchemaVariableVisitor.java

@Override
public Void visitExternalDataLookupOperator(ExternalDataLookupOperator op, Void arg)
        throws AlgebricksException {
    ArrayList<LogicalVariable> liveVariables = new ArrayList<LogicalVariable>();
    ArrayList<LogicalVariable> usedVariables = new ArrayList<LogicalVariable>();
    //get used variables
    op.getExpressionRef().getValue().getUsedVariables(usedVariables);
    //live variables - used variables
    for (Mutable<ILogicalOperator> c : op.getInputs()) {
        VariableUtilities.getLiveVariables(c.getValue(), liveVariables);
    }//www  . j  av a2s. com
    for (LogicalVariable v : liveVariables) {
        if (!usedVariables.contains(v)) {
            schemaVariables.add(v);
        }
    }
    VariableUtilities.getProducedVariables(op, schemaVariables);
    //+ produced variables
    return null;
}

From source file:at.tuwien.ifs.somtoolbox.apps.helper.DataMapper.java

/**
 * @see GrowingLayer#mapCompleteDataAfterTraining
 *///from   w ww .  j ava2 s .  c  o  m
// FIXME: this is just a copy of GrowingLayer#mapCompleteDataAfterTraining, would be good to have some code
// re-used..
// FIXME: this would also profit from multi-threading...
private void mapCompleteDataAfterTraining(GrowingSOM som, InputData data, SOMLibClassInformation classInfo,
        ArrayList<String> mappingExceptions, String labelerName, int numLabels) {
    Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Start mapping data.");
    InputDatum datum = null;
    Unit winner = null;
    int numVectors = data.numVectors();

    int skippedInstances = 0;
    for (int i = 0; i < data.numVectors(); i++) {
        try {
            InputDatum currentInput = data.getInputDatum(i);
            String inpLabel = currentInput.getLabel();
            if (classInfo != null && mappingExceptions.contains(classInfo.getClassName(inpLabel))) {
                skippedInstances++;
            }
        } catch (SOMLibFileFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    if (mappingExceptions.size() > 0) {
        Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Skipping classes: " + mappingExceptions
                + ", containing a total of " + skippedInstances + " inputs.");
    }

    StdErrProgressWriter progressWriter = new StdErrProgressWriter(numVectors - skippedInstances,
            "Mapping datum ", 50);
    L2Metric metric = new L2Metric();
    for (int i = 0; i < numVectors; i++) {
        datum = data.getInputDatum(i);

        String inpLabel = datum.getLabel();
        try {
            if (classInfo != null && mappingExceptions.contains(classInfo.getClassName(inpLabel))) {
                continue; // Skips this mapping step
            } else {
                winner = som.getLayer().getWinner(datum, metric);
                winner.addMappedInput(datum, false); // TODO: think about recursion
                progressWriter.progress();
            }
        } catch (SOMLibFileFormatException e) {
            // TODO Auto-generated catch block
            Logger.getLogger("at.tuwien.ifs.somtoolbox").info("This should never happen");
            e.printStackTrace();
        }
    }
    Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Finished mapping data.");
    som.getLayer().calculateQuantizationErrorForUnits();
    som.getLayer().clearLabels();

    Labeler labeler = null;

    if (labelerName != null) { // if labeling then label
        try {
            labeler = AbstractLabeler.instantiate(labelerName);
            Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Instantiated labeler " + labelerName);
        } catch (Exception e) {
            Logger.getLogger("at.tuwien.ifs.somtoolbox")
                    .severe("Could not instantiate labeler \"" + labelerName + "\".");
            System.exit(-1);
        }
    }

    if (labelerName != null) { // if labeling then label
        labeler.label(som, data, numLabels);
    }
}

From source file:edu.isi.karma.view.VWorksheet.java

public void updateHeaderViewNodes(ArrayList<VHNode> oldOrderedNodes) {

    ArrayList<String> oldPaths = new ArrayList<>();
    for (VHNode node : oldOrderedNodes)
        oldPaths.addAll(node.getAllPaths());

    ArrayList<String> newPaths = new ArrayList<>();
    for (VHNode node : this.headerViewNodes)
        newPaths.addAll(node.getAllPaths());

    //1/. Get all paths in old that are not in new
    ArrayList<String> pathsToDel = new ArrayList<>();
    for (String oldPath : oldPaths) {
        if (!newPaths.contains(oldPath)) {
            pathsToDel.add(oldPath);/*from w  w w.j  a v a2s . co m*/
        }
    }

    //2. Get all paths in new that are not in old
    ArrayList<String> pathsToAdd = new ArrayList<>();
    for (int i = 0; i < newPaths.size(); i++) {
        String newPath = newPaths.get(i);
        if (!oldPaths.contains(newPath)) {
            if (i != 0) {
                String after = newPaths.get(i - 1);
                int difference = StringUtils.countMatches(after, "/") - StringUtils.countMatches(newPath, "/");
                for (int k = 0; k < difference; k++) {
                    after = after.substring(0, after.lastIndexOf("/"));
                }
                pathsToAdd.add(newPath + "$$" + after);
            } else {
                pathsToAdd.add(newPath + "$$" + "null");
            }
        }
    }

    ArrayList<VHNode> allNodes = new ArrayList<>();
    allNodes.addAll(oldOrderedNodes);
    this.headerViewNodes = allNodes;

    for (String path : pathsToDel) {
        deleteHeaderViewPath(this.headerViewNodes, path);
    }

    for (String path : pathsToAdd) {
        addHeaderViewPath(path);
    }
}

From source file:com.darkenedsky.reddit.traders.RedditTraders.java

/**
 * Check if a user is banned//from  ww  w. ja  v a2  s.  c om
 * 
 * @param redditor
 *            redditor
 * @param redditor2
 *            another redditor to check in the same call (for efficiency)
 * @param subreddit
 *            subreddit name
 * @return true if the user is banned from the subreddit.
 */
public boolean isBanned(String redditor, String redditor2, String subreddit) throws Exception {

    Subreddit sub = new Subreddit();
    sub.setDisplayName(subreddit);
    List<String> mods = sub.getBannedUsers(config.getBotUser());
    ArrayList<String> lcmods = new ArrayList<String>();
    for (String m : mods) {
        lcmods.add(m.toLowerCase());
    }
    return lcmods.contains(redditor.toLowerCase()) || lcmods.contains(redditor2.toLowerCase());
}