@NotNull
  private static Collection<DeclarationDescriptor> filterAndStoreResolutionResult(
      @NotNull Collection<LookupResult> lookupResults,
      @NotNull JetSimpleNameExpression referenceExpression,
      @NotNull BindingTrace trace,
      @NotNull JetScope scopeToCheckVisibility,
      @NotNull LookupMode lookupMode,
      boolean storeResult) {
    if (lookupResults.isEmpty()) {
      return Collections.emptyList();
    }

    Collection<DeclarationDescriptor> descriptors = Sets.newLinkedHashSet();
    for (LookupResult lookupResult : lookupResults) {
      descriptors.addAll(lookupResult.descriptors);
    }

    Collection<JetScope> possibleResolutionScopes = Lists.newArrayList();
    for (LookupResult lookupResult : lookupResults) {
      if (!lookupResult.descriptors.isEmpty()) {
        possibleResolutionScopes.add(lookupResult.resolutionScope);
      }
    }
    if (possibleResolutionScopes.isEmpty()) {
      for (LookupResult lookupResult : lookupResults) {
        possibleResolutionScopes.add(lookupResult.resolutionScope);
      }
    }

    Collection<DeclarationDescriptor> filteredDescriptors;
    if (lookupMode == LookupMode.ONLY_CLASSES_AND_PACKAGES) {
      filteredDescriptors = Collections2.filter(descriptors, CLASSIFIERS_AND_PACKAGE_VIEWS);
    } else {
      filteredDescriptors = Sets.newLinkedHashSet();
      // functions and properties can be imported if lookupResult.packageLevel == true
      for (LookupResult lookupResult : lookupResults) {
        if (lookupResult.packageLevel) {
          filteredDescriptors.addAll(lookupResult.descriptors);
        } else {
          filteredDescriptors.addAll(
              Collections2.filter(lookupResult.descriptors, CLASSIFIERS_AND_PACKAGE_VIEWS));
        }
      }
    }

    if (storeResult) {
      storeResolutionResult(
          descriptors,
          filteredDescriptors,
          referenceExpression,
          possibleResolutionScopes,
          trace,
          scopeToCheckVisibility);
    }

    return filteredDescriptors;
  }
  protected Map<String, Object> createProductListContext(List<Product> products) {
    final Map<String, Object> productsContext = Maps.newHashMap();
    final List<Map<String, Object>> productsListContext = Lists.newArrayList();

    java.util.Collection<UUID> featuredImageIds =
        Collections2.transform(products, WebDataHelper.ENTITY_FEATURED_IMAGE);
    List<UUID> ids = new ArrayList<>(Collections2.filter(featuredImageIds, Predicates.notNull()));
    List<Attachment> allImages;
    List<Thumbnail> allThumbnails;
    if (ids.isEmpty()) {
      allImages = Collections.emptyList();
      allThumbnails = Collections.emptyList();
    } else {
      allImages = this.attachmentStore.get().findByIds(ids);
      allThumbnails = this.thumbnailStore.get().findAllForIds(ids);
    }

    ProductContextBuilder builder =
        new ProductContextBuilder(
            urlFactory,
            configurationService,
            entityLocalizationService,
            this.context.getTheme().getDefinition());

    for (final Product product : products) {
      java.util.Collection<Attachment> attachments =
          Collections2.filter(allImages, isEntityFeaturedImage(product));
      List<Image> images = new ArrayList<>();
      for (final Attachment attachment : attachments) {
        java.util.Collection<Thumbnail> thumbnails =
            Collections2.filter(allThumbnails, isThumbnailOfAttachment(attachment));
        Image image =
            new Image(entityLocalizationService.localize(attachment), new ArrayList<>(thumbnails));
        images.add(image);
      }
      List<org.mayocat.shop.catalog.model.Collection> productCollections =
          collectionStore.get().findAllForProduct(product);
      product.setCollections(productCollections);
      if (productCollections.size() > 0) {
        // Here we take the first collection in the list, but in the future we should have the
        // featured
        // collection as the parent entity of this product
        product.setFeaturedCollection(productCollections.get(0));
      }
      Map<String, Object> productContext =
          builder.build(entityLocalizationService.localize(product), images);
      productsListContext.add(productContext);
    }

    productsContext.put("list", productsListContext);
    return productsContext;
  }
  @Override
  protected Collection<PyElement> moveMembers(
      @NotNull final PyClass from,
      @NotNull final Collection<PyMemberInfo<PyFunction>> members,
      @NotNull final PyClass... to) {
    final Collection<PyFunction> methodsToMove =
        fetchElements(Collections2.filter(members, new AbstractFilter(false)));
    final Collection<PyFunction> methodsToAbstract =
        fetchElements(Collections2.filter(members, new AbstractFilter(true)));

    makeMethodsAbstract(methodsToAbstract, to);
    return moveMethods(from, methodsToMove, to);
  }
  /** Merge a list of base clusters into one. */
  private ClusterCandidate merge(IntStack mergeList, List<ClusterCandidate> baseClusters) {
    assert mergeList.size() > 0;
    final ClusterCandidate result = new ClusterCandidate();

    /*
     * Merge documents from all base clusters and update the score.
     */
    for (int i = 0; i < mergeList.size(); i++) {
      final ClusterCandidate cc = baseClusters.get(mergeList.get(i));
      result.documents.or(cc.documents);
      result.score += cc.score;
    }
    result.cardinality = (int) result.documents.cardinality();

    /*
     * Combine cluster labels and try to find the best description for the cluster.
     */
    final ArrayList<PhraseCandidate> phrases = new ArrayList<PhraseCandidate>(mergeList.size());
    for (int i = 0; i < mergeList.size(); i++) {
      final ClusterCandidate cc = baseClusters.get(mergeList.get(i));
      final float coverage = cc.cardinality / (float) result.cardinality;
      phrases.add(new PhraseCandidate(cc, coverage));
    }

    markSubSuperPhrases(phrases);
    Collections2.filter(phrases, notSelected).clear();

    markOverlappingPhrases(phrases);
    Collections2.filter(phrases, notSelected).clear();

    Collections.sort(
        phrases,
        new Comparator<PhraseCandidate>() {
          public int compare(PhraseCandidate p1, PhraseCandidate p2) {
            if (p1.coverage < p2.coverage) return 1;
            if (p1.coverage > p2.coverage) return -1;
            return 0;
          };
        });

    int max = maxPhrases;
    for (PhraseCandidate p : phrases) {
      if (max-- <= 0) break;
      result.phrases.add(p.cluster.phrases.get(0));
    }

    return result;
  }
  public List<HLocale> suggestLocales(final String query) {
    if (allLocales == null) {
      allLocales = localeServiceImpl.getAllJavaLanguages();
    }

    Collection<LocaleId> filtered =
        Collections2.filter(
            allLocales,
            new Predicate<LocaleId>() {
              @Override
              public boolean apply(LocaleId input) {
                return input.getId().startsWith(query);
              }
            });

    return new ArrayList<HLocale>(
        Collections2.transform(
            filtered,
            new Function<LocaleId, HLocale>() {
              @Override
              public HLocale apply(@Nullable LocaleId from) {
                return new HLocale(from);
              }
            }));
  }
  @Override
  public List<ObjectAction> getObjectActions(
      final List<ActionType> types,
      final Contributed contributed,
      final Filter<ObjectAction> filter) {

    // update our list of actions if requesting for contributed actions
    // and they have not yet been added
    // the "contributed.isIncluded()" guard is required because we cannot do this too early;
    // there must be a session available
    if (contributed.isIncluded() && !contributeeActionsAdded) {
      synchronized (this.objectActions) {
        final List<ObjectAction> actions = Lists.newArrayList(this.objectActions);
        actions.addAll(createContributeeActions());
        sortCacheAndUpdateActions(actions);
        contributeeActionsAdded = true;
      }
    }

    final List<ObjectAction> actions = Lists.newArrayList();
    for (final ActionType type : types) {
      final Collection<ObjectAction> filterActions =
          Collections2.filter(objectActionsByType.get(type), Filters.asPredicate(filter));
      actions.addAll(filterActions);
    }
    return Lists.newArrayList(
        Iterables.filter(actions, ContributeeMember.Predicates.regularElse(contributed)));
  }
 private void genYailFilesIfNecessary(List<String> sourceFiles)
     throws IOException, YailGenerationException {
   // Filter out the files that aren't really source files (i.e. that don't end in .scm or .yail)
   Collection<String> formAndYailSourceFiles =
       Collections2.filter(
           sourceFiles,
           new Predicate<String>() {
             @Override
             public boolean apply(String input) {
               return input.endsWith(FORM_PROPERTIES_EXTENSION) || input.endsWith(YAIL_EXTENSION);
             }
           });
   for (String sourceFile : formAndYailSourceFiles) {
     if (sourceFile.endsWith(FORM_PROPERTIES_EXTENSION)) {
       String rootPath =
           sourceFile.substring(0, sourceFile.length() - FORM_PROPERTIES_EXTENSION.length());
       String yailFilePath = rootPath + YAIL_EXTENSION;
       // Note: Famous last words: The following contains() makes this method O(n**2) but n should
       // be pretty small.
       if (!sourceFiles.contains(yailFilePath)) {
         generateYail(rootPath);
       }
     }
   }
 }
  @Override
  public List<OProperty> listProperties(
      OClass oClass, String tab, final DisplayMode mode, final Boolean extended) {
    Collection<OProperty> properties = oClass.properties();
    final String safeTab = tab != null ? tab : DEFAULT_TAB;
    final UIComponentsRegistry registry = OrienteerWebApplication.get().getUIComponentsRegistry();
    Collection<OProperty> filteredProperties =
        Collections2.filter(
            properties,
            new Predicate<OProperty>() {

              @Override
              public boolean apply(OProperty input) {
                String propertyTab = CustomAttributes.TAB.getValue(input);
                boolean ret = safeTab.equals(propertyTab != null ? propertyTab : DEFAULT_TAB);
                if (extended == null) return ret;
                else {
                  CustomAttributes attr =
                      DisplayMode.EDIT.equals(mode)
                          ? CustomAttributes.EDIT_COMPONENT
                          : CustomAttributes.VIEW_COMPONENT;
                  String component = attr.getValue(input);
                  if (component == null) return !extended;
                  return registry.getComponentFactory(mode, input.getType(), component).isExtended()
                      == extended;
                }
              }
            });
    if (filteredProperties == null || filteredProperties.isEmpty()) filteredProperties = properties;
    return ORDER_PROPERTIES_BY_ORDER.sortedCopy(filteredProperties);
  }
  public void analyse(Project project, SensorContext context) {
    this.project = project;
    this.context = context;

    Collection<SquidAstVisitor<LexerlessGrammar>> squidChecks = annotationCheckFactory.getChecks();
    List<SquidAstVisitor<LexerlessGrammar>> visitors = Lists.newArrayList(squidChecks);
    visitors.add(new FileLinesVisitor(project, fileLinesContextFactory));
    this.scanner =
        FlexAstScanner.create(
            createConfiguration(project), visitors.toArray(new SquidAstVisitor[visitors.size()]));
    Collection<java.io.File> files =
        InputFileUtils.toFiles(project.getFileSystem().mainFiles(Flex.KEY));
    files = ImmutableList.copyOf(Collections2.filter(files, Predicates.not(MXML_FILTER)));
    scanner.scanFiles(files);

    Collection<SourceCode> squidSourceFiles =
        scanner.getIndex().search(new QueryByType(SourceFile.class));
    save(squidSourceFiles);

    Collection<SourceCode> squidPackages =
        scanner.getIndex().search(new QueryByType(FlexSquidPackage.class));
    for (SourceCode pkg : squidPackages) {
      String packageName = pkg.getKey();
      if (!"".equals(packageName)) {
        Directory directory = resourceBridge.findDirectory(packageName);
        context.saveMeasure(directory, CoreMetrics.PACKAGES, 1.0);
      }
    }
  }
 /**
  * Constructor.
  *
  * @param configurations varargs array of configuration instances
  */
 public EncryptionConfigurationCriterion(
     @Nonnull @NonnullElements @NotEmpty EncryptionConfiguration... configurations) {
   Constraint.isNotNull(configurations, "List of configurations cannot be null");
   configs =
       new ArrayList<>(Collections2.filter(Arrays.asList(configurations), Predicates.notNull()));
   Constraint.isGreaterThanOrEqual(1, configs.size(), "At least one configuration is required");
 }
 @Override
 @Transactional(readOnly = true)
 public List<PropertyValueWithDescriptor> getPropertyValuesWithDescriptor(
     Entity entity, int entityId) {
   return Lists.newArrayList(
       Collections2.filter(
           Collections2.transform(
               getPropertyValues(entity, entityId),
               new Function<PropertyValue, PropertyValueWithDescriptor>() {
                 @Override
                 public PropertyValueWithDescriptor apply(PropertyValue value) {
                   PropertyExtensionDescriptor propertyExtensionDescriptor;
                   try {
                     propertyExtensionDescriptor =
                         extensionManager.getPropertyExtensionDescriptor(
                             value.getExtension(), value.getName());
                   } catch (PropertyExtensionNotFoundException ex) {
                     propertyExtensionDescriptor = null;
                   }
                   return new PropertyValueWithDescriptor(
                       propertyExtensionDescriptor, value.getValue());
                 }
               }),
           new Predicate<PropertyValueWithDescriptor>() {
             @Override
             public boolean apply(PropertyValueWithDescriptor it) {
               return it.getDescriptor() != null;
             }
           }));
 }
示例#12
0
                  @Override
                  public Collection<JetType> invoke() {
                    if (resolveSession.isClassSpecial(
                        DescriptorUtils.getFQName(LazyClassDescriptor.this))) {
                      return Collections.emptyList();
                    } else {
                      JetClassOrObject classOrObject =
                          declarationProvider.getOwnerInfo().getCorrespondingClassOrObject();
                      if (classOrObject == null) {
                        return Collections.emptyList();
                      } else {
                        List<JetType> allSupertypes =
                            resolveSession
                                .getInjector()
                                .getDescriptorResolver()
                                .resolveSupertypes(
                                    getScopeForClassHeaderResolution(),
                                    LazyClassDescriptor.this,
                                    classOrObject,
                                    resolveSession.getTrace());

                        return Lists.newArrayList(
                            Collections2.filter(allSupertypes, VALID_SUPERTYPE));
                      }
                    }
                  }
 private Iterator<Resource> getFilesFromParams() throws IOException {
   System.err.printf(
       "%s system property not specified, using 'dir'" + " parameter from configuration file\n",
       DIR_PROPERTY);
   String resource = (String) getConfigParameterValue("dir");
   String suffix = (String) getConfigParameterValue("suffix");
   if (resource != null) {
     System.err.printf("Reading files from classpath directory: %s\n", resource);
     Reflections reflections =
         new Reflections(
             new ConfigurationBuilder()
                 .setUrls(ClasspathHelper.forPackage(""))
                 .setScanners(new ResourcesScanner()));
     Set<String> files = reflections.getResources(Pattern.compile(".*\\." + suffix));
     Collection<Resource> resources =
         Collections2.transform(files, new StringToResourceFunction("/"));
     final Pattern p = Pattern.compile("^" + resource);
     Collection<Resource> filtered =
         Collections2.filter(
             resources,
             new Predicate<Resource>() {
               @Override
               public boolean apply(Resource input) {
                 Matcher m = p.matcher(input.name);
                 return m.find();
               }
             });
     return filtered.iterator();
   } else {
     throw new IOException(String.format("Parameter 'dir' must be specified"));
   }
 }
示例#14
0
  public Collection<OccupationPeriodReference> getPeriodReferences(
      final OccupationPeriodType type, final Integer semester, final List<Integer> years) {
    return Collections2.filter(
        getOccupationPeriodReferencesSet(),
        new Predicate<OccupationPeriodReference>() {

          @Override
          public boolean apply(OccupationPeriodReference reference) {

            if (type != null && reference.getPeriodType() != type) {
              return false;
            }

            if (semester != null
                && reference.getSemester() != null
                && reference.getSemester() != semester) {
              return false;
            }

            if (years != null && !reference.getCurricularYears().getYears().containsAll(years)) {
              return false;
            }

            return true;
          }
        });
  }
  public static Collection<RepositoryElement> getChildren(
      final RepositoryDirectory parent, final Collection<?> items) {
    List<RepositoryElement> elements =
        Lists.newArrayList(
            Iterators.transform(
                items.iterator(),
                new Function<Object, RepositoryElement>() {
                  public RepositoryElement apply(Object from) {
                    if (from instanceof BuildableItemWithBuildWrappers) {
                      return new ProjectElement(
                          parent, ((BuildableItemWithBuildWrappers) from).asProject());
                    }
                    if (from instanceof MultiBranchProject) {
                      return new MultiBranchProjectElement(parent, (MultiBranchProject) from);
                    }
                    if (from instanceof Job) {
                      return new ProjectElement(parent, (Job) from);
                    }

                    return null;
                  }
                }));

    // Squash ones we couldn't sensibly find an element for.
    return Collections2.filter(
        elements,
        new Predicate<RepositoryElement>() {
          @Override
          public boolean apply(RepositoryElement input) {
            return input != null;
          }
        });
  }
示例#16
0
 @NotNull
 @Override
 public Collection<? extends JetType> getSupertypes() {
   if (supertypes == null) {
     if (resolveSession.isClassSpecial(DescriptorUtils.getFQName(LazyClassDescriptor.this))) {
       this.supertypes = Collections.emptyList();
     } else {
       JetClassOrObject classOrObject =
           declarationProvider.getOwnerInfo().getCorrespondingClassOrObject();
       if (classOrObject == null) {
         this.supertypes = Collections.emptyList();
       } else {
         List<JetType> allSupertypes =
             resolveSession
                 .getInjector()
                 .getDescriptorResolver()
                 .resolveSupertypes(
                     getScopeForClassHeaderResolution(),
                     LazyClassDescriptor.this,
                     classOrObject,
                     resolveSession.getTrace());
         List<JetType> validSupertypes =
             Lists.newArrayList(Collections2.filter(allSupertypes, VALID_SUPERTYPE));
         this.supertypes = validSupertypes;
         findAndDisconnectLoopsInTypeHierarchy(validSupertypes);
       }
     }
   }
   return supertypes;
 }
  /**
   * Set the flows available for possible use.
   *
   * @param flows the flows available for possible use
   */
  public void setAvailableFlows(
      @Nonnull @NonnullElements final Collection<SubjectCanonicalizationFlowDescriptor> flows) {
    ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this);
    Constraint.isNotNull(flows, "Flow collection cannot be null");

    availableFlows = new ArrayList<>(Collections2.filter(flows, Predicates.notNull()));
  }
示例#18
0
  @Override
  public String toString() {
    String fsList =
        Joiner.on(", ")
            .join(
                Collections2.transform(
                    Collections2.filter(
                        this.getFiles(),
                        new Predicate<StoreFile>() {
                          public boolean apply(StoreFile sf) {
                            return sf.getReader() != null;
                          }
                        }),
                    new Function<StoreFile, String>() {
                      public String apply(StoreFile sf) {
                        return StringUtils.humanReadableInt(
                            (sf.getReader() == null) ? 0 : sf.getReader().length());
                      }
                    }));

    return "regionName="
        + regionName
        + ", storeName="
        + storeName
        + ", fileCount="
        + this.getFiles().size()
        + ", fileSize="
        + StringUtils.humanReadableInt(totalSize)
        + ((fsList.isEmpty()) ? "" : " (" + fsList + ")")
        + ", priority="
        + priority
        + ", time="
        + timeInNanos;
  }
  private static Collection<FqName> computeSuggestions(@NotNull JetSimpleNameExpression element) {
    final PsiFile file = element.getContainingFile();
    if (!(file instanceof JetFile)) {
      return Collections.emptyList();
    }

    final String referenceName = element.getReferencedName();

    if (!StringUtil.isNotEmpty(referenceName)) {
      return Collections.emptyList();
    }

    assert referenceName != null;

    List<FqName> result = Lists.newArrayList();
    result.addAll(getClassNames(referenceName, (JetFile) file));
    result.addAll(getJetTopLevelFunctions(referenceName, element, file.getProject()));
    result.addAll(getJetExtensionFunctions(referenceName, element, file.getProject()));

    return Collections2.filter(
        result,
        new Predicate<FqName>() {
          @Override
          public boolean apply(@Nullable FqName fqName) {
            assert fqName != null;
            return ImportInsertHelper.doNeedImport(
                new ImportPath(fqName, false), null, (JetFile) file);
          }
        });
  }
示例#20
0
  @SuppressWarnings("unchecked")
  private static void addRRset(
      Name name, final Message response, Record[] records, final int section) {
    Multimap<RequestType, Record> rrsets = ArrayListMultimap.create();
    for (Record r : records) {
      RequestType type = RequestType.typeOf(r.getType());
      rrsets.get(type).addAll(Collections2.filter(Arrays.asList(records), type));
    }
    Predicate<Record> checkNewRecord =
        new Predicate<Record>() {

          @Override
          public boolean apply(Record input) {
            for (int s = 1; s <= section; s++) {
              if (response.findRecord(input, s)) {
                return false;
              }
            }
            return true;
          }
        };
    if (rrsets.containsKey(RequestType.CNAME)) {
      for (Record cnames : Iterables.filter(rrsets.removeAll(RequestType.CNAME), checkNewRecord)) {
        response.addRecord(cnames, section);
      }
    }
    for (Record sectionRecord : Iterables.filter(rrsets.values(), checkNewRecord)) {
      response.addRecord(sectionRecord, section);
    }
  }
  private ComboBoxModel createRemoteBranchDropdownModel() {
    final SortedComboBoxModel<GitRemoteBranch> sortedRemoteBranches =
        new SortedComboBoxModel<GitRemoteBranch>(new BranchComparator());

    final GitRepoInfo gitRepoInfo = this.getInfo();

    assert gitRepoInfo != null;
    final GitRemoteBranch remoteTrackingBranch = this.getRemoteTrackingBranch();

    // only show valid remote branches
    sortedRemoteBranches.addAll(
        Collections2.filter(
            gitRepoInfo.getRemoteBranches(),
            new Predicate<GitRemoteBranch>() {
              @Override
              public boolean apply(final GitRemoteBranch remoteBranch) {
                /* two conditions:
                 *   1. remote must be a vso/tfs remote
                 *   2. this isn't the remote tracking branch of current local branch
                 */
                return tfGitRemotes.contains(remoteBranch.getRemote())
                    && !remoteBranch.equals(remoteTrackingBranch);
              }
            }));

    sortedRemoteBranches.setSelectedItem(getDefaultBranch(sortedRemoteBranches.getItems()));

    return sortedRemoteBranches;
  }
  protected List<Vertex> getFilteredVertices() {
    if (isAclEnabled()) {
      // Get All nodes when called should filter with ACL
      List<OnmsNode> onmsNodes = getNodeDao().findAll();

      // Transform the onmsNodes list to a list of Ids
      final List<Integer> nodes =
          Lists.transform(
              onmsNodes,
              new Function<OnmsNode, Integer>() {
                @Override
                public Integer apply(OnmsNode node) {
                  return node.getId();
                }
              });

      // Filter out the nodes that are not viewable by the user.
      return Lists.newArrayList(
          Collections2.filter(
              m_vertexProvider.getVertices(),
              new Predicate<Vertex>() {
                @Override
                public boolean apply(Vertex vertex) {
                  return nodes.contains(vertex.getNodeID());
                }
              }));
    } else {
      return m_vertexProvider.getVertices();
    }
  }
示例#23
0
  @SuppressWarnings("unchecked")
  public SimpleHelpMap(CraftServer server) {
    this.helpTopics =
        new TreeMap<String, HelpTopic>(
            HelpTopicComparator
                .topicNameComparatorInstance()); // Using a TreeMap for its explicit sorting on key
    this.topicFactoryMap = new HashMap<Class, HelpTopicFactory<Command>>();
    this.server = server;
    this.yaml = new HelpYamlReader(server);

    Predicate indexFilter = Predicates.not(Predicates.instanceOf(CommandAliasHelpTopic.class));
    if (!yaml.commandTopicsInMasterIndex()) {
      indexFilter = Predicates.and(indexFilter, Predicates.not(new IsCommandTopicPredicate()));
    }

    this.defaultTopic =
        new IndexHelpTopic(
            "Index",
            null,
            null,
            Collections2.filter(helpTopics.values(), indexFilter),
            "Use /help [n] to get page n of help.");

    registerHelpTopicFactory(
        MultipleCommandAlias.class, new MultipleCommandAliasHelpTopicFactory());
  }
示例#24
0
  private void checkPossiblesTimeboxes(
      final Participant participant, List<TimeBox> possibleTbs, Priority priority) {

    if (possibleTbs.size() == 1) {

      boolean allocated = allocateTimeBox(possibleTbs.get(0), participant);
      if (allocated) return;
    }

    if (!possibleTbs.isEmpty()) {

      buffer.put(participant, Lists.newArrayList(possibleTbs));
      System.out.println("insert " + possibleTbs.size() + " timeboxes in the buffer");

      final Priority nextPriority = getNextPriority(priority);

      if (nextPriority != null) {

        System.out.println("set priority level to : " + nextPriority.getRole());

        // filter the unavaibilities to get only the ones matching the current priority level
        Collection<Unavailability> unavailabilities =
            Collections2.filter(
                this.unavailabilities,
                new Predicate<Unavailability>() {
                  public boolean apply(Unavailability a) {
                    Person p = a.getPerson();
                    return (p.equals(participant.getStudent())
                            || p.equals(participant.getFollowingTeacher()))
                        && (p.getRole() == nextPriority.getRole());
                  }
                });

        System.out.println("unavailabilities found: " + unavailabilities.size());
        System.out.println("{");
        for (Unavailability ua : unavailabilities) {
          System.out.println(ua.getPeriod().getFrom() + " - " + ua.getPeriod().getTo());
        }
        System.out.println("}");

        if (!unavailabilities.isEmpty()) {
          for (TimeBox timeBox : Lists.newArrayList(possibleTbs)) {

            System.out.println(
                "check unavailability "
                    + (new DateTime(timeBox.getFrom()).toString("dd/MM/yyyy HH:mm")));

            // Check if there is no unavailabilities for that timebox
            if (!AlgoPlanningUtils.isAvailable(unavailabilities, timeBox)) {
              System.out.println("removing one timebox...");
              possibleTbs.remove(timeBox);
            }
          }
        }

        // let's do it again
        checkPossiblesTimeboxes(participant, possibleTbs, nextPriority);
      }
    }
  }
  public static DescribeServicesResponseType describeService(final DescribeServicesType request) {
    final DescribeServicesResponseType reply = request.getReply();
    Topology.touch(request);
    if (request.getServices().isEmpty()) {
      final ComponentId compId =
          (request.getByServiceType() != null)
              ? ComponentIds.lookup(request.getByServiceType().toLowerCase())
              : Empyrean.INSTANCE;
      final boolean showEventStacks = Boolean.TRUE.equals(request.getShowEventStacks());
      final boolean showEvents = Boolean.TRUE.equals(request.getShowEvents()) || showEventStacks;

      final Function<ServiceConfiguration, ServiceStatusType> transformToStatus =
          ServiceConfigurations.asServiceStatus(showEvents, showEventStacks);
      final List<Predicate<ServiceConfiguration>> filters =
          new ArrayList<Predicate<ServiceConfiguration>>() {
            {
              if (request.getByPartition() != null) {
                Partitions.exists(request.getByPartition());
                this.add(Filters.partition(request.getByPartition()));
              }
              if (request.getByState() != null) {
                final Component.State stateFilter =
                    Component.State.valueOf(request.getByState().toUpperCase());
                this.add(Filters.state(stateFilter));
              }
              if (!request.getServiceNames().isEmpty()) {
                this.add(Filters.name(request.getServiceNames()));
              }
              this.add(Filters.host(request.getByHost()));
              this.add(
                  Filters.listAllOrInternal(
                      request.getListAll(),
                      request.getListUserServices(),
                      request.getListInternal()));
            }
          };
      final Predicate<Component> componentFilter = Filters.componentType(compId);
      final Predicate<ServiceConfiguration> configPredicate = Predicates.and(filters);

      List<ServiceConfiguration> replyConfigs = Lists.newArrayList();
      for (final Component comp : Components.list()) {
        if (componentFilter.apply(comp)) {
          Collection<ServiceConfiguration> acceptedConfigs =
              Collections2.filter(comp.services(), configPredicate);
          replyConfigs.addAll(acceptedConfigs);
        }
      }
      ImmutableList<ServiceConfiguration> sortedReplyConfigs =
          ServiceOrderings.defaultOrdering().immutableSortedCopy(replyConfigs);
      final Collection<ServiceStatusType> transformedReplyConfigs =
          Collections2.transform(sortedReplyConfigs, transformToStatus);
      reply.getServiceStatuses().addAll(transformedReplyConfigs);
    } else {
      for (ServiceId s : request.getServices()) {
        reply.getServiceStatuses().add(TypeMappers.transform(s, ServiceStatusType.class));
      }
    }
    return reply;
  }
示例#26
0
 @Override
 public List<OProperty> getDisplayableProperties(OClass oClass) {
   Collection<OProperty> properties = oClass.properties();
   Collection<OProperty> filteredProperties =
       Collections2.filter(properties, PropertyDisplayablePredicate.INSTANCE);
   if (filteredProperties == null || filteredProperties.isEmpty()) filteredProperties = properties;
   return ORDER_PROPERTIES_BY_ORDER.sortedCopy(filteredProperties);
 }
示例#27
0
 public String toString() {
   return Objects.toStringHelper(ServiceManager.class)
       .add(
           "services",
           Collections2.filter(
               this.services, Predicates.not(Predicates.instanceOf(NoOpService.class))))
       .toString();
 }
示例#28
0
 /**
  * If no media type has a profile parameter, then simply return all the media types.
  *
  * <p>Otherwise, though, filter out the {@link MediaType#APPLICATION_JSON_TYPE generic
  * application/json} media type if it is present.
  */
 private List<MediaType> acceptedMediaTypes() {
   final List<MediaType> acceptableMediaTypes = getHttpHeaders().getAcceptableMediaTypes();
   if (Collections2.filter(acceptableMediaTypes, MEDIA_TYPE_CONTAINS_PROFILE).isEmpty()) {
     return acceptableMediaTypes;
   }
   return Lists.newArrayList(
       Iterables.filter(acceptableMediaTypes, MEDIA_TYPE_NOT_GENERIC_APPLICATION_JSON));
 }
 @Override
 public boolean onCommand(CommandSender sender, String[] args) {
   FileConfiguration conf = market.getConfig();
   String storageType = conf.getString("storage.type");
   String user = conf.getString("storage.mysql_user");
   String pass = conf.getString("storage.mysql_pass");
   String db = conf.getString("storage.mysql_database");
   String addr = conf.getString("storage.mysql_address");
   int port = conf.getInt("storage.mysql_port");
   final String infiniteSeller = conf.getString("infinite.seller");
   market.reloadConfig();
   conf = market.getConfig();
   if (!storageType.equalsIgnoreCase(conf.getString("storage.type"))
       || !user.equals(conf.getString("storage.mysql_user"))
       || !pass.equals(conf.getString("storage.mysql_pass"))
       || !db.equals(conf.getString("storage.mysql_database"))
       || !addr.equals(conf.getString("storage.mysql_address"))
       || port != conf.getInt("storage.mysql_port")) {
     AsyncDatabase asyncDb = market.getStorage().getAsyncDb();
     asyncDb.cancel();
     if (asyncDb.isProcessing()) {
       sender.sendMessage(ChatColor.YELLOW + "DB queue is currently running, please wait...");
       while (asyncDb.isProcessing()) {}
     }
     asyncDb.close();
     market.initializeStorage();
   }
   if (!infiniteSeller.equalsIgnoreCase(conf.getString("infinite.seller"))) {
     market.infiniteSeller = market.getConfig().getString("infinite.seller");
     Collection<Listing> infinite =
         Collections2.filter(
             market.getStorage().getAllListings(),
             new Predicate<Listing>() {
               @Override
               public boolean apply(Listing listing) {
                 return listing.getSeller().equalsIgnoreCase(infiniteSeller);
               }
             });
     String seller = market.getInfiniteSeller();
     for (Listing listing : infinite) {
       listing.seller = seller;
       market
           .getStorage()
           .getAsyncDb()
           .addStatement(
               new QueuedStatement("UPDATE listings SET seller=? WHERE id=?")
                   .setValue(seller)
                   .setValue(listing.getId()));
     }
     market.getInterfaceHandler().updateAllViewers();
   }
   market.getConfigHandler().reloadLocaleYML();
   locale.setSelected();
   market.buildWorldLinks();
   sender.sendMessage(locale.get("cmd.prefix") + market.getLocale().get("config_reloaded"));
   return true;
 }
示例#30
0
 @Monitor(name = "AvailableServersCount", type = DataSourceType.GAUGE)
 public int getAvailableServersCount() {
   ILoadBalancer lb = getLoadBalancer();
   List<Server> servers = lb.getAllServers();
   if (servers == null) {
     return 0;
   }
   return Collections2.filter(servers, predicate.getServerOnlyPredicate()).size();
 }