Esempio n. 1
1
 private boolean containsColumn(Collection columns, String column) {
   if (columns.contains(column)) return true;
   for (Iterator it = columns.iterator(); it.hasNext(); ) {
     if (((String) it.next()).equalsIgnoreCase(column)) return true;
   }
   return false;
 }
Esempio n. 2
1
  protected Collection<TransactionOutputEx> getSpendableOutputs() {
    Collection<TransactionOutputEx> list = _backing.getAllUnspentOutputs();

    // Prune confirmed outputs for coinbase outputs that are not old enough
    // for spending. Also prune unconfirmed receiving coins except for change
    int blockChainHeight = getBlockChainHeight();
    Iterator<TransactionOutputEx> it = list.iterator();
    while (it.hasNext()) {
      TransactionOutputEx output = it.next();
      if (output.isCoinBase) {
        int confirmations = blockChainHeight - output.height;
        if (confirmations < COINBASE_MIN_CONFIRMATIONS) {
          it.remove();
          continue;
        }
      }
      // Unless we allow zero confirmation spending we prune all unconfirmed outputs sent from
      // foreign addresses
      if (!_allowZeroConfSpending) {
        if (output.height == -1 && !isFromMe(output.outPoint.hash)) {
          // Prune receiving coins that is not change sent to ourselves
          it.remove();
        }
      }
    }
    return list;
  }
 public void setSwingDataCollection(Collection<ICFSecurityISOCountryObj> value) {
   final String S_ProcName = "setSwingDataCollection";
   swingDataCollection = value;
   if (swingDataCollection == null) {
     arrayOfISOCountry = new ICFSecurityISOCountryObj[0];
   } else {
     int len = value.size();
     arrayOfISOCountry = new ICFSecurityISOCountryObj[len];
     Iterator<ICFSecurityISOCountryObj> iter = swingDataCollection.iterator();
     int idx = 0;
     while (iter.hasNext() && (idx < len)) {
       arrayOfISOCountry[idx++] = iter.next();
     }
     if (idx < len) {
       throw CFLib.getDefaultExceptionFactory()
           .newRuntimeException(
               getClass(),
               S_ProcName,
               "Collection iterator did not fully populate the array copy");
     }
     if (iter.hasNext()) {
       throw CFLib.getDefaultExceptionFactory()
           .newRuntimeException(
               getClass(),
               S_ProcName,
               "Collection iterator had left over items when done populating array copy");
     }
     Arrays.sort(arrayOfISOCountry, compareISOCountryByQualName);
   }
   PickerTableModel tblDataModel = getDataModel();
   if (tblDataModel != null) {
     tblDataModel.fireTableDataChanged();
   }
 }
  /*
   * (non-Javadoc)
   * @see de.hpi.bpt.hypergraph.abs.IDirectedHyperGraph#getEdgesWithSourcesAndTargets(java.util.Collection, java.util.Collection)
   */
  public Collection<E> getEdgesWithSourcesAndTargets(Collection<V> ss, Collection<V> ts) {
    Collection<E> result = new ArrayList<E>();
    if (ss == null && ts == null) return result;
    if (ss.size() == 0 && ts.size() == 0) return result;

    if (ss != null && ss.size() > 0) {
      V v = ss.iterator().next();
      Collection<E> es = this.getEdgesWithSource(v);
      if (es == null) return result;
      Iterator<E> i = es.iterator();
      while (i.hasNext()) {
        E e = i.next();
        if (e.hasSources(ss) && e.hasTargets(ts)) result.add(e);
      }
    } else if (ts != null && ts.size() > 0) {
      V v = ts.iterator().next();
      Collection<E> es = this.getEdgesWithTarget(v);
      if (es == null) return result;
      Iterator<E> i = es.iterator();
      while (i.hasNext()) {
        E e = i.next();
        if (e.hasSources(ss) && e.hasTargets(ts)) result.add(e);
      }
    }

    return result;
  }
 private void createMemberState(MemberStateImpl memberState) {
   final Node node = factory.node;
   memberState.setAddress(node.getThisAddress());
   memberState.getMemberHealthStats().setOutOfMemory(node.isOutOfMemory());
   memberState.getMemberHealthStats().setActive(node.isActive());
   memberState
       .getMemberHealthStats()
       .setServiceThreadStats(node.getCpuUtilization().serviceThread);
   memberState.getMemberHealthStats().setOutThreadStats(node.getCpuUtilization().outThread);
   memberState.getMemberHealthStats().setInThreadStats(node.getCpuUtilization().inThread);
   PartitionService partitionService = factory.getPartitionService();
   Set<Partition> partitions = partitionService.getPartitions();
   memberState.clearPartitions();
   for (Partition partition : partitions) {
     if (partition.getOwner() != null && partition.getOwner().localMember()) {
       memberState.addPartition(partition.getPartitionId());
     }
   }
   Collection<HazelcastInstanceAwareInstance> proxyObjects =
       new ArrayList<HazelcastInstanceAwareInstance>(factory.getProxies());
   createMemState(memberState, proxyObjects.iterator(), InstanceType.MAP);
   createMemState(memberState, proxyObjects.iterator(), InstanceType.QUEUE);
   createMemState(memberState, proxyObjects.iterator(), InstanceType.TOPIC);
   createRuntimeProps(memberState);
   // uncomment when client changes are made
   // createMemState(memberState, proxyObjects.iterator(), InstanceType.ATOMIC_LONG);
   // createMemState(memberState, proxyObjects.iterator(), InstanceType.COUNT_DOWN_LATCH);
   // createMemState(memberState, proxyObjects.iterator(), InstanceType.SEMAPHORE);
 }
  void release() {
    if (childRowToIdMap != null) {
      Collection delegates = childRowToIdMap.values();
      Iterator iter = delegates.iterator();
      while (iter.hasNext()) {
        SWTAccessibleDelegate childDelegate = ((Accessible) iter.next()).delegate;
        if (childDelegate != null) {
          childDelegate.internal_dispose_SWTAccessibleDelegate();
          childDelegate.release();
        }
      }

      childRowToIdMap.clear();
      childRowToIdMap = null;
    }

    if (childColumnToIdMap != null) {
      Collection delegates = childColumnToIdMap.values();
      Iterator iter = delegates.iterator();
      while (iter.hasNext()) {
        SWTAccessibleDelegate childDelegate = ((Accessible) iter.next()).delegate;
        if (childDelegate != null) {
          childDelegate.internal_dispose_SWTAccessibleDelegate();
          childDelegate.release();
        }
      }

      childColumnToIdMap.clear();
      childColumnToIdMap = null;
    }
  }
Esempio n. 7
0
  private synchronized void updateLocalTradeSessions(Collection<TradeSession> remoteList) {
    // Get all the local sessions
    Collection<TradeSession> localList = _db.getAll();

    // Iterate over local items to find records to delete or update locally
    Iterator<TradeSession> localIt = localList.iterator();
    while (localIt.hasNext()) {
      TradeSession localItem = localIt.next();
      TradeSession remoteItem = findAndEliminate(localItem, remoteList);
      if (remoteItem == null) {
        // A local item is not in the remote list, remove it locally
        _db.delete(localItem.id);
      } else {
        // A local item is in the new list, see if it needs to be updated
        if (needsUpdate(localItem, remoteItem)) {
          _db.update(remoteItem);
        }
      }
    }

    // Iterate over remaining remote items and insert them
    Iterator<TradeSession> remoteIt = remoteList.iterator();
    while (remoteIt.hasNext()) {
      TradeSession remoteItem = remoteIt.next();
      _db.insert(remoteItem);
    }
  }
Esempio n. 8
0
 public void renderClassDescriptor(
     ClassDescriptor descriptor, StringBuilder builder, String keyword) {
   if (descriptor.getKind() != ClassKind.CLASS_OBJECT) {
     renderVisibility(descriptor.getVisibility(), builder);
   }
   if (descriptor.getKind() != ClassKind.TRAIT
       && descriptor.getKind() != ClassKind.OBJECT
       && descriptor.getKind() != ClassKind.CLASS_OBJECT) {
     renderModality(descriptor.getModality(), builder);
   }
   builder.append(renderKeyword(keyword));
   if (descriptor.getKind() != ClassKind.CLASS_OBJECT) {
     builder.append(" ");
     renderName(descriptor, builder);
     renderTypeParameters(descriptor.getTypeConstructor().getParameters(), builder);
   }
   if (!descriptor.equals(JetStandardClasses.getNothing())) {
     Collection<? extends JetType> supertypes = descriptor.getTypeConstructor().getSupertypes();
     if (supertypes.isEmpty()
         || supertypes.size() == 1 && JetStandardClasses.isAny(supertypes.iterator().next())) {
     } else {
       builder.append(" : ");
       for (Iterator<? extends JetType> iterator = supertypes.iterator(); iterator.hasNext(); ) {
         JetType supertype = iterator.next();
         builder.append(renderType(supertype));
         if (iterator.hasNext()) {
           builder.append(", ");
         }
       }
     }
   }
 }
Esempio n. 9
0
  void filterServiceEventReceivers(
      final ServiceEvent evt, final Collection /*<ServiceListenerEntry>*/ receivers) {
    ArrayList srl = fwCtx.services.get(EventHook.class.getName());
    if (srl != null) {
      HashSet ctxs = new HashSet();
      for (Iterator ir = receivers.iterator(); ir.hasNext(); ) {
        ctxs.add(((ServiceListenerEntry) ir.next()).getBundleContext());
      }
      int start_size = ctxs.size();
      RemoveOnlyCollection filtered = new RemoveOnlyCollection(ctxs);

      for (Iterator i = srl.iterator(); i.hasNext(); ) {
        ServiceReferenceImpl sr = ((ServiceRegistrationImpl) i.next()).reference;
        EventHook eh = (EventHook) sr.getService(fwCtx.systemBundle);
        if (eh != null) {
          try {
            eh.event(evt, filtered);
          } catch (Exception e) {
            fwCtx.debug.printStackTrace(
                "Failed to call event hook  #" + sr.getProperty(Constants.SERVICE_ID), e);
          }
        }
      }
      // NYI, refactor this for speed!?
      if (start_size != ctxs.size()) {
        for (Iterator ir = receivers.iterator(); ir.hasNext(); ) {
          if (!ctxs.contains(((ServiceListenerEntry) ir.next()).getBundleContext())) {
            ir.remove();
          }
        }
      }
    }
  }
  /** {@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);
  }
Esempio n. 11
0
  public void doIt() {
    Iterator iter;
    Collection ref;

    ref = new ArrayList();
    Populator.fillIt(ref);
    iter = ref.iterator();
    while (iter.hasNext()) {
      System.out.print(iter.next() + " ");
    } // end while loop
    System.out.println();

    Collections.reverse((List) ref);
    iter = ref.iterator();
    while (iter.hasNext()) {
      System.out.print(iter.next() + " ");
    } // end while loop
    System.out.println();

    Comparator aComparator = Collections.reverseOrder();
    Collections.sort((List) ref, aComparator);
    iter = ref.iterator();
    while (iter.hasNext()) {
      System.out.print(iter.next() + " ");
    } // end while loop
    System.out.println();
  } // end doIt()
  protected String refreshListSelection(String layerName) {
    try {

      Collection collection = geopistaEditor.getSelection();
      if (collection.iterator().hasNext()) {
        GeopistaFeature feature = (GeopistaFeature) collection.iterator().next();
        if (feature == null) {
          logger.error("feature: " + feature);
          return null;
        }

        if (layerName != null && feature.getLayer() != null) {
          if (!layerName.equals(feature.getLayer().getName())) return null;
        }
        // String id = checkNull(feature.getAttribute(0));
        String id = checkNull(feature.getSystemId());
        logger.info("id: -" + id + "-");
        return id;
      }
    } catch (Exception ex) {

      this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      ex.printStackTrace(pw);
      logger.error("Exception: " + sw.toString());
      return null;
    }
    return null;
  }
Esempio n. 13
0
  /*
   * (non-Javadoc)
   * @see de.hpi.bpt.hypergraph.abs.IHyperGraph#removeVertices(java.util.Collection)
   */
  public Collection<V> removeVertices(Collection<V> vs) {
    if (vs == null || vs.size() == 0) return null;

    Collection<E> es = this.getEdges(vs.iterator().next());
    Iterator<E> i = es.iterator();
    while (i.hasNext()) i.next().removeVertices(vs);

    return new ArrayList<V>(vs);
  }
Esempio n. 14
0
 public <T extends Anim> void clearanims(Class<T> type) {
   for (Iterator<Anim> i = nanims.iterator(); i.hasNext(); ) {
     Anim a = i.next();
     if (type.isInstance(a)) i.remove();
   }
   for (Iterator<Anim> i = anims.iterator(); i.hasNext(); ) {
     Anim a = i.next();
     if (type.isInstance(a)) i.remove();
   }
 }
Esempio n. 15
0
 @Override
 public Class<?> getComponentClass() {
   Object o = this.getValue(this.thisObject);
   if (o instanceof Collection) {
     Collection c = (Collection) o;
     if (c.iterator().hasNext()) {
       return c.iterator().next().getClass();
     }
   }
   return Object.class;
 }
Esempio n. 16
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;
  }
Esempio n. 17
0
  /*
   * (non-Javadoc)
   * @see de.hpi.bpt.hypergraph.abs.IHyperGraph#getEdges(java.util.Collection)
   */
  public Collection<E> getEdges(Collection<V> vs) {
    if (vs == null || vs.size() == 0) return Collections.<E>emptyList();

    Collection<E> result = new ArrayList<E>();
    V v = vs.iterator().next();
    Collection<E> es = this.getEdges(v);
    Iterator<E> i = es.iterator();
    while (i.hasNext()) {
      E e = i.next();
      if (e.connectsVertices(vs)) result.add(e);
    }

    return result;
  }
Esempio n. 18
0
  /**
   * Checks equality of two objects based on the equality of their fields, items, or .equals()
   * method.
   *
   * @param obj1
   * @param obj2
   * @return
   */
  public static <T> boolean equal(T obj1, T obj2) {
    if (obj1 == null || obj2 == null) {
      // If they're both null, we call this equal
      if (obj1 == null && obj2 == null) return true;
      else return false;
    }

    if (!obj1.getClass().equals(obj2.getClass())) return false;

    if (obj1.equals(obj2)) return true;

    List<Pair> vals = new ArrayList<Pair>();

    // If obj1 and obj2 are Collections, get the objects in them
    if (Collection.class.isAssignableFrom(obj1.getClass())) {

      Collection c1 = (Collection) obj1;
      Collection c2 = (Collection) obj2;

      if (c1.size() != c2.size()) return false;

      Iterator itr1 = c1.iterator();
      Iterator itr2 = c2.iterator();

      while (itr1.hasNext() && itr2.hasNext()) {
        vals.add(new Pair(itr1.next(), itr2.next()));
      }
    }

    // Get field values from obj1 and obj2
    PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(obj1);
    for (PropertyDescriptor property : properties) {

      // ignore getClass() and isEmpty()
      if (property.getName().equals("class") || property.getName().equals("empty")) continue;

      Object val1 = invokeMethod(obj1, property.getReadMethod(), null, property.getName());
      Object val2 = invokeMethod(obj2, property.getReadMethod(), null, property.getName());

      vals.add(new Pair(val1, val2));
    }

    if (vals.isEmpty()) return false;

    for (Pair pair : vals) {
      if (!equal(pair.left, pair.right)) return false;
    }

    return true;
  }
Esempio n. 19
0
  public static void main(String[] args) {
    Collection<Suit> suits = Arrays.asList(Suit.values());
    Collection<Rank> ranks = Arrays.asList(Rank.values());

    List<Card> deck = new ArrayList<Card>();
    for (Iterator<Suit> i = suits.iterator(); i.hasNext(); )
      for (Iterator<Rank> j = ranks.iterator(); j.hasNext(); )
        deck.add(new Card(i.next(), j.next()));

    // Preferred idiom for nested iteration on collections and arrays
    //        for (Suit suit : suits)
    //            for (Rank rank : ranks)
    //                deck.add(new Card(suit, rank));
  }
Esempio n. 20
0
  /**
   * Compare two collections by size, then by contents. List comparisons will preserve order. All
   * other collections will be treated with bag semantics.
   */
  private static boolean sameOrEquals(
      Collection<?> collection,
      Collection<?> otherCollection,
      Map<PendingComparison, Comparison> pending,
      Map<Object, Object> pairs) {
    if (collection.size() != otherCollection.size()) {
      return false;
    }

    if (collection instanceof List<?>) {
      // Lists we can simply iterate over
      Iterator<?> it = collection.iterator();
      Iterator<?> otherIt = otherCollection.iterator();
      while (it.hasNext()) {
        assert otherIt.hasNext();
        Object element = it.next();
        Object otherElement = otherIt.next();
        if (!sameOrEquals(element, otherElement, pending)) {
          return false;
        }
        if (pairs != null) {
          pairs.put(element, otherElement);
        }
      }
    } else {
      // Do an n*m comparison on any other collection type
      List<Object> values = new ArrayList<Object>(collection);
      List<Object> otherValues = new ArrayList<Object>(otherCollection);
      it:
      for (Iterator<Object> it = values.iterator(); it.hasNext(); ) {
        Object value = it.next();
        for (Iterator<Object> otherIt = otherValues.iterator(); otherIt.hasNext(); ) {
          Object otherValue = otherIt.next();
          if (sameOrEquals(value, otherValue, pending)) {
            if (pairs != null) {
              pairs.put(value, otherValue);
            }
            // If a match is found, remove both values from their lists
            it.remove();
            otherIt.remove();
            continue it;
          }
        }
        // A match for the value wasn't found
        return false;
      }
      assert values.isEmpty() && otherValues.isEmpty();
    }
    return true;
  }
Esempio n. 21
0
  /**
   * 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);
  }
 private Set<String> getLongInstanceNames() {
   Set<String> setLongInstanceNames = new HashSet<String>(maxVisibleInstanceCount);
   Collection<HazelcastInstanceAwareInstance> proxyObjects =
       new ArrayList<HazelcastInstanceAwareInstance>(factory.getProxies());
   collectInstanceNames(setLongInstanceNames, proxyObjects.iterator(), InstanceType.MAP);
   collectInstanceNames(setLongInstanceNames, proxyObjects.iterator(), InstanceType.QUEUE);
   collectInstanceNames(setLongInstanceNames, proxyObjects.iterator(), InstanceType.TOPIC);
   // uncomment when client changes are made
   // collectInstanceNames(setLongInstanceNames, proxyObjects.iterator(),
   // InstanceType.ATOMIC_NUMBER);
   // collectInstanceNames(setLongInstanceNames, proxyObjects.iterator(),
   // InstanceType.COUNT_DOWN_LATCH);
   // collectInstanceNames(setLongInstanceNames, proxyObjects.iterator(), InstanceType.SEMAPHORE);
   return setLongInstanceNames;
 }
  /**
   * 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);
    }
  }
Esempio n. 24
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);
  }
Esempio n. 25
0
  private void setRoutingName(AccessNode accessNode, PlanNode node, Command command)
      throws QueryPlannerException, TeiidComponentException {

    // Look up connector binding name
    try {
      Object modelID = node.getProperty(NodeConstants.Info.MODEL_ID);
      if (modelID == null || modelID instanceof TempMetadataID) {
        if (command instanceof StoredProcedure) {
          modelID = ((StoredProcedure) command).getModelID();
        } else if (!(command instanceof Create || command instanceof Drop)) {
          Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(command, true);
          GroupSymbol group = groups.iterator().next();

          modelID = metadata.getModelID(group.getMetadataID());
        }
      }
      String cbName = metadata.getFullName(modelID);
      accessNode.setModelName(cbName);
      accessNode.setModelId(modelID);
      accessNode.setConformedTo((Set<Object>) node.getProperty(Info.CONFORMED_SOURCES));
    } catch (QueryMetadataException e) {
      throw new QueryPlannerException(
          QueryPlugin.Event.TEIID30251, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30251));
    }
  }
Esempio n. 26
0
  protected void encodeFrozenRows(FacesContext context, DataTable table) throws IOException {
    Collection<?> frozenRows = table.getFrozenRows();
    if (frozenRows == null || frozenRows.isEmpty()) {
      return;
    }

    ResponseWriter writer = context.getResponseWriter();
    String clientId = table.getClientId(context);
    String var = table.getVar();
    String rowIndexVar = table.getRowIndexVar();
    Map<String, Object> requestMap = context.getExternalContext().getRequestMap();

    writer.startElement("tbody", null);
    writer.writeAttribute("class", DataTable.DATA_CLASS, null);

    int index = 0;
    for (Iterator<? extends Object> it = frozenRows.iterator(); it.hasNext(); ) {
      requestMap.put(var, it.next());

      if (rowIndexVar != null) {
        requestMap.put(rowIndexVar, index);
      }

      encodeRow(context, table, clientId, index, rowIndexVar);
    }

    writer.endElement("tbody");
  }
  /** {@inheritDoc} */
  public void applyFederationFilter(final Collection list, final Class objectType) {
    final Set<Long> manageableShopIds =
        shopFederationStrategy.getAccessibleShopIdsByCurrentManager();
    final Iterator<CarrierDTO> carriersIt = list.iterator();
    while (carriersIt.hasNext()) {
      final CarrierDTO carrier = carriersIt.next();

      try {
        final Map<ShopDTO, Boolean> shops =
            carrierService.getAssignedCarrierShops(carrier.getCarrierId());
        boolean manageable = false;
        for (final ShopDTO shop : shops.keySet()) {
          if (manageableShopIds.contains(shop.getShopId())) {
            manageable = true;
            break;
          }
        }

        if (!manageable) {
          carriersIt.remove();
        }
      } catch (Exception exp) {
        carriersIt.remove();
      }
    }
  }
Esempio n. 28
0
 public boolean predicate2(Object dm, Designer dsgr) {
   if (!(dm instanceof MClassifier)) return NO_PROBLEM;
   MClassifier cls = (MClassifier) dm;
   String myName = cls.getName();
   //@ if (myName.equals(Name.UNSPEC)) return NO_PROBLEM;
   String myNameString = myName;
   if (myNameString.length() == 0) return NO_PROBLEM;
   Collection pkgs = cls.getElementImports2();
   if (pkgs == null) return NO_PROBLEM;
   for (Iterator iter = pkgs.iterator(); iter.hasNext();) {
     MElementImport imp = (MElementImport)iter.next();
     MNamespace ns = imp.getPackage();
     Collection siblings = ns.getOwnedElements();
     if (siblings == null) return NO_PROBLEM;
     Iterator enum = siblings.iterator();
     while (enum.hasNext()) {
       MElementImport eo = (MElementImport) enum.next();
       MModelElement me = (MModelElement) eo.getModelElement();
       if (!(me instanceof MClassifier)) continue;
       if (me == cls) continue;
       String meName = me.getName();
       if (meName == null || meName.equals("")) continue;
       if (meName.equals(myNameString)) return PROBLEM_FOUND;
     }
   };
   return NO_PROBLEM;
 }
Esempio n. 29
0
  public static JSONObject toJson(PsSite site, String detailLevel) {
    JSONObject json = new JSONObject();
    if (site != null) {
      json.put(PsSite.ID, int2String(site.getId()));
      json.put(PsSite.NAME, site.getName());

      if (!PsApi.DETAIL_LEVEL_LOW.equals(detailLevel)) {

        json.put(PsSite.DESCRIPTION, site.getDescription());
        json.put(PsSite.STATUS, site.getStatus());

        JSONArray listOfHosts = new JSONArray();
        Collection<PsHost> listOfHostsInSite = site.getHosts();
        Iterator<PsHost> iter = listOfHostsInSite.iterator();
        while (iter.hasNext()) {
          PsHost currentHost = (PsHost) iter.next();
          if (PsApi.DETAIL_LEVEL_MEDIUM.equals(detailLevel)) {
            JSONObject currentHostJson = toJson(currentHost, PsApi.DETAIL_LEVEL_LOW);
            listOfHosts.add(currentHostJson);
          }
          if (PsApi.DETAIL_LEVEL_HIGH.equals(detailLevel)) {
            JSONObject currentHostJson = toJson(currentHost, PsApi.DETAIL_LEVEL_HIGH);
            listOfHosts.add(currentHostJson);
          }
        }
        json.put(PsSite.HOSTS, listOfHosts);
      }
    }
    return json;
  }
  /** 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;
  }