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.alfresco.module.org_alfresco_module_rm.capability.RMAfterInvocationProvider.java

private Object[] decide(Authentication authentication, Object object, ConfigAttributeDefinition config,
        Object[] returnedObject) {
    // Assumption: value is not null
    BitSet incudedSet = new BitSet(returnedObject.length);

    List<ConfigAttributeDefintion> supportedDefinitions = extractSupportedDefinitions(config);

    if (supportedDefinitions.size() == 0) {
        return returnedObject;
    }/*from   w  w w.  j  a v  a2  s.co  m*/

    for (int i = 0, l = returnedObject.length; i < l; i++) {
        Object current = returnedObject[i];

        int parentReadCheck = checkRead(getParentReadCheckNode(current));
        int childReadChek = checkRead(getChildReadCheckNode(current));

        for (ConfigAttributeDefintion cad : supportedDefinitions) {
            incudedSet.set(i, true);
            NodeRef testNodeRef = null;
            if (cad.parent) {
                if (StoreRef.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = null;
                } else if (NodeRef.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = nodeService.getPrimaryParent((NodeRef) current).getParentRef();
                } else if (ChildAssociationRef.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = ((ChildAssociationRef) current).getParentRef();
                } else if (PermissionCheckValue.class.isAssignableFrom(current.getClass())) {
                    NodeRef nodeRef = ((PermissionCheckValue) current).getNodeRef();
                    testNodeRef = nodeService.getPrimaryParent(nodeRef).getParentRef();
                } else {
                    throw new ACLEntryVoterException(
                            "The specified parameter is recognized: " + current.getClass());
                }
            } else {
                if (StoreRef.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = nodeService.getRootNode((StoreRef) current);
                } else if (NodeRef.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = (NodeRef) current;
                } else if (ChildAssociationRef.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = ((ChildAssociationRef) current).getChildRef();
                } else if (PermissionCheckValue.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = ((PermissionCheckValue) current).getNodeRef();
                } else {
                    throw new ACLEntryVoterException(
                            "The specified parameter is recognized: " + current.getClass());
                }
            }

            if (logger.isDebugEnabled()) {
                logger.debug("\t" + cad.typeString + " test on " + testNodeRef + " from "
                        + current.getClass().getName());
            }

            if (isUnfiltered(testNodeRef)) {
                continue;
            }

            int readCheck = childReadChek;
            if (cad.parent) {
                readCheck = parentReadCheck;
            }

            if (incudedSet.get(i) && (testNodeRef != null)
                    && (readCheck != AccessDecisionVoter.ACCESS_GRANTED)) {
                incudedSet.set(i, false);
            }

        }
    }

    if (incudedSet.cardinality() == returnedObject.length) {
        return returnedObject;
    } else {
        Object[] answer = new Object[incudedSet.cardinality()];
        for (int i = incudedSet.nextSetBit(0), p = 0; i >= 0; i = incudedSet.nextSetBit(++i), p++) {
            answer[p] = returnedObject[i];
        }
        return answer;
    }
}

From source file:org.apache.openjpa.kernel.StateManagerImpl.java

public boolean writeDetached(ObjectOutput out) throws IOException {
    BitSet idxs = new BitSet(_meta.getFields().length);
    lock();/*from   www  . j a v a  2 s  .  c  om*/
    try {
        boolean detsm = DetachManager.writeDetachedState(this, out, idxs);
        if (detsm)
            _flags |= FLAG_DETACHING;

        FieldMetaData[] fmds = _meta.getFields();
        for (int i = 0; i < fmds.length; i++) {
            if (fmds[i].isTransient())
                continue;
            provideField(_pc, _single, i);
            _single.serialize(out, !idxs.get(i));
            _single.clear();
        }
        return true;
    } catch (RuntimeException re) {
        throw translate(re);
    } finally {
        _flags &= ~FLAG_DETACHING;
        unlock();
    }
}

From source file:com.netease.news.utils.SplitInput.java

/**
 * Perform a split on the specified input file. Results will be written to files of the same name in the specified
 * training and test output directories. The {@link #validate()} method is called prior to executing the split.
 *//* www.j  a v  a2s  .c o m*/
public void splitFile(Path inputFile) throws IOException {
    Configuration conf = getConf();
    FileSystem fs = inputFile.getFileSystem(conf);
    if (fs.getFileStatus(inputFile) == null) {
        throw new IOException(inputFile + " does not exist");
    }
    if (fs.getFileStatus(inputFile).isDir()) {
        throw new IOException(inputFile + " is a directory");
    }

    validate();

    Path testOutputFile = new Path(testOutputDirectory, inputFile.getName());
    Path trainingOutputFile = new Path(trainingOutputDirectory, inputFile.getName());

    int lineCount = countLines(fs, inputFile, charset);

    log.info("{} has {} lines", inputFile.getName(), lineCount);

    int testSplitStart = 0;
    int testSplitSize = this.testSplitSize; // don't modify state
    BitSet randomSel = null;

    if (testRandomSelectionPct > 0 || testRandomSelectionSize > 0) {
        testSplitSize = this.testRandomSelectionSize;

        if (testRandomSelectionPct > 0) {
            testSplitSize = Math.round(lineCount * testRandomSelectionPct / 100.0f);
        }
        log.info("{} test split size is {} based on random selection percentage {}", inputFile.getName(),
                testSplitSize, testRandomSelectionPct);
        long[] ridx = new long[testSplitSize];
        RandomSampler.sample(testSplitSize, lineCount - 1, testSplitSize, 0, ridx, 0, RandomUtils.getRandom());
        randomSel = new BitSet(lineCount);
        for (long idx : ridx) {
            randomSel.set((int) idx + 1);
        }
    } else {
        if (testSplitPct > 0) { // calculate split size based on percentage
            testSplitSize = Math.round(lineCount * testSplitPct / 100.0f);
            log.info("{} test split size is {} based on percentage {}", inputFile.getName(), testSplitSize,
                    testSplitPct);
        } else {
            log.info("{} test split size is {}", inputFile.getName(), testSplitSize);
        }

        if (splitLocation > 0) { // calculate start of split based on percentage
            testSplitStart = Math.round(lineCount * splitLocation / 100.0f);
            if (lineCount - testSplitStart < testSplitSize) {
                // adjust split start downwards based on split size.
                testSplitStart = lineCount - testSplitSize;
            }
            log.info("{} test split start is {} based on split location {}", inputFile.getName(),
                    testSplitStart, splitLocation);
        }

        if (testSplitStart < 0) {
            throw new IllegalArgumentException(
                    "test split size for " + inputFile + " is too large, it would produce an "
                            + "empty training set from the initial set of " + lineCount + " examples");
        } else if (lineCount - testSplitSize < testSplitSize) {
            log.warn(
                    "Test set size for {} may be too large, {} is larger than the number of "
                            + "lines remaining in the training set: {}",
                    inputFile, testSplitSize, lineCount - testSplitSize);
        }
    }
    int trainCount = 0;
    int testCount = 0;
    if (!useSequence) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(fs.open(inputFile), charset));
        Writer trainingWriter = new OutputStreamWriter(fs.create(trainingOutputFile), charset);
        Writer testWriter = new OutputStreamWriter(fs.create(testOutputFile), charset);

        try {

            String line;
            int pos = 0;
            while ((line = reader.readLine()) != null) {
                pos++;

                Writer writer;
                if (testRandomSelectionPct > 0) { // Randomly choose
                    writer = randomSel.get(pos) ? testWriter : trainingWriter;
                } else { // Choose based on location
                    writer = pos > testSplitStart ? testWriter : trainingWriter;
                }

                if (writer == testWriter) {
                    if (testCount >= testSplitSize) {
                        writer = trainingWriter;
                    } else {
                        testCount++;
                    }
                }
                if (writer == trainingWriter) {
                    trainCount++;
                }
                writer.write(line);
                writer.write('\n');
            }

        } finally {
            Closeables.close(reader, true);
            Closeables.close(trainingWriter, false);
            Closeables.close(testWriter, false);
        }
    } else {
        SequenceFileIterator<Writable, Writable> iterator = new SequenceFileIterator<Writable, Writable>(
                inputFile, false, fs.getConf());
        SequenceFile.Writer trainingWriter = SequenceFile.createWriter(fs, fs.getConf(), trainingOutputFile,
                iterator.getKeyClass(), iterator.getValueClass());
        SequenceFile.Writer testWriter = SequenceFile.createWriter(fs, fs.getConf(), testOutputFile,
                iterator.getKeyClass(), iterator.getValueClass());
        try {

            int pos = 0;
            while (iterator.hasNext()) {
                pos++;
                SequenceFile.Writer writer;
                if (testRandomSelectionPct > 0) { // Randomly choose
                    writer = randomSel.get(pos) ? testWriter : trainingWriter;
                } else { // Choose based on location
                    writer = pos > testSplitStart ? testWriter : trainingWriter;
                }

                if (writer == testWriter) {
                    if (testCount >= testSplitSize) {
                        writer = trainingWriter;
                    } else {
                        testCount++;
                    }
                }
                if (writer == trainingWriter) {
                    trainCount++;
                }
                Pair<Writable, Writable> pair = iterator.next();
                writer.append(pair.getFirst(), pair.getSecond());
            }

        } finally {
            Closeables.close(iterator, true);
            Closeables.close(trainingWriter, false);
            Closeables.close(testWriter, false);
        }
    }
    log.info("file: {}, input: {} train: {}, test: {} starting at {}", inputFile.getName(), lineCount,
            trainCount, testCount, testSplitStart);

    // testing;
    if (callback != null) {
        callback.splitComplete(inputFile, lineCount, trainCount, testCount, testSplitStart);
    }
}

From source file:org.apache.clerezza.utils.Uri.java

/**
 * Validate the URI characters within a specific component.
 * The component must be performed after escape encoding. Or it doesn't
 * include escaped characters.//w  w  w  .  j  av  a  2 s.  c o  m
 * <p>
 * It's not that much strict, generous.  The strict validation might be
 * performed before being called this method.
 *
 * @param component the characters sequence within the component
 * @param soffset the starting offset of the given component
 * @param eoffset the ending offset of the given component
 * if -1, it means the length of the component
 * @param generous those characters that are allowed within a component
 * @return if true, it's the correct URI character sequence
 */
protected boolean validate(char[] component, int soffset, int eoffset, BitSet generous) {
    // validate each component by generous characters
    if (eoffset == -1) {
        eoffset = component.length - 1;
    }
    for (int i = soffset; i <= eoffset; i++) {
        if (!generous.get(component[i])) {
            return false;
        }
    }
    return true;
}

From source file:org.apache.clerezza.utils.Uri.java

/**
 * Pre-validate the unescaped URI string within a specific component.
 *
 * @param component the component string within the component
 * @param disallowed those characters disallowed within the component
 * @return if true, it doesn't have the disallowed characters
 * if false, the component is undefined or an incorrect one
 *///from   w w  w  . j  a v a2 s .  co  m
protected boolean prevalidate(String component, BitSet disallowed) {
    // prevalidate the given component by disallowed characters
    if (component == null) {
        return false; // undefined
    }
    char[] target = component.toCharArray();
    for (int i = 0; i < target.length; i++) {
        if (disallowed.get(target[i])) {
            return false;
        }
    }
    return true;
}

From source file:edu.brown.hstore.PartitionExecutor.java

/**
 * For the given transaction's ClientResponse, figure out whether we can
 * send it back to the client right now or whether we need to initiate
 * two-phase commit./*  w ww . j  av a  2s.c o m*/
 * 
 * @param ts
 * @param cresponse
 */
public void processClientResponse(LocalTransaction ts, ClientResponseImpl cresponse) {
    // IMPORTANT: If we executed this locally and only touched our
    // partition, then we need to commit/abort right here
    // 2010-11-14: The reason why we can do this is because we will just
    // ignore the commit
    // message when it shows from the Dtxn.Coordinator. We should probably
    // double check with Evan on this...
    boolean is_singlepartitioned = ts.isPredictSinglePartition();
    Status status = cresponse.getStatus();

    if (d) {
        LOG.debug(String.format(
                "%s - Processing ClientResponse at partition %d [handle=%d, status=%s, singlePartition=%s, local=%s]",
                ts, this.partitionId, cresponse.getClientHandle(), status, ts.isPredictSinglePartition(),
                ts.isExecLocal(this.partitionId)));
        if (t) {
            LOG.trace(ts + " Touched Partitions: " + ts.getTouchedPartitions().values());
            LOG.trace(ts + " Done Partitions: " + ts.getDonePartitions());
        }
    }

    // -------------------------------
    // ALL: Single-Partition Transactions
    // -------------------------------
    if (is_singlepartitioned) {
        // Commit or abort the transaction
        this.finishWork(ts, (status == Status.OK));

        // If the txn was mispredicted, then we will pass the information
        // over to the HStoreSite
        // so that it can re-execute the transaction. We want to do this
        // first so that the txn gets re-executed
        // as soon as possible...
        if (status == Status.ABORT_MISPREDICT) {
            if (d)
                LOG.debug(String.format("%s - Restarting because transaction is mispredicted", ts));
            // We don't want to delete the transaction here because whoever
            // is going to requeue it for
            // us will need to know what partitions that the transaction
            // touched when it executed before
            this.hstore_site.transactionRequeue(ts, status);
        }
        // Use the separate post-processor thread to send back the result
        else if (hstore_conf.site.exec_postprocessing_thread) {
            if (t)
                LOG.trace(String.format("%s - Sending ClientResponse to post-processing thread [status=%s]", ts,
                        cresponse.getStatus()));
            this.hstore_site.queueClientResponse(ts, cresponse);
        }
        // Send back the result right now!
        else {
            if (hstore_conf.site.exec_command_logging)
                ts.markLogEnabled();
            this.hstore_site.sendClientResponse(ts, cresponse);
            ts.markAsDeletable();
            this.hstore_site.deleteTransaction(ts.getTransactionId(), status);
        }
    }
    // -------------------------------
    // COMMIT: Distributed Transaction
    // -------------------------------
    else if (status == Status.OK) {
        // We have to send a prepare message to all of our remote
        // HStoreSites
        // We want to make sure that we don't go back to ones that we've
        // already told
        BitSet donePartitions = ts.getDonePartitions();
        tmp_preparePartitions.clear();
        for (Integer p : ts.getPredictTouchedPartitions()) {
            if (donePartitions.get(p.intValue()) == false) {
                tmp_preparePartitions.add(p);
            }
        } // FOR

        // We need to set the new ExecutionMode before we invoke
        // transactionPrepare
        // because the LocalTransaction handle might get cleaned up
        // immediately
        ExecutionMode newMode = null;
        if (hstore_conf.site.exec_speculative_execution) {
            newMode = (ts.isExecReadOnly(this.partitionId) ? ExecutionMode.COMMIT_READONLY
                    : ExecutionMode.COMMIT_NONE);
        } else {
            newMode = ExecutionMode.DISABLED;
        }
        this.setExecutionMode(ts, newMode);

        if (hstore_conf.site.txn_profiling)
            ts.profiler.startPostPrepare();
        TransactionPrepareCallback callback = ts.initTransactionPrepareCallback(cresponse);
        assert (callback != null) : "Missing TransactionPrepareCallback for " + ts + " [initialized="
                + ts.isInitialized() + "]";
        this.hstore_coordinator.transactionPrepare(ts, callback, tmp_preparePartitions);
    }
    // -------------------------------
    // ABORT: Distributed Transaction
    // -------------------------------
    else {
        // Send back the result to the client right now, since there's no
        // way
        // that we're magically going to be able to recover this and get
        // them a result
        // This has to come before the network messages above because this
        // will clean-up the
        // LocalTransaction state information
        this.hstore_site.sendClientResponse(ts, cresponse);

        // Then send a message all the partitions involved that the party is
        // over
        // and that they need to abort the transaction. We don't actually
        // care when we get the
        // results back because we'll start working on new txns right away.
        if (hstore_conf.site.txn_profiling)
            ts.profiler.startPostFinish();
        TransactionFinishCallback finish_callback = ts.initTransactionFinishCallback(status);
        this.hstore_coordinator.transactionFinish(ts, status, finish_callback);
    }
}

From source file:org.docx4j.fonts.fop.fonts.truetype.TTFFile.java

private boolean readUnicodeCmap(FontFileReader in, long cmapUniOffset, int encodingID) throws IOException {
    //Read CMAP table and correct mtxTab.index
    int mtxPtr = 0;

    // Read unicode cmap
    seekTab(in, "cmap", cmapUniOffset);
    int cmapFormat = in.readTTFUShort();
    /*int cmap_length =*/ in.readTTFUShort(); //skip cmap length

    if (log.isDebugEnabled()) {
        log.debug("CMAP format: " + cmapFormat);
    }/*from w  ww  .j a  va2 s. c o  m*/

    if (cmapFormat == 4) {
        in.skip(2); // Skip version number
        int cmapSegCountX2 = in.readTTFUShort();
        int cmapSearchRange = in.readTTFUShort();
        int cmapEntrySelector = in.readTTFUShort();
        int cmapRangeShift = in.readTTFUShort();

        if (log.isDebugEnabled()) {
            log.debug("segCountX2   : " + cmapSegCountX2);
            log.debug("searchRange  : " + cmapSearchRange);
            log.debug("entrySelector: " + cmapEntrySelector);
            log.debug("rangeShift   : " + cmapRangeShift);
        }

        int[] cmapEndCounts = new int[cmapSegCountX2 / 2];
        int[] cmapStartCounts = new int[cmapSegCountX2 / 2];
        int[] cmapDeltas = new int[cmapSegCountX2 / 2];
        int[] cmapRangeOffsets = new int[cmapSegCountX2 / 2];

        for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
            cmapEndCounts[i] = in.readTTFUShort();
        }

        in.skip(2); // Skip reservedPad

        for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
            cmapStartCounts[i] = in.readTTFUShort();
        }

        for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
            cmapDeltas[i] = in.readTTFShort();
        }

        //int startRangeOffset = in.getCurrentPos();

        for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
            cmapRangeOffsets[i] = in.readTTFUShort();
        }

        int glyphIdArrayOffset = in.getCurrentPos();

        BitSet eightBitGlyphs = new BitSet(256);

        // Insert the unicode id for the glyphs in mtxTab
        // and fill in the cmaps ArrayList

        for (int i = 0; i < cmapStartCounts.length; i++) {

            if (log.isTraceEnabled()) {
                log.trace(i + ": " + cmapStartCounts[i] + " - " + cmapEndCounts[i]);
            }
            if (log.isDebugEnabled()) {
                if (isInPrivateUseArea(cmapStartCounts[i], cmapEndCounts[i])) {
                    log.debug("Font contains glyphs in the Unicode private use area:"
                            + Integer.toHexString(cmapStartCounts[i]) + " - "
                            + Integer.toHexString(cmapEndCounts[i]));
                }
            }

            for (int j = cmapStartCounts[i]; j <= cmapEndCounts[i]; j++) {

                // Update lastChar
                if (j < 256 && j > lastChar) {
                    lastChar = (short) j;
                }

                if (j < 256) {
                    eightBitGlyphs.set(j);
                }

                if (mtxPtr < mtxTab.length) {
                    int glyphIdx;
                    // the last character 65535 = .notdef
                    // may have a range offset
                    if (cmapRangeOffsets[i] != 0 && j != 65535) {
                        int glyphOffset = glyphIdArrayOffset + ((cmapRangeOffsets[i] / 2)
                                + (j - cmapStartCounts[i]) + (i) - cmapSegCountX2 / 2) * 2;
                        in.seekSet(glyphOffset);
                        glyphIdx = (in.readTTFUShort() + cmapDeltas[i]) & 0xffff;

                        unicodeMapping.add(new UnicodeMapping(glyphIdx, j));
                        mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(j));

                        if (encodingID == 0 && j >= 0xF020 && j <= 0xF0FF) {
                            //Experimental: Mapping 0xF020-0xF0FF to 0x0020-0x00FF
                            //Tested with Wingdings and Symbol TTF fonts which map their
                            //glyphs in the region 0xF020-0xF0FF.
                            int mapped = j - 0xF000;
                            if (!eightBitGlyphs.get(mapped)) {
                                //Only map if Unicode code point hasn't been mapped before
                                unicodeMapping.add(new UnicodeMapping(glyphIdx, mapped));
                                mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(mapped));
                            }
                        }

                        // Also add winAnsiWidth
                        List v = (List) ansiIndex.get(new Integer(j));
                        if (v != null) {
                            Iterator e = v.listIterator();
                            while (e.hasNext()) {
                                Integer aIdx = (Integer) e.next();
                                ansiWidth[aIdx.intValue()] = mtxTab[glyphIdx].getWx();

                                if (log.isTraceEnabled()) {
                                    log.trace("Added width " + mtxTab[glyphIdx].getWx() + " uni: " + j
                                            + " ansi: " + aIdx.intValue());
                                }
                            }
                        }

                        if (log.isTraceEnabled()) {
                            log.trace("Idx: " + glyphIdx + " Delta: " + cmapDeltas[i] + " Unicode: " + j
                                    + " name: " + mtxTab[glyphIdx].getName());
                        }
                    } else {
                        glyphIdx = (j + cmapDeltas[i]) & 0xffff;

                        if (glyphIdx < mtxTab.length) {
                            mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(j));
                        } else {
                            log.debug("Glyph " + glyphIdx + " out of range: " + mtxTab.length);
                        }

                        unicodeMapping.add(new UnicodeMapping(glyphIdx, j));
                        if (glyphIdx < mtxTab.length) {
                            mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(j));
                        } else {
                            log.debug("Glyph " + glyphIdx + " out of range: " + mtxTab.length);
                        }

                        // Also add winAnsiWidth
                        List v = (List) ansiIndex.get(new Integer(j));
                        if (v != null) {
                            Iterator e = v.listIterator();
                            while (e.hasNext()) {
                                Integer aIdx = (Integer) e.next();
                                ansiWidth[aIdx.intValue()] = mtxTab[glyphIdx].getWx();
                            }
                        }

                        //getLogger().debug("IIdx: " +
                        //    mtxPtr +
                        //    " Delta: " + cmap_deltas[i] +
                        //    " Unicode: " + j +
                        //    " name: " +
                        //    mtxTab[(j+cmap_deltas[i]) & 0xffff].name);

                    }
                    if (glyphIdx < mtxTab.length) {
                        if (mtxTab[glyphIdx].getUnicodeIndex().size() < 2) {
                            mtxPtr++;
                        }
                    }
                }
            }
        }
    } else {
        log.error("Cmap format not supported: " + cmapFormat);
        return false;
    }
    return true;
}

From source file:org.alfresco.repo.security.permissions.impl.acegi.ACLEntryAfterInvocationProvider.java

@SuppressWarnings("rawtypes")
private Object[] decide(Authentication authentication, Object object, ConfigAttributeDefinition config,
        Object[] returnedObject) throws AccessDeniedException {
    // Assumption: value is not null
    BitSet incudedSet = new BitSet(returnedObject.length);

    List<ConfigAttributeDefintion> supportedDefinitions = extractSupportedDefinitions(config);

    if (supportedDefinitions.size() == 0) {
        return returnedObject;
    }//www .ja v  a2s. c  om

    for (int i = 0, l = returnedObject.length; i < l; i++) {
        Object current = returnedObject[i];
        for (ConfigAttributeDefintion cad : supportedDefinitions) {
            incudedSet.set(i, true);
            NodeRef testNodeRef = null;
            if (cad.typeString.equals(AFTER_ACL_NODE)) {
                if (StoreRef.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = nodeService.getRootNode((StoreRef) current);
                } else if (NodeRef.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = (NodeRef) current;
                } else if (ChildAssociationRef.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = ((ChildAssociationRef) current).getChildRef();
                } else if (Pair.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = (NodeRef) ((Pair) current).getSecond();
                } else if (PermissionCheckValue.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = ((PermissionCheckValue) current).getNodeRef();
                } else {
                    throw new ACLEntryVoterException(
                            "The specified parameter is recognized: " + current.getClass());
                }
            } else if (cad.typeString.equals(AFTER_ACL_PARENT)) {
                if (StoreRef.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = null;
                } else if (NodeRef.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = nodeService.getPrimaryParent((NodeRef) current).getParentRef();
                } else if (ChildAssociationRef.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = ((ChildAssociationRef) current).getParentRef();
                } else if (Pair.class.isAssignableFrom(current.getClass())) {
                    testNodeRef = (NodeRef) ((Pair) current).getSecond();
                } else if (PermissionCheckValue.class.isAssignableFrom(current.getClass())) {
                    NodeRef nodeRef = ((PermissionCheckValue) current).getNodeRef();
                    testNodeRef = nodeService.getPrimaryParent(nodeRef).getParentRef();
                } else {
                    throw new ACLEntryVoterException(
                            "The specified parameter is recognized: " + current.getClass());
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("\t" + cad.typeString + " test on " + testNodeRef + " from "
                        + current.getClass().getName());
            }

            if (isUnfiltered(testNodeRef)) {
                continue;
            }

            if (incudedSet.get(i) && (testNodeRef != null) && (permissionService.hasPermission(testNodeRef,
                    cad.required.toString()) == AccessStatus.DENIED)) {
                incudedSet.set(i, false);
            }

        }
    }

    if (incudedSet.cardinality() == returnedObject.length) {
        return returnedObject;
    } else {
        Object[] answer = new Object[incudedSet.cardinality()];
        for (int i = incudedSet.nextSetBit(0), p = 0; i >= 0; i = incudedSet.nextSetBit(++i), p++) {
            answer[p] = returnedObject[i];
        }
        return answer;
    }
}

From source file:org.apache.fop.fonts.truetype.OpenFont.java

private boolean readUnicodeCmap(long cmapUniOffset, int encodingID) throws IOException {
    //Read CMAP table and correct mtxTab.index
    int mtxPtr = 0;

    // Read unicode cmap
    seekTab(fontFile, OFTableName.CMAP, cmapUniOffset);
    int cmapFormat = fontFile.readTTFUShort();
    /*int cmap_length =*/ fontFile.readTTFUShort(); //skip cmap length

    if (log.isDebugEnabled()) {
        log.debug("CMAP format: " + cmapFormat);
    }//from w ww.  j a  va2  s.c  o  m

    if (cmapFormat == 4) {
        fontFile.skip(2); // Skip version number
        int cmapSegCountX2 = fontFile.readTTFUShort();
        int cmapSearchRange = fontFile.readTTFUShort();
        int cmapEntrySelector = fontFile.readTTFUShort();
        int cmapRangeShift = fontFile.readTTFUShort();

        if (log.isDebugEnabled()) {
            log.debug("segCountX2   : " + cmapSegCountX2);
            log.debug("searchRange  : " + cmapSearchRange);
            log.debug("entrySelector: " + cmapEntrySelector);
            log.debug("rangeShift   : " + cmapRangeShift);
        }

        int[] cmapEndCounts = new int[cmapSegCountX2 / 2];
        int[] cmapStartCounts = new int[cmapSegCountX2 / 2];
        int[] cmapDeltas = new int[cmapSegCountX2 / 2];
        int[] cmapRangeOffsets = new int[cmapSegCountX2 / 2];

        for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
            cmapEndCounts[i] = fontFile.readTTFUShort();
        }

        fontFile.skip(2); // Skip reservedPad

        for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
            cmapStartCounts[i] = fontFile.readTTFUShort();
        }

        for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
            cmapDeltas[i] = fontFile.readTTFShort();
        }

        //int startRangeOffset = in.getCurrentPos();

        for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
            cmapRangeOffsets[i] = fontFile.readTTFUShort();
        }

        int glyphIdArrayOffset = fontFile.getCurrentPos();

        BitSet eightBitGlyphs = new BitSet(256);

        // Insert the unicode id for the glyphs in mtxTab
        // and fill in the cmaps ArrayList
        for (int i = 0; i < cmapStartCounts.length; i++) {

            if (log.isTraceEnabled()) {
                log.trace(i + ": " + cmapStartCounts[i] + " - " + cmapEndCounts[i]);
            }
            if (log.isDebugEnabled()) {
                if (isInPrivateUseArea(cmapStartCounts[i], cmapEndCounts[i])) {
                    log.debug("Font contains glyphs in the Unicode private use area: "
                            + Integer.toHexString(cmapStartCounts[i]) + " - "
                            + Integer.toHexString(cmapEndCounts[i]));
                }
            }

            for (int j = cmapStartCounts[i]; j <= cmapEndCounts[i]; j++) {

                // Update lastChar
                if (j < 256 && j > lastChar) {
                    lastChar = (short) j;
                }

                if (j < 256) {
                    eightBitGlyphs.set(j);
                }

                if (mtxPtr < mtxTab.length) {
                    int glyphIdx;
                    // the last character 65535 = .notdef
                    // may have a range offset
                    if (cmapRangeOffsets[i] != 0 && j != 65535) {
                        int glyphOffset = glyphIdArrayOffset + ((cmapRangeOffsets[i] / 2)
                                + (j - cmapStartCounts[i]) + (i) - cmapSegCountX2 / 2) * 2;
                        fontFile.seekSet(glyphOffset);
                        glyphIdx = (fontFile.readTTFUShort() + cmapDeltas[i]) & 0xffff;
                        //mtxTab[glyphIdx].setName(mtxTab[glyphIdx].getName() + " - "+(char)j);
                        unicodeMappings.add(new UnicodeMapping(this, glyphIdx, j));
                        mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(j));

                        if (encodingID == 0 && j >= 0xF020 && j <= 0xF0FF) {
                            //Experimental: Mapping 0xF020-0xF0FF to 0x0020-0x00FF
                            //Tested with Wingdings and Symbol TTF fonts which map their
                            //glyphs in the region 0xF020-0xF0FF.
                            int mapped = j - 0xF000;
                            if (!eightBitGlyphs.get(mapped)) {
                                //Only map if Unicode code point hasn't been mapped before
                                unicodeMappings.add(new UnicodeMapping(this, glyphIdx, mapped));
                                mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(mapped));
                            }
                        }

                        // Also add winAnsiWidth
                        List<Integer> v = ansiIndex.get(new Integer(j));
                        if (v != null) {
                            for (Integer aIdx : v) {
                                ansiWidth[aIdx.intValue()] = mtxTab[glyphIdx].getWx();

                                if (log.isTraceEnabled()) {
                                    log.trace("Added width " + mtxTab[glyphIdx].getWx() + " uni: " + j
                                            + " ansi: " + aIdx.intValue());
                                }
                            }
                        }

                        if (log.isTraceEnabled()) {
                            log.trace("Idx: " + glyphIdx + " Delta: " + cmapDeltas[i] + " Unicode: " + j
                                    + " name: " + mtxTab[glyphIdx].getName());
                        }
                    } else {
                        glyphIdx = (j + cmapDeltas[i]) & 0xffff;

                        if (glyphIdx < mtxTab.length) {
                            mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(j));
                        } else {
                            log.debug("Glyph " + glyphIdx + " out of range: " + mtxTab.length);
                        }

                        unicodeMappings.add(new UnicodeMapping(this, glyphIdx, j));
                        if (glyphIdx < mtxTab.length) {
                            mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(j));
                        } else {
                            log.debug("Glyph " + glyphIdx + " out of range: " + mtxTab.length);
                        }

                        // Also add winAnsiWidth
                        List<Integer> v = ansiIndex.get(new Integer(j));
                        if (v != null) {
                            for (Integer aIdx : v) {
                                ansiWidth[aIdx.intValue()] = mtxTab[glyphIdx].getWx();
                            }
                        }

                        //getLogger().debug("IIdx: " +
                        //    mtxPtr +
                        //    " Delta: " + cmap_deltas[i] +
                        //    " Unicode: " + j +
                        //    " name: " +
                        //    mtxTab[(j+cmap_deltas[i]) & 0xffff].name);

                    }
                    if (glyphIdx < mtxTab.length) {
                        if (mtxTab[glyphIdx].getUnicodeIndex().size() < 2) {
                            mtxPtr++;
                        }
                    }
                }
            }
        }
    } else {
        log.error("Cmap format not supported: " + cmapFormat);
        return false;
    }
    return true;
}

From source file:org.alfresco.module.org_alfresco_module_rm.capability.RMAfterInvocationProvider.java

private ResultSet decide(Authentication authentication, Object object, ConfigAttributeDefinition config,
        ResultSet returnedObject) {
    if (returnedObject == null) {
        return null;
    }/*from  ww w.j a  v  a2 s  . co  m*/

    BitSet inclusionMask = new BitSet(returnedObject.length());
    FilteringResultSet filteringResultSet = new FilteringResultSet(returnedObject, inclusionMask);

    List<ConfigAttributeDefintion> supportedDefinitions = extractSupportedDefinitions(config);

    Integer maxSize = null;
    if (returnedObject.getResultSetMetaData().getSearchParameters().getMaxItems() >= 0) {
        maxSize = Integer.valueOf(returnedObject.getResultSetMetaData().getSearchParameters().getMaxItems());
    }
    if ((maxSize == null) && (returnedObject.getResultSetMetaData().getSearchParameters()
            .getLimitBy() == LimitBy.FINAL_SIZE)) {
        maxSize = Integer.valueOf(returnedObject.getResultSetMetaData().getSearchParameters().getLimit());
    }
    // Allow for skip
    if ((maxSize != null)
            && (returnedObject.getResultSetMetaData().getSearchParameters().getSkipCount() >= 0)) {
        maxSize = Integer
                .valueOf(maxSize + returnedObject.getResultSetMetaData().getSearchParameters().getSkipCount());
    }

    if (supportedDefinitions.size() == 0) {
        if (maxSize == null) {
            return returnedObject;
        } else if (returnedObject.length() > maxSize.intValue()) {
            for (int i = 0; i < maxSize.intValue(); i++) {
                inclusionMask.set(i, true);
            }
            filteringResultSet.setResultSetMetaData(new SimpleResultSetMetaData(
                    returnedObject.getResultSetMetaData().getLimitedBy(), PermissionEvaluationMode.EAGER,
                    returnedObject.getResultSetMetaData().getSearchParameters()));
            return filteringResultSet;
        } else {
            for (int i = 0; i < returnedObject.length(); i++) {
                inclusionMask.set(i, true);
            }
            filteringResultSet.setResultSetMetaData(new SimpleResultSetMetaData(
                    returnedObject.getResultSetMetaData().getLimitedBy(), PermissionEvaluationMode.EAGER,
                    returnedObject.getResultSetMetaData().getSearchParameters()));
            return filteringResultSet;
        }
    }

    // record the start time
    long startTimeMillis = System.currentTimeMillis();

    // set the default, unlimited resultset type
    filteringResultSet.setResultSetMetaData(new SimpleResultSetMetaData(
            returnedObject.getResultSetMetaData().getLimitedBy(), PermissionEvaluationMode.EAGER,
            returnedObject.getResultSetMetaData().getSearchParameters()));

    for (int i = 0; i < returnedObject.length(); i++) {
        long currentTimeMillis = System.currentTimeMillis();

        // All permission checks must pass
        inclusionMask.set(i, true);

        if (!nodeService.exists(returnedObject.getNodeRef(i))) {
            inclusionMask.set(i, false);
        } else {
            int parentCheckRead = checkRead(returnedObject.getChildAssocRef(i).getParentRef());
            int childCheckRead = checkRead(returnedObject.getNodeRef(i));

            for (ConfigAttributeDefintion cad : supportedDefinitions) {
                NodeRef testNodeRef = returnedObject.getNodeRef(i);
                int checkRead = childCheckRead;
                if (cad.parent) {
                    testNodeRef = returnedObject.getChildAssocRef(i).getParentRef();
                    checkRead = parentCheckRead;
                }

                if (isUnfiltered(testNodeRef)) {
                    continue;
                }

                if (inclusionMask.get(i) && (testNodeRef != null)
                        && (checkRead != AccessDecisionVoter.ACCESS_GRANTED)) {
                    inclusionMask.set(i, false);
                }
            }
        }

        // Bug out if we are limiting by size
        if ((maxSize != null) && (filteringResultSet.length() > maxSize.intValue())) {
            // Remove the last match to fix the correct size
            inclusionMask.set(i, false);
            filteringResultSet.setResultSetMetaData(
                    new SimpleResultSetMetaData(LimitBy.FINAL_SIZE, PermissionEvaluationMode.EAGER,
                            returnedObject.getResultSetMetaData().getSearchParameters()));
            break;
        }
    }
    return filteringResultSet;
}