@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));
 }
  @Override
  public Collection<Target> getReverseDeps(Iterable<Target> targets) {
    Set<Target> result = CompactHashSet.create();
    Map<Target, Collection<Target>> rawReverseDeps = getRawReverseDeps(targets);
    warnIfMissingTargets(targets, rawReverseDeps.keySet());

    CompactHashSet<Target> visited = CompactHashSet.create();

    Set<Label> keys =
        CompactHashSet.create(
            Collections2.transform(rawReverseDeps.keySet(), TARGET_LABEL_FUNCTION));
    for (Collection<Target> parentCollection : rawReverseDeps.values()) {
      for (Target parent : parentCollection) {
        if (visited.add(parent)) {
          if (parent instanceof Rule && dependencyFilter != DependencyFilter.ALL_DEPS) {
            for (Label label : getAllowedDeps((Rule) parent)) {
              if (keys.contains(label)) {
                result.add(parent);
              }
            }
          } else {
            result.add(parent);
          }
        }
      }
    }
    return result;
  }
  public static CSVBinding getBinding(final String column, final String field, Set<String> cols) {
    CSVBinding cb = new CSVBinding();
    cb.field = field;
    cb.column = column;

    if (cols == null || cols.isEmpty()) {
      if (cb.column == null) cb.column = field;
      return cb;
    }

    for (String col : cols) {
      if (cb.bindings == null) cb.bindings = Lists.newArrayList();
      cb.bindings.add(CSVBinding.getBinding(field + "." + col, col, null));
    }

    cb.update = true;
    cb.search =
        Joiner.on(" AND ")
            .join(
                Collections2.transform(
                    cols,
                    new Function<String, String>() {

                      @Override
                      public String apply(String input) {
                        return String.format("self.%s = :%s_%s_", input, field, input);
                      }
                    }));

    return cb;
  }
  @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"}));
  }
Beispiel #5
0
  @NotNull
  private Collection<PsiElement> getDeclarationsByDescriptor(
      @NotNull DeclarationDescriptor declarationDescriptor) {
    Collection<PsiElement> declarations;
    if (declarationDescriptor instanceof PackageViewDescriptor) {
      final PackageViewDescriptor aPackage = (PackageViewDescriptor) declarationDescriptor;
      Collection<JetFile> files = trace.get(BindingContext.PACKAGE_TO_FILES, aPackage.getFqName());

      if (files == null) {
        return Collections
            .emptyList(); // package can be defined out of Kotlin sources, e. g. in library or Java
        // code
      }

      declarations =
          Collections2.transform(
              files,
              new Function<JetFile, PsiElement>() {
                @Override
                public PsiElement apply(@Nullable JetFile file) {
                  assert file != null : "File is null for aPackage " + aPackage;
                  return file.getPackageDirective().getNameIdentifier();
                }
              });
    } else {
      declarations =
          Collections.singletonList(
              BindingContextUtils.descriptorToDeclaration(
                  trace.getBindingContext(), declarationDescriptor));
    }
    return declarations;
  }
 @Override
 public void execute() throws MojoExecutionException, MojoFailureException {
   StaticLoggerBinder.getSingleton().setMavenLog(this.getLog());
   try {
     final List<Artifact> artifacts = getListOfArtifacts();
     LOG.debug("artifacts={}", artifacts);
     final ArrayList<File> files =
         new ArrayList<File>(Collections2.transform(artifacts, toFileFunction));
     final ArrayList<String> hashBaseNames =
         new ArrayList<String>(Collections2.transform(files, toBomStringFunction));
     addHashEntryForPom(hashBaseNames);
     writeResults(hashBaseNames);
   } catch (IOException ex) {
     throw new MojoExecutionException(ex.toString(), ex);
   }
 }
  /**
   * 从待执行队列中获取所有有资格执行的作业上下文.
   *
   * @param ineligibleJobContexts 无资格执行的作业上下文
   * @return 有资格执行的作业上下文集合
   */
  public Collection<JobContext> getAllEligibleJobContexts(
      final Collection<JobContext> ineligibleJobContexts) {
    if (!regCenter.isExisted(ReadyNode.ROOT)) {
      return Collections.emptyList();
    }
    Collection<String> ineligibleJobNames =
        Collections2.transform(
            ineligibleJobContexts,
            new Function<JobContext, String>() {

              @Override
              public String apply(final JobContext input) {
                return input.getJobConfig().getJobName();
              }
            });
    List<String> jobNames = regCenter.getChildrenKeys(ReadyNode.ROOT);
    List<JobContext> result = new ArrayList<>(jobNames.size());
    for (String each : jobNames) {
      if (ineligibleJobNames.contains(each)) {
        continue;
      }
      Optional<CloudJobConfiguration> jobConfig = configService.load(each);
      if (!jobConfig.isPresent()) {
        regCenter.remove(ReadyNode.getReadyJobNodePath(each));
        continue;
      }
      if (!runningService.isJobRunning(each)
          || JobExecutionType.DAEMON == jobConfig.get().getJobExecutionType()) {
        result.add(JobContext.from(jobConfig.get(), ExecutionType.READY));
      }
    }
    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);
              }
            }));
  }
  public DescribeAlarmsForMetricResponseType describeAlarmsForMetric(
      DescribeAlarmsForMetricType request) throws CloudWatchException {
    DescribeAlarmsForMetricResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();

    try {
      // IAM Action Check
      checkActionPermission(PolicySpec.CLOUDWATCH_DESCRIBEALARMSFORMETRIC, ctx);
      final OwnerFullName ownerFullName = ctx.getUserFullName();
      final String accountId = ownerFullName.getAccountNumber();
      final Map<String, String> dimensionMap =
          TransformationFunctions.DimensionsToMap.INSTANCE.apply(
              validateDimensions(request.getDimensions()));
      final String metricName = validateMetricName(request.getMetricName(), true);
      final String namespace = validateNamespace(request.getNamespace(), true);
      final Integer period = validatePeriod(request.getPeriod(), false);
      final Statistic statistic = validateStatistic(request.getStatistic(), false);
      final Units unit = validateUnits(request.getUnit(), true);
      Collection<AlarmEntity> results =
          AlarmManager.describeAlarmsForMetric(
              accountId, dimensionMap, metricName, namespace, period, statistic, unit);
      MetricAlarms metricAlarms = new MetricAlarms();
      metricAlarms.setMember(
          Lists.newArrayList(
              Collections2.<AlarmEntity, MetricAlarm>transform(
                  results, TransformationFunctions.AlarmEntityToMetricAlarm.INSTANCE)));
      reply.getDescribeAlarmsForMetricResult().setMetricAlarms(metricAlarms);
    } catch (Exception ex) {
      handleException(ex);
    }
    return reply;
  }
  @GET
  @Path("/{serverName}/segments")
  @Produces(MediaType.APPLICATION_JSON)
  public Response getServerSegments(
      @PathParam("serverName") String serverName, @QueryParam("full") String full) {
    Response.ResponseBuilder builder = Response.status(Response.Status.OK);
    DruidServer server = serverInventoryView.getInventoryValue(serverName);
    if (server == null) {
      return Response.status(Response.Status.NOT_FOUND).build();
    }

    if (full != null) {
      return builder.entity(server.getSegments().values()).build();
    }

    return builder
        .entity(
            Collections2.transform(
                server.getSegments().values(),
                new Function<DataSegment, String>() {
                  @Override
                  public String apply(DataSegment segment) {
                    return segment.getIdentifier();
                  }
                }))
        .build();
  }
Beispiel #11
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);
    }
  }
Beispiel #12
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
        + "]]";
  }
  @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);
    }
  }
  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) {}"));
  }
Beispiel #15
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();
      }
    }
  @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;
  }
  @SuppressWarnings("unchecked")
  private void addAuditLogEntries(Feed feed, Integer maxResults, Integer startIndex) {
    FeedData feedData = getFeedData(maxResults, startIndex);

    addTotalEntriesMarkup(feed, feedData.totalEntries);
    addStartIndexMarkup(feed, feedData.startIndex);

    // add links to next and previous pages if any exist, and to first/last pages
    int nextPageStartIndex = feedData.startIndex + feedData.maxResults;
    int previousPageStartIndex = max(feedData.startIndex - feedData.maxResults, 0);
    int firstPageStartIndex = 0;
    int lastPageStartIndex =
        (int) Math.floor((feedData.totalEntries - 1) / feedData.maxResults) * feedData.maxResults;

    if (nextPageStartIndex < feedData.totalEntries) {
      addLink(
          feed, uriBuilder.buildAuditLogFeedUri(feedData.maxResults, nextPageStartIndex), "next");
      addLink(
          feed, uriBuilder.buildAuditLogFeedUri(feedData.maxResults, lastPageStartIndex), "last");
    }

    if (feedData.startIndex > 0) {
      addLink(
          feed, uriBuilder.buildAuditLogFeedUri(feedData.maxResults, firstPageStartIndex), "first");
      addLink(
          feed,
          uriBuilder.buildAuditLogFeedUri(feedData.maxResults, previousPageStartIndex),
          "previous");
    }

    // transform AuditLogEntry elements to rome Entry elements and add to the feed
    feed.getEntries()
        .addAll(Collections2.transform(feedData.entries, auditLogEntryToFeedEntryFn()));
  }
Beispiel #18
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();
  }
 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"));
   }
 }
  @Override
  public void setAdditionalDefaultGroups(Set<String> groupNames) {
    try {
      if (groupNames == null) return;

      final Map<String, Role> nameToRole =
          Maps.uniqueIndex(roleService.loadAll(), Roles.roleToNameFunction());
      final List<String> groupIds =
          Lists.newArrayList(
              Collections2.transform(
                  groupNames,
                  new Function<String, String>() {
                    @Nullable
                    @Override
                    public String apply(@Nullable String groupName) {
                      if (groupName == null || !nameToRole.containsKey(groupName)) {
                        return null;
                      }
                      return nameToRole.get(groupName).getId();
                    }
                  }));
      fields.put(ADDITIONAL_DEFAULT_GROUPS, groupIds);
    } catch (NotFoundException e) {
      LOG.error("Unable to convert group names to ids", e);
      throw new IllegalStateException("Unable to convert group names to ids", e);
    }
  }
  private static Collection<FqName> getJavaClasses(
      @NotNull final String typeName, @NotNull Project project, final GlobalSearchScope scope) {
    PsiShortNamesCache cache = PsiShortNamesCache.getInstance(project);

    PsiClass[] classes =
        cache.getClassesByName(
            typeName,
            new DelegatingGlobalSearchScope(scope) {
              @Override
              public boolean contains(@NotNull VirtualFile file) {
                return myBaseScope.contains(file) && file.getFileType() != JetFileType.INSTANCE;
              }
            });

    return Collections2.transform(
        Lists.newArrayList(classes),
        new Function<PsiClass, FqName>() {
          @Nullable
          @Override
          public FqName apply(@Nullable PsiClass javaClass) {
            assert javaClass != null;
            return new FqName(javaClass.getQualifiedName());
          }
        });
  }
  private static Collection<FqName> getJetExtensionFunctions(
      @NotNull final String referenceName,
      @NotNull JetSimpleNameExpression expression,
      @NotNull Project project) {
    JetShortNamesCache namesCache = JetCacheManager.getInstance(project).getNamesCache();
    Collection<DeclarationDescriptor> jetCallableExtensions =
        namesCache.getJetCallableExtensions(
            new Condition<String>() {
              @Override
              public boolean value(String callableExtensionName) {
                return callableExtensionName.equals(referenceName);
              }
            },
            expression,
            GlobalSearchScope.allScope(project));

    return Sets.newHashSet(
        Collections2.transform(
            jetCallableExtensions,
            new Function<DeclarationDescriptor, FqName>() {
              @Override
              public FqName apply(@Nullable DeclarationDescriptor declarationDescriptor) {
                assert declarationDescriptor != null;
                return DescriptorUtils.getFQName(declarationDescriptor).toSafe();
              }
            }));
  }
 @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;
             }
           }));
 }
Beispiel #24
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();
  }
Beispiel #25
0
  /**
   * @param spec
   * @param dir
   */
  public static File generateSchema(
      final BeanModel spec, final String namespaceParam, final File fileOrDir) {
    final SchemaGenerator gen = newGenerator(fileOrDir);

    final String namespace = String.format("%s.xml", spec.getCommonNamespace());
    final Collection<SchemaElement> elements =
        Collections2.transform(
            spec.getDefinitions(),
            new Function<Definition, SchemaElement>() {
              @Override
              public SchemaElement apply(final Definition def) {
                return new SchemaElement(SchemaContext.getSchemaType(def), SchemaContext.elm(def));
              }
            });
    final SchemaContext context = new SchemaContext(spec, namespace, elements);

    final File schemaFile;
    // in our case the target directory may actually be the schema file
    if (fileOrDir.exists() && fileOrDir.isFile()) {
      schemaFile = fileOrDir;
    } else {
      final File subDir = IO.assertDirExists(new File(fileOrDir, namespace.replace('.', '/')));
      schemaFile = new File(subDir, "schema.xsd");
    }

    gen.generateFile(context, schemaFile, schemaTemplate);
    return schemaFile;
  }
Beispiel #26
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();
  }
Beispiel #27
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;
    }
  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;
  }
 public Collection<String> getServerNames() {
   return Collections2.transform(
       PluginImpl.getInstance().getServers(),
       new Function<Hypervisor, String>() {
         public String apply(@Nullable Hypervisor input) {
           return input.getHypervisorHost();
         }
       });
 }
 public GroupEventHandlerImpl(FilteredGroupsProvider filteredGroupsProvider) {
   Preconditions.checkNotNull(filteredGroupsProvider);
   // filtered groups are treated in a case-insensitive manner.
   // We convert them all to lowercase for comparison.
   filteredGroups =
       ImmutableSet.copyOf(
           Collections2.transform(
               filteredGroupsProvider.getGroups(), IdentifierUtils.TO_LOWER_CASE));
 }