/** {@inheritDoc} */
 protected Objects.ToStringHelper string() {
   return toStringHelper(this)
       .omitNullValues()
       .add("code", code)
       .add("location", location.orNull())
       .add("message", message.orNull());
 }
Esempio n. 2
0
  @Override
  public Model save() {
    Model save = super.save();

    save.putInstance(EQUIPPED_ITEM, equippedWeapon.orNull());
    save.putInstance(EQUIPPED_ARMOR, equippedArmor.orNull());

    return save;
  }
Esempio n. 3
0
 @Override
 public String toString() {
   return toStringHelper(this)
       .omitNullValues()
       .add("arn", arn)
       .add("id", id)
       .add("name", name.orNull())
       .add("path", path.orNull())
       .add("createDate", createDate)
       .toString();
 }
Esempio n. 4
0
 @Override
 public String toString() {
   return Objects.toStringHelper(this)
       .add("select", select)
       .add("from", from)
       .add("where", where.orNull())
       .add("groupBy", groupBy)
       .add("having", having.orNull())
       .add("orderBy", orderBy)
       .add("limit", limit.orNull())
       .add("offset", offset.orNull())
       .toString();
 }
Esempio n. 5
0
 public String toString() {
   switch (type) {
     case ADDED:
       return "[MISSING] -> "
           + TextValueSerializer.asString(Optional.fromNullable((Object) newGeometry.orNull()));
     case REMOVED:
       return TextValueSerializer.asString(Optional.fromNullable((Object) oldGeometry.orNull()))
           + " -> [MISSING]";
     case MODIFIED:
     default:
       return diff.toString();
   }
 }
Esempio n. 6
0
  /**
   * Parses the given CSVRecords from a CSV file into a List of objects.
   *
   * @param records must be non-empty
   * @param errors for recording validation errors
   */
  private TabularParseResult<T> readProcedures(
      final List<CSVRecord> records, final Collection<TabularUploadError> errors) {
    int firstRow = 0;

    // Detect if the first row is a header and strip if so.
    if (fRowTranslator.isHeaderRow(records.get(0))) {
      LOGGER.debug("Ignoring a header row in the CSV.");
      firstRow = 1;
    }

    LOGGER.trace(
        "About to translate {} records from CSV into Procedure objects.",
        records.size() - firstRow);

    // Parse each line and record errors.
    final ArrayList<T> procedures = new ArrayList<>(records.size());
    for (int i = firstRow; i < records.size(); ++i) {
      final CSVRecord row = records.get(i);
      final Optional<T> rowObject = fRowTranslator.translateRow(row, errors, i + 1);
      // Per TabularParseResult, represent invalid objects as nulls.
      procedures.add(rowObject.orNull());
    }

    return new TabularParseResult<>(procedures, errors);
  }
Esempio n. 7
0
 @Override
 public String asText() {
   switch (type) {
     case ADDED:
       return type.name().toCharArray()[0]
           + "\t"
           + TextValueSerializer.asString(Optional.fromNullable((Object) newGeometry.orNull()));
     case REMOVED:
       return type.name().toCharArray()[0]
           + "\t"
           + TextValueSerializer.asString(Optional.fromNullable((Object) oldGeometry.orNull()));
     case MODIFIED:
     default:
       return type.name().toCharArray()[0] + "\t" + diff.asText();
   }
 }
 public Method get(MethodInvocation invocation) {
   Class<?> owner = invocation.getDelegate().getClass();
   String name = invocation.getName();
   Class<?>[] parameterTypes = invocation.getParameterTypes();
   MethodInvocationKey key = new MethodInvocationKey(owner, name, parameterTypes);
   lock.readLock().lock();
   Optional<Method> cached = store.get(key);
   if (cached == null) {
     cacheMiss++;
     lock.readLock().unlock();
     lock.writeLock().lock();
     try {
       cached = store.get(key);
       if (cached == null) {
         cached = lookup(owner, name, parameterTypes);
         if (cacheMiss % 10 == 0) {
           removeDirtyEntries();
         }
         store.put(key, cached);
       }
       lock.readLock().lock();
     } finally {
       lock.writeLock().unlock();
     }
   } else {
     cacheHit++;
   }
   try {
     return cached.orNull();
   } finally {
     lock.readLock().unlock();
   }
 }
Esempio n. 9
0
 protected ToStringHelper string() {
   return Objects.toStringHelper(this)
       .omitNullValues()
       .add("relation", relation)
       .add("type", type.orNull())
       .add("href", href);
 }
 public NsiV2RequestDetails(
     Optional<URI> replyTo, String correlationId, String requesterNsa, String providerNsa) {
   this.replyTo = replyTo.orNull();
   this.correlationId = correlationId;
   this.requesterNsa = Preconditions.checkNotNull(requesterNsa, "requesterNsa is required");
   this.providerNsa = Preconditions.checkNotNull(providerNsa, "providerNsa is required");
 }
 @Override
 public String toString() {
   return toStringHelper("")
       .omitNullValues()
       .add("items", items)
       .add("nextRecord", nextRecord.orNull())
       .toString();
 }
Esempio n. 12
0
 @GET
 public List<ImageBean> getImagesByAppname(
     @QueryParam("app") Optional<String> appName,
     @QueryParam("start") Optional<Integer> start,
     @QueryParam("size") Optional<Integer> size)
     throws Exception {
   return imageDAO.getImages(appName.orNull(), start.or(1), size.or(DEFAULT_PAGE_SIZE));
 }
Esempio n. 13
0
 /** {@inheritDoc} */
 protected Objects.ToStringHelper string() {
   return toStringHelper(this)
       .omitNullValues()
       .add("name", name)
       .add("description", description.orNull())
       .add("beginTime", beginTime)
       .add("endTime", endTime);
 }
 @Override
 public String toString() {
   return toStringHelper("")
       .omitNullValues()
       .add("name", name)
       .add("type", type)
       .add("identifier", identifier.orNull())
       .toString();
 }
Esempio n. 15
0
  static Response response(ResponseCode code, Optional<Result> result, String... messages) {
    Response response = Responses.empty().setResponseCode(code).setResult(result.orNull());
    if (messages.length > 0) {
      response.setDetails(
          FluentIterable.from(Arrays.asList(messages)).transform(MESSAGE_TO_DETAIL).toList());
    }

    return response;
  }
Esempio n. 16
0
  /** {@inheritDoc} */
  @Override
  protected void processTemplate(FreenetRequest request, TemplateContext templateContext)
      throws RedirectException {
    super.processTemplate(request, templateContext);
    String soneId = request.getHttpRequest().getParam("sone");
    Optional<Sone> sone = webInterface.getCore().getSone(soneId);
    templateContext.set("sone", sone.orNull());
    templateContext.set("soneId", soneId);
    if (!sone.isPresent()) {
      return;
    }
    List<Post> sonePosts = sone.get().getPosts();
    sonePosts.addAll(webInterface.getCore().getDirectedPosts(sone.get().getId()));
    Collections.sort(sonePosts, Post.TIME_COMPARATOR);
    Pagination<Post> postPagination =
        new Pagination<Post>(sonePosts, webInterface.getCore().getPreferences().getPostsPerPage())
            .setPage(parseInt(request.getHttpRequest().getParam("postPage"), 0));
    templateContext.set("postPagination", postPagination);
    templateContext.set("posts", postPagination.getItems());
    Set<PostReply> replies = sone.get().getReplies();
    final Map<Post, List<PostReply>> repliedPosts = new HashMap<Post, List<PostReply>>();
    for (PostReply reply : replies) {
      Optional<Post> post = reply.getPost();
      if (!post.isPresent()
          || repliedPosts.containsKey(post.get())
          || sone.get().equals(post.get().getSone())
          || (sone.get().getId().equals(post.get().getRecipientId().orNull()))) {
        continue;
      }
      repliedPosts.put(post.get(), webInterface.getCore().getReplies(post.get().getId()));
    }
    List<Post> posts = new ArrayList<Post>(repliedPosts.keySet());
    Collections.sort(
        posts,
        new Comparator<Post>() {

          @Override
          public int compare(Post leftPost, Post rightPost) {
            return (int)
                Math.min(
                    Integer.MAX_VALUE,
                    Math.max(
                        Integer.MIN_VALUE,
                        repliedPosts.get(rightPost).get(0).getTime()
                            - repliedPosts.get(leftPost).get(0).getTime()));
          }
        });

    Pagination<Post> repliedPostPagination =
        new Pagination<Post>(posts, webInterface.getCore().getPreferences().getPostsPerPage())
            .setPage(parseInt(request.getHttpRequest().getParam("repliedPostPage"), 0));
    templateContext.set("repliedPostPagination", repliedPostPagination);
    templateContext.set("repliedPosts", repliedPostPagination.getItems());
  }
Esempio n. 17
0
 public TaskRunner create(
     final long delay, final String containerId, final TaskRunner.Listener listener) {
   return TaskRunner.builder()
       .delayMillis(delay)
       .config(taskConfig)
       .docker(docker)
       .healthChecker(healthChecker.orNull())
       .existingContainerId(containerId)
       .listener(new BroadcastingListener(concat(this.listeners, asList(listener))))
       .registrar(registrar)
       .build();
 }
Esempio n. 18
0
  public static Optional<File> resolveArtifact(
      String groupId,
      String artifactId,
      String version,
      Optional<String> type,
      Optional<String> classifier,
      Optional<List<Repository>> customRepositories) {
    Optional<File> result;

    LocalRepository localRepository =
        MavenSettingsUtil.getLocalRepository(MavenSettingsUtil.loadSettings());
    RepositorySystem system = AetherBootstrap.newRepositorySystem();
    RepositorySystemSession session =
        AetherBootstrap.newRepositorySystemSession(
            system, localRepository.getBasedir().getAbsolutePath());

    Artifact artifact =
        new DefaultArtifact(groupId, artifactId, classifier.orNull(), type.orNull(), version);
    ArtifactRequest artifactRequest = new ArtifactRequest();
    artifactRequest.setArtifact(artifact);
    artifactRequest.setRepositories(
        MavenSettingsUtil.getRemoteRepositories(
            MavenSettingsUtil.loadSettings(), customRepositories.orNull()));

    try {
      ArtifactResult artifactResult = system.resolveArtifact(session, artifactRequest);
      artifact = artifactResult.getArtifact();
      if (artifact != null) {
        result = Optional.fromNullable(artifact.getFile());
      } else {
        result = Optional.absent();
      }
    } catch (ArtifactResolutionException e) {
      // TODO add error handling -> maybe throw an exception that indicates the error or return an
      // Optional
      result = Optional.absent();
    }

    return result;
  }
Esempio n. 19
0
 public WhereClause normalize(EvaluatingNormalizer normalizer) {
   if (noMatch || query == null) {
     return this;
   }
   Symbol normalizedQuery = normalizer.normalize(query);
   if (normalizedQuery == query) {
     return this;
   }
   WhereClause normalizedWhereClause =
       new WhereClause(normalizedQuery, docKeys.orNull(), partitions);
   normalizedWhereClause.clusteredBy = clusteredBy;
   return normalizedWhereClause;
 }
Esempio n. 20
0
 @Override
 public String toString() {
   return Objects.toStringHelper(this)
       .omitNullValues()
       .add("id", id)
       .add("name", name)
       .add("type", type)
       .add("accountId", accountId)
       .add("ownerId", ownerId)
       .add("dnssecStatus", dnssecStatus)
       .add("primarySrc", primarySrc.orNull())
       .toString();
 }
Esempio n. 21
0
 /** {@inheritDoc} */
 protected Objects.ToStringHelper string() {
   return super.string()
       .omitNullValues()
       .add("items", tags)
       .add("machineType", machineType)
       .add("status", status)
       .add("statusMessage", statusMessage.orNull())
       .add("zone", zone)
       .add("networkInterfaces", networkInterfaces)
       .add("disks", disks)
       .add("metadata", metadata)
       .add("serviceAccounts", serviceAccounts);
 }
 /** {@inheritDoc} */
 protected Objects.ToStringHelper string() {
   return super.string()
       .omitNullValues()
       .add("targetLink", targetLink)
       .add("targetId", targetId.orNull())
       .add("clientOperationId", clientOperationId.orNull())
       .add("status", status)
       .add("statusMessage", statusMessage.orNull())
       .add("user", user)
       .add("progress", progress.orNull())
       .add("insertTime", insertTime)
       .add("startTime", startTime.orNull())
       .add("endTime", endTime.orNull())
       .add("httpError", httpError.orNull())
       .add("operationType", operationType)
       .add("errors", errors)
       .add("region", region.orNull())
       .add("zone", zone.orNull());
 }
Esempio n. 23
0
  // Optional.of(T) 创建指定引用的Optional实例,若引用为null则快速失败
  @Test
  public void testOf() {
    Optional<Integer> possible = Optional.of(5);
    assertThat(possible.get(), is(5)); // 返回Optional所包含的引用,若引用缺失,则抛出java.lang.IllegalStateException
    assertThat(possible.isPresent(), is(true)); // 如果Optional包含非null的引用(引用存在),返回true
    assertThat(possible.or(-1), is(5)); // 返回Optional所包含的引用,若引用缺失,返回指定的值
    assertThat(possible.orNull(), is(5)); // 返回Optional所包含的引用,若引用缺失,返回null

    try {
      Optional.of(null);
      fail("Expected NullPointerException");
    } catch (NullPointerException e) {
    }
  }
Esempio n. 24
0
  // Optional.absent() 创建引用缺失的Optional实例
  @Test
  public void testAbsent() {
    Optional<Integer> optional = Optional.absent();
    assertThat(optional.isPresent(), is(false));

    try {
      assertThat(optional.or(-1), is(-1)); // 返回Optional所包含的引用,若引用缺失,返回指定的值
      assertThat(optional.orNull() == null, is(true)); // 返回Optional所包含的引用,若引用缺失,返回null
      optional.get(); // 返回Optional所包含的引用,若引用缺失,则抛出java.lang.IllegalStateException
      fail("Expected IllegalStateException");
    } catch (IllegalStateException e) {
      assertThat(e.getMessage(), endsWith("cannot be called on an absent value"));
    }
  }
Esempio n. 25
0
  @Override
  public IDescription getChildWithKeyword(final String keyword) {
    final Optional<IDescription> optional =
        Iterables.tryFind(
            getChildren(),
            new Predicate<IDescription>() {

              @Override
              public boolean apply(final IDescription input) {
                return input.getKeyword().equals(keyword);
              }
            });
    return optional.orNull();
  }
 /**
  * Create procedure description from XML text stored in ValidProcedureTime table
  *
  * @param procedure Hibernate procedure entity
  * @param vpt Hibernate ValidProcedureTime entity
  * @param version Requested SOS version
  * @param session Hibernate session
  * @return created SosProcedureDescription
  * @throws OwsExceptionReport If an error occurs
  */
 public SosProcedureDescription createSosProcedureDescriptionFromValidProcedureTime(
     Procedure procedure,
     String requestedDescriptionFormat,
     ValidProcedureTime vpt,
     String version,
     Locale i18n,
     Session session)
     throws OwsExceptionReport {
   if (vpt != null) {
     checkOutputFormatWithDescriptionFormat(
         procedure.getIdentifier(), vpt, requestedDescriptionFormat, getFormat(vpt));
   } else {
     checkOutputFormatWithDescriptionFormat(
         procedure.getIdentifier(), procedure, requestedDescriptionFormat, getFormat(procedure));
   }
   Optional<SosProcedureDescription> description =
       create(procedure, requestedDescriptionFormat, vpt, i18n, session);
   if (description.isPresent()) {
     enrich(
         description.get(),
         procedure,
         version,
         requestedDescriptionFormat,
         getValidTime(vpt),
         null,
         i18n,
         session);
     if (!requestedDescriptionFormat.equals(description.get().getDescriptionFormat())) {
       SosProcedureDescription converted =
           convert(
               description.get().getDescriptionFormat(),
               requestedDescriptionFormat,
               description.get());
       converted.setDescriptionFormat(requestedDescriptionFormat);
       return converted;
     }
   }
   return description.orNull();
 }
Esempio n. 27
0
  @Override
  public PagedIterable<T> apply(ListPage<T> input) {
    if (input.nextMarker() == null) return PagedIterables.of(input);

    Optional<Object> project =
        tryFind(request.getCaller().get().getArgs(), instanceOf(String.class));

    Optional<Object> listOptions =
        tryFind(request.getInvocation().getArgs(), instanceOf(ListOptions.class));

    assert project.isPresent()
        : String.format(
            "programming error, method %s should have a string param for the " + "project",
            request.getCaller().get().getInvokable());

    return PagedIterables.advance(
        input,
        fetchNextPage(
            project.get().toString(),
            (String) input.nextMarker().orNull(),
            (ListOptions) listOptions.orNull()));
  }
  /**
   * Return a new Curator connection to the ensemble. It is the caller's responsibility to start and
   * close the connection.
   */
  public CuratorFramework newCurator() {
    // Make all of the curator threads daemon threads so they don't block the JVM from terminating.
    // Also label them
    // with the ensemble they're connecting to, in case someone is trying to sort through a thread
    // dump.
    ThreadFactory threadFactory =
        new ThreadFactoryBuilder()
            .setNameFormat("CuratorFramework[" + _connectString.or(DEFAULT_CONNECT_STRING) + "]-%d")
            .setDaemon(true)
            .build();

    org.apache.curator.RetryPolicy retry =
        _setterRetryPolicy.or(
            (_configRetryPolicy != null) ? _configRetryPolicy : DEFAULT_RETRY_POLICY);
    return CuratorFrameworkFactory.builder()
        .ensembleProvider(new ResolvingEnsembleProvider(_connectString.or(DEFAULT_CONNECT_STRING)))
        .retryPolicy(retry)
        .sessionTimeoutMs(Ints.checkedCast(_sessionTimeout.toMilliseconds()))
        .connectionTimeoutMs(Ints.checkedCast(_connectionTimeout.toMilliseconds()))
        .namespace(_namespace.orNull())
        .threadFactory(threadFactory)
        .build();
  }
Esempio n. 29
0
 private static @Nullable Object stripOptional(@Nullable Object value) {
   if (value == null) {
     return null;
   }
   if (value instanceof Optional) {
     Optional<?> val = (Optional<?>) value;
     return val.orNull();
   }
   if (isUnshadedGuavaOptionalClass(value)) {
     // this is just for plugin tests that run against shaded glowroot-core
     Class<?> optionalClass = value.getClass().getSuperclass();
     // just tested that super class is not null in condition
     checkNotNull(optionalClass);
     try {
       Method orNullMethod = optionalClass.getMethod("orNull");
       return orNullMethod.invoke(value);
     } catch (Exception e) {
       logger.error(e.getMessage(), e);
       return null;
     }
   }
   return value;
 }
Esempio n. 30
0
 /**
  * @return the {@code FieldType} corresponding to the {@link Optional}'s value.
  * @see #forValue(Object)
  */
 public static FieldType forValue(Optional<Object> field) {
   return forValue(field.orNull());
 }