/** {@inheritDoc} */
  @Override
  public Map<K, V> peekAll(
      @Nullable Collection<? extends K> keys,
      @Nullable GridPredicate<? super GridCacheEntry<K, V>>[] filter) {
    if (keys == null || keys.isEmpty()) return emptyMap();

    final Collection<K> skipped = new GridLeanSet<K>();

    final Map<K, V> map = peekAll0(keys, filter, skipped);

    if (map.size() + skipped.size() != keys.size()) {
      map.putAll(
          dht.peekAll(
              F.view(
                  keys,
                  new P1<K>() {
                    @Override
                    public boolean apply(K k) {
                      return !map.containsKey(k) && !skipped.contains(k);
                    }
                  }),
              filter));
    }

    return map;
  }
Ejemplo n.º 2
0
  public static JpsRemoteProto.Message.Request createCompileRequest(
      final JpsRemoteProto.Message.Request.CompilationRequest.Type command,
      String project,
      Collection<String> modules,
      Collection<String> artifacts,
      Map<String, String> userData,
      Collection<String> paths) {

    final JpsRemoteProto.Message.Request.CompilationRequest.Builder builder =
        JpsRemoteProto.Message.Request.CompilationRequest.newBuilder().setCommandType(command);
    builder.setProjectId(project);
    if (!modules.isEmpty()) {
      builder.addAllModuleName(modules);
    }
    if (!artifacts.isEmpty()) {
      builder.addAllArtifactName(artifacts);
    }
    if (!userData.isEmpty()) {
      for (Map.Entry<String, String> entry : userData.entrySet()) {
        final String key = entry.getKey();
        final String value = entry.getValue();
        if (key != null && value != null) {
          builder.addBuilderParameter(createPair(key, value));
        }
      }
    }
    if (!paths.isEmpty()) {
      builder.addAllFilePath(paths);
    }
    return JpsRemoteProto.Message.Request.newBuilder()
        .setRequestType(JpsRemoteProto.Message.Request.Type.COMPILE_REQUEST)
        .setCompileRequest(builder.build())
        .build();
  }
  private List<HighlightInfo> getHighlights() {
    if (myReadAccessRanges.isEmpty() && myWriteAccessRanges.isEmpty()) {
      return Collections.emptyList();
    }
    Set<Pair<Object, TextRange>> existingMarkupTooltips = new HashSet<Pair<Object, TextRange>>();
    for (RangeHighlighter highlighter : myEditor.getMarkupModel().getAllHighlighters()) {
      existingMarkupTooltips.add(
          Pair.create(
              highlighter.getErrorStripeTooltip(),
              new TextRange(highlighter.getStartOffset(), highlighter.getEndOffset())));
    }

    List<HighlightInfo> result =
        new ArrayList<HighlightInfo>(myReadAccessRanges.size() + myWriteAccessRanges.size());
    for (TextRange range : myReadAccessRanges) {
      ContainerUtil.addIfNotNull(
          createHighlightInfo(
              range, HighlightInfoType.ELEMENT_UNDER_CARET_READ, existingMarkupTooltips),
          result);
    }
    for (TextRange range : myWriteAccessRanges) {
      ContainerUtil.addIfNotNull(
          createHighlightInfo(
              range, HighlightInfoType.ELEMENT_UNDER_CARET_WRITE, existingMarkupTooltips),
          result);
    }
    return result;
  }
 /**
  * Update index (delete and remove files)
  *
  * @param project the project
  * @param root a vcs root
  * @param added added/modified files to commit
  * @param removed removed files to commit
  * @param exceptions a list of exceptions to update
  * @return true if index was updated successfully
  */
 private static boolean updateIndex(
     final Project project,
     final VirtualFile root,
     final Collection<FilePath> added,
     final Collection<FilePath> removed,
     final List<VcsException> exceptions) {
   boolean rc = true;
   if (!added.isEmpty()) {
     try {
       GitFileUtils.addPaths(project, root, added);
     } catch (VcsException ex) {
       exceptions.add(ex);
       rc = false;
     }
   }
   if (!removed.isEmpty()) {
     try {
       GitFileUtils.delete(project, root, removed, "--ignore-unmatch");
     } catch (VcsException ex) {
       exceptions.add(ex);
       rc = false;
     }
   }
   return rc;
 }
  private boolean merge(boolean mergeDialogInvokedFromNotification) {
    try {
      final Collection<VirtualFile> initiallyUnmergedFiles = getUnmergedFiles(myRoots);
      if (initiallyUnmergedFiles.isEmpty()) {
        LOG.info("merge: no unmerged files");
        return mergeDialogInvokedFromNotification ? true : proceedIfNothingToMerge();
      } else {
        showMergeDialog(initiallyUnmergedFiles);

        final Collection<VirtualFile> unmergedFilesAfterResolve = getUnmergedFiles(myRoots);
        if (unmergedFilesAfterResolve.isEmpty()) {
          LOG.info("merge no more unmerged files");
          return mergeDialogInvokedFromNotification ? true : proceedAfterAllMerged();
        } else {
          LOG.info("mergeFiles unmerged files remain: " + unmergedFilesAfterResolve);
          if (mergeDialogInvokedFromNotification) {
            notifyUnresolvedRemainAfterNotification();
          } else {
            notifyUnresolvedRemain();
          }
        }
      }
    } catch (VcsException e) {
      if (myVcs.getExecutableValidator().checkExecutableAndNotifyIfNeeded()) {
        notifyException(e);
      }
    }
    return false;
  }
  /**
   * Removes locks regardless of whether they are owned or not for given version and keys.
   *
   * @param ver Lock version.
   * @param keys Keys.
   */
  @SuppressWarnings({"unchecked"})
  public void removeLocks(GridCacheVersion ver, Collection<? extends K> keys) {
    if (keys.isEmpty()) return;

    Collection<GridRichNode> nodes = ctx.remoteNodes(keys);

    try {
      // Send request to remove from remote nodes.
      GridDistributedUnlockRequest<K, V> req = new GridDistributedUnlockRequest<K, V>(keys.size());

      req.version(ver);

      for (K key : keys) {
        while (true) {
          GridDistributedCacheEntry<K, V> entry = peekexx(key);

          try {
            if (entry != null) {
              GridCacheMvccCandidate<K> cand = entry.candidate(ver);

              if (cand != null) {
                // Remove candidate from local node first.
                if (entry.removeLock(cand.version())) {
                  // If there is only local node in this lock's topology,
                  // then there is no reason to distribute the request.
                  if (nodes.isEmpty()) continue;

                  req.addKey(entry.key(), entry.getOrMarshalKeyBytes(), ctx);
                }
              }
            }

            break;
          } catch (GridCacheEntryRemovedException ignored) {
            if (log.isDebugEnabled())
              log.debug(
                  "Attempted to remove lock from removed entry (will retry) [rmvVer="
                      + ver
                      + ", entry="
                      + entry
                      + ']');
          }
        }
      }

      if (nodes.isEmpty()) return;

      req.completedVersions(ctx.tm().committedVersions(ver), ctx.tm().rolledbackVersions(ver));

      if (!req.keyBytes().isEmpty())
        // We don't wait for reply to this message.
        ctx.io().safeSend(nodes, req, null);
    } catch (GridException ex) {
      U.error(log, "Failed to unlock the lock for keys: " + keys, ex);
    }
  }
  @SuppressWarnings("squid:S1244")
  private static String selectBestEncoding(String acceptEncodingHeader) {
    // multiple encodings are accepted; determine best one

    Collection<String> bestEncodings = new HashSet<>(3);
    double bestQ = 0.0;
    Collection<String> unacceptableEncodings = new HashSet<>(3);
    boolean willAcceptAnything = false;

    for (String token : COMMA.split(acceptEncodingHeader)) {
      ContentEncodingQ contentEncodingQ = parseContentEncodingQ(token);
      String contentEncoding = contentEncodingQ.getContentEncoding();
      double q = contentEncodingQ.getQ();
      if (ANY_ENCODING.equals(contentEncoding)) {
        willAcceptAnything = q > 0.0;
      } else if (SUPPORTED_ENCODINGS.contains(contentEncoding)) {
        if (q > 0.0) {
          // This is a header quality comparison.
          // So it is safe to suppress warning squid:S1244
          if (q == bestQ) {
            bestEncodings.add(contentEncoding);
          } else if (q > bestQ) {
            bestQ = q;
            bestEncodings.clear();
            bestEncodings.add(contentEncoding);
          }
        } else {
          unacceptableEncodings.add(contentEncoding);
        }
      }
    }

    if (bestEncodings.isEmpty()) {
      // nothing was acceptable to us
      if (willAcceptAnything) {
        if (unacceptableEncodings.isEmpty()) {
          return SUPPORTED_ENCODINGS.get(0);
        } else {
          for (String encoding : SUPPORTED_ENCODINGS) {
            if (!unacceptableEncodings.contains(encoding)) {
              return encoding;
            }
          }
        }
      }
    } else {
      for (String encoding : SUPPORTED_ENCODINGS) {
        if (bestEncodings.contains(encoding)) {
          return encoding;
        }
      }
    }

    return NO_ENCODING;
  }
  private void processDeletedFiles(Project project) {
    final List<Pair<FilePath, WorkingCopyFormat>> deletedFiles =
        new ArrayList<Pair<FilePath, WorkingCopyFormat>>();
    final Collection<FilePath> filesToProcess = new ArrayList<FilePath>();
    List<VcsException> exceptions = new ArrayList<VcsException>();
    final AbstractVcsHelper vcsHelper = AbstractVcsHelper.getInstance(project);

    try {
      fillDeletedFiles(project, deletedFiles, filesToProcess);
      if (deletedFiles.isEmpty() && filesToProcess.isEmpty() || myUndoingMove) return;
      SvnVcs vcs = SvnVcs.getInstance(project);
      final VcsShowConfirmationOption.Value value = vcs.getDeleteConfirmation().getValue();
      if (value != VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY) {
        if (!deletedFiles.isEmpty()) {
          final Collection<FilePath> confirmed =
              promptAboutDeletion(deletedFiles, vcs, value, vcsHelper);
          if (confirmed != null) {
            filesToProcess.addAll(confirmed);
          }
        }
        if (filesToProcess != null && !filesToProcess.isEmpty()) {
          runInBackground(
              project,
              "Deleting files from Subversion",
              createDeleteRunnable(project, vcs, filesToProcess, exceptions));
        }
        final List<FilePath> deletedFilesFiles =
            ObjectsConvertor.convert(
                deletedFiles,
                new Convertor<Pair<FilePath, WorkingCopyFormat>, FilePath>() {
                  @Override
                  public FilePath convert(Pair<FilePath, WorkingCopyFormat> o) {
                    return o.getFirst();
                  }
                });
        for (FilePath file : deletedFilesFiles) {
          final FilePath parent = file.getParentPath();
          if (parent != null) {
            myFilesToRefresh.add(parent.getVirtualFile());
          }
        }
        if (filesToProcess != null) {
          deletedFilesFiles.removeAll(filesToProcess);
        }
        for (FilePath file : deletedFilesFiles) {
          FileUtil.delete(file.getIOFile());
        }
      }
    } catch (SVNException e) {
      exceptions.add(new VcsException(e));
    }
    if (!exceptions.isEmpty()) {
      vcsHelper.showErrors(exceptions, SvnBundle.message("delete.files.errors.title"));
    }
  }
Ejemplo n.º 9
0
  /** Return class names form jet sources in given scope which should be visible as Java classes. */
  @NotNull
  @Override
  public PsiClass[] getClassesByName(
      @NotNull @NonNls String name, @NotNull GlobalSearchScope scope) {
    List<PsiClass> result = new ArrayList<PsiClass>();

    IDELightClassGenerationSupport lightClassGenerationSupport =
        IDELightClassGenerationSupport.getInstanceForIDE(project);
    MultiMap<String, FqName> packageClasses =
        lightClassGenerationSupport.getAllPackageClasses(scope);

    // .namespace classes can not be indexed, since they have no explicit declarations
    Collection<FqName> fqNames = packageClasses.get(name);
    if (!fqNames.isEmpty()) {
      for (FqName fqName : fqNames) {
        PsiClass psiClass =
            JavaElementFinder.getInstance(project).findClass(fqName.getFqName(), scope);
        if (psiClass != null) {
          result.add(psiClass);
        }
      }
    }

    // Quick check for classes from getAllClassNames()
    Collection<JetClassOrObject> classOrObjects =
        JetShortClassNameIndex.getInstance().get(name, project, scope);
    if (classOrObjects.isEmpty()) {
      return result.toArray(new PsiClass[result.size()]);
    }

    for (JetClassOrObject classOrObject : classOrObjects) {
      FqName fqName = JetPsiUtil.getFQName(classOrObject);
      if (fqName != null) {
        assert fqName.shortName().getName().equals(name)
            : "A declaration obtained from index has non-matching name:\n"
                + "in index: "
                + name
                + "\n"
                + "declared: "
                + fqName.shortName()
                + "("
                + fqName
                + ")";
        PsiClass psiClass =
            JavaElementFinder.getInstance(project).findClass(fqName.getFqName(), scope);
        if (psiClass != null) {
          result.add(psiClass);
        }
      }
    }

    return result.toArray(new PsiClass[result.size()]);
  }
  @SmallTest
  @MediumTest
  @LargeTest
  public void testCollectionIsEmpty() throws JSONException {
    JSONArray array = new JSONArray();

    Collection<Integer> collection = GraphObject.Factory.createList(array, Integer.class);
    assertTrue(collection.isEmpty());

    array.put(5);
    assertFalse(collection.isEmpty());
  }
 private void checkOverwrites(final Project project) {
   final Collection<AddedFileInfo> addedFileInfos = myAddedFiles.get(project);
   final Collection<File> deletedFiles = myDeletedFiles.get(project);
   if (addedFileInfos.isEmpty() || deletedFiles.isEmpty()) return;
   final Iterator<AddedFileInfo> iterator = addedFileInfos.iterator();
   while (iterator.hasNext()) {
     AddedFileInfo addedFileInfo = iterator.next();
     final File ioFile = new File(addedFileInfo.myDir.getPath(), addedFileInfo.myName);
     if (deletedFiles.remove(ioFile)) {
       iterator.remove();
     }
   }
 }
Ejemplo n.º 12
0
 public boolean isIncluded(final Node node) {
   if (node.isRootNode()) {
     return true;
   }
   if (includedCategories.isEmpty() && includedProperties.isEmpty()) {
     return true;
   } else if (containsAny(node.getCategories(), includedCategories)) {
     return true;
   } else if (includedProperties.contains(node.getPropertyPath())) {
     return true;
   }
   return false;
 }
Ejemplo n.º 13
0
  public boolean process(String[] args, BytecodeReader reader, JavaParser parser) {
    program.initBytecodeReader(reader);
    program.initJavaParser(parser);

    initOptions();
    processArgs(args);

    Collection files = program.options().files();

    if (program.options().hasOption("-version")) {
      printVersion();
      return false;
    }
    if (program.options().hasOption("-help") || files.isEmpty()) {
      printUsage();
      return false;
    }

    try {
      for (Iterator iter = files.iterator(); iter.hasNext(); ) {
        String name = (String) iter.next();
        if (!new File(name).exists())
          System.err.println("WARNING: file \"" + name + "\" does not exist");
        program.addSourceFile(name);
      }

      for (Iterator iter = program.compilationUnitIterator(); iter.hasNext(); ) {
        CompilationUnit unit = (CompilationUnit) iter.next();
        if (unit.fromSource()) {
          Collection errors = unit.parseErrors();
          Collection warnings = new LinkedList();
          // compute static semantic errors when there are no parse errors or
          // the recover from parse errors option is specified
          if (errors.isEmpty() || program.options().hasOption("-recover"))
            unit.errorCheck(errors, warnings);
          if (!errors.isEmpty()) {
            processErrors(errors, unit);
            return false;
          } else {
            if (!warnings.isEmpty()) processWarnings(warnings, unit);
            processNoErrors(unit);
          }
        }
      }
    } catch (Exception e) {
      System.err.println(e.getMessage());
      e.printStackTrace();
    }
    return true;
  }
Ejemplo n.º 14
0
  @NotNull
  public static <H> H selectMostSpecificMember(
      @NotNull Collection<H> overridables,
      @NotNull Function1<H, CallableDescriptor> descriptorByHandle) {
    assert !overridables.isEmpty() : "Should have at least one overridable descriptor";

    if (overridables.size() == 1) {
      return CollectionsKt.first(overridables);
    }

    Collection<H> candidates = new ArrayList<H>(2);
    List<CallableDescriptor> callableMemberDescriptors =
        CollectionsKt.map(overridables, descriptorByHandle);

    H transitivelyMostSpecific = CollectionsKt.first(overridables);
    CallableDescriptor transitivelyMostSpecificDescriptor =
        descriptorByHandle.invoke(transitivelyMostSpecific);

    for (H overridable : overridables) {
      CallableDescriptor descriptor = descriptorByHandle.invoke(overridable);
      if (isMoreSpecificThenAllOf(descriptor, callableMemberDescriptors)) {
        candidates.add(overridable);
      }
      if (isMoreSpecific(descriptor, transitivelyMostSpecificDescriptor)
          && !isMoreSpecific(transitivelyMostSpecificDescriptor, descriptor)) {
        transitivelyMostSpecific = overridable;
      }
    }

    if (candidates.isEmpty()) {
      return transitivelyMostSpecific;
    } else if (candidates.size() == 1) {
      return CollectionsKt.first(candidates);
    }

    H firstNonFlexible = null;
    for (H candidate : candidates) {
      //noinspection ConstantConditions
      if (!FlexibleTypesKt.isFlexible(descriptorByHandle.invoke(candidate).getReturnType())) {
        firstNonFlexible = candidate;
        break;
      }
    }
    if (firstNonFlexible != null) {
      return firstNonFlexible;
    }

    return CollectionsKt.first(candidates);
  }
Ejemplo n.º 15
0
  @Override
  public boolean removeAll(Collection<?> collection) {
    if (collection.isEmpty()) {
      return false;
    }

    if (collection instanceof EnumSet) {
      EnumSet<?> set = (EnumSet<?>) collection;
      if (!isValidType(set.elementClass)) {
        return false;
      }

      HugeEnumSet<E> hugeSet = (HugeEnumSet<E>) set;
      boolean changed = false;
      for (int i = 0; i < bits.length; i++) {
        long oldBits = bits[i];
        long newBits = oldBits & ~hugeSet.bits[i];
        if (oldBits != newBits) {
          bits[i] = newBits;
          size += Long.bitCount(newBits) - Long.bitCount(oldBits);
          changed = true;
        }
      }
      return changed;
    }
    return super.removeAll(collection);
  }
Ejemplo n.º 16
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} */
  @Override
  public Map<K, V> peekAll(
      @Nullable Collection<? extends K> keys, @Nullable Collection<GridCachePeekMode> modes)
      throws GridException {
    if (keys == null || keys.isEmpty()) return emptyMap();

    final Collection<K> skipped = new GridLeanSet<K>();

    final Map<K, V> map =
        !modes.contains(PARTITIONED_ONLY)
            ? peekAll0(keys, modes, ctx.tm().localTxx(), skipped)
            : new GridLeanMap<K, V>(0);

    if (map.size() != keys.size() && !modes.contains(NEAR_ONLY)) {
      map.putAll(
          dht.peekAll(
              F.view(
                  keys,
                  new P1<K>() {
                    @Override
                    public boolean apply(K k) {
                      return !map.containsKey(k) && !skipped.contains(k);
                    }
                  }),
              modes));
    }

    return map;
  }
  public void checkLineMarkers(
      @NotNull Collection<LineMarkerInfo> markerInfos, @NotNull String text) {
    String fileName = myFile == null ? "" : myFile.getName() + ": ";
    String failMessage = "";

    for (LineMarkerInfo info : markerInfos) {
      if (!containsLineMarker(info, myLineMarkerInfos.values())) {
        if (!failMessage.isEmpty()) failMessage += '\n';
        failMessage +=
            fileName
                + "Extra line marker highlighted "
                + rangeString(text, info.startOffset, info.endOffset)
                + ": '"
                + info.getLineMarkerTooltip()
                + "'";
      }
    }

    for (LineMarkerInfo expectedLineMarker : myLineMarkerInfos.values()) {
      if (!markerInfos.isEmpty() && !containsLineMarker(expectedLineMarker, markerInfos)) {
        if (!failMessage.isEmpty()) failMessage += '\n';
        failMessage +=
            fileName
                + "Line marker was not highlighted "
                + rangeString(text, expectedLineMarker.startOffset, expectedLineMarker.endOffset)
                + ": '"
                + expectedLineMarker.getLineMarkerTooltip()
                + "'";
      }
    }

    if (!failMessage.isEmpty()) Assert.fail(failMessage);
  }
Ejemplo n.º 19
0
  private void applyStart(GridJob job) {

    String fullJobId = job.getFullJobId();
    Collection<JobActor> actors = jobActorMap.get(fullJobId);
    if (actors.isEmpty()) {
      JobActor jobActor = createJobActor(job);
      addJobActor(fullJobId, jobActor);
      actors = jobActorMap.get(fullJobId);
    }

    if (job.getNode() == null) {
      log.warn("No node for job being started: {}", fullJobId);
      return;
    }

    log.debug("Starting job {} on {}", fullJobId, job.getNode().getShortName());

    String nodeName = job.getNode().getShortName();
    if (actors.size() > 1) {
      log.warn("More than one actor for job being started: " + fullJobId);
    }

    JobActor jobActor = actors.iterator().next();

    int i = 0;
    GridJob[] nodeJobs = job.getNode().getSlots();
    for (int s = 0; s < nodeJobs.length; s++) {
      GridJob nodeJob = nodeJobs[s];
      if (nodeJob == null) continue;
      if (!nodeJob.getFullJobId().equals(fullJobId)) continue;

      if (i > 0) {
        jobActor = cloneJobActor(fullJobId);
      }

      PVector endPos = getLatticePos(nodeName, s + "");
      // TODO: random outside location in direction of vector from 0,0,0
      PVector startPos = new PVector(1000, 1000, 1000);
      jobActor.pos = startPos;

      if (tweenChanges) {
        // scale duration to the distance that needs to be traveled
        float distance = jobActor.pos.dist(endPos);
        float duration = (DURATION_JOB_START * distance / DISTANCE_JOB_START) * 0.6f;

        Tween tween =
            new Tween("start_job_" + fullJobId + "#" + i, getTweenDuration(duration))
                .addPVector(jobActor.pos, endPos)
                .call(jobActor, "jobStarted")
                .setEasing(Tween.SINE_OUT)
                .noAutoUpdate();

        jobActor.tweens.add(tween);
      } else {
        jobActor.pos.set(endPos);
      }

      i++;
    }
  }
Ejemplo n.º 20
0
  private AgentInstance[] getAgentInstancesForStmt(
      String statementId, ContextPartitionSelector selector) {
    Collection<Integer> agentInstanceIds = getAgentInstanceIds(selector);
    if (agentInstanceIds == null || agentInstanceIds.isEmpty()) {
      return new AgentInstance[0];
    }

    List<AgentInstance> instances = new ArrayList<AgentInstance>(agentInstanceIds.size());
    for (Integer agentInstanceId : agentInstanceIds) {
      ContextControllerTreeAgentInstanceList instancesList = agentInstances.get(agentInstanceId);
      if (instancesList != null) {
        Iterator<AgentInstance> instanceIt = instancesList.getAgentInstances().iterator();
        for (; instanceIt.hasNext(); ) {
          AgentInstance instance = instanceIt.next();
          if (instance
              .getAgentInstanceContext()
              .getStatementContext()
              .getStatementId()
              .equals(statementId)) {
            instances.add(instance);
          }
        }
      }
    }
    return instances.toArray(new AgentInstance[instances.size()]);
  }
Ejemplo n.º 21
0
  private boolean confirmClose(String action, Collection modifiedLayers) {
    if (modifiedLayers.isEmpty()) {
      return true;
    }

    JOptionPane pane =
        new JOptionPane(
            StringUtil.split(
                modifiedLayers.size()
                    + " dataset"
                    + StringUtil.s(modifiedLayers.size())
                    + " "
                    + ((modifiedLayers.size() > 1) ? "have" : "has")
                    + " been modified ("
                    + ((modifiedLayers.size() > 3) ? "e.g. " : "")
                    + StringUtil.toCommaDelimitedString(
                        new ArrayList(modifiedLayers)
                            .subList(0, Math.min(3, modifiedLayers.size())))
                    + "). Continue?",
                80),
            JOptionPane.WARNING_MESSAGE);
    pane.setOptions(new String[] {action, "Cancel"});
    pane.createDialog(this, AppContext.getMessage("GeopistaName")).setVisible(true);

    return pane.getValue().equals(action);
  }
  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);
    }
  }
  /** {@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));
  }
Ejemplo n.º 24
0
 @Nullable
 public static Visibility findMaxVisibility(
     @NotNull Collection<? extends CallableMemberDescriptor> descriptors) {
   if (descriptors.isEmpty()) {
     return Visibilities.DEFAULT_VISIBILITY;
   }
   Visibility maxVisibility = null;
   for (CallableMemberDescriptor descriptor : descriptors) {
     Visibility visibility = descriptor.getVisibility();
     assert visibility != Visibilities.INHERITED
         : "Visibility should have been computed for " + descriptor;
     if (maxVisibility == null) {
       maxVisibility = visibility;
       continue;
     }
     Integer compareResult = Visibilities.compare(visibility, maxVisibility);
     if (compareResult == null) {
       maxVisibility = null;
     } else if (compareResult > 0) {
       maxVisibility = visibility;
     }
   }
   if (maxVisibility == null) {
     return null;
   }
   for (CallableMemberDescriptor descriptor : descriptors) {
     Integer compareResult = Visibilities.compare(maxVisibility, descriptor.getVisibility());
     if (compareResult == null || compareResult < 0) {
       return null;
     }
   }
   return maxVisibility;
 }
Ejemplo n.º 25
0
  /**
   * Makes WikiText from a Collection.
   *
   * @param links Collection to make into WikiText.
   * @param separator Separator string to use.
   * @param numItems How many items to show.
   * @return The WikiText
   */
  protected String wikitizeCollection(Collection links, String separator, int numItems) {
    if (links == null || links.isEmpty()) return "";

    StringBuffer output = new StringBuffer();

    Iterator it = links.iterator();
    int count = 0;

    //
    //  The output will be B Item[1] A S B Item[2] A S B Item[3] A
    //
    while (it.hasNext() && ((count < numItems) || (numItems == ALL_ITEMS))) {
      String value = (String) it.next();

      if (count > 0) {
        output.append(m_after);
        output.append(m_separator);
      }

      output.append(m_before);

      // Make a Wiki markup link. See TranslatorReader.
      output.append("[" + m_engine.beautifyTitle(value) + "|" + value + "]");
      count++;
    }

    //
    //  Output final item - if there have been none, no "after" is printed
    //
    if (count > 0) output.append(m_after);

    return output.toString();
  }
Ejemplo n.º 26
0
 private static boolean containsCoordinatorResponse(Collection<PingData> rsps) {
   if (rsps == null || rsps.isEmpty()) return false;
   for (PingData rsp : rsps) {
     if (rsp.isCoord()) return true;
   }
   return false;
 }
Ejemplo n.º 27
0
 public boolean hasActions(Collection<DocumentReference> refs) {
   if (refs.isEmpty()) return !myGlobalStack.isEmpty();
   for (DocumentReference each : refs) {
     if (!getStack(each).isEmpty()) return true;
   }
   return false;
 }
  private static String getSubmitHandler(
      FacesContext context,
      UIComponent component,
      Collection<ClientBehaviorContext.Parameter> params,
      boolean preventDefault) {

    StringBuilder builder = new StringBuilder(256);

    String formClientId = getFormClientId(component, context);
    String componentClientId = component.getClientId(context);

    builder.append("qab.sf(document.getElementById('");
    builder.append(formClientId);
    builder.append("'),{");

    appendProperty(builder, componentClientId, componentClientId);

    if ((null != params) && (!params.isEmpty())) {
      for (ClientBehaviorContext.Parameter param : params) {
        appendProperty(builder, param.getName(), param.getValue());
      }
    }

    builder.append("})");

    if (preventDefault) {
      builder.append(";return false");
    }

    return builder.toString();
  }
  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();
  }
  private static String getChainedHandler(
      FacesContext context,
      UIComponent component,
      List<ClientBehavior> behaviors,
      Collection<ClientBehaviorContext.Parameter> params,
      String behaviorEventName,
      String userHandler) {

    StringBuilder builder = new StringBuilder(100);
    builder.append("jsf.util.chain(this,event,");

    appendScriptToChain(builder, userHandler);

    boolean submitting =
        appendBehaviorsToChain(builder, context, component, behaviors, behaviorEventName, params);

    boolean hasParams = ((null != params) && !params.isEmpty());

    if (!submitting && hasParams) {
      String submitHandler = getSubmitHandler(context, component, params, false);

      appendScriptToChain(builder, submitHandler);

      submitting = true;
    }

    builder.append(")");

    if (submitting && ("action".equals(behaviorEventName) || "click".equals(behaviorEventName))) {
      builder.append(";return false");
    }

    return builder.toString();
  }