Example usage for java.util BitSet set

List of usage examples for java.util BitSet set

Introduction

In this page you can find the example usage for java.util BitSet set.

Prototype

public void set(int bitIndex) 

Source Link

Document

Sets the bit at the specified index to true .

Usage

From source file:org.openecomp.sdnc.sli.aai.AAIRequest.java

protected String getRequestPath() throws MalformedURLException {
    Set<String> uniqueResources = extractUniqueResourceSetFromKeys(requestProperties.stringPropertyNames());
    BitSet bitset = new BitSet();
    for (String key : uniqueResources) {
        if (tagValues.containsKey(key)) {
            Object tmpValue = tagValues.get(key);
            if (tmpValue != null) {
                String value = tmpValue.toString();
                int bitIndex = Integer.parseInt(value);
                bitset.set(bitIndex);
            }//w ww  . j  a  v a2s  .  c  o  m
        }
    }

    String path = bitsetPaths.get(bitset);
    if (path == null) {
        throw new MalformedURLException(
                "PATH not found for key string containing valies :" + requestProperties.toString());
    }
    return path;
}

From source file:mastodon.algorithms.MHLinearAlgorithm.java

protected void tryPruning() {
    //choose the number of species in list to perturb based on a Poisson distributions with rate equal to variable "mean" above
    int numberToSet = 0;
    int numberToClear = 0;

    while (numberToSet < 1 || numberToSet > currPrunedSpeciesCount) {
        numberToSet = pd.sample() + 1;//from   ww  w  .j  a  v  a2 s.c  om
    }

    if (numberToSet > (bts.getTaxaCount() - currPrunedSpeciesCount)) {
        numberToSet = bts.getTaxaCount() - currPrunedSpeciesCount;
    }

    //if we are pruning by one more species now, clear one species less from the pruning list this time
    if (currPruning.cardinality() < currPrunedSpeciesCount) {
        numberToClear = numberToSet - 1;
    } else {
        numberToClear = numberToSet;
    }

    BitSet bitsToSet = new BitSet();
    BitSet bitsToClear = new BitSet();

    for (int e = 0; e < numberToSet; e++) {
        int choice = 0;
        while (true) {
            choice = (int) (Random.nextDouble() * bts.getTaxaCount());
            if (!currPruning.get(choice) && !bitsToSet.get(choice)) {
                break;
            }
        }
        bitsToSet.set(choice);
    }

    for (int e = 0; e < numberToClear; e++) {
        int choice = 0;
        while (true) {
            choice = (int) (Random.nextDouble() * bts.getTaxaCount());
            if (currPruning.get(choice) && !bitsToClear.get(choice)) {
                break;
            }
        }
        bitsToClear.set(choice);
    }

    currPruning.or(bitsToSet);
    currPruning.xor(bitsToClear);

    currScore = bts.pruneFast(currPruning);
    bts.unPrune();

}

From source file:com.netspective.commons.acl.AccessControlListTest.java

public void testAuthenticatedUsersPermissionErrors()
        throws DataModelException, InvocationTargetException, InstantiationException, NoSuchMethodException,
        IllegalAccessException, IOException, PermissionNotFoundException, RoleNotFoundException {
    AccessControlListsComponent aclc = (AccessControlListsComponent) XdmComponentFactory.get(
            AccessControlListsComponent.class, new Resource(AccessControlListTest.class, RESOURCE_NAME_THREE),
            XdmComponentFactory.XDMCOMPFLAGS_DEFAULT);

    // Verify _something_ was loaded...
    assertNotNull(aclc);// w  w w . j  a v a2 s.c  o  m

    AccessControlListsManager aclm = aclc.getItems();
    assertNotNull(aclm);

    AccessControlList defaultAcl = aclc.getItems().getDefaultAccessControlList();
    assertNotNull(defaultAcl);

    // Independently created User...
    ValueContext vcTwo = ValueSources.getInstance().createDefaultValueContext();
    MutableAuthenticatedUser userTwo = new BasicAuthenticatedUser();
    userTwo.setUserId("admin");
    userTwo.setUserName("Administrator");

    // Experiment with AuthenticatedUsers and Roles/Permissions
    assertNull(userTwo.getUserRoleNames());

    boolean exceptionThrown = true;

    try {
        userTwo.setRoles(aclm, new String[] { "/acl/role/invalid-user" });
        exceptionThrown = false;
    } catch (RoleNotFoundException e) {
        assertTrue(exceptionThrown);
    }

    assertTrue(exceptionThrown);

    try {
        userTwo.setPermissions(aclm, new String[] { "/acl/app/orders/invalidate_order" });
        exceptionThrown = false;
    } catch (PermissionNotFoundException e) {
        assertTrue(exceptionThrown);
    }

    assertTrue(exceptionThrown);

    // Verify proper behavior upon setting null roles or permissions
    userTwo.setRoles(aclm, null);
    assertNull(userTwo.getUserRoleNames());
    assertNull(userTwo.getUserPermissions());

    userTwo.setPermissions(aclm, null);
    assertNull(userTwo.getUserPermissions());

    String[] userTwoRoles = { "/acl/role/normal-user" };
    userTwo.setRoles(aclm, userTwoRoles);
    assertEquals(userTwoRoles, userTwo.getUserRoleNames());

    Role normalUser = defaultAcl.getRole("/acl/role/normal-user");
    //      BitSet aclNormalUserPermissionSet = normalUser.getChildPermissions();
    BitSet aclNormalUserPermissionSet = new BitSet(defaultAcl.getHighestPermissionId());
    aclNormalUserPermissionSet.set(1);
    aclNormalUserPermissionSet.set(2);
    aclNormalUserPermissionSet.set(3);
    aclNormalUserPermissionSet.set(4);
    aclNormalUserPermissionSet.set(5);

    assertEquals(aclNormalUserPermissionSet, normalUser.getPermissions());

    assertEquals(normalUser.getPermissions(), userTwo.getUserPermissions());
    assertEquals(aclNormalUserPermissionSet, userTwo.getUserPermissions());

    userTwo.setRoles(aclm, userTwoRoles);
    assertTrue(userTwo.hasAnyPermission(aclm, new String[] { "/acl/app/orders/create_order",
            "/acl/app/orders/view_order", "/acl/app/orders/edit_order" }));
    assertTrue(userTwo.hasAnyPermission(aclm, new String[] { "/acl/app/orders/delete_order",
            "/acl/app/orders/view_order", "/acl/app/orders/edit_order" }));
    assertFalse(userTwo.hasPermission(aclm, "/acl/app/orders/delete_order"));
    assertFalse(userTwo.hasAnyPermission(aclm, new String[] { "/acl/app/orders/delete_order" }));

    try {
        userTwo.hasAnyPermission(aclm,
                new String[] { "/acl/app/orders/invalidate_order", "/acl/app/orders/misplace_order" });
        exceptionThrown = false;
    } catch (PermissionNotFoundException e) {
        assertTrue(exceptionThrown);
    }

    assertTrue(exceptionThrown);

    try {
        userTwo.hasPermission(aclm, "/acl/app/orders/invalidate_order");
        exceptionThrown = false;
    } catch (PermissionNotFoundException e) {
        assertTrue(exceptionThrown);
    }

    assertTrue(exceptionThrown);

    assertTrue(userTwo.hasPermission(aclm, "/acl/app/orders/view_order"));
}

From source file:ca.oson.json.gson.functional.DefaultTypeAdaptersTest.java

public void testBitSetSerialization() throws Exception {
    //Gson gson = new Gson();
    BitSet bits = new BitSet();
    bits.set(1);
    bits.set(3, 6);//from   w ww.j a v a2s. co m
    bits.set(9);
    String json = oson.toJson(bits);
    assertEquals("[0,1,0,1,1,1,0,0,0,1]", json);
}

From source file:com.netspective.commons.acl.AccessControlListTest.java

/**
 * This test makes sure that an ACL is read properly from a file containing multiple <access-control-list>
 * tags with one having the default name of "acl" and the rest having other names.
 *///from   www  . j  a va  2  s  .  co m
public void testMultipleACLWithDefaultDataModelSchemaImportFromXmlValid() throws RoleNotFoundException,
        PermissionNotFoundException, DataModelException, InvocationTargetException, NoSuchMethodException,
        InstantiationException, IllegalAccessException, IOException {
    AccessControlListsComponent aclc = (AccessControlListsComponent) XdmComponentFactory.get(
            AccessControlListsComponent.class, new Resource(AccessControlListTest.class, RESOURCE_NAME_THREE),
            XdmComponentFactory.XDMCOMPFLAGS_DEFAULT);

    // Verify _something_ was loaded...
    assertNotNull(aclc);

    // Verify exactly _one_ ACL was loaded...
    AccessControlListsManager aclm = aclc.getItems();
    assertNotNull("Expected: AccessControlListsManager object, Found: null", aclm);
    AccessControlLists acls = aclm.getAccessControlLists();
    Integer expectedNumACLs = new Integer(3);
    assertNotNull("Expected: AccessControlLists object, Found: null", acls);
    assertEquals("Expected: " + expectedNumACLs + " ACLs, Found: " + acls.size(), expectedNumACLs.intValue(),
            acls.size());

    // Verify basic statistics about the ACLS object
    assertEquals(17, acls.getHighestPermissionId());
    assertEquals(8, acls.getHighestRoleId());

    assertEquals(17, acls.getNextPermissionId());
    assertEquals(8, acls.getNextRoleId());

    assertEquals(17, acls.permissionsCount());
    assertEquals(8, acls.rolesCount());

    // Verify the defaultAcl and the acl named "acl" are the same
    AccessControlList defaultAcl = aclm.getDefaultAccessControlList();
    AccessControlList aclAcl = aclm.getAccessControlList(AccessControlList.ACLNAME_DEFAULT);
    AccessControlList aclTwoAcl = aclm.getAccessControlList(AccessControlList.ACLNAME_DEFAULT + "_two");
    AccessControlList aclThreeAcl = aclm.getAccessControlList(AccessControlList.ACLNAME_DEFAULT + "_three");
    assertNotNull("Expected: Non-Null ACL named " + AccessControlList.ACLNAME_DEFAULT + ", Found: null",
            defaultAcl);
    assertNotNull("Expected: Non-Null ACL named " + AccessControlList.ACLNAME_DEFAULT + ", Found: null",
            aclAcl);
    assertNotNull("Expected: Non-Null ACL named " + AccessControlList.ACLNAME_DEFAULT + "_two, Found: null",
            aclTwoAcl);
    assertNotNull("Expected: Non-Null ACL named " + AccessControlList.ACLNAME_DEFAULT + "_three, Found: null",
            aclThreeAcl);
    assertEquals("Expected: ACL with name 'acl', Found: ACL with name " + defaultAcl.getName(), aclAcl,
            defaultAcl);
    assertEquals("Expected: ACL with name 'acl', Found: ACL with name " + aclAcl.getName(),
            AccessControlList.ACLNAME_DEFAULT, aclAcl.getName());
    assertEquals("Expected: ACL with name 'acl_two', Found: ACL with name " + aclTwoAcl.getName(),
            AccessControlList.ACLNAME_DEFAULT + "_two", aclTwoAcl.getName());
    assertEquals("Expected: ACL with name 'acl_three', Found: ACL with name " + aclThreeAcl.getName(),
            AccessControlList.ACLNAME_DEFAULT + "_three", aclThreeAcl.getName());

    // Verify the number of permissions loaded for each ACL
    Map aclAclPermissions = aclAcl.getPermissionsByName();
    Map aclTwoAclPermissions = aclTwoAcl.getPermissionsByName();
    Map aclThreeAclPermissions = aclThreeAcl.getPermissionsByName();
    assertEquals("Expected: Total permissions = 7, Found: Total permissions = " + aclAclPermissions.size(), 7,
            aclAclPermissions.size());
    assertEquals("Expected: Total permissions = 5, Found: Total permissions = " + aclTwoAclPermissions.size(),
            5, aclTwoAclPermissions.size());
    assertEquals("Expected: Total permissions = 5, Found: Total permissions = " + aclThreeAclPermissions.size(),
            5, aclThreeAclPermissions.size());

    // Verify the number of roles loaded for each ACL
    Map aclAclRoles = aclAcl.getRolesByName();
    Map aclTwoAclRoles = aclTwoAcl.getRolesByName();
    Map aclThreeAclRoles = aclThreeAcl.getRolesByName();
    assertEquals(3, aclAclRoles.size());
    assertEquals(3, aclTwoAclRoles.size());
    assertEquals(2, aclThreeAclRoles.size());

    // Verify the index of the /acl/role/normal-user permission is 10
    Role aclNormalUser = aclAcl.getRole("/acl/role/normal-user");
    Role aclTwoNormalUser = aclTwoAcl.getRole("/acl_two/role/normal-user");
    Role aclThreeReadOnlyUser = aclThreeAcl.getRole("/acl_three/role/read-only-user");
    assertEquals("Expected: Id for /acl/role/normal-user = 2, Found: " + aclNormalUser.getId(), 2,
            aclNormalUser.getId());
    assertEquals("Expected: Id for /acl_two/role/normal-user = 5, Found: " + aclTwoNormalUser.getId(), 5,
            aclTwoNormalUser.getId());
    assertEquals("Expected: Id for /acl_three/role/read-only-user = 7, Found: " + aclThreeReadOnlyUser.getId(),
            7, aclThreeReadOnlyUser.getId());

    //TODO: Fix Role so that the bit corresponding to the role's Id is not set in the role's permissions BitSet

    // Verify the set of permissions for /acl/role/normal-user are exactly what we expect
    BitSet aclNormalUserPermissionSet = aclNormalUser.getPermissions();
    BitSet aclExpectedPermissionSet = new BitSet(aclAcl.getHighestPermissionId());
    aclExpectedPermissionSet.set(1);
    aclExpectedPermissionSet.set(2);
    aclExpectedPermissionSet.set(3);
    aclExpectedPermissionSet.set(4);
    aclExpectedPermissionSet.set(5);
    //TODO: Fix this after Role's have been fixed
    //      assertEquals("Expected: Permissions for /acl/role/normal-user = " + aclExpectedPermissionSet + ", Found: " + aclNormalUserPermissionSet, aclExpectedPermissionSet, aclNormalUserPermissionSet);

    // Verify the set of permissions for /acl_two/role/normal-user are exactly what we expect
    BitSet aclTwoNormalUserPermissionSet = aclTwoNormalUser.getPermissions();
    BitSet aclTwoExpectedPermissionSet = new BitSet(aclTwoAcl.getHighestPermissionId());
    aclTwoExpectedPermissionSet.set(8);
    aclTwoExpectedPermissionSet.set(9);
    aclTwoExpectedPermissionSet.set(10);
    aclTwoExpectedPermissionSet.set(11);
    //TODO: Fix this after Role's have been fixed
    //      System.out.println("\n/acl_two/role/normal-user(" + aclTwoNormalUser.getId() + "): " + aclTwoNormalUserPermissionSet + "\n");
    //      assertEquals("Expected: Permissions for /acl_two/role/normal-user = " + aclTwoExpectedPermissionSet + ", Found: " + aclTwoNormalUserPermissionSet, aclTwoExpectedPermissionSet, aclTwoNormalUserPermissionSet);

    // Verify the set of permissions for /acl_three/role/read-only-user are exactly what we expect
    BitSet aclThreeReadOnlyUserPermissionSet = aclThreeReadOnlyUser.getPermissions();
    BitSet aclThreeExpectedPermissionSet = new BitSet(aclThreeAcl.getHighestPermissionId());
    aclThreeExpectedPermissionSet.set(12);
    aclThreeExpectedPermissionSet.set(13);
    aclThreeExpectedPermissionSet.set(15);
    //TODO: Fix this after Roles have been fixed
    //      assertEquals("Expected: Permissions for /acl_three/role/read-only-user = " + aclThreeExpectedPermissionSet + ", Found: " + aclThreeReadOnlyUserPermissionSet, aclThreeExpectedPermissionSet, aclThreeReadOnlyUserPermissionSet);

    aclc.printErrorsAndWarnings();
}

From source file:ca.oson.json.gson.functional.DefaultTypeAdaptersTest.java

public void testBitSetDeserialization() throws Exception {
    BitSet expected = new BitSet();
    expected.set(0);
    expected.set(2, 6);//from w w w  .j a  va2s .  c  o  m
    expected.set(8);

    String json = oson.toJson(expected);
    assertEquals(expected, oson.fromJson(json, BitSet.class));

    json = "[1,0,1,1,1,1,0,0,1,0,0,0]";
    assertEquals(expected, oson.fromJson(json, BitSet.class));

    json = "[\"1\",\"0\",\"1\",\"1\",\"1\",\"1\",\"0\",\"0\",\"1\"]";
    assertEquals(expected, oson.fromJson(json, BitSet.class));

    json = "[true,false,true,true,true,true,false,false,true,false,false]";
    assertEquals(expected, oson.fromJson(json, BitSet.class));
}

From source file:org.apache.mahout.benchmark.VectorBenchmarks.java

private void setUpVectors(int cardinality, int numNonZeros, int numVectors) {
    for (int i = 0; i < numVectors; i++) {
        Vector v = new SequentialAccessSparseVector(cardinality, numNonZeros); // sparsity!
        BitSet featureSpace = new BitSet(cardinality);
        int[] indexes = new int[numNonZeros];
        double[] values = new double[numNonZeros];
        int j = 0;
        while (j < numNonZeros) {
            double value = r.nextGaussian();
            int index = r.nextInt(cardinality);
            if (!featureSpace.get(index) && value != 0) {
                featureSpace.set(index);
                indexes[j] = index;//  w  w  w .  j  av  a2s . co m
                values[j++] = value;
                v.set(index, value);
            }
        }
        randomVectorIndices.add(indexes);
        randomVectorValues.add(values);
        randomVectors.add(v);
    }
}

From source file:edu.uci.ics.hyracks.algebricks.rewriter.rules.ExtractCommonOperatorsRule.java

private void computeClusters(Mutable<ILogicalOperator> parentRef, Mutable<ILogicalOperator> opRef,
        MutableInt currentClusterId) {/*from w w w. ja  va2  s  .  c om*/
    // only replicate operator has multiple outputs
    int outputIndex = 0;
    if (opRef.getValue().getOperatorTag() == LogicalOperatorTag.REPLICATE) {
        ReplicateOperator rop = (ReplicateOperator) opRef.getValue();
        List<Mutable<ILogicalOperator>> outputs = rop.getOutputs();
        for (outputIndex = 0; outputIndex < outputs.size(); outputIndex++) {
            if (outputs.get(outputIndex).equals(parentRef)) {
                break;
            }
        }
    }
    AbstractLogicalOperator aop = (AbstractLogicalOperator) opRef.getValue();
    Pair<int[], int[]> labels = aop.getPhysicalOperator().getInputOutputDependencyLabels(opRef.getValue());
    List<Mutable<ILogicalOperator>> inputs = opRef.getValue().getInputs();
    for (int i = 0; i < inputs.size(); i++) {
        Mutable<ILogicalOperator> inputRef = inputs.get(i);
        if (labels.second[outputIndex] == 1 && labels.first[i] == 0) { // 1 -> 0
            if (labels.second.length == 1) {
                clusterMap.put(opRef, currentClusterId);
                // start a new cluster
                MutableInt newClusterId = new MutableInt(++lastUsedClusterId);
                computeClusters(opRef, inputRef, newClusterId);
                BitSet waitForList = clusterWaitForMap.get(currentClusterId.getValue());
                if (waitForList == null) {
                    waitForList = new BitSet();
                    clusterWaitForMap.put(currentClusterId.getValue(), waitForList);
                }
                waitForList.set(newClusterId.getValue());
            }
        } else { // 0 -> 0 and 1 -> 1
            MutableInt prevClusterId = clusterMap.get(opRef);
            if (prevClusterId == null || prevClusterId.getValue().equals(currentClusterId.getValue())) {
                clusterMap.put(opRef, currentClusterId);
                computeClusters(opRef, inputRef, currentClusterId);
            } else {
                // merge prevClusterId and currentClusterId: update all the map entries that has currentClusterId to prevClusterId
                for (BitSet bs : clusterWaitForMap.values()) {
                    if (bs.get(currentClusterId.getValue())) {
                        bs.clear(currentClusterId.getValue());
                        bs.set(prevClusterId.getValue());
                    }
                }
                currentClusterId.setValue(prevClusterId.getValue());
            }
        }
    }
}

From source file:org.apache.hadoop.mapred.TestSequenceFileInputFormat.java

public void testFormat() throws Exception {
    JobConf job = new JobConf(conf);
    FileSystem fs = FileSystem.getLocal(conf);
    Path dir = new Path(System.getProperty("test.build.data", ".") + "/mapred");
    Path file = new Path(dir, "test.seq");

    Reporter reporter = Reporter.NULL;//from   ww  w .j  a  va2s .c  om

    int seed = new Random().nextInt();
    //LOG.info("seed = "+seed);
    Random random = new Random(seed);

    fs.delete(dir, true);

    FileInputFormat.setInputPaths(job, dir);

    // for a variety of lengths
    for (int length = 0; length < MAX_LENGTH; length += random.nextInt(MAX_LENGTH / 10) + 1) {

        //LOG.info("creating; entries = " + length);

        // create a file with length entries
        SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, file, IntWritable.class,
                BytesWritable.class);
        try {
            for (int i = 0; i < length; i++) {
                IntWritable key = new IntWritable(i);
                byte[] data = new byte[random.nextInt(10)];
                random.nextBytes(data);
                BytesWritable value = new BytesWritable(data);
                writer.append(key, value);
            }
        } finally {
            writer.close();
        }

        // try splitting the file in a variety of sizes
        InputFormat<IntWritable, BytesWritable> format = new SequenceFileInputFormat<IntWritable, BytesWritable>();
        IntWritable key = new IntWritable();
        BytesWritable value = new BytesWritable();
        for (int i = 0; i < 3; i++) {
            int numSplits = random.nextInt(MAX_LENGTH / (SequenceFile.SYNC_INTERVAL / 20)) + 1;
            //LOG.info("splitting: requesting = " + numSplits);
            InputSplit[] splits = format.getSplits(job, numSplits);
            //LOG.info("splitting: got =        " + splits.length);

            // check each split
            BitSet bits = new BitSet(length);
            for (int j = 0; j < splits.length; j++) {
                RecordReader<IntWritable, BytesWritable> reader = format.getRecordReader(splits[j], job,
                        reporter);
                try {
                    int count = 0;
                    while (reader.next(key, value)) {
                        // if (bits.get(key.get())) {
                        // LOG.info("splits["+j+"]="+splits[j]+" : " + key.get());
                        // LOG.info("@"+reader.getPos());
                        // }
                        assertFalse("Key in multiple partitions.", bits.get(key.get()));
                        bits.set(key.get());
                        count++;
                    }
                    //LOG.info("splits["+j+"]="+splits[j]+" count=" + count);
                } finally {
                    reader.close();
                }
            }
            assertEquals("Some keys in no partition.", length, bits.cardinality());
        }

    }
}

From source file:org.lockss.plugin.base.TestDefaultUrlCacher.java

void setSuppressValidation(UrlCacher uc) {
    BitSet fetchFlags = new BitSet();
    fetchFlags.set(UrlCacher.SUPPRESS_CONTENT_VALIDATION);
    uc.setFetchFlags(fetchFlags);/*from  w w w. ja va2  s.c  om*/
}