protected static void PrintUserInfoList() {
   Collection<UserID> collection = registeredUsers.values();
   Iterator<UserID> it = collection.iterator();
   while (it.hasNext()) {
     System.out.println(it.next());
   }
 }
  /** {@inheritDoc} */
  @Override
  public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr)
      throws IgniteCheckedException {
    super.finishUnmarshal(ctx, ldr);

    if (writes != null) unmarshalTx(writes, false, ctx, ldr);

    if (reads != null) unmarshalTx(reads, false, ctx, ldr);

    if (grpLockKeyBytes != null && grpLockKey == null)
      grpLockKey = ctx.marshaller().unmarshal(grpLockKeyBytes, ldr);

    if (dhtVerKeys != null && dhtVers == null) {
      assert dhtVerVals != null;
      assert dhtVerKeys.size() == dhtVerVals.size();

      Iterator<IgniteTxKey> keyIt = dhtVerKeys.iterator();
      Iterator<GridCacheVersion> verIt = dhtVerVals.iterator();

      dhtVers = U.newHashMap(dhtVerKeys.size());

      while (keyIt.hasNext()) {
        IgniteTxKey key = keyIt.next();

        key.finishUnmarshal(ctx.cacheContext(key.cacheId()), ldr);

        dhtVers.put(key, verIt.next());
      }
    }

    if (txNodesBytes != null) txNodes = ctx.marshaller().unmarshal(txNodesBytes, ldr);
  }
Exemple #3
0
  // get signs using an additional arg for a target rel
  private Collection<Sign> getSignsFromPredAndTargetRel(String pred, String targetRel) {

    Collection<Word> words = (Collection<Word>) _predToWords.get(pred);
    String specialTokenConst = null;

    // for robustness, when using supertagger, add words for pred sans sense index
    int dotIndex = -1;
    if (_supertagger != null
        && !Character.isDigit(pred.charAt(0))
        && // skip numbers
        (dotIndex = pred.lastIndexOf('.')) > 0
        && pred.length() > dotIndex + 1
        && pred.charAt(dotIndex + 1) != '_') // skip titles, eg Mr._Smith
    {
      String barePred = pred.substring(0, dotIndex);
      Collection<Word> barePredWords = (Collection<Word>) _predToWords.get(barePred);
      if (words == null) words = barePredWords;
      else if (barePredWords != null) {
        Set<Word> unionWords = new HashSet<Word>(words);
        unionWords.addAll(barePredWords);
        words = unionWords;
      }
    }

    if (words == null) {
      specialTokenConst = tokenizer.getSpecialTokenConstant(tokenizer.isSpecialToken(pred));
      if (specialTokenConst == null) return null;
      // lookup words with pred = special token const
      Collection<Word> specialTokenWords = (Collection<Word>) _predToWords.get(specialTokenConst);
      // replace special token const with pred
      if (specialTokenWords == null) return null;
      words = new ArrayList<Word>(specialTokenWords.size());
      for (Iterator<Word> it = specialTokenWords.iterator(); it.hasNext(); ) {
        Word stw = it.next();
        Word w = Word.createSurfaceWord(stw, pred);
        words.add(w);
      }
    }

    List<Sign> retval = new ArrayList<Sign>();
    for (Iterator<Word> it = words.iterator(); it.hasNext(); ) {
      Word w = it.next();
      try {
        SignHash signs = getSignsFromWord(w, specialTokenConst, pred, targetRel);
        retval.addAll(signs.asSignSet());
      }
      // shouldn't happen
      catch (LexException exc) {
        System.err.println("Unexpected lex exception for word " + w + ": " + exc);
      }
    }
    return retval;
  }
  /**
   * Returns the live methods of a program whose root methods are the <tt>main</tt> method of a set
   * of classes.
   *
   * @param classes Names of classes containing root methods
   * @param context Repository for accessing BLOAT stuff
   * @return The <tt>MemberRef</tt>s of the live methods
   */
  private static Collection liveMethods(final Collection classes, final BloatContext context) {

    // Determine the roots of the call graph
    final Set roots = new HashSet();
    Iterator iter = classes.iterator();
    while (iter.hasNext()) {
      final String className = (String) iter.next();
      try {
        final ClassEditor ce = context.editClass(className);
        final MethodInfo[] methods = ce.methods();

        for (int i = 0; i < methods.length; i++) {
          final MethodEditor me = context.editMethod(methods[i]);

          if (!me.name().equals("main")) {
            continue;
          }

          BloatBenchmark.tr("  Root " + ce.name() + "." + me.name() + me.type());
          roots.add(me.memberRef());
        }

      } catch (final ClassNotFoundException ex1) {
        BloatBenchmark.err.println("** Could not find class: " + ex1.getMessage());
        System.exit(1);
      }
    }

    if (roots.isEmpty()) {
      BloatBenchmark.err.print("** No main method found in classes: ");
      iter = classes.iterator();
      while (iter.hasNext()) {
        final String name = (String) iter.next();
        BloatBenchmark.err.print(name);
        if (iter.hasNext()) {
          BloatBenchmark.err.print(", ");
        }
      }
      BloatBenchmark.err.println("");
    }

    context.setRootMethods(roots);
    final CallGraph cg = context.getCallGraph();

    final Set liveMethods = new TreeSet(new MemberRefComparator());
    liveMethods.addAll(cg.liveMethods());

    return (liveMethods);
  }
  /**
   * Output the specified {@link Collection} in proper columns.
   *
   * @param stuff the stuff to print
   */
  public void printColumns(final Collection stuff) throws IOException {
    if ((stuff == null) || (stuff.size() == 0)) {
      return;
    }

    int width = getTermwidth();
    int maxwidth = 0;

    for (Iterator i = stuff.iterator();
        i.hasNext();
        maxwidth = Math.max(maxwidth, i.next().toString().length())) {;
    }

    StringBuffer line = new StringBuffer();

    int showLines;

    if (usePagination) showLines = getTermheight() - 1; // page limit
    else showLines = Integer.MAX_VALUE;

    for (Iterator i = stuff.iterator(); i.hasNext(); ) {
      String cur = (String) i.next();

      if ((line.length() + maxwidth) > width) {
        printString(line.toString().trim());
        printNewline();
        line.setLength(0);
        if (--showLines == 0) { // Overflow
          printString(loc.getString("display-more"));
          flushConsole();
          int c = readVirtualKey();
          if (c == '\r' || c == '\n') showLines = 1; // one step forward
          else if (c != 'q') showLines = getTermheight() - 1; // page forward

          back(loc.getString("display-more").length());
          if (c == 'q') break; // cancel
        }
      }

      pad(cur, maxwidth + 3, line);
    }

    if (line.length() > 0) {
      printString(line.toString().trim());
      printNewline();
      line.setLength(0);
    }
  }
Exemple #6
0
  private V3LcapMessage makeTestVoteMessage(Collection voteBlocks) throws IOException {
    mPollMgr.setStateDir("key", tempDir);
    V3LcapMessage msg =
        new V3LcapMessage(
            "ArchivalID_2",
            "key",
            "Plug42",
            m_testBytes,
            m_testBytes,
            V3LcapMessage.MSG_VOTE,
            987654321,
            m_testID,
            tempDir,
            theDaemon);

    // Set msg vote blocks.
    for (Iterator ix = voteBlocks.iterator(); ix.hasNext(); ) {
      msg.addVoteBlock((VoteBlock) ix.next());
    }

    msg.setHashAlgorithm(LcapMessage.getDefaultHashAlgorithm());
    msg.setArchivalId(m_archivalID);
    msg.setPluginVersion("PlugVer42");
    return msg;
  }
  /** INTERNAL: Transform the object-level value into a database-level value */
  public Object getFieldValue(Object objectValue, AbstractSession session) {
    DatabaseMapping mapping = getMapping();
    Object fieldValue = objectValue;
    if ((mapping != null)
        && (mapping.isDirectToFieldMapping() || mapping.isDirectCollectionMapping())) {
      // CR#3623207, check for IN Collection here not in mapping.
      if (objectValue instanceof Collection) {
        // This can actually be a collection for IN within expressions... however it would be better
        // for expressions to handle this.
        Collection values = (Collection) objectValue;
        Vector fieldValues = new Vector(values.size());
        for (Iterator iterator = values.iterator(); iterator.hasNext(); ) {
          Object value = iterator.next();
          if (!(value instanceof Expression)) {
            value = getFieldValue(value, session);
          }
          fieldValues.add(value);
        }
        fieldValue = fieldValues;
      } else {
        if (mapping.isDirectToFieldMapping()) {
          fieldValue = ((AbstractDirectMapping) mapping).getFieldValue(objectValue, session);
        } else if (mapping.isDirectCollectionMapping()) {
          fieldValue = ((DirectCollectionMapping) mapping).getFieldValue(objectValue, session);
        }
      }
    }

    return fieldValue;
  }
Exemple #8
0
  // get signs with additional args for a known special token const, target pred and target rel
  private SignHash getSignsFromWord(
      Word w, String specialTokenConst, String targetPred, String targetRel) throws LexException {

    Collection<MorphItem> morphItems =
        (specialTokenConst == null) ? (Collection<MorphItem>) _words.get(w) : null;

    if (morphItems == null) {
      // check for special tokens
      if (specialTokenConst == null) {
        specialTokenConst =
            tokenizer.getSpecialTokenConstant(tokenizer.isSpecialToken(w.getForm()));
        targetPred = w.getForm();
      }
      if (specialTokenConst != null) {
        Word key = Word.createSurfaceWord(w, specialTokenConst);
        morphItems = (Collection<MorphItem>) _words.get(key);
      }
      // otherwise throw lex exception
      if (morphItems == null) throw new LexException(w + " not in lexicon");
    }

    SignHash result = new SignHash();

    for (Iterator<MorphItem> MI = morphItems.iterator(); MI.hasNext(); ) {
      getWithMorphItem(w, MI.next(), targetPred, targetRel, result);
    }

    return result;
  }
Exemple #9
0
  /**
   * Restart of the application server :
   *
   * <p>All running services are stopped. LookupManager is flushed.
   *
   * <p>Client code that started us should notice the special return value and restart us.
   */
  protected final void doExecute(AdminCommandContext context) {
    try {
      // unfortunately we can't rely on constructors with HK2...
      if (registry == null)
        throw new NullPointerException(
            new LocalStringsImpl(getClass())
                .get("restart.server.internalError", "registry was not set"));

      init(context);

      if (!verbose) {
        // do it now while we still have the Logging service running...
        reincarnate();
      }
      // else we just return a special int from System.exit()

      Collection<Module> modules = registry.getModules("com.sun.enterprise.osgi-adapter");
      if (modules.size() == 1) {
        final Module mgmtAgentModule = modules.iterator().next();
        mgmtAgentModule.stop();
      } else
        context.getLogger().warning(strings.get("restart.server.badNumModules", modules.size()));

    } catch (Exception e) {
      context.getLogger().severe(strings.get("restart.server.failure", e));
    }

    int ret = RESTART_NORMAL;

    if (debug != null) ret = debug ? RESTART_DEBUG_ON : RESTART_DEBUG_OFF;

    System.exit(ret);
  }
Exemple #10
0
 // look up and apply coarts for given rels to each sign in result
 private void applyCoarts(List<String> coartRels, Collection<Sign> result) {
   List<Sign> inputSigns = new ArrayList<Sign>(result);
   result.clear();
   List<Sign> outputSigns = new ArrayList<Sign>(inputSigns.size());
   // for each rel, lookup coarts and apply to input signs, storing results in output signs
   for (Iterator<String> it = coartRels.iterator(); it.hasNext(); ) {
     String rel = it.next();
     Collection<String> preds = (Collection<String>) _coartRelsToPreds.get(rel);
     if (preds == null) continue; // not expected
     Collection<Sign> coartResult = getSignsFromRelAndPreds(rel, preds);
     if (coartResult == null) continue;
     for (Iterator<Sign> it2 = coartResult.iterator(); it2.hasNext(); ) {
       Sign coartSign = it2.next();
       // apply to each input
       for (int j = 0; j < inputSigns.size(); j++) {
         Sign sign = inputSigns.get(j);
         grammar.rules.applyCoart(sign, coartSign, outputSigns);
       }
     }
     // switch output to input for next iteration
     inputSigns.clear();
     inputSigns.addAll(outputSigns);
     outputSigns.clear();
   }
   // add results back
   result.addAll(inputSigns);
 }
Exemple #11
0
  /**
   * Deletes a very specific mapping from the replica catalog. The LFN must be matches, the PFN, and
   * all PFN attributes specified in the replica catalog entry. More than one entry could
   * theoretically be removed. Upon removal of an entry, all attributes associated with the PFN also
   * evaporate (cascading deletion).
   *
   * @param lfn is the logical directory in the tuple.
   * @param tuple is a description of the PFN and its attributes.
   * @return the number of removed entries, either 0 or 1.
   */
  public int delete(String lfn, ReplicaCatalogEntry tuple) {
    int result = 0;
    if (lfn == null || tuple == null) {
      return result;
    }

    Collection c = (Collection) mLFNMap.get(lfn);
    if (c == null) {
      return result;
    }

    List l = new ArrayList();
    for (Iterator i = c.iterator(); i.hasNext(); ) {
      ReplicaCatalogEntry rce = (ReplicaCatalogEntry) i.next();
      if (!matchMe(rce, tuple)) {
        l.add(rce);
      }
    }

    // anything removed?
    if (l.size() != c.size()) {
      result = c.size() - l.size();
      mLFNMap.put(lfn, l);
    }

    // done
    return result;
  }
Exemple #12
0
  /**
   * Retrieves multiple entries for a given logical directory, up to the complete catalog.
   * Retrieving full catalogs should be harmful, but may be helpful in online display or portal.
   *
   * <p>
   *
   * @param lfns is a set of logical directory strings to look up.
   * @param handle is the resource handle, restricting the LFNs.
   * @return a map indexed by the LFN. Each value is a set of physical filenames.
   */
  public Map lookupNoAttributes(Set lfns, String handle) {
    Map result = new HashMap();
    if (lfns == null || lfns.size() == 0) {
      return result;
    }

    for (Iterator i = lfns.iterator(); i.hasNext(); ) {
      String lfn = (String) i.next();
      Collection c = (Collection) mLFNMap.get(lfn);
      if (c != null) {
        List value = new ArrayList();

        for (Iterator j = c.iterator(); j.hasNext(); ) {
          ReplicaCatalogEntry rce = (ReplicaCatalogEntry) j.next();
          String pool = rce.getResourceHandle();
          if (pool == null && handle == null
              || pool != null && handle != null && pool.equals(handle)) {
            value.add(rce.getPFN());
          }
        }

        // only put found LFNs into result
        result.put(lfn, value);
      }
    }

    // done
    return result;
  }
Exemple #13
0
 public static File[] toFileArray(Collection fileObjects) {
   Set files = new HashSet(fileObjects.size() * 4 / 3 + 1);
   for (Iterator i = fileObjects.iterator(); i.hasNext(); ) {
     files.add(FileUtil.toFile((FileObject) i.next()));
   }
   files.remove(null);
   return (File[]) files.toArray(new File[files.size()]);
 }
  /** {@inheritDoc} */
  @Override
  public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr)
      throws IgniteCheckedException {
    super.finishUnmarshal(ctx, ldr);

    if (ownedValKeys != null && ownedVals == null) {
      ownedVals = U.newHashMap(ownedValKeys.size());

      assert ownedValKeys.size() == ownedValVals.size();

      Iterator<IgniteTxKey> keyIter = ownedValKeys.iterator();

      Iterator<CacheVersionedValue> valIter = ownedValVals.iterator();

      while (keyIter.hasNext()) {
        IgniteTxKey key = keyIter.next();

        GridCacheContext cctx = ctx.cacheContext(key.cacheId());

        CacheVersionedValue val = valIter.next();

        key.finishUnmarshal(cctx, ldr);

        val.finishUnmarshal(cctx, ldr);

        ownedVals.put(key, val);
      }
    }

    if (retVal != null && retVal.cacheId() != 0) {
      GridCacheContext cctx = ctx.cacheContext(retVal.cacheId());

      assert cctx != null : retVal.cacheId();

      retVal.finishUnmarshal(cctx, ldr);
    }

    if (filterFailedKeys != null) {
      for (IgniteTxKey key : filterFailedKeys) {
        GridCacheContext cctx = ctx.cacheContext(key.cacheId());

        key.finishUnmarshal(cctx, ldr);
      }
    }
  }
 // Check all iterators for correct size counts
 private void checkSizes(int expectedSize) {
   assertEquals("size()", _nbhm.size(), expectedSize);
   Collection<String> vals = _nbhm.values();
   checkSizes("values()", vals.size(), vals.iterator(), expectedSize);
   Set<String> keys = _nbhm.keySet();
   checkSizes("keySet()", keys.size(), keys.iterator(), expectedSize);
   Set<Entry<String, String>> ents = _nbhm.entrySet();
   checkSizes("entrySet()", ents.size(), ents.iterator(), expectedSize);
 }
 public static void writeLinesToFile(String path, Collection<String> lines) throws IOException {
   try (PrintWriter writer = new PrintWriter(path)) {
     Iterator<String> it = lines.iterator();
     while (it.hasNext()) {
       String line = it.next();
       writer.println(line);
     }
   }
 }
  /**
   * Returns counters iterator for specified group.
   *
   * @param grpName Name of the group to iterate.
   * @return Counters iterator.
   */
  public Iterator<Counter> iterateGroup(String grpName) {
    Collection<Counter> grpCounters = new ArrayList<>();

    for (HadoopLongCounter counter : cntrs.values()) {
      if (grpName.equals(counter.group())) grpCounters.add(new HadoopV2Counter(counter));
    }

    return grpCounters.iterator();
  }
Exemple #18
0
 protected void handleMapValues() {
   Collection set = getMap().values();
   Iterator it = set.iterator();
   int count = 0;
   while (it.hasNext()) {
     count++;
     println(it.next());
   }
   println("Total " + count);
 }
Exemple #19
0
  /**
   * <br>
   * <em>Purpose:</em> Convert text using supplied parameters * in a 'text' message, specified by:
   * %num%, where num starts from 1; * parameters should be reusable in the same message and do not
   * have to be used in passed order. for example: <br>
   * <br>
   *
   * <pre>
   *    MyMsg  :A %3% message taking %1% parameters for reasons of %3%, but not %2%.
   * </pre>
   *
   * would return, using parameters : (3, triviality, fun) <br>
   * <br>
   *
   * <pre>
   *    MyMsg  :A fun message taking 3 parameters for reasons of fun, but not triviality.
   * </pre>
   *
   * <br>
   * <em>Assumptions:</em> any additional parameters are appended at the end with commas; if there
   * are not enough params, then (unknown) is inserted instead.
   *
   * @param text, String with embedded %1% style paramenter tags
   * @param altText, String
   * @param params, Collection of parameters
   * @return String
   */
  public String convert(String key, String alttext, Collection params) {

    String text = null;
    try {
      text = text(key);
    } catch (MissingResourceException mr) {
      return alttext;
    }
    if ((text == null) || (text.length() == 0)) {
      return alttext;
    }

    int size = params.size();
    StringBuffer buf = new StringBuffer(text.length() + size * 10);
    StringTokenizer st = new StringTokenizer(text, delim, true);
    int max = 0;
    boolean finding = true;
    while (st.hasMoreTokens()) {
      String next = st.nextToken();
      if (next.equals(delim)) {
        if (finding) {
          finding = false;
        } else {
          finding = true;
        }
      } else {
        if (finding) {
          // System.out.println(next);
          buf.append(next);
        } else {
          try {
            Integer j = new Integer(next);
            int num = j.intValue();
            max = (max < num ? num : max);
            String val = getParam(num, params);
            // System.out.println(",val"+num+": "+val);
            buf.append(val);
          } catch (NumberFormatException nfe) {
            // throw new SAFSException("wrong format: "+delim+next+delim+", text: "+text);
            System.err.println("Bad format for \"" + key + "\" in " + getBundleName() + ":" + text);
            return alttext;
          }
        }
      }
    }
    Iterator j = params.iterator();
    for (int i = 1; j.hasNext(); i++) { // append additional params with commas
      Object next = j.next();
      if (i > max) {
        buf.append(", ");
        buf.append(next == null ? "(null)" : translate(next.toString()));
      }
    }
    return buf.toString();
  }
Exemple #20
0
 public boolean addAll(int index, Collection c) {
   if (c == null || c.isEmpty()) return false;
   boolean changed = false;
   Iterator i = c.iterator();
   while (i.hasNext()) {
     add(index, i.next());
     changed = true;
     if (index >= 0) index++;
   }
   return changed;
 }
Exemple #21
0
 /**
  * <br>
  * <em>Purpose:</em> grab a param from a Collection, if not there, append (unknown); * it will
  * also attempt to 'translate' the value obtained before returning it, using * the same resource
  * file, if it cannot translate, then it just returns the parameter * at the position. If a param
  * is null then "(null)" will be returned.
  *
  * @param num, int, starting from 1
  * @param params, Collection
  * @return String, if not found in 'params' then "(unknown)" is found
  */
 protected String getParam(int num, Collection params) {
   // System.out.println(", params: "+params);
   Iterator j = params.iterator();
   for (int i = 1; j.hasNext(); i++) {
     Object next = j.next();
     if (i == num) {
       return (next == null ? "(null)" : translate(next.toString()));
     }
   }
   return "(unknown)";
 }
Exemple #22
0
 // get signs for rel via preds, or null if none
 private Collection<Sign> getSignsFromRelAndPreds(String rel, Collection<String> preds) {
   List<Sign> retval = new ArrayList<Sign>();
   for (Iterator<String> it = preds.iterator(); it.hasNext(); ) {
     String pred = it.next();
     Collection<Sign> signs = getSignsFromPredAndTargetRel(pred, rel);
     if (signs != null) retval.addAll(signs);
   }
   // return null if none survive filter
   if (retval.size() > 0) return retval;
   else return null;
 }
Exemple #23
0
  public static void replaceResources(Collection src, Collection dest, NodeFactory f, Map o2n)
      throws ModelException {

    Iterator it = src.iterator();

    while (it.hasNext()) {

      Statement st = (Statement) it.next();
      dest.add(replaceResources(st, f, o2n));
    }
  }
  public Map defaultArguments() {
    Map defaults = new LinkedHashMap();
    Collection values = defaultArguments.values();

    Iterator iter = values.iterator();
    while (iter.hasNext()) {
      ArgumentImpl argument = (ArgumentImpl) iter.next();
      defaults.put(argument.name(), argument.clone());
    }
    return defaults;
  }
 private static void generateCallParameters(
     PrintWriter writer, TypeMap type_map, Collection<ParameterDeclaration> params) {
   if (params.size() > 0) {
     Iterator<ParameterDeclaration> it = params.iterator();
     generateCallParameter(writer, type_map, it.next());
     while (it.hasNext()) {
       writer.print(", ");
       generateCallParameter(writer, type_map, it.next());
     }
   }
 }
Exemple #26
0
  String filter(String[] args, boolean include) {
    verifyCommand(args, String.format(_filterHelp, args[0]), null, 3, 3);

    Collection<String> list = new ArrayList<String>(Processor.split(args[1]));
    Pattern pattern = Pattern.compile(args[2]);

    for (Iterator<String> i = list.iterator(); i.hasNext(); ) {
      if (pattern.matcher(i.next()).matches() == include) i.remove();
    }
    return Processor.join(list);
  }
Exemple #27
0
 private void writeState(XMLWriter writer) {
   writer.startTag(RepositoriesViewContentHandler.REPOSITORIES_VIEW_TAG, null, true);
   // Write the repositories
   Collection repos = Arrays.asList(getKnownRepositoryLocations());
   Iterator it = repos.iterator();
   while (it.hasNext()) {
     CVSRepositoryLocation location = (CVSRepositoryLocation) it.next();
     RepositoryRoot root = getRepositoryRootFor(location);
     root.writeState(writer);
   }
   writer.endTag(RepositoriesViewContentHandler.REPOSITORIES_VIEW_TAG);
 }
Exemple #28
0
  public void testGetUrls() {
    HashSet stringCollection = new HashSet();
    stringCollection.add("test");

    AuState auState =
        makeAuState(mau, -1, -1, -1, -1, 123, stringCollection, 1, -1.0, 1.0, historyRepo);
    Collection col = auState.getCrawlUrls();
    Iterator colIter = col.iterator();
    assertTrue(colIter.hasNext());
    assertEquals("test", colIter.next());
    assertFalse(colIter.hasNext());
  }
  protected static void printUserList(Collection<UserID> users) {

    Iterator<UserID> it = users.iterator();

    while (it.hasNext()) {
      UserID user = it.next();
      System.out.println(
          "Username: "******"Name: " + user.getName() + " " + user.getAttributes());
    }

    if (users.isEmpty()) System.out.println("No results");
  }
Exemple #30
0
  @Test
  public void testUserDefinedCompaction() throws Exception {
    Keyspace keyspace = Keyspace.open(KEYSPACE1);
    final String cfname = "Standard3"; // use clean(no sstable) CF
    ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfname);

    // disable compaction while flushing
    cfs.disableAutoCompaction();

    final int ROWS_PER_SSTABLE = 10;
    for (int i = 0; i < ROWS_PER_SSTABLE; i++) {
      DecoratedKey key = Util.dk(String.valueOf(i));
      RowMutation rm = new RowMutation(KEYSPACE1, key.key);
      rm.add(
          cfname,
          ByteBufferUtil.bytes("col"),
          ByteBufferUtil.EMPTY_BYTE_BUFFER,
          System.currentTimeMillis());
      rm.apply();
    }
    cfs.forceBlockingFlush();
    Collection<SSTableReader> sstables = cfs.getSSTables();

    assert sstables.size() == 1;
    SSTableReader sstable = sstables.iterator().next();

    int prevGeneration = sstable.descriptor.generation;
    String file = new File(sstable.descriptor.filenameFor(Component.DATA)).getName();
    // submit user defined compaction on flushed sstable
    CompactionManager.instance.forceUserDefinedCompaction(file);
    // wait until user defined compaction finishes
    do {
      Thread.sleep(100);
    } while (CompactionManager.instance.getPendingTasks() > 0
        || CompactionManager.instance.getActiveCompactions() > 0);
    // CF should have only one sstable with generation number advanced
    sstables = cfs.getSSTables();
    assert sstables.size() == 1;
    assert sstables.iterator().next().descriptor.generation == prevGeneration + 1;
  }