@Override
 public File.FileList list(
     PaginationAndSorting paginationAndSorting,
     String folderPath,
     Optional<List<String>> patterns,
     Optional<FileType> fileType,
     Optional<String> gotoPath) {
   DsmWebapiRequest request =
       new DsmWebapiRequest(getApiId(), API_VERSION, getApiInfo().getPath(), METHOD_LIST)
           .parameter(PARAMETER_FOLDER_PATH, folderPath)
           .parameter(PARAMETER_OFFSET, Integer.toString(paginationAndSorting.getOffset()))
           .parameter(PARAMETER_LIMIT, Integer.toString(paginationAndSorting.getLimit()))
           .parameter(PARAMETER_SORT_BY, paginationAndSorting.getSortBy().getRepresentation())
           .parameter(
               PARAMETER_SORT_DIRECTION,
               paginationAndSorting.getSortDirection().getRepresentation())
           .parameter(
               PARAMETER_PATTERN,
               Joiner.on(',').join(patterns.orElse(Collections.<String>emptyList())))
           .parameter(PARAMETER_FILETYPE, fileType.orElse(FileType.ALL).getRepresentation())
           .parameter(PARAMETER_GOTO_PATH, gotoPath.orElse(""))
           .parameter(PARAMETER_ADDITIONAL, PARAMETER_VALUE_ADDITIONAL);
   FileListResponse response =
       getDsmWebapiClient()
           .call(request, FileListResponse.class, new FileListErrorHandler(folderPath));
   return response.getData();
 }
  /**
   * Transforms a block entity with the change of block type. This is driven from the delta between
   * the old and new block type prefabs, but takes into account changes made to the block entity.
   *
   * @param blockEntity The entity to update
   * @param oldType The previous type of the block
   * @param type The new type of the block
   */
  private void updateBlockEntityComponents(
      EntityRef blockEntity,
      Block oldType,
      Block type,
      Set<Class<? extends Component>> retainComponents) {
    BlockComponent blockComponent = blockEntity.getComponent(BlockComponent.class);

    Optional<Prefab> oldPrefab = oldType.getPrefab();
    EntityBuilder oldEntityBuilder = entityManager.newBuilder(oldPrefab.orElse(null));
    oldEntityBuilder.addComponent(
        new BlockComponent(oldType, new Vector3i(blockComponent.getPosition())));
    BeforeEntityCreated oldEntityEvent =
        new BeforeEntityCreated(oldPrefab.orElse(null), oldEntityBuilder.iterateComponents());
    blockEntity.send(oldEntityEvent);
    for (Component comp : oldEntityEvent.getResultComponents()) {
      oldEntityBuilder.addComponent(comp);
    }

    Optional<Prefab> newPrefab = type.getPrefab();
    EntityBuilder newEntityBuilder = entityManager.newBuilder(newPrefab.orElse(null));
    newEntityBuilder.addComponent(
        new BlockComponent(type, new Vector3i(blockComponent.getPosition())));
    BeforeEntityCreated newEntityEvent =
        new BeforeEntityCreated(newPrefab.orElse(null), newEntityBuilder.iterateComponents());
    blockEntity.send(newEntityEvent);
    for (Component comp : newEntityEvent.getResultComponents()) {
      newEntityBuilder.addComponent(comp);
    }

    for (Component component : blockEntity.iterateComponents()) {
      if (!COMMON_BLOCK_COMPONENTS.contains(component.getClass())
          && !entityManager
              .getComponentLibrary()
              .getMetadata(component.getClass())
              .isRetainUnalteredOnBlockChange()
          && !newEntityBuilder.hasComponent(component.getClass())
          && !retainComponents.contains(component.getClass())) {
        blockEntity.removeComponent(component.getClass());
      }
    }

    blockComponent.setBlock(type);
    blockEntity.saveComponent(blockComponent);

    HealthComponent health = blockEntity.getComponent(HealthComponent.class);
    if (health == null && type.isDestructible()) {
      blockEntity.addComponent(
          new HealthComponent(type.getHardness(), type.getHardness() / BLOCK_REGEN_SECONDS, 1.0f));
    } else if (health != null && !type.isDestructible()) {
      blockEntity.removeComponent(HealthComponent.class);
    } else if (health != null && type.isDestructible()) {
      health.maxHealth = type.getHardness();
      health.currentHealth = Math.min(health.currentHealth, health.maxHealth);
      blockEntity.saveComponent(health);
    }

    for (Component comp : newEntityBuilder.iterateComponents()) {
      copyIntoPrefab(blockEntity, comp, retainComponents);
    }
  }
예제 #3
0
 public IngestionModule build() {
   // @formatter:off
   return new IngestionModule(
       updateMetrics.orElse(DEFAULT_UPDATE_METRICS),
       updateMetadata.orElse(DEFAULT_UPDATE_METADATA),
       updateSuggestions.orElse(DEFAULT_UPDATE_SUGGESTIONS),
       maxConcurrentWrites.orElse(DEFAULT_MAX_CONCURRENT_WRITES),
       filter);
   // @formatter:on
 }
예제 #4
0
 public String toOneLineString() {
   return String.format(
       "%s\t%s\t%s\t%s\t%s\t%-25s %-25s %s",
       toString(isValid()),
       toString(this.success),
       toString(this.sourceTerm.isPresent() ? this.getSourceTermType() : "-"),
       toString(this.targetTerm.isPresent() ? this.getTargetTermType() : "-"),
       toString(this.method),
       sourceLemma.orElse("-"),
       targetLemma.orElse("-"),
       this.comment.orElse("-"));
 }
예제 #5
0
  @Override
  public Optional<DataPoint<PhysicalActivity>> asDataPoint(JsonNode sessionNode) {

    checkNotNull(sessionNode);

    String activityName = asRequiredString(sessionNode, "activityType");

    PhysicalActivity.Builder builder = new PhysicalActivity.Builder(activityName);

    Optional<Double> distance = asOptionalDouble(sessionNode, "distance");

    if (distance.isPresent()) {
      builder.setDistance(new LengthUnitValue(MILE, distance.get()));
    }

    Optional<OffsetDateTime> startDateTime = asOptionalOffsetDateTime(sessionNode, "startTime");
    Optional<Double> durationInSec = asOptionalDouble(sessionNode, "duration");

    if (startDateTime.isPresent() && durationInSec.isPresent()) {
      DurationUnitValue durationUnitValue = new DurationUnitValue(SECOND, durationInSec.get());
      builder.setEffectiveTimeFrame(
          ofStartDateTimeAndDuration(startDateTime.get(), durationUnitValue));
    }

    asOptionalBigDecimal(sessionNode, "calories")
        .ifPresent(calories -> builder.setCaloriesBurned(new KcalUnitValue(KILOCALORIE, 96.8)));

    PhysicalActivity measure = builder.build();

    Optional<String> externalId = asOptionalString(sessionNode, "id");

    return Optional.of(
        newDataPoint(measure, RESOURCE_API_SOURCE_NAME, externalId.orElse(null), null));
  }
예제 #6
0
  @Override
  public String parseMime(String baseName) {
    String ext = FilenameUtils.getExtension(baseName);
    Optional<String> mime = Optional.ofNullable(extensionRegistry.get(ext));

    return mime.orElse(MIME_FOR_UNKNOWN);
  }
  /**
   * Maps a JSON response node from the Fitbit API into a {@link StepCount} measure
   *
   * @param node a JSON node for an individual object in the "activities-steps" array retrieved from
   *     the activities/steps Fitbit API endpoint
   * @return a {@link DataPoint} object containing a {@link StepCount} measure with the appropriate
   *     values from the node parameter, wrapped as an {@link Optional}
   */
  @Override
  protected Optional<DataPoint<StepCount>> asDataPoint(JsonNode node) {

    int stepCountValue = Integer.parseInt(asRequiredString(node, "value"));

    if (stepCountValue == 0) {
      return Optional.empty();
    }

    StepCount.Builder builder = new StepCount.Builder(stepCountValue);

    Optional<LocalDate> stepDate = asOptionalLocalDate(node, "dateTime");

    if (stepDate.isPresent()) {
      LocalDateTime startDateTime = stepDate.get().atTime(0, 0, 0, 0);

      builder.setEffectiveTimeFrame(
          TimeInterval.ofStartDateTimeAndDuration(
              combineDateTimeAndTimezone(startDateTime),
              new DurationUnitValue(DurationUnit.DAY, 1)));
    }

    StepCount measure = builder.build();
    Optional<Long> externalId = asOptionalLong(node, "logId");
    return Optional.of(newDataPoint(measure, externalId.orElse(null)));
  }
예제 #8
0
  public static ProjectVulnerabilityRating updateProjectVulnerabilityRatingFromRequest(
      Optional<ProjectVulnerabilityRating> projectVulnerabilityRatings, ResourceRequest request) {
    String projectId = request.getParameter(PortalConstants.PROJECT_ID);
    ProjectVulnerabilityRating projectVulnerabilityRating =
        projectVulnerabilityRatings.orElse(
            new ProjectVulnerabilityRating()
                .setProjectId(projectId)
                .setVulnerabilityIdToReleaseIdToStatus(new HashMap<>()));

    String vulnerabilityId = request.getParameter(PortalConstants.VULNERABILITY_ID);
    String releaseId = request.getParameter(PortalConstants.RELEASE_ID);
    if (!projectVulnerabilityRating.isSetVulnerabilityIdToReleaseIdToStatus()) {
      projectVulnerabilityRating.setVulnerabilityIdToReleaseIdToStatus(new HashMap<>());
    }

    Map<String, Map<String, List<VulnerabilityCheckStatus>>> vulnerabilityIdToReleaseIdToStatus =
        projectVulnerabilityRating.getVulnerabilityIdToReleaseIdToStatus();
    if (!vulnerabilityIdToReleaseIdToStatus.containsKey(vulnerabilityId)) {
      vulnerabilityIdToReleaseIdToStatus.put(vulnerabilityId, new HashMap<>());
    }
    if (!vulnerabilityIdToReleaseIdToStatus.get(vulnerabilityId).containsKey(releaseId)) {
      vulnerabilityIdToReleaseIdToStatus.get(vulnerabilityId).put(releaseId, new ArrayList<>());
    }

    List<VulnerabilityCheckStatus> vulnerabilityCheckStatusHistory =
        vulnerabilityIdToReleaseIdToStatus.get(vulnerabilityId).get(releaseId);
    VulnerabilityCheckStatus vulnerabilityCheckStatus =
        newVulnerabilityCheckStatusFromRequest(request);
    vulnerabilityCheckStatusHistory.add(vulnerabilityCheckStatus);

    return projectVulnerabilityRating;
  }
예제 #9
0
  static void optionalTest() {
    // 不要这样,这与!=null没什么区别
    Optional<String> stringOptional = Optional.of("alibaba");
    if (stringOptional.isPresent()) {
      System.out.println(stringOptional.get().length());
    }
    Optional<String> optionalValue = Optional.of("alibaba");
    // 下面是推荐的常用操作
    optionalValue.ifPresent(s -> System.out.println(s + " contains red"));
    // 增加到集合汇总
    List<String> results = Lists.newArrayList();
    optionalValue.ifPresent(results::add);
    // 增加到集合中,并返回操作结果
    Optional<Boolean> added = optionalValue.map(results::add);

    // 无值的optional
    Optional<String> optionalString = Optional.empty();
    // 不存在值,返回“No word”
    String result = optionalValue.orElse("No word");
    // 没值,计算一个默认值
    result = optionalString.orElseGet(() -> System.getProperty("user.dir"));
    // 无值,抛一个异常
    try {
      result = optionalString.orElseThrow(NoSuchElementException::new);
    } catch (Throwable t) {
      t.getCause();
    }
  }
예제 #10
0
  private static Optional<ThrowingConsumer<Context>> validateImportMessage(
      final RequestMessage message) throws OpProcessorException {
    final Optional<List> l = message.optionalArgs(Tokens.ARGS_IMPORTS);
    if (!l.isPresent()) {
      final String msg =
          String.format(
              "A message with an [%s] op code requires a [%s] argument.",
              Tokens.OPS_IMPORT, Tokens.ARGS_IMPORTS);
      throw new OpProcessorException(
          msg,
          ResponseMessage.build(message)
              .code(ResultCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS)
              .result(msg)
              .create());
    }

    if (l.orElse(new ArrayList()).size() == 0) {
      final String msg =
          String.format(
              "A message with an [%s] op code requires that the [%s] argument has at least one import string specified.",
              Tokens.OPS_IMPORT, Tokens.ARGS_IMPORTS);
      throw new OpProcessorException(
          msg,
          ResponseMessage.build(message)
              .code(ResultCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS)
              .result(msg)
              .create());
    }

    return Optional.empty();
  }
 @Override
 protected boolean set(EntityMinecartCommandBlock container, Optional<Text> value) {
   container
       .getCommandBlockLogic()
       .setLastOutput(SpongeTexts.toComponent(value.orElse(Text.of())));
   return true;
 }
  @Override
  @SuppressWarnings("unchecked")
  public <T> T getBean(Class<T> clazz) {
    Object bean = beans.get(clazz);
    if (bean != null) {
      return (T) bean;
    }

    BeanDefinition beanDefinition = beanDefinitions.get(clazz);
    if (beanDefinition != null && beanDefinition instanceof AnnotatedBeanDefinition) {
      Optional<Object> optionalBean = createAnnotatedBean(beanDefinition);
      optionalBean.ifPresent(b -> beans.put(clazz, b));
      initialize(bean, clazz);
      return (T) optionalBean.orElse(null);
    }

    Optional<Class<?>> concreteClazz = BeanFactoryUtils.findConcreteClass(clazz, getBeanClasses());
    if (!concreteClazz.isPresent()) {
      return null;
    }

    beanDefinition = beanDefinitions.get(concreteClazz.get());
    bean = inject(beanDefinition);
    beans.put(concreteClazz.get(), bean);
    initialize(bean, concreteClazz.get());
    return (T) bean;
  }
예제 #13
0
  @Override
  public Optional<String> transform(Generator cg, File model) {
    final DependencyManager mgr = cg.getDependencyMgr();
    final Optional<String> className = fileToClassName(model.getName());
    Optional<String> packageName = packageName(className.orElse(EMPTY));
    mgr.clearDependencies();

    if (packageName.isPresent()) {
      if (mgr.isIgnored(packageName.get())) {
        packageName = Optional.empty();
      } else {
        mgr.ignorePackage(packageName.get());
      }
    }

    final Optional<String> view =
        Optional.of(
            renderJavadoc(cg, model)
                + renderPackage(model)
                + renderImports(cg, model)
                + renderClasses(cg, model));

    if (packageName.isPresent()) {
      mgr.acceptPackage(packageName.get());
    }

    return view;
  }
예제 #14
0
 @Test
 public void testOptional() {
   Optional<String> fullName = Optional.ofNullable(null);
   Assert.assertEquals("Optional.empty", fullName.toString());
   Assert.assertEquals("[none]", fullName.orElseGet(() -> "[none]"));
   Assert.assertEquals("[none2]", fullName.orElse("[none2]"));
 }
예제 #15
0
  private Object execute(RedisCallback callback) {
    try (Jedis jedis = pool.getResource()) {

      Optional<Object> optional = callback.doWithRedis(jedis);

      return optional.orElse(null);
    }
  }
 /**
  * Attempts to compile a script and cache it in the request {@link javax.script.ScriptEngine}.
  * This is only possible if the {@link javax.script.ScriptEngine} implementation implements {@link
  * javax.script.Compilable}. In the event that the requested {@link javax.script.ScriptEngine}
  * does not implement it, the method will return empty.
  */
 public Optional<CompiledScript> compile(final String script, final Optional<String> language)
     throws ScriptException {
   final String lang = language.orElse("gremlin-groovy");
   try {
     return Optional.of(scriptEngines.compile(script, lang));
   } catch (UnsupportedOperationException uoe) {
     return Optional.empty();
   }
 }
  @Test
  public void testEmptyRegistryPackage() throws Exception {
    Map<String, Object> emptyRegistryMap = new HashMap<>();

    RegistryPackageTypeConverter rptConverter = new RegistryPackageTypeConverter();
    Optional<RegistryPackageType> optionalRegistryPackage = rptConverter.convert(emptyRegistryMap);
    RegistryPackageType registryPackage = optionalRegistryPackage.orElse(null);

    assertThat(registryPackage, nullValue());
  }
예제 #18
0
 @Nullable
 public static String annotateColumnComment(Optional<String> comment, boolean partitionKey) {
   String normalizedComment = comment.orElse("").trim();
   if (partitionKey) {
     if (normalizedComment.isEmpty()) {
       normalizedComment = "Partition Key";
     } else {
       normalizedComment = "Partition Key: " + normalizedComment;
     }
   }
   return normalizedComment.isEmpty() ? null : normalizedComment;
 }
예제 #19
0
 public GlobalObject get(int id, int x, int y, int height) {
   Optional<GlobalObject> obj =
       objects
           .stream()
           .filter(
               object ->
                   object.getObjectId() == id
                       && object.getX() == x
                       && object.getY() == y
                       && object.getHeight() == height)
           .findFirst();
   return obj.orElse(null);
 }
 /**
  * Returns the git username stored in the secured preferences for the given user. The user is
  * usually the user that is logged in to CS-Studio. If no user is provided, system user is used.
  *
  * @param forUser the user for whom the username is to be retrieved
  * @return the username if it exists, or null otherwise
  */
 public static String getUsername(Optional<String> forUser) {
   String user = forUser.orElse(System.getProperty(SYSTEM_PROPERTY_USER_NAME));
   try {
     return SecurePreferences.getSecurePreferences()
         .node(Activator.ID)
         .node(user)
         .get(PREF_USERNAME, null);
   } catch (StorageException | IOException e) {
     SaveRestoreService.LOGGER.log(
         Level.WARNING, "Could not read the username from secured storage.", e);
     return null;
   }
 }
예제 #21
0
  @Test
  public void _07_옵션_다루기() {
    final Optional<String> optional = words.stream().filter(w -> w.contains("red")).findFirst();
    try {
      optional.ifPresent(
          v -> {
            throw new RuntimeException();
          });
      assert false; // 이 행은 실행되면 안됨.
    } catch (RuntimeException e) {

    }

    // 비어있는 경우는 실행되지 않음.
    Optional.empty()
        .ifPresent(
            v -> {
              throw new RuntimeException();
            });

    Set<String> results = new HashSet<>();
    optional.ifPresent(results::add);
    assertThat(results.contains("tired"), is(true));

    // 실행 결과를 받고 싶은 경우에는 map 사용.
    results = new HashSet<>();
    Optional<Boolean> added = optional.map(results::add);
    assertThat(added, is(Optional.of(Boolean.TRUE)));

    // 대상이 빈경우에는 empty Optional 반환
    Optional<Boolean> a = Optional.empty().map(v -> true);
    assertThat(a.isPresent(), is(false));

    Optional<String> emptyOptional = Optional.empty();

    // orElse로 기본값 지정 가능
    String result = emptyOptional.orElse("기본값");
    assertThat(result, is("기본값"));

    // 기본값 생성하는 코드 호출 가능
    result = emptyOptional.orElseGet(() -> System.getProperty("user.dir"));
    assertThat(result, is(System.getProperty("user.dir")));

    // 값이 없는 경우 예외 던지기
    try {
      emptyOptional.orElseThrow(NoSuchElementException::new);
      assert false;
    } catch (NoSuchElementException e) {

    }
  }
예제 #22
0
  public static <S, V extends Comparable<V>> Move<S> best(Evaluate.Directional<S, V> eval) {
    return (S incumbent, Stream<S> locality) -> {
      Optional<S> max =
          locality.max(
              new Comparator<S>() {
                public int compare(S a, S b) {
                  return eval.apply(a).compareTo(eval.apply(b));
                }
              });

      Optional<S> best = max.map((S s) -> eval.prefer(incumbent, s));
      return Optional.of(best.orElse(incumbent));
    };
  }
예제 #23
0
  public ClickedRepository(
      final java.util.Optional<java.sql.Connection> transactionContext,
      final javax.sql.DataSource dataSource,
      final org.revenj.postgres.QueryProvider queryProvider,
      final org.revenj.postgres.ObjectConverter<gen.model.test.Clicked> converter,
      final org.revenj.patterns.ServiceLocator locator) {

    this.transactionContext = transactionContext;
    this.dataSource = dataSource;
    this.queryProvider = queryProvider;
    this.transactionConnection = transactionContext.orElse(null);
    this.converter = converter;
    this.locator = locator;
  }
예제 #24
0
  public static HTTPResponse createResponse(
      final StatusLine line, final Headers responseHeaders, final Optional<InputStream> stream) {
    Optional<String> contentLengthHeader =
        responseHeaders.getFirstHeaderValue(HeaderConstants.CONTENT_LENGTH);

    MIMEType type = responseHeaders.getContentType().orElse(MIMEType.APPLICATION_OCTET_STREAM);
    Optional<Long> length = responseHeaders.getContentLength();

    Optional<Payload> payload =
        stream
            .filter(is -> line.getStatus().isBodyContentAllowed())
            .map(is -> new InputStreamPayload(is, type, length.orElse(-1L)));

    return new HTTPResponse(payload, line, responseHeaders);
  }
예제 #25
0
파일: Revenj.java 프로젝트: dstimac/revenj
 public static Container setup(
     DataSource dataSource,
     Properties properties,
     Optional<ClassLoader> classLoader,
     Iterator<SystemAspect> aspects)
     throws IOException {
   ClassLoader loader = classLoader.orElse(Thread.currentThread().getContextClassLoader());
   SimpleContainer container =
       new SimpleContainer("true".equals(properties.getProperty("revenj.resolveUnknown")));
   container.registerInstance(properties);
   container.registerInstance(ServiceLocator.class, container, false);
   container.registerInstance(DataSource.class, dataSource, false);
   container.registerInstance(ClassLoader.class, loader, false);
   String ns = properties.getProperty("revenj.namespace");
   SimpleDomainModel domainModel = new SimpleDomainModel(ns, loader);
   container.registerInstance(DomainModel.class, domainModel, false);
   container.registerFactory(DataContext.class, LocatorDataContext::asDataContext, false);
   container.registerFactory(UnitOfWork.class, LocatorDataContext::asUnitOfWork, false);
   PluginLoader plugins = new ServicesPluginLoader(loader);
   container.registerInstance(PluginLoader.class, plugins, false);
   PostgresDatabaseNotification databaseNotification =
       new PostgresDatabaseNotification(
           dataSource, Optional.of(domainModel), properties, container);
   container.registerInstance(EagerNotification.class, databaseNotification, false);
   container.registerInstance(DataChangeNotification.class, databaseNotification, true);
   ChangeNotification.registerContainer(container, databaseNotification);
   container.registerFactory(RepositoryBulkReader.class, PostgresBulkReader::create, false);
   container.registerInstance(
       PermissionManager.class, new RevenjPermissionManager(container), false);
   container.registerClass(
       new Generic<Serialization<String>>() {}.type, DslJsonSerialization.class, false);
   int total = 0;
   if (aspects != null) {
     JinqMetaModel.configure(container);
     while (aspects.hasNext()) {
       aspects.next().configure(container);
       total++;
     }
   }
   String nsAfter = properties.getProperty("revenj.namespace");
   if (!Objects.equals(ns, nsAfter)) {
     domainModel.updateNamespace(nsAfter);
   }
   properties.setProperty("revenj.aspectsCount", Integer.toString(total));
   return container;
 }
예제 #26
0
  private static Optional<ThrowingConsumer<Context>> validateUseMessage(
      final RequestMessage message) throws OpProcessorException {
    final Optional<List> l = message.optionalArgs(Tokens.ARGS_COORDINATES);
    if (!l.isPresent()) {
      final String msg =
          String.format(
              "A message with an [%s] op code requires a [%s] argument.",
              Tokens.OPS_USE, Tokens.ARGS_COORDINATES);
      throw new OpProcessorException(
          msg,
          ResponseMessage.build(message)
              .code(ResultCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS)
              .result(msg)
              .create());
    }

    final List coordinates = l.orElse(new ArrayList());
    if (coordinates.size() == 0) {
      final String msg =
          String.format(
              "A message with an [%s] op code requires that the [%s] argument has at least one set of valid maven coordinates specified.",
              Tokens.OPS_USE, Tokens.ARGS_COORDINATES);
      throw new OpProcessorException(
          msg,
          ResponseMessage.build(message)
              .code(ResultCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS)
              .result(msg)
              .create());
    }

    if (!coordinates.stream().allMatch(ControlOpProcessor::validateCoordinates)) {
      final String msg =
          String.format(
              "A message with an [%s] op code requires that all [%s] specified are valid maven coordinates with a group, artifact, and version.",
              Tokens.OPS_USE, Tokens.ARGS_COORDINATES);
      throw new OpProcessorException(
          msg,
          ResponseMessage.build(message)
              .code(ResultCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS)
              .result(msg)
              .create());
    }

    return Optional.empty();
  }
 @RequestMapping(
     method = RequestMethod.POST,
     consumes = "application/json",
     produces = "application/json")
 @ResponseBody
 public WsResponse<Usuario> login(@RequestBody LoginViewModel lvm, HttpServletResponse response) {
   response.addHeader("Content-type", "application/json;charset=UTF-8");
   Usuario usuario = null;
   if (lvm != null) {
     List<Usuario> lstUsuarios = repo.findByLogin(lvm.getLogin());
     Optional<Usuario> optUsuario =
         lstUsuarios.stream().filter(u -> u.checkSenha(lvm.getSenha())).findFirst();
     usuario = optUsuario.orElse(null);
   }
   if (usuario != null) {
     return new WsResponse<>(usuario);
   } else {
     return new WsResponse<>(null, "Falha no login");
   }
 }
예제 #28
0
  private static void renderText(List<DisplayCommand> displayList, InlineBox layoutBox) {
    // there needs to be some major refactoring before this is less ugly.
    // TODO eliminate the current wonky lookup for extracting a node
    // TODO include the parent box when rendering text without using this
    // check
    // FIXME text rendering is not contained because inline layout and
    // cascading(?) do not exist yet.
    Node sourceNode = layoutBox.getStyledNode().getNode();

    if (sourceNode.getType() == NodeType.TEXT) {
      Optional<Color> colorVal = getColor(layoutBox, "color");
      Color fontColor = colorVal.orElse(Color.BLACK);

      Dimensions dims = layoutBox.getDimensions();
      Rect paddingBox = dims.paddingBox();
      String text = ((TextNode) sourceNode).getText();
      Deque<LineBox> lines = layoutBox.getLines();

      // displayList.add(new RenderText(text, lines, paddingBox,
      // fontColor));
    }
  }
예제 #29
0
 @JsonCreator
 public NativeRpcProtocolModule(
     @JsonProperty("host") String host,
     @JsonProperty("port") Integer port,
     @JsonProperty("parentThreads") Integer parentThreads,
     @JsonProperty("childThreads") Integer childThreads,
     @JsonProperty("maxFrameSize") Integer maxFrameSize,
     @JsonProperty("heartbeatInterval") Long heartbeatInterval,
     @JsonProperty("sendTimeout") Long sendTimeout,
     @JsonProperty("encoding") Optional<NativeEncoding> encoding) {
   this.address =
       new InetSocketAddress(
           Optional.ofNullable(host).orElse(DEFAULT_HOST),
           Optional.ofNullable(port).orElse(DEFAULT_PORT));
   this.parentThreads = Optional.ofNullable(parentThreads).orElse(DEFAULT_PARENT_THREADS);
   this.childThreads = Optional.ofNullable(childThreads).orElse(DEFAULT_CHILD_THREADS);
   this.maxFrameSize = Optional.ofNullable(maxFrameSize).orElse(DEFAULT_MAX_FRAME_SIZE);
   this.heartbeatInterval =
       Optional.ofNullable(heartbeatInterval).orElse(DEFAULT_HEARTBEAT_INTERVAL);
   this.sendTimeout = Optional.ofNullable(sendTimeout).orElse(DEFAULT_SEND_TIMEOUT);
   this.encoding = encoding.orElse(NativeEncoding.GZIP);
 }
  public void testObjInRelation() {
    Optional<RelationTriple> extraction =
        mkExtraction(
            "1\tScania-Vabis\t2\tnsubj\tNNP\tORGANIZATION\n"
                + "2\testablished\t0\troot\tVB\tO\n"
                + "3\tproduction\t4\tcompound\tNN\tO\n"
                + "4\tplant\t2\tdobj\tNN\tO\n"
                + "5\toutside\t6\tcase\tIN\tO\n"
                + "6\tSödertälje\t2\tnmod:outside\tNN\tO\n");
    assertTrue("No extraction for sentence!", extraction.isPresent());
    assertEquals(
        "1.0\tScania-Vabis\testablished production plant outside\tSödertälje",
        extraction.get().toString());

    extraction =
        mkExtraction(
            "1\tHun\t2\tcompound\tNNP\tPERSON\n"
                + "2\tSen\t3\tnsubj\tNNP\tPERSON\n"
                + "3\tplayed\t0\troot\tVBD\tO\n"
                + "4\tgolf\t3\tdobj\tNN\tO\n"
                + "5\twith\t6\tcase\tIN\tO\n"
                + "6\tShinawatra\t3\tnmod:with\tNNP\tPERSON\n");
    assertTrue("No extraction for sentence!", extraction.isPresent());
    assertEquals("1.0\tHun Sen\tplayed golf with\tShinawatra", extraction.get().toString());

    extraction =
        mkExtraction(
            "1\tHun\t2\tcompound\tNNP\tPERSON\n"
                + "2\tSen\t3\tnsubj\tNNP\tPERSON\n"
                + "3\tplayed\t0\troot\tVBD\tO\n"
                + "4\tgolf\t3\tdobj\tNN\tO\n"
                + "5\tShinawatra\t3\tnmod:with\tNNP\tPERSON\n"
                + "6\tCambodia\t3\tdobj\tNNP\tLOCATION\n");
    assertFalse(
        "Should not have found extraction for sentence! Incorrectly found: "
            + extraction.orElse(null),
        extraction.isPresent());
  }