Exemplo n.º 1
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 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"));
   }
 }
  public void testOrderedPermutationSetSizeOverflow() {
    // 12 elements won't overflow
    assertEquals(
        479001600 /*12!*/,
        Collections2.orderedPermutations(newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))
            .size());
    // 13 elements overflow an int
    assertEquals(
        Integer.MAX_VALUE,
        Collections2.orderedPermutations(newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))
            .size());
    // 21 elements overflow a long
    assertEquals(
        Integer.MAX_VALUE,
        Collections2.orderedPermutations(
                newArrayList(
                    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21))
            .size());

    // Almost force an overflow in the binomial coefficient calculation
    assertEquals(
        1391975640 /*C(34,14)*/,
        Collections2.orderedPermutations(concat(nCopies(20, 1), nCopies(14, 2))).size());
    // Do force an overflow in the binomial coefficient calculation
    assertEquals(
        Integer.MAX_VALUE,
        Collections2.orderedPermutations(concat(nCopies(21, 1), nCopies(14, 2))).size());
  }
  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
 @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;
             }
           }));
 }
  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;
  }
  @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;
  }
Exemplo n.º 8
0
 private static Set<String> getTemplates(Collection<GeneratedJob> jobs) {
   Collection<String> templateNames =
       Collections2.transform(
           jobs,
           new Function<GeneratedJob, String>() {
             @Override
             public String apply(GeneratedJob input) {
               return input.getTemplateName();
             }
           });
   return new LinkedHashSet<String>(Collections2.filter(templateNames, Predicates.notNull()));
 }
  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;
  }
Exemplo n.º 10
0
  @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);
  }
Exemplo n.º 11
0
 @NotNull
 public static Collection<GitRepository> getRepositoriesForFiles(
     @NotNull Project project, @NotNull Collection<VirtualFile> files) {
   final GitRepositoryManager manager = getRepositoryManager(project);
   com.google.common.base.Function<VirtualFile, GitRepository> ROOT_TO_REPO =
       new com.google.common.base.Function<VirtualFile, GitRepository>() {
         @Override
         public GitRepository apply(@Nullable VirtualFile root) {
           return root != null ? manager.getRepositoryForRoot(root) : null;
         }
       };
   return Collections2.filter(
       Collections2.transform(sortFilesByGitRootsIgnoringOthers(files).keySet(), ROOT_TO_REPO),
       Predicates.notNull());
 }
Exemplo n.º 12
0
 @Override
 public Point newLocation() {
   Preconditions.checkNotNull(wish);
   // [stas] just for fun
   return new Point(
       natural()
           .sortedCopy(
               ImmutableList.of(
                   wish.getX(),
                   0,
                   sizeRetriever.windowSize().getWidth()
                       - sizeRetriever.getComponentsSize().getWidth()))
           .get(1),
       Ordering.natural()
           .sortedCopy(
               Arrays.asList(
                   natural()
                           .min(
                               Lists.asList(
                                   sizeRetriever.windowSize().getHeight()
                                       - sizeRetriever.getMaxElementSize().getHeight(),
                                   Collections2.transform(
                                           lowest,
                                           new Function<Point, Integer>() {
                                             @Override
                                             public Integer apply(Point input) {
                                               return input.getY();
                                             }
                                           })
                                       .toArray(new Integer[] {})))
                       - (lowest.isEmpty() ? 0 : sizeRetriever.getMaxElementSize().getHeight()),
                   natural()
                           .max(
                               Lists.asList(
                                   Point.HIGHEST.getY(),
                                   Collections2.transform(
                                           highest,
                                           new Function<Point, Integer>() {
                                             @Override
                                             public Integer apply(Point input) {
                                               return input.getY();
                                             }
                                           })
                                       .toArray(new Integer[] {})))
                       + (highest.isEmpty() ? 0 : sizeRetriever.getMaxElementSize().getHeight()),
                   wish.getY()))
           .get(1));
 }
Exemplo n.º 13
0
  /** 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;
  }
  @Override
  public Collection<PyThreadInfo> getThreads() {
    cleanOtherDebuggers();

    List<PyThreadInfo> threads = collectAllThreads();

    if (myOtherDebuggers.size() > 0) {
      // here we add process id to thread name in case there are more then one process
      return Collections.unmodifiableCollection(
          Collections2.transform(
              threads,
              new Function<PyThreadInfo, PyThreadInfo>() {
                @Override
                public PyThreadInfo apply(PyThreadInfo t) {
                  String threadName = ThreadRegistry.threadName(t.getName(), t.getId());
                  PyThreadInfo newThread =
                      new PyThreadInfo(
                          t.getId(), threadName, t.getFrames(), t.getStopReason(), t.getMessage());
                  newThread.updateState(t.getState(), t.getFrames());
                  return newThread;
                }
              }));
    } else {
      return Collections.unmodifiableCollection(threads);
    }
  }
Exemplo n.º 15
0
  /*
   * ************************** REFUNDS ********************************
   */
  @GET
  @Path("/{accountId:" + UUID_PATTERN + "}/" + REFUNDS)
  @Produces(APPLICATION_JSON)
  public Response getRefunds(
      @PathParam("accountId") final String accountId,
      @javax.ws.rs.core.Context final HttpServletRequest request)
      throws AccountApiException, PaymentApiException {
    final TenantContext tenantContext = context.createContext(request);

    final Account account =
        accountUserApi.getAccountById(UUID.fromString(accountId), tenantContext);
    final List<Refund> refunds = paymentApi.getAccountRefunds(account, tenantContext);
    final List<RefundJson> result =
        new ArrayList<RefundJson>(
            Collections2.transform(
                refunds,
                new Function<Refund, RefundJson>() {
                  @Override
                  public RefundJson apply(Refund input) {
                    // TODO Return adjusted items and audits
                    return new RefundJson(input, null, null);
                  }
                }));

    return Response.status(Status.OK).entity(result).build();
  }
Exemplo n.º 16
0
  @GET
  @Path("/{accountId:" + UUID_PATTERN + "}/" + PAYMENT_METHODS)
  @Produces(APPLICATION_JSON)
  public Response getPaymentMethods(
      @PathParam("accountId") final String accountId,
      @QueryParam(QUERY_PAYMENT_METHOD_PLUGIN_INFO) @DefaultValue("false")
          final Boolean withPluginInfo,
      @javax.ws.rs.core.Context final HttpServletRequest request)
      throws AccountApiException, PaymentApiException {
    final TenantContext tenantContext = context.createContext(request);

    final Account account =
        accountUserApi.getAccountById(UUID.fromString(accountId), tenantContext);
    final List<PaymentMethod> methods =
        paymentApi.getPaymentMethods(account, withPluginInfo, tenantContext);
    final List<PaymentMethodJson> json =
        new ArrayList<PaymentMethodJson>(
            Collections2.transform(
                methods,
                new Function<PaymentMethod, PaymentMethodJson>() {
                  @Override
                  public PaymentMethodJson apply(final PaymentMethod input) {
                    return PaymentMethodJson.toPaymentMethodJson(account, input);
                  }
                }));

    return Response.status(Status.OK).entity(json).build();
  }
Exemplo n.º 17
0
  @GET
  @Path("/{accountId:" + UUID_PATTERN + "}/" + BUNDLES)
  @Produces(APPLICATION_JSON)
  public Response getAccountBundles(
      @PathParam("accountId") final String accountId,
      @QueryParam(QUERY_EXTERNAL_KEY) final String externalKey,
      @javax.ws.rs.core.Context final HttpServletRequest request)
      throws AccountApiException, SubscriptionApiException {
    final TenantContext tenantContext = context.createContext(request);

    final UUID uuid = UUID.fromString(accountId);
    accountUserApi.getAccountById(uuid, tenantContext);

    final List<SubscriptionBundle> bundles =
        (externalKey != null)
            ? subscriptionApi.getSubscriptionBundlesForAccountIdAndExternalKey(
                uuid, externalKey, tenantContext)
            : subscriptionApi.getSubscriptionBundlesForAccountId(uuid, tenantContext);

    final Collection<BundleJson> result =
        Collections2.transform(
            bundles,
            new Function<SubscriptionBundle, BundleJson>() {
              @Override
              public BundleJson apply(final SubscriptionBundle input) {
                return new BundleJson(input, null, null, null);
              }
            });
    return Response.status(Status.OK).entity(result).build();
  }
  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;
          }
        });
  }
Exemplo n.º 19
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;
          }
        });
  }
Exemplo n.º 20
0
  /** {@inheritDoc} */
  @Override
  public String toString() {
    final String columns =
        Joiner.on(", ")
            .join(
                Collections2.transform(
                    this.getColumns(),
                    new Function<AbstractColumn, String>() {

                      @Override
                      public String apply(AbstractColumn input) {
                        final StringBuffer out = new StringBuffer();
                        out.append(input instanceof PkColumn ? "ID [" : "COL [");

                        out.append("name=");
                        out.append(input.getName());
                        out.append(", type=");
                        out.append(input.getSqlType());

                        out.append("]");
                        return out.toString();
                      }
                    }));

    return "Table [owner="
        + this.entity.getName() //
        + ", name="
        + this.getQName() //
        + ", columns=["
        + columns
        + "]]";
  }
Exemplo n.º 21
0
  private String getRemoveSql() {
    if (this.removeSql != null) {
      return this.removeSql;
    }

    synchronized (this) {
      if (this.removeSql != null) {
        return this.removeSql;
      }

      this.removeColumns = new AbstractColumn[this.pkColumns.size()];
      this.pkColumns.values().toArray(this.removeColumns);

      final Collection<String> restrictions =
          Collections2.transform(
              this.pkColumns.values(),
              new Function<AbstractColumn, String>() {

                @Override
                public String apply(AbstractColumn input) {
                  return input.getName() + " = ?";
                }
              });

      return this.removeSql =
          "DELETE FROM " + this.getQName() + " WHERE " + Joiner.on(" AND ").join(restrictions);
    }
  }
Exemplo n.º 22
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);
      }
    }
  }
 /**
  * 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");
 }
Exemplo n.º 24
0
    @Override
    public int complete(
        final String buffer, final int cursor, final List<CharSequence> candidates) {
      final int idx = buffer.lastIndexOf(SEPARATOR);

      final Optional<DataSchemaNode> currentNode = getCurrentNode(remoteSchemaContext, buffer);
      if (currentNode.isPresent() && currentNode.get() instanceof DataNodeContainer) {
        final Collection<DataSchemaNode> childNodes =
            ((DataNodeContainer) currentNode.get()).getChildNodes();
        final Collection<String> transformed =
            Collections2.transform(
                childNodes,
                new Function<DataSchemaNode, String>() {
                  @Override
                  public String apply(final DataSchemaNode input) {
                    return IOUtil.qNameToKeyString(
                        input.getQName(),
                        mappedModulesNamespace.get(input.getQName().getNamespace()).getLocalName());
                  }
                });

        fillCandidates(buffer.substring(idx + 1), candidates, transformed);
      }

      return idx == -1 ? 0 : idx + 1;
    }
  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();
    }
  }
Exemplo n.º 26
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;
 }
Exemplo n.º 27
0
    @Override
    public GetTablespaceListResponse getAllTablespaces(RpcController controller, NullProto request)
        throws ServiceException {
      rlock.lock();
      try {

        // retrieves tablespaces from catalog store
        final List<TablespaceProto> tableSpaces = Lists.newArrayList(store.getTablespaces());

        // retrieves tablespaces from linked meta data
        tableSpaces.addAll(
            Collections2.transform(
                linkedMetadataManager.getTablespaces(),
                new Function<Pair<String, URI>, TablespaceProto>() {
                  @Override
                  public TablespaceProto apply(Pair<String, URI> input) {
                    return TablespaceProto.newBuilder()
                        .setSpaceName(input.getFirst())
                        .setUri(input.getSecond().toString())
                        .build();
                  }
                }));

        return GetTablespaceListResponse.newBuilder()
            .setState(OK)
            .addAllTablespace(tableSpaces)
            .build();

      } catch (Throwable t) {
        printStackTraceIfError(LOG, t);
        throw new ServiceException(t);
      } finally {
        rlock.unlock();
      }
    }
  /**
   * 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()));
  }
  @Test
  public void write_onPatchWithInnerObject_fullyWritesInnerObject() {
    TestData original = new TestData();
    TestData updated = new TestData();
    updated.setInnerData(new InnerTestData());

    Patch<TestData> patch =
        MakePatch.from(original).to(updated).with(new ReflectivePatchCalculator<>());
    JsonObject json = toJson(patch);

    assertTrue(json.has("innerData"));
    assertTrue(json.get("innerData").isJsonObject());

    JsonObject innerJson = json.get("innerData").getAsJsonObject();
    Collection<String[]> fields =
        Collections2.transform(
            innerJson.entrySet(),
            entry -> new String[] {entry.getKey(), entry.getValue().getAsString()});
    assertThat(
        fields,
        containsInAnyOrder(
            new String[] {"json-name-alias", "inner-named-value"},
            new String[] {"name1", "inner-value-1"},
            new String[] {"name2", "inner-value-2"}));
  }
Exemplo n.º 30
0
  public void testMultiPackageFunction() {
    myFixture.configureByText(
        JetFileType.INSTANCE,
        "package test.testing\n" + "fun other(v : Int) = 12\n" + "fun other(v : String) {}");

    StubPackageMemberDeclarationProvider provider =
        new StubPackageMemberDeclarationProvider(
            new FqName("test.testing"), getProject(), GlobalSearchScope.projectScope(getProject()));

    List<JetNamedFunction> other =
        Lists.newArrayList(provider.getFunctionDeclarations(Name.identifier("other")));
    Collection<String> functionTexts =
        Collections2.transform(
            other,
            new Function<JetNamedFunction, String>() {
              @Override
              public String apply(JetNamedFunction function) {
                return function.getText();
              }
            });

    assertSize(2, other);
    assertTrue(functionTexts.contains("fun other(v : Int) = 12"));
    assertTrue(functionTexts.contains("fun other(v : String) {}"));
  }