Exemple #1
0
 /**
  * <br>
  * <em>Purpose:</em> convenience function to build a Collection with params <br>
  * <em>Assumptions:</em> calls 'convert(text, Collection of params)'
  */
 public String convert(String text, String alttext, String p1, String p2, String p3) {
   Collection c = new LinkedList();
   c.add(p1);
   c.add(p2);
   c.add(p3);
   return convert(text, alttext, c);
 }
Exemple #2
0
  public ConfigFile(String path) throws IOException {
    filePath = path;
    charset = Charset.forName("UTF-8");
    if (!new File(path).exists()) return;

    Collection<Line> currentLines = globalLines;
    InputStreamReader isr = new InputStreamReader(new FileInputStream(path), charset);
    BufferedReader br = new BufferedReader(isr);
    try {
      String l = br.readLine();
      while (l != null) {
        // 解决跨平台文本文件换行符不同的问题
        while (!l.isEmpty()
            && (l.charAt(l.length() - 1) == '\r' || l.charAt(l.length() - 1) == '\n'))
          l = l.substring(0, l.length() - 1);

        Sector sec = parseSectorName(l);
        if (sec != null) {
          currentLines = sec.lines;
          sectors.add(sec);
        } else {
          Line line = parseLine(l);
          currentLines.add(line);
        }

        l = br.readLine();
      }
    } finally {
      br.close();
      isr.close();
    }
  }
  /**
   * @param in Object input.
   * @return Read collection.
   * @throws IOException If failed.
   * @throws ClassNotFoundException If failed.
   */
  private Collection<Object> readFieldsCollection(ObjectInput in)
      throws IOException, ClassNotFoundException {
    assert fields;

    int size = in.readInt();

    if (size == -1) return null;

    Collection<Object> res = new ArrayList<>(size);

    for (int i = 0; i < size; i++) {
      int size0 = in.readInt();

      Collection<Object> col = new ArrayList<>(size0);

      for (int j = 0; j < size0; j++) col.add(in.readObject());

      assert col.size() == size0;

      res.add(col);
    }

    assert res.size() == size;

    return res;
  }
Exemple #4
0
  public static void collectResourcesSO(Model m, Collection target) throws ModelException {

    for (Enumeration en = m.elements(); en.hasMoreElements(); ) {

      Statement st = (Statement) en.nextElement();
      if (!(st.object() instanceof Literal) && !(st.object() instanceof Statement))
        target.add(st.object());
      target.add(st.subject());
    }
  }
Exemple #5
0
  // returns list of statements
  protected static void replaceMultSPO(
      Statement st, NodeFactory f, Map o2n, Collection result, RDFNode toReplace, int position)
      throws ModelException {

    Collection replacements;

    if (toReplace instanceof Statement) {

      List l = new ArrayList();
      replaceMult((Statement) toReplace, f, o2n, l);

      if (l.size() == 1 && toReplace == l.get(0)) {
        result.add(st);
        return; // keep the same
      } else replacements = l;

    } else {

      Object ro = o2n.get(toReplace);

      if (ro instanceof Collection) replacements = (Collection) ro;
      else if (ro != null) {

        replacements = new ArrayList();
        replacements.add(ro);

      } else { // no replacement needed

        result.add(st); // keep the same statement
        return;
      }
    }

    for (Iterator it = replacements.iterator(); it.hasNext(); ) {

      Statement rs = null;
      Object rr = it.next();

      switch (position) {
        case 0:
          rs = f.createStatement((Resource) rr, st.predicate(), st.object());
          break;
        case 1:
          rs = f.createStatement(st.subject(), (Resource) rr, st.object());
          break;
        case 2:
          rs = f.createStatement(st.subject(), st.predicate(), (RDFNode) rr);
          break;
      }
      result.add(rs);
    }
  }
 private static StartOptions[] getStartOptions(int options) {
   if (options == 0) {
     return new StartOptions[0];
   }
   Collection<StartOptions> result = new ArrayList<Module.StartOptions>(2);
   if ((options & Bundle.START_TRANSIENT) != 0) {
     result.add(StartOptions.TRANSIENT);
   }
   if ((options & Bundle.START_ACTIVATION_POLICY) != 0) {
     result.add(StartOptions.USE_ACTIVATION_POLICY);
   }
   return result.toArray(new StartOptions[result.size()]);
 }
  public Collection switches() {
    Collection<CommandLineSwitch> results = new LinkedList<CommandLineSwitch>();

    // We replace values that are spaces only so Fit can detect them
    for (CommandLineSwitch cls : getCommandLine().getSwitches()) {
      if (cls instanceof SingleValueSwitch && cls.getDefaultValue().equals("    ")) {
        results.add(new SingleValueSwitch(cls.getName(), "****four spaces****", cls.isMandatory()));
      } else {
        results.add(cls);
      }
    }

    return results;
  }
  public static Collection<Statistic> merge(Collection<Statistic>... results) {
    Collection<Statistic> newResults = new ArrayList<Statistic>();
    if (results.length == 0) {
      return Collections.emptySet();
    } else if (results.length == 1) {
      return results[0];
    } else {

      List<String> indivNames = new ArrayList<String>();
      for (Collection<Statistic> result : results) {
        for (Statistic individual : result) {
          if (!indivNames.contains(individual.name)) {
            indivNames.add(individual.name);
          }
        }
      }

      for (String indivName : indivNames) {
        Statistic indivStat = new Statistic(indivName);
        for (Collection<Statistic> result : results) {
          for (Statistic individual : result) {
            if (indivName.equals(individual.name)) {
              indivStat.add(individual);
            }
          }
        }
        newResults.add(indivStat);
      }
      return newResults;
    }
  }
  /** {@inheritDoc} */
  @Override
  public void explicitUndeploy(UUID nodeId, String rsrcName) {
    Collection<SharedDeployment> undeployed = new LinkedList<SharedDeployment>();

    synchronized (mux) {
      for (Iterator<List<SharedDeployment>> i1 = cache.values().iterator(); i1.hasNext(); ) {
        List<SharedDeployment> deps = i1.next();

        for (Iterator<SharedDeployment> i2 = deps.iterator(); i2.hasNext(); ) {
          SharedDeployment dep = i2.next();

          if (dep.hasName(rsrcName)) {
            if (!dep.isUndeployed()) {
              dep.undeploy();

              dep.onRemoved();

              // Undeploy.
              i2.remove();

              undeployed.add(dep);

              if (log.isInfoEnabled()) log.info("Undeployed per-version class loader: " + dep);
            }

            break;
          }
        }

        if (deps.isEmpty()) i1.remove();
      }
    }

    recordUndeployed(null, undeployed);
  }
  /** {@inheritDoc} */
  @Override
  protected Collection<E> dequeue0(int cnt) {
    WindowHolder tup = ref.get();

    AtomicInteger size = tup.size();
    Collection<T> evts = tup.collection();

    Collection<E> resCol = new ArrayList<>(cnt);

    while (true) {
      int curSize = size.get();

      if (curSize > 0) {
        if (size.compareAndSet(curSize, curSize - 1)) {
          E res = pollInternal(evts, tup.set());

          if (res != null) {
            resCol.add(res);

            if (resCol.size() >= cnt) return resCol;
          } else {
            size.incrementAndGet();

            return resCol;
          }
        }
      } else return resCol;
    }
  }
 /**
  * Sort changes by roots
  *
  * @param changes a change list
  * @param exceptions exceptions to collect
  * @return sorted changes
  */
 private static Map<VirtualFile, Collection<Change>> sortChangesByGitRoot(
     @NotNull List<Change> changes, List<VcsException> exceptions) {
   Map<VirtualFile, Collection<Change>> result = new HashMap<VirtualFile, Collection<Change>>();
   for (Change change : changes) {
     final ContentRevision afterRevision = change.getAfterRevision();
     final ContentRevision beforeRevision = change.getBeforeRevision();
     // nothing-to-nothing change cannot happen.
     assert beforeRevision != null || afterRevision != null;
     // note that any path will work, because changes could happen within single vcs root
     final FilePath filePath =
         afterRevision != null ? afterRevision.getFile() : beforeRevision.getFile();
     final VirtualFile vcsRoot;
     try {
       // the parent paths for calculating roots in order to account for submodules that contribute
       // to the parent change. The path "." is never is valid change, so there should be no
       // problem
       // with it.
       vcsRoot = GitUtil.getGitRoot(filePath.getParentPath());
     } catch (VcsException e) {
       exceptions.add(e);
       continue;
     }
     Collection<Change> changeList = result.get(vcsRoot);
     if (changeList == null) {
       changeList = new ArrayList<Change>();
       result.put(vcsRoot, changeList);
     }
     changeList.add(change);
   }
   return result;
 }
Exemple #12
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;
    }
Exemple #13
0
  /* process call edge constraint */
  public void process(CallConstraint c) {
    Node csrc = c.ncaller.getRep();
    Node cdst = c.ncallee.getRep();
    assert (cdst.graph == this);

    if (heapfix && csrc.graph == this && !csrc.isheap && cdst.isheap)
      w.addFirst(new UnifyConstraint(csrc, cdst));

    Collection<CallEdge> ced = cedges.get(c.call);
    if (ced != null)
      for (CallEdge e : ced) {
        Node esrc = e.src.getRep();
        Node edst = e.dst.getRep();
        if (edst == cdst && e.call.equals(c.call)) {
          if (esrc != csrc) {
            Graph g = esrc.graph;
            assert (g != this || !Options.mergeGraphs.value);
            g.w.addFirst(new UnifyConstraint(esrc, csrc));
          }
          return;
        }
      }
    else {
      ced = new ArrayList<CallEdge>();
      cedges.put(c.call, ced);
    }

    ced.add(new CallEdge(csrc, cdst, c.call));
  }
  /** {@inheritDoc} */
  @SuppressWarnings("TypeMayBeWeakened")
  @Nullable
  private Collection<Object> unmarshalFieldsCollection(
      @Nullable Collection<byte[]> byteCol, GridCacheContext<K, V> ctx, ClassLoader ldr)
      throws GridException {
    assert ctx != null;
    assert ldr != null;

    Collection<Object> col = unmarshalCollection(byteCol, ctx, ldr);
    Collection<Object> col0 = null;

    if (col != null) {
      col0 = new ArrayList<>(col.size());

      for (Object o : col) {
        List<Object> list = (List<Object>) o;
        List<Object> list0 = new ArrayList<>(list.size());

        for (Object obj : list)
          list0.add(obj != null ? ctx.marshaller().unmarshal((byte[]) obj, ldr) : null);

        col0.add(list0);
      }
    }

    return col0;
  }
 /*
  * Parses the data in the given input stream as a sequence of DER encoded
  * X.509 CRLs (in binary or base 64 encoded format) OR as a single PKCS#7
  * encoded blob (in binary or base 64 encoded format).
  */
 private Collection<? extends java.security.cert.CRL> parseX509orPKCS7CRL(InputStream is)
     throws CRLException, IOException {
   Collection<X509CRLImpl> coll = new ArrayList<>();
   byte[] data = readOneBlock(is);
   if (data == null) {
     return new ArrayList<>(0);
   }
   try {
     PKCS7 pkcs7 = new PKCS7(data);
     X509CRL[] crls = pkcs7.getCRLs();
     // CRLs are optional in PKCS #7
     if (crls != null) {
       return Arrays.asList(crls);
     } else {
       // no crls provided
       return new ArrayList<>(0);
     }
   } catch (ParsingException e) {
     while (data != null) {
       coll.add(new X509CRLImpl(data));
       data = readOneBlock(is);
     }
   }
   return coll;
 }
Exemple #16
0
 /**
  * @param sector 为 null 时指代文件起首的全局 sector(无名称)
  * @return null,则没有找到相应sector
  */
 public Collection<String> listKeys(String sector) {
   Collection<Line> lines = getSectorLines(sector);
   if (lines == null) return null;
   Collection<String> ret = new ArrayList<String>();
   for (Line l : lines) ret.add(l.key);
   return ret;
 }
  /**
   * @param key Key to add to read set.
   * @param val Value.
   * @param drVer Data center replication version.
   * @param skipStore Skip store flag.
   * @throws IgniteCheckedException If failed.
   * @return {@code True} if entry has been enlisted.
   */
  public boolean addEntry(
      GridCacheContext cacheCtx,
      IgniteTxKey key,
      GridCacheOperation op,
      CacheObject val,
      @Nullable GridCacheVersion drVer,
      boolean skipStore)
      throws IgniteCheckedException {
    checkInternal(key);

    GridNearCacheEntry cached = cacheCtx.near().peekExx(key.key());

    try {
      if (cached == null) {
        evicted.add(key);

        return false;
      } else {
        cached.unswap();

        CacheObject peek = cached.peek(true, false, false, null);

        if (peek == null && cached.evictInternal(false, xidVer, null)) {
          cached.context().cache().removeIfObsolete(key.key());

          evicted.add(key);

          return false;
        } else {
          IgniteTxEntry txEntry =
              new IgniteTxEntry(cacheCtx, this, op, val, -1L, -1L, cached, drVer, skipStore);

          writeMap.put(key, txEntry);

          return true;
        }
      }
    } catch (GridCacheEntryRemovedException ignore) {
      evicted.add(key);

      if (log.isDebugEnabled())
        log.debug(
            "Got removed entry when adding reads to remote transaction (will ignore): " + cached);

      return false;
    }
  }
  @Override
  public AbstractFile[] ls() throws IOException, UnsupportedFileOperationException {
    List<GuestFileInfo> fileInfos = new ArrayList<GuestFileInfo>();
    int index = 0;
    VsphereConnHandler connHandler = null;
    try {

      connHandler = getConnHandler();

      ManagedObjectReference fileManager = getFileManager(connHandler);
      boolean haveRemaining;
      do {
        GuestListFileInfo res =
            connHandler
                .getClient()
                .getVimPort()
                .listFilesInGuest(fileManager, vm, credentials, getPathInVm(), index, null, null);
        haveRemaining = (res.getRemaining() != 0);

        fileInfos.addAll(res.getFiles());
        index = fileInfos.size();
      } while (haveRemaining);

      String parentPath = PathUtils.removeTrailingSeparator(fileURL.getPath()) + SEPARATOR;

      Collection<AbstractFile> res = new ArrayList<AbstractFile>();
      for (GuestFileInfo f : fileInfos) {
        final String name = getFileName(f.getPath());
        if (name.equals(".") || name.equals("..")) {
          continue;
        }

        FileURL childURL = (FileURL) fileURL.clone();
        childURL.setPath(parentPath + name);

        AbstractFile newFile = new VSphereFile(childURL, this, f);
        res.add(newFile);
      }
      return res.toArray(new AbstractFile[0]);
    } catch (FileFaultFaultMsg e) {
      translateandLogException(e);
    } catch (GuestOperationsFaultFaultMsg e) {
      translateandLogException(e);
    } catch (InvalidStateFaultMsg e) {
      translateandLogException(e);
    } catch (RuntimeFaultFaultMsg e) {
      translateandLogException(e);
    } catch (TaskInProgressFaultMsg e) {
      translateandLogException(e);
    } catch (InvalidPropertyFaultMsg e) {
      translateandLogException(e);
    } catch (URISyntaxException e) {
      translateandLogException(e);
    } finally {
      releaseConnHandler(connHandler);
    }
    // we never get here..
    return null;
  }
  /**
   * The added suite will be always executed locally, but in parallel with other locally or remotely
   * running tests. This comes handy for tests that cannot be distributed for some environmental
   * reasons, but still would benefit from parallel execution.
   *
   * <p>Note, that local suites will be executed on local node even if grid topology only allows
   * remote nodes.
   *
   * @param localSuite Test to execute locally in parallel with other local or distributed tests.
   */
  @SuppressWarnings({"TypeMayBeWeakened"})
  public void addTest(GridJunit3LocalTestSuite localSuite) {
    if (!locTests.contains(localSuite.getName())) {
      locTests.add(localSuite.getName());
    }

    addTest((Test) localSuite);
  }
Exemple #20
0
 /**
  * Determines all files and folders that belong to a given project and adds them to the supplied
  * Collection.
  *
  * @param filteredFiles destination collection of Files
  * @param project project to examine
  */
 public static void addProjectFiles(
     Collection filteredFiles,
     Collection rootFiles,
     Collection rootFilesExclusions,
     Project project) {
   FileStatusCache cache = CvsVersioningSystem.getInstance().getStatusCache();
   Sources sources = ProjectUtils.getSources(project);
   SourceGroup[] sourceGroups = sources.getSourceGroups(Sources.TYPE_GENERIC);
   for (int j = 0; j < sourceGroups.length; j++) {
     SourceGroup sourceGroup = sourceGroups[j];
     FileObject srcRootFo = sourceGroup.getRootFolder();
     File rootFile = FileUtil.toFile(srcRootFo);
     try {
       getCVSRootFor(rootFile);
     } catch (IOException e) {
       // the folder is not under a versioned root
       continue;
     }
     rootFiles.add(rootFile);
     boolean containsSubprojects = false;
     FileObject[] rootChildren = srcRootFo.getChildren();
     Set projectFiles = new HashSet(rootChildren.length);
     for (int i = 0; i < rootChildren.length; i++) {
       FileObject rootChildFo = rootChildren[i];
       if (CvsVersioningSystem.FILENAME_CVS.equals(rootChildFo.getNameExt())) continue;
       File child = FileUtil.toFile(rootChildFo);
       // #67900 Added special treatment for .cvsignore files
       if (sourceGroup.contains(rootChildFo)
           || CvsVersioningSystem.FILENAME_CVSIGNORE.equals(rootChildFo.getNameExt())) {
         // TODO: #60516 deep scan is required here but not performed due to performace reasons
         projectFiles.add(child);
       } else {
         int status = cache.getStatus(child).getStatus();
         if (status != FileInformation.STATUS_NOTVERSIONED_EXCLUDED) {
           rootFilesExclusions.add(child);
           containsSubprojects = true;
         }
       }
     }
     if (containsSubprojects) {
       filteredFiles.addAll(projectFiles);
     } else {
       filteredFiles.add(rootFile);
     }
   }
 }
  /** {@inheritDoc} */
  @Override
  public synchronized Iterable<String> getGroupNames() {
    Collection<String> res = new HashSet<>();

    for (HadoopCounter counter : cntrs.values()) res.add(counter.group());

    return res;
  }
Exemple #22
0
  public static void collectPredicates(Model m, Collection target) throws ModelException {

    for (Enumeration en = m.elements(); en.hasMoreElements(); ) {

      Statement st = (Statement) en.nextElement();
      target.add(st.predicate());
    }
  }
Exemple #23
0
 public void startServer() throws Exception {
   while (true) {
     Socket s = server.accept();
     cClient.add(new ClientConn(s));
     ta.append("NEW-CLIENT " + s.getInetAddress() + ":" + s.getPort());
     ta.append("\n" + "CLIENTS-COUNT: " + cClient.size() + "\n\n");
   }
 }
Exemple #24
0
 private static void addInField(Node n, Field f, FieldEdge e) {
   Collection<FieldEdge> s = n.infields.get(f);
   if (s == null) {
     s = new ArrayList<FieldEdge>();
     n.infields.put(f, s);
   }
   s.add(e);
 }
Exemple #25
0
  /** {@inheritDoc} */
  @Override
  public Collection<UUID> nodeIds() {
    Collection<UUID> ids = new GridLeanSet<UUID>();

    ids.add(cctx.nodeId());
    ids.addAll(mappings.keySet());

    return ids;
  }
  /**
   * 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();
  }
  /**
   * @param entry Entry to enlist.
   * @throws IgniteCheckedException If failed.
   * @return {@code True} if entry was enlisted.
   */
  private boolean addEntry(IgniteTxEntry entry) throws IgniteCheckedException {
    checkInternal(entry.txKey());

    GridCacheContext cacheCtx = entry.context();

    if (!cacheCtx.isNear()) cacheCtx = cacheCtx.dht().near().context();

    GridNearCacheEntry cached = cacheCtx.near().peekExx(entry.key());

    if (cached == null) {
      evicted.add(entry.txKey());

      return false;
    } else {
      cached.unswap();

      try {
        CacheObject val = cached.peek(true, false, false, null);

        if (val == null && cached.evictInternal(false, xidVer, null)) {
          evicted.add(entry.txKey());

          return false;
        } else {
          // Initialize cache entry.
          entry.cached(cached);

          writeMap.put(entry.txKey(), entry);

          addExplicit(entry);

          return true;
        }
      } catch (GridCacheEntryRemovedException ignore) {
        evicted.add(entry.txKey());

        if (log.isDebugEnabled())
          log.debug("Got removed entry when adding to remote transaction (will ignore): " + cached);

        return false;
      }
    }
  }
 public Collection<String[]> findAnswers(
     int question, boolean right, Collection<String[]> students) {
   Collection<String[]> peeps = new LinkedList<String[]>();
   for (String[] person : students) {
     if ((person[question].equals(key[question])) == right) {
       peeps.add(person);
     }
   }
   return peeps;
 }
    /** {@inheritDoc} */
    @Override
    public Collection<? extends ComputeJob> split(int gridSize, Serializable arg) {
      if (log.isInfoEnabled())
        log.info("Splitting task [task=" + this + ", gridSize=" + gridSize + ", arg=" + arg + ']');

      Collection<GridCancelTestJob> jobs = new ArrayList<>(SPLIT_COUNT);

      for (int i = 0; i < SPLIT_COUNT; i++) jobs.add(new GridCancelTestJob());

      return jobs;
    }
 private static Collection<Node> getNodeMatching(Node body, String regexp) {
   final Collection<Node> nodes = new ArrayList<>();
   if (body.getNodeName().matches(regexp)) nodes.add(body);
   if (body.getChildNodes().getLength() == 0) return nodes;
   NodeList returnList = body.getChildNodes();
   for (int k = 0; k < returnList.getLength(); k++) {
     final Node node = returnList.item(k);
     nodes.addAll(getNodeMatching(node, regexp));
   }
   return nodes;
 }