示例#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;
 }
  public Collection executeStoredProcedure(
      String sProcedureName, Vector parameters, boolean ValueObjectCollectionFlage)
      throws FrameworkDAOException {

    Collection coll = null;

    try {

      if (ValueObjectCollectionFlage) {
        coll = getConnection().executeStoredProcedure(sProcedureName, parameters, this);
      } else {
        coll = getConnection().executeStoredProcedure(sProcedureName, parameters);
      }
    } catch (Exception exc) {
      throw new FrameworkDAOException(
          "S_Framework_Entry_UIDAO:executeStoredProcedure() - " + exc, exc);
    }

    // Now check the enumeration and if there is none then log it in the base object
    if (coll.size() <= 0) {
      printMessage("S_Framework_Entry_UIDAO:executeStoredProcedure() - Collection is empty.");
    }

    return (coll);
  }
 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();
   }
 }
示例#4
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;
  }
示例#5
0
  private void handleNewExternalTransactionsInt(Collection<TransactionEx> transactions)
      throws WapiException {
    // Transform and put into two arrays with matching indexes
    ArrayList<TransactionEx> texArray = new ArrayList<TransactionEx>(transactions.size());
    ArrayList<Transaction> txArray = new ArrayList<Transaction>(transactions.size());
    for (TransactionEx tex : transactions) {
      try {
        txArray.add(Transaction.fromByteReader(new ByteReader(tex.binary)));
        texArray.add(tex);
      } catch (TransactionParsingException e) {
        // We hit a transaction that we cannot parse. Log but otherwise ignore it
        _logger.logError("Received transaction that we cannot parse: " + tex.txid.toString());
        continue;
      }
    }

    // Grab and handle parent transactions
    fetchStoreAndValidateParentOutputs(txArray);

    // Store transaction locally
    for (int i = 0; i < txArray.size(); i++) {
      _backing.putTransaction(texArray.get(i));
      onNewTransaction(texArray.get(i), txArray.get(i));
    }
  }
示例#6
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();
          }
        }
      }
    }
  }
示例#7
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;
 }
示例#8
0
  @Test
  public void testDropDatabaseWithAllTables() throws Exception {
    Map<String, List<String>> createdTablesMap = createBaseDatabaseAndTables();

    // Each time we drop one database, check all databases and their tables.
    for (String databaseName : new ArrayList<>(createdTablesMap.keySet())) {
      // drop one database
      assertTrue(catalog.existDatabase(databaseName));
      catalog.dropDatabase(databaseName);
      createdTablesMap.remove(databaseName);

      // check all tables which belong to other databases
      for (Map.Entry<String, List<String>> entry : createdTablesMap.entrySet()) {
        assertTrue(catalog.existDatabase(entry.getKey()));

        // checking all tables for this database
        Collection<String> tablesForThisDatabase = catalog.getAllTableNames(entry.getKey());
        assertEquals(createdTablesMap.get(entry.getKey()).size(), tablesForThisDatabase.size());
        for (String tableName : tablesForThisDatabase) {
          assertTrue(
              createdTablesMap
                  .get(entry.getKey())
                  .contains(IdentifierUtil.extractSimpleName(tableName)));
        }
      }
    }

    // Finally, default and system database will remain. So, its result is 1.
    assertEquals(2, catalog.getAllDatabaseNames().size());
  }
 @Nullable
 private static PyType getCallableType(@NotNull PsiElement resolved, @NotNull Context context) {
   if (resolved instanceof PySubscriptionExpression) {
     final PySubscriptionExpression subscriptionExpr = (PySubscriptionExpression) resolved;
     final PyExpression operand = subscriptionExpr.getOperand();
     final Collection<String> operandNames =
         resolveToQualifiedNames(operand, context.getTypeContext());
     if (operandNames.contains("typing.Callable")) {
       final PyExpression indexExpr = subscriptionExpr.getIndexExpression();
       if (indexExpr instanceof PyTupleExpression) {
         final PyTupleExpression tupleExpr = (PyTupleExpression) indexExpr;
         final PyExpression[] elements = tupleExpr.getElements();
         if (elements.length == 2) {
           final PyExpression parametersExpr = elements[0];
           final PyExpression returnTypeExpr = elements[1];
           if (parametersExpr instanceof PyListLiteralExpression) {
             final List<PyCallableParameter> parameters = new ArrayList<>();
             final PyListLiteralExpression listExpr = (PyListLiteralExpression) parametersExpr;
             for (PyExpression argExpr : listExpr.getElements()) {
               parameters.add(new PyCallableParameterImpl(null, getType(argExpr, context)));
             }
             final PyType returnType = getType(returnTypeExpr, context);
             return new PyCallableTypeImpl(parameters, returnType);
           }
           if (isEllipsis(parametersExpr)) {
             return new PyCallableTypeImpl(null, getType(returnTypeExpr, context));
           }
         }
       }
     }
   }
   return null;
 }
示例#10
0
  @Override
  public void removeCollection(Context context, Community community, Collection collection)
      throws SQLException, AuthorizeException, IOException {
    // Check authorisation
    authorizeService.authorizeAction(context, community, Constants.REMOVE);

    community.removeCollection(collection);
    ArrayList<String> removedIdentifiers = collectionService.getIdentifiers(context, collection);
    String removedHandle = collection.getHandle();
    UUID removedId = collection.getID();

    collection.removeCommunity(community);
    if (CollectionUtils.isEmpty(collection.getCommunities())) {
      collectionService.delete(context, collection);
    }

    log.info(
        LogManager.getHeader(
            context,
            "remove_collection",
            "community_id=" + community.getID() + ",collection_id=" + collection.getID()));

    // Remove any mappings
    context.addEvent(
        new Event(
            Event.REMOVE,
            Constants.COMMUNITY,
            community.getID(),
            Constants.COLLECTION,
            removedId,
            removedHandle,
            removedIdentifiers));
  }
 @NotNull
 private Set<VcsRef> readBranches(@NotNull GitRepository repository) {
   StopWatch sw = StopWatch.start("readBranches in " + repository.getRoot().getName());
   VirtualFile root = repository.getRoot();
   repository.update();
   Collection<GitLocalBranch> localBranches = repository.getBranches().getLocalBranches();
   Collection<GitRemoteBranch> remoteBranches = repository.getBranches().getRemoteBranches();
   Set<VcsRef> refs = new THashSet<VcsRef>(localBranches.size() + remoteBranches.size());
   for (GitLocalBranch localBranch : localBranches) {
     refs.add(
         myVcsObjectsFactory.createRef(
             localBranch.getHash(), localBranch.getName(), GitRefManager.LOCAL_BRANCH, root));
   }
   for (GitRemoteBranch remoteBranch : remoteBranches) {
     refs.add(
         myVcsObjectsFactory.createRef(
             remoteBranch.getHash(),
             remoteBranch.getNameForLocalOperations(),
             GitRefManager.REMOTE_BRANCH,
             root));
   }
   String currentRevision = repository.getCurrentRevision();
   if (currentRevision != null) { // null => fresh repository
     refs.add(
         myVcsObjectsFactory.createRef(
             HashImpl.build(currentRevision), "HEAD", GitRefManager.HEAD, root));
   }
   sw.report();
   return refs;
 }
  /** 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;
  }
示例#13
0
  /**
   * This method receives a normalized list of non-dominated solutions and return the inverted one.
   * This operation is needed for minimization problem
   *
   * @param solutionList The front to invert
   * @return The inverted front
   */
  public static <S extends Solution<?>> List<S> selectNRandomDifferentSolutions(
      int numberOfSolutionsToBeReturned, List<S> solutionList) {
    if (null == solutionList) {
      throw new JMetalException("The solution list is null");
    } else if (solutionList.size() == 0) {
      throw new JMetalException("The solution list is empty");
    } else if (solutionList.size() < numberOfSolutionsToBeReturned) {
      throw new JMetalException(
          "The solution list size ("
              + solutionList.size()
              + ") is less than "
              + "the number of requested solutions ("
              + numberOfSolutionsToBeReturned
              + ")");
    }

    JMetalRandom randomGenerator = JMetalRandom.getInstance();
    List<S> resultList = new ArrayList<>(numberOfSolutionsToBeReturned);

    if (solutionList.size() == 1) {
      resultList.add(solutionList.get(0));
    } else {
      Collection<Integer> positions = new HashSet<>(numberOfSolutionsToBeReturned);
      while (positions.size() < numberOfSolutionsToBeReturned) {
        int nextPosition = randomGenerator.nextInt(0, solutionList.size() - 1);
        if (!positions.contains(nextPosition)) {
          positions.add(nextPosition);
          resultList.add(solutionList.get(nextPosition));
        }
      }
    }

    return resultList;
  }
示例#14
0
  private static void checkForUnexpectedErrors() {
    AnalyzeExhaust exhaust =
        WholeProjectAnalyzerFacade.analyzeProjectWithCacheOnAFile((JetFile) getFile());
    Collection<Diagnostic> diagnostics = exhaust.getBindingContext().getDiagnostics();

    if (diagnostics.size() != 0) {
      String[] expectedErrorStrings =
          InTextDirectivesUtils.findListWithPrefix("// ERROR:", getFile().getText());

      System.out.println(getFile().getText());

      Collection<String> expectedErrors = new HashSet<String>(Arrays.asList(expectedErrorStrings));

      StringBuilder builder = new StringBuilder();
      boolean hasErrors = false;

      for (Diagnostic diagnostic : diagnostics) {
        if (diagnostic.getSeverity() == Severity.ERROR) {
          String errorText = IdeErrorMessages.RENDERER.render(diagnostic);
          if (!expectedErrors.contains(errorText)) {
            hasErrors = true;
            builder.append("// ERROR: ").append(errorText).append("\n");
          }
        }
      }

      Assert.assertFalse(
          "There should be no unexpected errors after applying fix (Use \"// ERROR:\" directive): \n"
              + builder.toString(),
          hasErrors);
    }
  }
 private void growCollectionIfNecessary(final Collection collection, final int index) {
   if (index >= collection.size() && index < this.autoGrowCollectionLimit) {
     for (int i = collection.size(); i <= index; i++) {
       collection.add(null);
     }
   }
 }
  /** {@inheritDoc} */
  @Override
  public final Map<UUID, GridNodeMetrics> metrics(Collection<UUID> nodeIds)
      throws GridSpiException {
    assert !F.isEmpty(nodeIds);

    long now = U.currentTimeMillis();

    Collection<UUID> expired = new LinkedList<>();

    for (UUID id : nodeIds) {
      GridNodeMetrics nodeMetrics = metricsMap.get(id);

      Long ts = tsMap.get(id);

      if (nodeMetrics == null || ts == null || ts < now - metricsExpireTime) expired.add(id);
    }

    if (!expired.isEmpty()) {
      Map<UUID, GridNodeMetrics> refreshed = metrics0(expired);

      for (UUID id : refreshed.keySet()) tsMap.put(id, now);

      metricsMap.putAll(refreshed);
    }

    return F.view(metricsMap, F.contains(nodeIds));
  }
示例#17
0
  /** Tests https://jira.jboss.org/jira/browse/JGRP-1079 for unicast messages */
  public void testOOBUnicastMessageLoss() throws Exception {
    MyReceiver receiver = new MySleepingReceiver("C2", 1000);
    b.setReceiver(receiver);

    a.getProtocolStack().getTransport().setOOBRejectionPolicy("discard");

    final int NUM = 10;
    final Address dest = b.getAddress();
    for (int i = 1; i <= NUM; i++) {
      Message msg = new Message(dest, null, i);
      msg.setFlag(Message.OOB);
      a.send(msg);
    }

    Collection<Integer> msgs = receiver.getMsgs();

    for (int i = 0; i < 20; i++) {
      if (msgs.size() == NUM) break;
      Util.sleep(1000);
      // sendStableMessages(c1,c2); // not needed for unicasts !
    }

    assert msgs.size() == NUM
        : "expected " + NUM + " messages but got " + msgs.size() + ", msgs=" + Util.print(msgs);
    for (int i = 1; i <= NUM; i++) {
      assert msgs.contains(i);
    }
  }
示例#18
0
  /** Tests https://jira.jboss.org/jira/browse/JGRP-1079 */
  public void testOOBMessageLoss() throws Exception {
    Util.close(b); // we only need 1 channel
    MyReceiver receiver = new MySleepingReceiver("C1", 1000);
    a.setReceiver(receiver);

    TP transport = a.getProtocolStack().getTransport();
    transport.setOOBRejectionPolicy("discard");

    final int NUM = 10;

    for (int i = 1; i <= NUM; i++) {
      Message msg = new Message(null, null, i);
      msg.setFlag(Message.OOB);
      a.send(msg);
    }
    STABLE stable = (STABLE) a.getProtocolStack().findProtocol(STABLE.class);
    if (stable != null) stable.runMessageGarbageCollection();
    Collection<Integer> msgs = receiver.getMsgs();

    for (int i = 0; i < 20; i++) {
      if (msgs.size() == NUM) break;
      Util.sleep(1000);
      sendStableMessages(a, b);
    }

    System.out.println("msgs = " + Util.print(msgs));

    assert msgs.size() == NUM
        : "expected " + NUM + " messages but got " + msgs.size() + ", msgs=" + Util.print(msgs);
    for (int i = 1; i <= NUM; i++) {
      assert msgs.contains(i);
    }
  }
  /**
   * This method returns nearest words for target word, based on tree structure. This method is
   * recommended to use if you're going to call for nearest words multiple times.
   *
   * @param word
   * @param n
   * @param resetTree
   * @return
   */
  protected Collection<String> wordsNearest(String word, int n, boolean resetTree) {
    if (!vocab.hasToken(word)) return new ArrayList<>();

    // build new tree if it wasnt created before, or resetTree == TRUE
    if (vpTree == null || resetTree) {
      List<DataPoint> points = new ArrayList<>();
      for (String label : vocab.words()) {
        points.add(new DataPoint(vocab.indexOf(label), getWordVectorMatrix(label)));
      }
      vpTree = new VPTree(points);
    }
    List<DataPoint> add = new ArrayList<>();
    List<Double> distances = new ArrayList<>();

    // we need n+1 to address original datapoint removal
    vpTree.search(new DataPoint(0, getWordVectorMatrix(word)), n + 1, add, distances);

    Collection<String> ret = new ArrayList<>();
    for (DataPoint e : add) {
      String label = vocab.wordAtIndex(e.getIndex());
      if (!label.equals(word)) ret.add(label);
    }

    return ret;
  }
  private void setChangeSets(BuildRun buildRun, BuildInfo info) {
    for (VcsModification change : info.getChanges()) {
      // See if we have this ChangeSet in the system.
      ChangeSetFilter filter = new ChangeSetFilter();
      String id = change.getId();

      filter.reference.add(id);
      Collection<ChangeSet> changeSetList = config.getV1Instance().get().changeSets(filter);
      if (changeSetList.isEmpty()) {
        // We don't have one yet. Create one.
        StringBuilder name = new StringBuilder();
        name.append('\'');
        name.append(change.getUserName());
        if (change.getDate() != null) {
          name.append("\' on \'");
          name.append(new DB.DateTime(change.getDate()));
        }
        name.append('\'');

        Map<String, Object> attributes = new HashMap<String, Object>();
        attributes.put("Description", change.getComment());
        ChangeSet changeSet =
            config.getV1Instance().create().changeSet(name.toString(), id, attributes);

        changeSetList = new ArrayList<ChangeSet>(1);
        changeSetList.add(changeSet);
      }

      Set<PrimaryWorkitem> workitems = determineWorkitems(change.getComment());
      associateWithBuildRun(buildRun, changeSetList, workitems);
    }
  }
示例#21
0
  @Override
  public void addCollection(Context context, Community community, Collection collection)
      throws SQLException, AuthorizeException {
    // Check authorisation
    authorizeService.authorizeAction(context, community, Constants.ADD);

    log.info(
        LogManager.getHeader(
            context,
            "add_collection",
            "community_id=" + community.getID() + ",collection_id=" + collection.getID()));

    if (!community.getCollections().contains(collection)) {
      community.addCollection(collection);
      collection.addCommunity(community);
    }
    context.addEvent(
        new Event(
            Event.ADD,
            Constants.COMMUNITY,
            community.getID(),
            Constants.COLLECTION,
            collection.getID(),
            community.getHandle(),
            getIdentifiers(context, community)));
  }
  private void associateWithBuildRun(
      BuildRun buildRun, Collection<ChangeSet> changeSets, Set<PrimaryWorkitem> workitems) {
    for (ChangeSet changeSet : changeSets) {
      buildRun.getChangeSets().add(changeSet);
      for (PrimaryWorkitem workitem : workitems) {
        if (workitem.isClosed()) {
          logger.println(MessagesRes.workitemClosedCannotAttachData(workitem.getDisplayID()));
          continue;
        }

        final Collection<BuildRun> completedIn = workitem.getCompletedIn();
        final List<BuildRun> toRemove = new ArrayList<BuildRun>(completedIn.size());

        changeSet.getPrimaryWorkitems().add(workitem);

        for (BuildRun otherRun : completedIn) {
          if (otherRun.getBuildProject().equals(buildRun.getBuildProject())) {
            toRemove.add(otherRun);
          }
        }

        for (BuildRun buildRunDel : toRemove) {
          completedIn.remove(buildRunDel);
        }

        completedIn.add(buildRun);
      }
    }
  }
示例#23
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);
  }
示例#24
0
    /** {@inheritDoc} */
    @Override
    protected Collection<GridComputeJobAdapter> split(int gridSize, Object arg)
        throws GridException {
      assert rsrc1 != null;
      assert rsrc2 != null;
      assert rsrc3 != null;
      assert rsrc4 != null;
      assert log != null;

      log.info("Injected shared resource1 into task: " + rsrc1);
      log.info("Injected shared resource2 into task: " + rsrc2);
      log.info("Injected shared resource3 into task: " + rsrc3);
      log.info("Injected shared resource4 into task: " + rsrc4);
      log.info("Injected log resource into task: " + log);

      task1Rsrc1 = rsrc1;
      task1Rsrc2 = rsrc2;
      task1Rsrc3 = rsrc3;
      task1Rsrc4 = rsrc4;

      Collection<GridComputeJobAdapter> jobs = new ArrayList<>(gridSize);

      for (int i = 0; i < gridSize; i++) {
        jobs.add(new GridSharedJob1());
      }

      return jobs;
    }
 @Nullable
 private static PyGenericType getGenericType(
     @NotNull PsiElement element, @NotNull Context context) {
   if (element instanceof PyCallExpression) {
     final PyCallExpression assignedCall = (PyCallExpression) element;
     final PyExpression callee = assignedCall.getCallee();
     if (callee != null) {
       final Collection<String> calleeQNames =
           resolveToQualifiedNames(callee, context.getTypeContext());
       if (calleeQNames.contains("typing.TypeVar")) {
         final PyExpression[] arguments = assignedCall.getArguments();
         if (arguments.length > 0) {
           final PyExpression firstArgument = arguments[0];
           if (firstArgument instanceof PyStringLiteralExpression) {
             final String name = ((PyStringLiteralExpression) firstArgument).getStringValue();
             if (name != null) {
               return new PyGenericType(name, getGenericTypeBound(arguments, context));
             }
           }
         }
       }
     }
   }
   return null;
 }
示例#26
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;
  }
示例#27
0
  @Test
  public void testCreateAndDropManyDatabases() throws Exception {
    List<String> createdDatabases = new ArrayList<>();
    InfoSchemaMetadataDictionary dictionary = new InfoSchemaMetadataDictionary();
    String namePrefix = "database_";
    final int NUM = 10;
    for (int i = 0; i < NUM; i++) {
      String databaseName = namePrefix + i;
      assertFalse(catalog.existDatabase(databaseName));
      catalog.createDatabase(databaseName, TajoConstants.DEFAULT_TABLESPACE_NAME);
      assertTrue(catalog.existDatabase(databaseName));
      createdDatabases.add(databaseName);
    }

    Collection<String> allDatabaseNames = catalog.getAllDatabaseNames();
    for (String databaseName : allDatabaseNames) {
      assertTrue(
          databaseName.equals(DEFAULT_DATABASE_NAME)
              || createdDatabases.contains(databaseName)
              || dictionary.isSystemDatabase(databaseName));
    }
    // additional ones are 'default' and 'system' databases.
    assertEquals(NUM + 2, allDatabaseNames.size());

    Collections.shuffle(createdDatabases);
    for (String tobeDropped : createdDatabases) {
      assertTrue(catalog.existDatabase(tobeDropped));
      catalog.dropDatabase(tobeDropped);
      assertFalse(catalog.existDatabase(tobeDropped));
    }
  }
  private void recheck() {
    // If this is the oldest node.
    if (oldestNode.get().id().equals(cctx.localNodeId())) {
      Collection<UUID> remaining = remaining();

      if (!remaining.isEmpty()) {
        try {
          cctx.io()
              .safeSend(
                  cctx.discovery().nodes(remaining),
                  new GridDhtPartitionsSingleRequest(exchId),
                  SYSTEM_POOL,
                  null);
        } catch (IgniteCheckedException e) {
          U.error(
              log,
              "Failed to request partitions from nodes [exchangeId="
                  + exchId
                  + ", nodes="
                  + remaining
                  + ']',
              e);
        }
      }
      // Resend full partition map because last attempt failed.
      else {
        if (spreadPartitions()) onDone(exchId.topologyVersion());
      }
    } else sendPartitions();

    // Schedule another send.
    scheduleRecheck();
  }
示例#29
0
  private void playOutExplosion(GlowPlayer player, Iterable<BlockVector> blocks) {
    Collection<ExplosionMessage.Record> records = new ArrayList<>();

    Location clientLoc = location.clone();
    clientLoc.setX((int) clientLoc.getX());
    clientLoc.setY((int) clientLoc.getY());
    clientLoc.setZ((int) clientLoc.getZ());

    for (BlockVector block : blocks) {
      byte x = (byte) (block.getBlockX() - clientLoc.getBlockX());
      byte y = (byte) (block.getBlockY() - clientLoc.getBlockY());
      byte z = (byte) (block.getBlockZ() - clientLoc.getBlockZ());
      records.add(new ExplosionMessage.Record(x, y, z));
    }

    Vector velocity = player.getVelocity();
    ExplosionMessage message =
        new ExplosionMessage(
            (float) location.getX(),
            (float) location.getY(),
            (float) location.getZ(),
            5,
            (float) velocity.getX(),
            (float) velocity.getY(),
            (float) velocity.getZ(),
            records);

    player.getSession().send(message);
  }
示例#30
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()