public static void main(String[] args) {

    Collection<String> collection = new HashSet<String>();
    collection.add("one");
    collection.add("two");

    Iterator<String> iterator = collection.iterator();
    while (iterator.hasNext()) {
      String s = iterator.next();
      System.out.println(s);
    }
    System.out.println("======================================");

    TreeSet<String> set = new TreeSet<String>(collection);
    Iterator<String> itor = set.iterator();
    while (itor.hasNext()) {
      System.out.println(itor.next());
    }

    Collection<String> colList = new ArrayList<String>();
    colList.add("one");
    colList.add("two");
    colList.add("three");

    if (colList.containsAll(collection)) {
      System.out.println("true");
    }

    System.out.println("=================");

    String[] strings = colList.toArray(new String[0]);
    String[] strings1 = (String[]) colList.toArray();
  }
  // FIXME: does not integrate with recursive session method calls: recursionEnter/Exit and also
  // recurse do not match the control flow of recursive calls, and hence runtime type monitoring
  // does not work.
  private Node translateSJRecursion(SJRecursion r, QQ qq)
        // recursionEnter inserted by node factory, but translation is finished here..
      {
    SJSessionOperationExt soe = getSJSessionOperationExt(r);

    Position pos = r.position();

    Collection<Object> mapping = new LinkedList<Object>();

    String bname = getRecursionBooleanName(soe.targetNames(), r.label());

    mapping.add(bname);
    mapping.add(bname);

    String translation = "for (boolean %s = true; %s; ) { }";
    For f = (For) qq.parseStmt(translation, mapping.toArray());

    mapping.clear();

    r = (SJRecursion) r.inits(f.inits());
    r = (SJRecursion) r.cond(f.cond());

    List stmts = new LinkedList();

    stmts.addAll(r.body().statements());

    translation = "%s = %E;";
    mapping.add(bname);
    mapping.add(((Eval) stmts.remove(0)).expr()); // Factor out constant.

    Eval e = (Eval) qq.parseStmt(translation, mapping.toArray());

    stmts.add(0, e);

    r = (SJRecursion) r.body(sjnf.Block(pos, stmts));

    /*// Appending the recursion-exit hook. // Disabled to support delegation from within recursion scopes (socket will be null on recursion-exit).
    List<Local> targets = new LinkedList<Local>(); // FIXME: should be SJLocalSockets.

    for (String sjname : soe.targetNames()) // Unicast optimisation for SJRecursionExit is done within the NodeFactory method - this pass comes after SJUnicastOptimiser.
    {
    	targets.add(sjnf.Local(pos, sjnf.Id(pos, sjname))); // Would it be bad to instead alias the recursionEnter targets?
    }

    SJRecursionExit re = sjnf.SJRecursionExit(pos, targets); // Problem: the sockets argument array is not yet filled (for other (internal) basic operations, this was done earlier by SJSessionOperationParser)...

    re = (SJRecursionExit) SJVariableParser.parseSJSessionOperation(this, re); // ...Current fix: use those routines form those earlier passes.
    re = (SJRecursionExit) SJSessionOperationParser.fixSJBasicOperationArguments(this, re);*/

    // return sjnf.Block(pos, r, sjnf.Eval(pos, re));
    return sjnf.Block(pos, r);
  }
  @NotNull
  private static PsiSubstitutor replaceVariables(Collection<InferenceVariable> inferenceVariables) {
    final List<InferenceVariable> targetVars = new ArrayList<InferenceVariable>();
    PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
    final InferenceVariable[] oldVars =
        inferenceVariables.toArray(new InferenceVariable[inferenceVariables.size()]);
    for (InferenceVariable variable : oldVars) {
      final InferenceVariable newVariable =
          new InferenceVariable(
              variable.getCallContext(), variable.getParameter(), variable.getName());
      substitutor =
          substitutor.put(
              variable,
              JavaPsiFacade.getElementFactory(variable.getProject()).createType(newVariable));
      targetVars.add(newVariable);
      if (variable.isThrownBound()) {
        newVariable.setThrownBound();
      }
    }

    for (int i = 0; i < targetVars.size(); i++) {
      InferenceVariable var = targetVars.get(i);
      for (InferenceBound boundType : InferenceBound.values()) {
        for (PsiType bound : oldVars[i].getBounds(boundType)) {
          var.addBound(substitutor.substitute(bound), boundType, null);
        }
      }
    }
    return substitutor;
  }
  private Node translateSJInbranch(SJInbranch ib, QQ qq) {
    StringBuilder translation = new StringBuilder("{ ");
    Collection<Object> mapping = new LinkedList<Object>();

    String labVar = UniqueID.newID(SJ_INBRANCH_LABEL_FIELD_PREFIX);

    translation.append("%T %s = %E; ");
    mapping.add(qq.parseType(SJ_LABEL_CLASS));
    mapping.add(labVar);
    mapping.add(ib.inlabel());

    for (Iterator<SJInbranchCase> i = ib.branchCases().iterator(); i.hasNext(); ) {
      SJInbranchCase ibc = i.next();

      translation.append("if (%s.equals(%E)) { %LS } ");
      mapping.add(labVar);
      mapping.add(sjnf.StringLit(ib.position(), ibc.label().labelValue()));
      mapping.add(ibc.statements());

      if (i.hasNext()) {
        translation.append("else ");
      }
    }

    translation.append("else { throw new SJIOException(\"Unexpected inbranch label: \" + %s); }");
    mapping.add(labVar);

    // FIXME: need a final else case to better handle, if runtime monitoring is disabled,
    // non-sj-compatibility mode and in case of malicious peers.

    translation.append('}');

    return qq.parseStmt(translation.toString(), mapping.toArray());
  }
Exemple #5
0
  private static void testPotato(
      Class<? extends Collection> implClazz, Class<? extends List> argClazz) throws Throwable {
    try {
      System.out.printf("implClazz=%s, argClazz=%s\n", implClazz.getName(), argClazz.getName());
      final int iterations = 100000;
      final List<Integer> list = (List<Integer>) argClazz.newInstance();
      final Integer one = Integer.valueOf(1);
      final List<Integer> oneElementList = Collections.singletonList(one);
      final Constructor<? extends Collection> constr = implClazz.getConstructor(Collection.class);
      final Thread t =
          new CheckedThread() {
            public void realRun() {
              for (int i = 0; i < iterations; i++) {
                list.add(one);
                list.remove(one);
              }
            }
          };
      t.setDaemon(true);
      t.start();

      for (int i = 0; i < iterations; i++) {
        Collection<?> coll = constr.newInstance(list);
        Object[] elts = coll.toArray();
        check(elts.length == 0 || (elts.length == 1 && elts[0] == one));
      }
    } catch (Throwable t) {
      unexpected(t);
    }
  }
Exemple #6
0
  @Test
  public void testCookies_whenCookiesArePresent() {

    Collection<Cookie> cookies = new ArrayList<>();
    cookies.add(new Cookie("cookie1", "cookie1value"));
    cookies.add(new Cookie("cookie2", "cookie2value"));

    Map<String, String> expected = new HashMap<>();
    for (Cookie cookie : cookies) {
      expected.put(cookie.getName(), cookie.getValue());
    }

    Cookie[] cookieArray = cookies.toArray(new Cookie[cookies.size()]);

    when(servletRequest.getCookies()).thenReturn(cookieArray);

    assertTrue(
        "The count of cookies returned should be the same as those in the request",
        request.cookies().size() == 2);

    assertEquals(
        "A Map of Cookies should have been returned because they exist",
        expected,
        request.cookies());
  }
  @Nullable
  public static PsiClass[] getAllTestClasses(final TestClassFilter filter, boolean sync) {
    final PsiClass[][] holder = new PsiClass[1][];
    final Runnable process =
        () -> {
          final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();

          final Collection<PsiClass> set = new LinkedHashSet<>();
          final PsiManager manager = PsiManager.getInstance(filter.getProject());
          final GlobalSearchScope projectScope =
              GlobalSearchScope.projectScope(manager.getProject());
          final GlobalSearchScope scope = projectScope.intersectWith(filter.getScope());
          for (final PsiClass psiClass : AllClassesSearch.search(scope, manager.getProject())) {
            if (filter.isAccepted(psiClass)) {
              if (indicator != null) {
                indicator.setText2(
                    "Found test class " + ReadAction.compute(psiClass::getQualifiedName));
              }
              set.add(psiClass);
            }
          }
          holder[0] = set.toArray(new PsiClass[set.size()]);
        };
    if (sync) {
      ProgressManager.getInstance()
          .runProcessWithProgressSynchronously(
              process, "Searching For Tests...", true, filter.getProject());
    } else {
      process.run();
    }
    return holder[0];
  }
Exemple #8
0
  /**
   * Set an array parameter.<br>
   * See {@link #addParameter(String, Object...)} for details
   */
  public Query addParameter(String name, final Collection<?> values) {
    if (values == null) {
      throw new NullPointerException("Array parameter cannot be null");
    }

    return addParameter(name, values.toArray());
  }
Exemple #9
0
 /**
  * Constructs a vector containing the elements of the specified collection, in the order they are
  * returned by the collection's iterator.
  *
  * @param c the collection whose elements are to be placed into this vector
  * @throws NullPointerException if the specified collection is null
  * @since 1.2
  */
 public Vector(Collection<? extends E> c) {
   elementData = c.toArray();
   elementCount = elementData.length;
   // c.toArray might (incorrectly) not return Object[] (see 6260652)
   if (elementData.getClass() != Object[].class)
     elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
 }
Exemple #10
0
  /**
   * Update all known Provisioners of the new ResourceCapability
   *
   * @param resourceCapability The ResourceCapability object
   * @param deployedServices List of deployed services
   */
  void updateMonitors(
      ResourceCapability resourceCapability, List<DeployedService> deployedServices) {
    ProvisionLeaseManager[] mgrs;
    synchronized (leaseTable) {
      Collection<ProvisionLeaseManager> c = leaseTable.values();
      mgrs = c.toArray(new ProvisionLeaseManager[c.size()]);
    }
    if (mgrs == null) return;
    if (mgrs.length == 0) return;

    for (ProvisionLeaseManager mgr : mgrs) {
      try {
        mgr.provisioner.update(
            adapter.getInstantiator(), resourceCapability, deployedServices, serviceLimit);
      } catch (Throwable t) {
        if (logger.isLoggable(Level.FINEST))
          logger.log(Level.FINEST, "Updating ProvisionManager", t);
        boolean connected = false;

        /* Determine if we should even try to reconnect */
        final int category = ThrowableConstants.retryable(t);
        if (category == ThrowableConstants.INDEFINITE
            || category == ThrowableConstants.UNCATEGORIZED) {
          connected = mgr.reconnect();
        }

        if (!connected) {
          removeProvisionManager(mgr.provisioner, mgr.serviceID);
        }
      }
    }
  }
  /**
   * add a collection
   *
   * @param index
   * @param c a collection to add
   * @return true if the collection was modified
   */
  public boolean addAll(int index, Collection c) {
    if (c != null) {
      if (this.collection == null) this.collection = this.initCollection();
      boolean modified = false;
      int i = index;
      for (Iterator it = c.iterator(); it.hasNext(); ) {
        Object object = it.next();
        if (this.itemAllowed(object)) {
          this.add(i++, object);
        }
      }
      /* fire event */
      int[] positions = new int[c.size()];
      for (int j = 0; j < c.size(); j++) positions[j] = j + index;
      this.firePropertyChange(
          new ContentChangeEvent(
              this,
              PROPERTY_CONTENT,
              ContentChangeEvent.ADD,
              positions,
              (AbstractSibType[]) c.toArray(new AbstractSibType[] {})));

      return modified;
    }
    return false;
  }
 /**
  * @param databaseTableDescription - table for columns actually in the database
  * @param configColumns - column names of configurated columns
  */
 private void checkUnknownColumns(
     TableDescription databaseTableDescription, String[] configColumns) {
   Collection<String> c = getUnmappedColumns(databaseTableDescription.getTableName());
   String[] unmappedColumns = c.toArray(new String[0]);
   // check that unmapped columns exist in database
   for (String unmapped : c) {
     assertTrue(
         "Column: "
             + databaseTableDescription.getTableName()
             + "."
             + unmapped
             + " [declared as unknown, but] not in database",
         databaseTableDescription.getColumn(unmapped) != null);
   }
   String[] dbColumns = databaseTableDescription.getColumnNames();
   for (String theDbColumn : dbColumns) {
     if (!containsIgnoreCase(unmappedColumns, theDbColumn)) {
       assertTrue(
           "Table "
               + databaseTableDescription.getTableName()
               + " contains unknown column: '"
               + theDbColumn
               + "'",
           containsIgnoreCase(configColumns, theDbColumn));
     }
   }
 }
  public int run(String[] args) throws Exception {
    Configuration conf = getConf();
    Collection<String> topWords = parseTopWords(conf);
    String[] topWordsArr = topWords.toArray(new String[topWords.size()]);
    conf.setStrings(TOP_WORDS_KEY, topWordsArr);

    Job job = new Job(conf);
    job.setJarByClass(InversedIndexTool.class);
    job.setJobName("inversed_index");

    job.setMapOutputKeyClass(Text.class);
    job.setMapOutputValueClass(ArticleNameAndFrequency.class);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(ArticleNameAndFrequency.class);

    job.setMapperClass(Map.class);

    job.setInputFormatClass(TextInputFormat.class);
    job.setOutputFormatClass(TextOutputFormat.class);

    job.setNumReduceTasks(0);

    FileInputFormat.setInputPaths(job, inputPath);
    FileOutputFormat.setOutputPath(job, outputPath);
    boolean success = job.waitForCompletion(true);

    articlesCount = job.getCounters().findCounter(Counters.ARTICLE_COUNTER).getValue();
    return success ? 0 : 1;
  }
Exemple #14
0
 /**
  * This returns an enumeration of all Darts in Graph G in a canonical order starting with
  * firstDart. The order is canonical in the sense that it only depends on the oriented isomorphism
  * class of G (and firstDart). That is, if there is an oriented iso G <-> G' sending firstDart <->
  * firstDart', then that bijection will send getDarts <-> getDarts'.
  *
  * <p>This enumeration is useful in finding explicit bijections of isomorphic graphs.
  */
 public static Dart[] getDarts(Dart firstDart, Graph G) {
   /**
    * Description of algorithm: Return all the couples around V0=firstDart.V, then all couples
    * around V1, .... The order for couples around firstDart.V is counterclockwise starting with
    * firstDart.F. clockwise around V1,... So we need to order the vertices V0,V1,... and pick the
    * first face to use at each vertex and the rest is determined. Order on V0,... = first
    * encountered. Order on faces at vertex = first encountered.
    */
   distinctFIFO vQueue = new distinctFIFO();
   util.ConditionGetter fQueue = new util.ConditionGetter();
   fQueue.add(firstDart.getF());
   vQueue.put(firstDart.getV());
   Collection coups = new ArrayList();
   int coupsIndex = 0;
   Vertex V;
   while ((V = (Vertex) vQueue.remove()) != null) {
     Face F = (Face) fQueue.get(new incidence(V));
     for (int i = 0; i < V.size(); i++) {
       Face Fx = V.next(F, i);
       coups.add(new Dart(V, Fx));
       vQueue.put(Fx.next(V, 1));
       fQueue.add(Fx);
     }
   }
   return (Dart[]) coups.toArray(new Dart[coups.size()]);
 }
  public AddGradleDslPluginAction() {
    getTemplatePresentation()
        .setDescription(GradleBundle.message("gradle.codeInsight.action.apply_plugin.description"));
    getTemplatePresentation()
        .setText(GradleBundle.message("gradle.codeInsight.action.apply_plugin.text"));
    getTemplatePresentation().setIcon(GradleIcons.GradlePlugin);

    Collection<KeyValue> pluginDescriptions = new ArrayList<KeyValue>();
    for (GradlePluginDescriptionsExtension extension :
        GradlePluginDescriptionsExtension.EP_NAME.getExtensions()) {
      for (Map.Entry<String, String> pluginDescription :
          extension.getPluginDescriptions().entrySet()) {
        pluginDescriptions.add(
            KeyValue.create(pluginDescription.getKey(), pluginDescription.getValue()));
      }
    }

    myPlugins = pluginDescriptions.toArray(new KeyValue[pluginDescriptions.size()]);
    Arrays.sort(
        myPlugins,
        new Comparator<KeyValue>() {
          @Override
          public int compare(KeyValue o1, KeyValue o2) {
            return String.valueOf(o1.getKey()).compareTo(String.valueOf(o2.getKey()));
          }
        });
  }
 private String[] getStringProperty(String name, Object value) {
   // Don't log a warning if the value is null. The filter guarantees at least one of the necessary
   // properties
   // is there. If others are not, this method will get called with value equal to null.
   if (value == null) return new String[0];
   if (value instanceof String) {
     return new String[] {(String) value};
   }
   if (value instanceof String[]) {
     return (String[]) value;
   }
   Exception e = null;
   if (value instanceof Collection) {
     @SuppressWarnings("unchecked")
     Collection<String> temp = (Collection<String>) value;
     try {
       return temp.toArray(new String[temp.size()]);
     } catch (ArrayStoreException ase) {
       e = ase;
     }
   }
   log.log(
       LogService.LOG_WARNING,
       NLS.bind(
           MetaTypeMsg.INVALID_PID_METATYPE_PROVIDER_IGNORED,
           new Object[] {_bundle.getSymbolicName(), _bundle.getBundleId(), name, value}),
       e);
   return new String[0];
 }
Exemple #17
0
 /**
  * Returns the file representing the Git repository directory for the given file path or any of
  * its parent in the filesystem. If the file doesn't exits, is not a Git repository or an error
  * occurred while transforming the given path into a store <code>null</code> is returned.
  *
  * @param path expected format /file/{Workspace}/{projectName}[/{path}]
  * @return the .git folder if found or <code>null</code> the give path cannot be resolved to a
  *     file or it's not under control of a git repository
  * @throws CoreException
  */
 public static File getGitDir(IPath path) throws CoreException {
   Map<IPath, File> gitDirs = GitUtils.getGitDirs(path, Traverse.GO_UP);
   if (gitDirs == null) return null;
   Collection<File> values = gitDirs.values();
   if (values.isEmpty()) return null;
   return values.toArray(new File[] {})[0];
 }
  @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;
  }
Exemple #19
0
  private static void copyCollection(
      Object target,
      String[] effectiveProperties,
      String[] ignoreProperties,
      Boolean nullBeCopied,
      PropertyDescriptor targetPd,
      Object sourceValue,
      Method writeMethod)
      throws IllegalAccessException, InvocationTargetException, UtilException,
          ClassNotFoundException, InstantiationException, NoSuchFieldException {
    Method targetReadMethod = targetPd.getReadMethod();
    Collection targetValue = (Collection) targetReadMethod.invoke(target, null);
    List tempList = new ArrayList();
    if (sourceValue == null) {
      writeMethod.invoke(target, sourceValue);
      return;
    }
    if (targetValue == null) {
      if (Set.class.isAssignableFrom(targetPd.getPropertyType())) {
        targetValue = new HashSet();
      } else if (List.class.isAssignableFrom(targetPd.getPropertyType())) {
        targetValue = new ArrayList();
      } else {
        return;
      }
    }
    Object[] sourceArray = ((Collection) sourceValue).toArray();
    Object[] targetArray = targetValue.toArray();
    for (int i = 0; i < sourceArray.length; i++) {
      if (targetValue.contains(sourceArray[i])) {
        for (int j = 0; j < targetArray.length; j++) {
          if (sourceArray[i].equals(targetArray[j])) {
            copyProperties(
                sourceArray[i],
                targetArray[j],
                effectiveProperties,
                ignoreProperties,
                nullBeCopied);
            tempList.add(targetArray[j]);
            break;
          }
        }
      } else {
        Object tempTarget = Class.forName(sourceArray[i].getClass().getName()).newInstance();
        // 基本类型直接赋值
        if (sourceArray[i].getClass().isPrimitive() || sourceArray[i] instanceof String) {
          tempTarget = sourceArray[i];
        } else {
          copyProperties(
              sourceArray[i], tempTarget, effectiveProperties, ignoreProperties, nullBeCopied);
        }

        tempList.add(tempTarget);
      }
    }
    targetValue.clear();
    targetValue.addAll(tempList);
    return;
  }
  /**
   * Makes <tt>RTCPSDES</tt> packets for all the RTP streams that we're sending.
   *
   * @return a <tt>List</tt> of <tt>RTCPSDES</tt> packets for all the RTP streams that we're
   *     sending.
   */
  private RTCPSDESPacket makeSDESPacket() {
    Collection<RTCPSDES> sdesChunks = new ArrayList<RTCPSDES>();

    // Create an SDES for our own SSRC.
    RTCPSDES ownSDES = new RTCPSDES();

    SSRCInfo ourinfo = getStream().getStreamRTPManager().getSSRCCache().ourssrc;
    ownSDES.ssrc = (int) getLocalSSRC();
    Collection<RTCPSDESItem> ownItems = new ArrayList<RTCPSDESItem>();
    ownItems.add(new RTCPSDESItem(RTCPSDESItem.CNAME, ourinfo.sourceInfo.getCNAME()));

    // Throttle the source description bandwidth. See RFC3550#6.3.9
    // Allocation of Source Description Bandwidth.

    if (sdesCounter % 3 == 0) {
      if (ourinfo.name != null && ourinfo.name.getDescription() != null)
        ownItems.add(new RTCPSDESItem(RTCPSDESItem.NAME, ourinfo.name.getDescription()));
      if (ourinfo.email != null && ourinfo.email.getDescription() != null)
        ownItems.add(new RTCPSDESItem(RTCPSDESItem.EMAIL, ourinfo.email.getDescription()));
      if (ourinfo.phone != null && ourinfo.phone.getDescription() != null)
        ownItems.add(new RTCPSDESItem(RTCPSDESItem.PHONE, ourinfo.phone.getDescription()));
      if (ourinfo.loc != null && ourinfo.loc.getDescription() != null)
        ownItems.add(new RTCPSDESItem(RTCPSDESItem.LOC, ourinfo.loc.getDescription()));
      if (ourinfo.tool != null && ourinfo.tool.getDescription() != null)
        ownItems.add(new RTCPSDESItem(RTCPSDESItem.TOOL, ourinfo.tool.getDescription()));
      if (ourinfo.note != null && ourinfo.note.getDescription() != null)
        ownItems.add(new RTCPSDESItem(RTCPSDESItem.NOTE, ourinfo.note.getDescription()));
    }

    sdesCounter++;

    ownSDES.items = ownItems.toArray(new RTCPSDESItem[ownItems.size()]);

    sdesChunks.add(ownSDES);

    for (Map.Entry<Integer, byte[]> entry : cnameRegistry.entrySet()) {
      RTCPSDES sdes = new RTCPSDES();
      sdes.ssrc = entry.getKey();
      sdes.items = new RTCPSDESItem[] {new RTCPSDESItem(RTCPSDESItem.CNAME, entry.getValue())};
    }

    RTCPSDES[] sps = sdesChunks.toArray(new RTCPSDES[sdesChunks.size()]);
    RTCPSDESPacket sp = new RTCPSDESPacket(sps);

    return sp;
  }
Exemple #21
0
 private static String[] toStringArray(Collection coll) {
   Object[] objArray = coll.toArray();
   String[] strArray = new String[objArray.length];
   for (int i = 0; i < objArray.length; i++) {
     strArray[i] = (String) objArray[i];
   }
   return strArray;
 }
 @Override
 public CompilerMessage[] getMessages(CompilerMessageCategory category) {
   Collection<CompilerMessage> collection = myMessages.get(category);
   if (collection == null) {
     return CompilerMessage.EMPTY_ARRAY;
   }
   return collection.toArray(new CompilerMessage[collection.size()]);
 }
Exemple #23
0
  private static void copyClassesImpl(
      final String copyClassName,
      final Project project,
      final Map<PsiFile, PsiClass[]> classes,
      final HashMap<PsiFile, String> map,
      final Object targetDirectory,
      final PsiDirectory defaultTargetDirectory,
      final String commandName,
      final boolean selectInActivePanel,
      final boolean openInEditor) {
    final boolean[] result = new boolean[] {false};
    Runnable command =
        () -> {
          final Runnable action =
              () -> {
                try {
                  PsiDirectory target;
                  if (targetDirectory instanceof PsiDirectory) {
                    target = (PsiDirectory) targetDirectory;
                  } else {
                    target =
                        ((MoveDestination) targetDirectory)
                            .getTargetDirectory(defaultTargetDirectory);
                  }
                  Collection<PsiFile> files =
                      doCopyClasses(classes, map, copyClassName, target, project);
                  if (files != null) {
                    if (openInEditor) {
                      for (PsiFile file : files) {
                        CopyHandler.updateSelectionInActiveProjectView(
                            file, project, selectInActivePanel);
                      }
                      EditorHelper.openFilesInEditor(files.toArray(new PsiFile[files.size()]));
                    }

                    result[0] = true;
                  }
                } catch (final IncorrectOperationException ex) {
                  ApplicationManager.getApplication()
                      .invokeLater(
                          () ->
                              Messages.showMessageDialog(
                                  project,
                                  ex.getMessage(),
                                  RefactoringBundle.message("error.title"),
                                  Messages.getErrorIcon()));
                }
              };
          ApplicationManager.getApplication().runWriteAction(action);
        };
    CommandProcessor processor = CommandProcessor.getInstance();
    processor.executeCommand(project, command, commandName, null);

    if (result[0]) {
      ToolWindowManager.getInstance(project)
          .invokeLater(() -> ToolWindowManager.getInstance(project).activateEditorComponent());
    }
  }
 @SuppressWarnings("unchecked")
 private void evaluateProvidedArtefacts() {
   Object result =
       GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, PROVIDED_ARTEFACTS);
   if (result instanceof Collection) {
     final Collection artefactList = (Collection) result;
     providedArtefacts = (Class<?>[]) artefactList.toArray(new Class[artefactList.size()]);
   }
 }
Exemple #25
0
 /**
  * Returns an {@link Iterator} over a {@link Collection} of Throwable types which iterates over
  * its elements in a consistent order (maintaining an ordering that is consistent across different
  * runs makes it easier to compare sets generated by different implementations of the CFG
  * classes).
  *
  * @param coll The collection to iterate over.
  * @return An iterator which presents the elements of <code>coll</code> in order.
  */
 private static Iterator sortedThrowableIterator(Collection coll) {
   if (coll.size() <= 1) {
     return coll.iterator();
   } else {
     Object array[] = coll.toArray();
     Arrays.sort(array, new ThrowableComparator());
     return Arrays.asList(array).iterator();
   }
 }
Exemple #26
0
 /**
  * Appends all of the elements in the specified Collection to the end of this Vector, in the order
  * that they are returned by the specified Collection's Iterator. The behavior of this operation
  * is undefined if the specified Collection is modified while the operation is in progress. (This
  * implies that the behavior of this call is undefined if the specified Collection is this Vector,
  * and this Vector is nonempty.)
  *
  * @param c elements to be inserted into this Vector
  * @return {@code true} if this Vector changed as a result of the call
  * @throws NullPointerException if the specified collection is null
  * @since 1.2
  */
 public synchronized boolean addAll(Collection<? extends E> c) {
   modCount++;
   Object[] a = c.toArray();
   int numNew = a.length;
   ensureCapacityHelper(elementCount + numNew);
   System.arraycopy(a, 0, elementData, elementCount, numNew);
   elementCount += numNew;
   return numNew != 0;
 }
  /**
   * Return a query that will return docs like the passed lucene document ID.
   *
   * @param docNum the documentID of the lucene doc to generate the 'More Like This" query for.
   * @return a query that will return docs like the passed lucene document ID.
   */
  public Query like(int docNum) throws IOException {
    if (fieldNames == null) {
      // gather list of valid fields from lucene
      Collection<String> fields = MultiFields.getIndexedFields(ir);
      fieldNames = fields.toArray(new String[fields.size()]);
    }

    return createQuery(retrieveTerms(docNum));
  }
Exemple #28
0
 public NSArray(Collection<T> c) {
   super((SkipInit) null);
   if (c instanceof NSArray) {
     initObject(objc_initWithArray(this, initWithArray$, (NSArray<T>) c));
   } else {
     NSObject[] objects = c.toArray(new NSObject[c.size()]);
     initWithObjects(objects);
   }
 }
Exemple #29
0
    public PortalIterator(final PortalManager manager) {
      this.manager = manager;

      Collection<ABPortal> p = manager.allPortals.values();
      portals = p.toArray(new ABPortal[p.size()]);

      index = -1;
      last = null;
    }
 public static CompileScope createScopeWithArtifacts(
     final CompileScope baseScope,
     @NotNull Collection<Artifact> artifacts,
     boolean useCustomContentId) {
   baseScope.putUserData(ARTIFACTS_KEY, artifacts.toArray(new Artifact[artifacts.size()]));
   if (useCustomContentId) {
     baseScope.putUserData(CompilerManager.CONTENT_ID_KEY, ARTIFACTS_CONTENT_ID_KEY);
   }
   return baseScope;
 }