Example usage for java.util BitSet get

List of usage examples for java.util BitSet get

Introduction

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

Prototype

public boolean get(int bitIndex) 

Source Link

Document

Returns the value of the bit with the specified index.

Usage

From source file:org.wso2.andes.subscription.ClusterSubscriptionBitMapHandler.java

/**
 * Removing a subscription from the structure.
 *
 * @param subscription The subscription to remove
 *///from   ww w .  j av  a2  s .  c  om
@Override
public void removeWildCardSubscription(AndesSubscription subscription) {
    int subscriptionIndex = wildCardSubscriptionList.indexOf(subscription);

    if (subscriptionIndex > -1) {
        for (Map<String, BitSet> constituentTable : constituentTables) {
            for (Map.Entry<String, BitSet> constituentRow : constituentTable.entrySet()) {
                // For every row create a new BitSet with the values for the removed subscription removed
                String constituent = constituentRow.getKey();
                BitSet bitSet = constituentRow.getValue();
                BitSet newBitSet = new BitSet();

                int bitIndex = 0;

                for (int i = 0; i < bitSet.size(); i++) {
                    if (bitIndex == i) {
                        // If the this is the index to remove then skip this round
                        bitIndex++;
                    }
                    newBitSet.set(i, bitSet.get(bitIndex));
                    bitIndex++;
                }

                constituentTable.put(constituent, newBitSet);

            }
        }

        // Remove the subscription from subscription list
        wildCardSubscriptionList.remove(subscriptionIndex);
    } else {
        log.warn("Subscription for destination : " + subscription.getSubscribedDestination()
                + " is not found to " + "remove");
    }
}

From source file:org.lockss.util.NumberUtil.java

/**
 * Construct an alphabetical (base-26) sequence by incrementing the first
 * string alphabetically until it reaches the second string. The start string
 * is incremented by the given delta; if the delta does not divide into the
 * Levenstein distance between the start and end strings, an exception is
 * thrown. The strings must also be the same length.
 * <p>/*from ww w .  j a  va 2 s  . c o  m*/
 * The string is lower cased before the increment is applied, and then each
 * character position that was upper case in the original string is upper
 * cased in the resulting string. It is assumed that the two strings are
 * capitalised in the same pattern. An exception will be thrown if any
 * character is outside of a-z after lower casing.
 *
 * @param start an alphabetical string (case-insensitive)
 * @param end an alphabetical string (case-insensitive)
 * @param delta the increment between strings in the sequence; can be negative
 * @return a list of strings representing a sequence from <tt>start</tt> to <tt>end</tt>
 * @throws IllegalArgumentException if the delta does not divide into the gap or the strings are different lengths
 */
public static List<String> constructAlphabeticSequence(final String start, final String end, int delta)
        throws IllegalArgumentException {

    // Ensure the delta is positive
    if (delta == 0)
        throw new IllegalArgumentException("Delta cannot be 0.");

    // If the strings are equal, the sequence will be the single string
    if (start.equals(end))
        return new ArrayList<String>() {
            {
                add(start);
            }
        };

    // Check the string lengths are the same
    if (start.length() != end.length())
        throw new IllegalArgumentException(
                String.format("Start and end strings are different lengths: %s %s.", start, end));

    // Find the integer distance
    int distance = Math.abs(fromBase26(start) - fromBase26(end));
    //int distance = StringUtils.getLevenshteinDistance(start, end);
    // Check the delta divides into the gap
    if (distance % delta != 0) {
        throw new IllegalArgumentException(String.format(
                "The distance %s between start and end must be " + "divisible by delta %s.", distance, delta));
    }

    // Track the case of each character, so we can reset them before returning
    BitSet cases = new BitSet(start.length());
    for (int i = 0; i < start.length(); i++) {
        cases.set(i, Character.isUpperCase(start.charAt(i)));
    }

    // Increment alphabetically
    List<String> seq = new ArrayList<String>();
    int[] nums = constructSequence(fromBase26(start), fromBase26(end), delta);
    for (int i = 0; i < nums.length; i++) {
        String s = toBase26(nums[i]);
        // Pad the string to the correct length with 'a'
        s = StringUtils.leftPad(s, start.length(), 'a');
        // Re-case the chars
        char[] carr = s.toCharArray();
        for (int pos = 0; pos < cases.length(); pos++) {
            if (cases.get(pos))
                carr[pos] = Character.toUpperCase(carr[pos]);
        }
        seq.add(new String(carr));
    }
    return seq;
}

From source file:net.bioclipse.ds.sdk.pdewizard.DSTemplate.java

/**
 * This method duplicates the encoding in the CDKFingerPrintPropertyCalculator. 
 * This is required to read it back into 1024 bits.
 * @param value// w  w  w  .  j av a  2  s. co  m
 * @return
 */
public String encodeFPBase64(Object value) {
    if (value instanceof String)
        return (String) value;
    BitSet val = (BitSet) value;
    byte[] bytes = new byte[val.length() / 8 + 1];
    for (int i = 0; i < val.length(); i++) {
        if (val.get(i)) {
            bytes[bytes.length - i / 8 - 1] |= 1 << (i % 8);
        }
    }
    return new String(new Base64().encode(bytes));
}

From source file:org.apache.hadoop.mapred.TestSequenceFileAsTextInputFormat.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;/*ww  w.jav a  2  s.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,
                LongWritable.class);
        try {
            for (int i = 0; i < length; i++) {
                IntWritable key = new IntWritable(i);
                LongWritable value = new LongWritable(10 * i);
                writer.append(key, value);
            }
        } finally {
            writer.close();
        }

        // try splitting the file in a variety of sizes
        InputFormat<Text, Text> format = new SequenceFileAsTextInputFormat();

        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<Text, Text> reader = format.getRecordReader(splits[j], job, reporter);
                Class readerClass = reader.getClass();
                assertEquals("reader class is SequenceFileAsTextRecordReader.",
                        SequenceFileAsTextRecordReader.class, readerClass);
                Text value = reader.createValue();
                Text key = reader.createKey();
                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());
                        // }
                        int keyInt = Integer.parseInt(key.toString());
                        assertFalse("Key in multiple partitions.", bits.get(keyInt));
                        bits.set(keyInt);
                        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.wso2.carbon.user.core.authorization.PermissionTree.java

void getUIResourcesForRoles(String[] roles, List<String> resources, String path, TreeNode.Permission permission,
        TreeNode node) {//  w w  w  .  ja v  a  2s. co  m
    read.lock();
    try {
        String currentPath = path + "/" + node.getName();

        Map<String, BitSet> bsAllowed = node.getRoleAllowPermissions();
        for (String role : roles) {
            BitSet bs = bsAllowed.get(role);
            if (bs != null && bs.get(permission.ordinal())) {
                resources.add(currentPath);
                break;
            }
        }

        Map<String, TreeNode> children = node.getChildren();
        for (TreeNode treeNode : children.values()) {
            if (treeNode != null) {
                getUIResourcesForRoles(roles, resources, currentPath, permission, treeNode);
            }
        }
    } finally {
        read.unlock();
    }
}

From source file:org.wso2.carbon.user.core.authorization.PermissionTree.java

/**
 * Find the allowed Users for a given resource by traversing the whole
 * pemission tree./*from  w w  w. ja  va  2  s .c om*/
 *
 * @param sr         - search result to contain allowed users
 * @param node       - current node
 * @param permission - permission
 * @param pathParts  - list of path segments to traverse
 * @return - search result with allowed users
 */

SearchResult getAllowedUsersForResource(SearchResult sr, TreeNode node, TreeNode.Permission permission,
        List<String> pathParts) {
    read.lock();
    try {
        if (node == null) {
            node = root;
        }
        if (sr == null) {
            sr = new SearchResult();
        }

        /**
         * Add allowed users of the current node to our list in the sr
         */
        Map<String, BitSet> allowUsers = node.getUserAllowPermissions();
        for (Map.Entry<String, BitSet> entry : allowUsers.entrySet()) {
            BitSet bs = entry.getValue();
            if (bs.get(permission.ordinal())) {
                if (!sr.getAllowedEntities().contains(entry.getKey())) {
                    sr.getAllowedEntities().add(entry.getKey());
                }
            }
        }

        /**
         * Remove denied users of the current node from our list in the sr
         */
        Map<String, BitSet> denyUsers = node.getUserDenyPermissions();
        for (Map.Entry<String, BitSet> entry : denyUsers.entrySet()) {
            BitSet bs = entry.getValue();
            if (bs.get(permission.ordinal()) && sr.getAllowedEntities().contains(entry.getKey())) {
                sr.getAllowedEntities().remove(entry.getKey());
            }
        }

        if (pathParts == null || pathParts.isEmpty()) {
            sr.setLastNode(node);
            sr.setUnprocessedPaths(null);
            return sr;
        } else {
            String key = pathParts.get(0);
            if (key != null && key.length() > 0) {
                TreeNode child = node.getChild(key);
                if (child != null) {
                    pathParts.remove(0);
                    return getAllowedUsersForResource(sr, child, permission, pathParts);
                }
            }
            sr.setLastNode(node);
            return sr;
        }
    } finally {
        read.unlock();
    }
}

From source file:org.wso2.carbon.user.core.authorization.PermissionTree.java

/**
 * Find the denied users for a given resource by traversing the whole
 * pemission tree./*ww  w  . ja v  a  2  s.  co m*/
 *
 * @param sr         - search result to contain denied users
 * @param node       - current node
 * @param permission - permission
 * @param pathParts  - list of path segments to traverse
 * @return - search result with denied users
 */
SearchResult getDeniedUsersForResource(SearchResult sr, TreeNode node, TreeNode.Permission permission,
        List<String> pathParts) {
    read.lock();
    try {
        if (sr == null) {
            sr = new SearchResult();
        }

        if (node == null) {
            node = root;
        }

        /**
         * Add denied users of the current node to our list in the sr
         */
        Map<String, BitSet> denyUsers = node.getUserDenyPermissions();
        for (Map.Entry<String, BitSet> entry : denyUsers.entrySet()) {
            BitSet bs = entry.getValue();
            if (bs.get(permission.ordinal())) {
                if (!sr.getDeniedEntities().contains(entry.getKey())) {
                    sr.getDeniedEntities().add(entry.getKey());
                }
            }
        }

        /**
         * Remove allowed users of the current node from our list in the sr
         */
        Map<String, BitSet> allowUsers = node.getUserAllowPermissions();
        for (Map.Entry<String, BitSet> entry : allowUsers.entrySet()) {
            BitSet bs = entry.getValue();
            if (bs.get(permission.ordinal()) && sr.getDeniedEntities().contains(entry.getKey())) {
                sr.getDeniedEntities().remove(entry.getKey());
            }
        }

        if (pathParts == null || pathParts.isEmpty()) {
            sr.setLastNode(node);
            sr.setUnprocessedPaths(null);
            return sr;
        } else {
            String key = pathParts.get(0);
            if (key != null && key.length() > 0) {
                TreeNode child = node.getChild(key);
                if (child != null) {
                    pathParts.remove(0);
                    return getDeniedUsersForResource(sr, child, permission, pathParts);
                }
            }
            sr.setLastNode(node);
            return sr;
        }
    } finally {
        read.unlock();
    }
}

From source file:org.wso2.carbon.user.core.authorization.PermissionTree.java

/**
 * Find the allowed Roles for a given resource by traversing the whole
 * pemission tree.//  w  ww.jav  a2s  . co m
 *
 * @param sr         - search result to contain allowed roles
 * @param node       - current node
 * @param permission - permission
 * @param pathParts  - list of path segments to traverse
 * @return - search result with allowed roles
 */

SearchResult getAllowedRolesForResource(SearchResult sr, TreeNode node, TreeNode.Permission permission,
        List<String> pathParts) {
    read.lock();
    try {
        if (node == null) {
            node = root;
        }

        if (sr == null) {
            sr = new SearchResult();
        }

        /**
         * Add allowed roles of the current node to our list in the sr
         */
        Map<String, BitSet> allowRoles = node.getRoleAllowPermissions();
        for (Map.Entry<String, BitSet> entry : allowRoles.entrySet()) {
            BitSet bs = entry.getValue();
            if (bs.get(permission.ordinal())) {
                if (!sr.getAllowedEntities().contains(entry.getKey())) {
                    sr.getAllowedEntities().add(entry.getKey());
                }
            }
        }

        /**
         * Remove denied roles of the current node from our list in the sr
         */
        Map<String, BitSet> denyRoles = node.getRoleDenyPermissions();
        for (Map.Entry<String, BitSet> entry : denyRoles.entrySet()) {
            BitSet bs = entry.getValue();
            if (bs.get(permission.ordinal()) && sr.getAllowedEntities().contains(entry.getKey())) {
                sr.getAllowedEntities().remove(entry.getKey());
            }
        }

        if (pathParts == null || pathParts.isEmpty()) {
            sr.setLastNode(node);
            sr.setUnprocessedPaths(null);
            return sr;
        } else {
            String key = pathParts.get(0);
            if (key != null && key.length() > 0) {
                TreeNode child = node.getChild(key);
                if (child != null) {
                    pathParts.remove(0);
                    return getAllowedRolesForResource(sr, child, permission, pathParts);
                }
            }
            sr.setLastNode(node);
            return sr;
        }
    } finally {
        read.unlock();
    }
}

From source file:org.wso2.carbon.user.core.authorization.PermissionTree.java

/**
 * Find the denied Roles for a given resource by traversing the whole
 * pemission tree.//  w  w  w. j  a  v  a 2 s.  co  m
 *
 * @param sr         - search result to contain denied roles
 * @param node       - current node
 * @param permission - permission
 * @param pathParts  - list of path segments to traverse
 * @return - search result with denied roles
 */
SearchResult getDeniedRolesForResource(SearchResult sr, TreeNode node, TreeNode.Permission permission,
        List<String> pathParts) {

    read.lock();
    try {
        if (sr == null) {
            sr = new SearchResult();
        }

        if (node == null) {
            node = root;
        }

        /**
         * Add denied roles of the current node to our list in the sr
         */
        Map<String, BitSet> denyRoles = node.getRoleDenyPermissions();
        for (Map.Entry<String, BitSet> entry : denyRoles.entrySet()) {
            BitSet bs = entry.getValue();
            if (bs.get(permission.ordinal())) {
                if (!sr.getDeniedEntities().contains(entry.getKey())) {
                    sr.getDeniedEntities().add(entry.getKey());
                }
            }
        }

        /**
         * Remove allowed roles of the current node from our list in the sr
         */
        Map<String, BitSet> allowRoles = node.getRoleAllowPermissions();
        for (Map.Entry<String, BitSet> entry : allowRoles.entrySet()) {
            BitSet bs = entry.getValue();
            if (bs.get(permission.ordinal()) && sr.getDeniedEntities().contains(entry.getKey())) {
                sr.getDeniedEntities().remove(entry.getKey());
            }
        }

        if (pathParts == null || pathParts.isEmpty()) {
            sr.setLastNode(node);
            sr.setUnprocessedPaths(null);
            return sr;
        } else {
            String key = pathParts.get(0);
            if (key != null && key.length() > 0) {
                TreeNode child = node.getChild(key);
                if (child != null) {
                    pathParts.remove(0);
                    return getDeniedRolesForResource(sr, child, permission, pathParts);
                }
            }
            sr.setLastNode(node);
            return sr;
        }
    } finally {
        read.unlock();
    }
}

From source file:org.jpos.iso.ISOBasePackager.java

public void unpack(ISOComponent m, InputStream in) throws IOException, ISOException {
    LogEvent evt = new LogEvent(this, "unpack");
    try {//from   w  w  w. j  ava  2s. c o  m
        if (m.getComposite() != m)
            throw new ISOException("Can't call packager on non Composite");

        // if ISOMsg and headerLength defined
        //         if (m instanceof ISOMsg && ((ISOMsg) m).getHeader() == null && headerLength > 0) {
        //            byte[] h = new byte[headerLength];
        //            in.read(h, 0, headerLength);
        //            ((ISOMsg) m).setHeader(h);
        //         }

        if (!(fld[0] instanceof ISOMsgFieldPackager) && !(fld[0] instanceof ISOBitMapPackager)) {
            ISOComponent mti = fld[0].createComponent(0);
            fld[0].unpack(mti, in);
            m.set(mti);
        }
        BitSet bmap = null;
        int maxField = fld.length;
        if (emitBitMap()) {
            ISOBitMap bitmap = new ISOBitMap(-1);
            getBitMapfieldPackager().unpack(bitmap, in);
            bmap = (BitSet) bitmap.getValue();
            if (logger != null)
                evt.addMessage("<bitmap>" + bmap.toString() + "</bitmap>");
            m.set(bitmap);
            maxField = Math.min(maxField, bmap.size());
        }

        for (int i = getFirstField(); i < maxField; i++) {
            if (bmap == null && fld[i] == null)
                continue;

            if (bmap == null || bmap.get(i)) {
                if (fld[i] == null)
                    throw new ISOException("field packager '" + i + "' is null");

                ISOComponent c = fld[i].createComponent(i);
                fld[i].unpack(c, in);
                if (logger != null) {

                    evt.addMessage(
                            "<unpack fld=\"" + i + "\" packager=\"" + fld[i].getClass().getName() + "\">");
                    if (c.getValue() instanceof ISOMsg)
                        evt.addMessage(c.getValue());
                    else
                        evt.addMessage("  <value>" + c.getValue().toString() + "</value>");
                    evt.addMessage("</unpack>");
                }
                m.set(c);
            }
        }
        if (bmap != null && bmap.get(65) && fld.length > 128 && fld[65] instanceof ISOBitMapPackager) {
            bmap = (BitSet) ((ISOComponent) m.getChildren().get(65)).getValue();
            for (int i = 1; i < 64; i++) {
                if (bmap == null || bmap.get(i)) {
                    ISOComponent c = fld[i + 128].createComponent(i);
                    fld[i + 128].unpack(c, in);
                    if (logger != null) {
                        evt.addMessage("<unpack fld=\"" + i + 128 + "\" packager=\""
                                + fld[i + 128].getClass().getName() + "\">");
                        evt.addMessage("  <value>" + c.getValue().toString() + "</value>");
                        evt.addMessage("</unpack>");
                    }
                    m.set(c);
                }
            }
        }
    } catch (ISOException e) {
        evt.addMessage(e);
        throw e;
    } catch (EOFException e) {
        throw e;
    } catch (Exception e) {
        evt.addMessage(e);
        throw new ISOException(e);
    } finally {
        Logger.log(evt);
    }
}