예제 #1
0
 @Override
 protected Type doTypecheck(Environment env, Optional<Type> expected) {
   Type[] newTypes = new Type[objects.length];
   for (int i = 0; i < objects.length; i++) {
     final int sti = i;
     newTypes[i] =
         objects[i].typecheck(
             env,
             expected.map(
                 exp -> {
                   if (exp instanceof Tuple) return ((Tuple) exp).getTypeArray()[sti];
                   if (exp instanceof Intersection)
                     return ((Intersection) exp)
                         .getTypes()
                         .stream()
                         .filter(tpe -> tpe instanceof Tuple)
                         .filter(tpe -> ((Tuple) tpe).getTypeArray().length == objects.length)
                         .findFirst()
                         .get();
                   ToolError.reportError(
                       ErrorMessage.ACTUAL_FORMAL_TYPE_MISMATCH,
                       this,
                       getType().toString(),
                       exp.toString());
                   throw new RuntimeException();
                 }));
   }
   return new Tuple(newTypes);
 }
예제 #2
0
  @Override
  public PropertyNode getEnabledFlagNode() {
    Optional<VariableNode> propertyNode =
        getPropertyNode(ServerDiagnosticsType.ENABLED_FLAG.getBrowseName());

    return propertyNode.map(n -> (PropertyNode) n).orElse(null);
  }
예제 #3
0
  /**
   * Buying articles for business customers as employee.
   *
   * @param cart cart for the business customer, will be cleared
   * @param nickname nickname of the currently logged in employee
   * @param success notification of successfully buying articles
   * @return redirect to template "index" (home page)
   */
  @RequestMapping(value = "/checkout_employee", method = RequestMethod.POST)
  public String buyforbusinesscustomer(
      @ModelAttribute Cart cart,
      @RequestParam("bcustomer") String nickname,
      RedirectAttributes success) {

    Optional<UserAccount> businessCustomer = userAccountManager.findByUsername(nickname);
    return businessCustomer
        .map(
            account -> {
              Order order = new Order(account, Cash.CASH);

              cart.addItemsTo(order);

              orderManager.payOrder(order);
              orderManager.completeOrder(order);

              cart.clear();

              success.addFlashAttribute(
                  "success", "Die Bestellung für den Geschäftskunden ist abgeschlossen.");

              return "redirect:/";
            })
        .orElse("redirect:/cart");
  }
 public static void respond(
     HttpExchange exchange, String redirectUrl, String name, Optional<String> message)
     throws IOException {
   LOG.finer(
       () ->
           "Redirecting to "
               + name
               + " ["
               + redirectUrl
               + "]"
               + message.map(m -> ": " + m).orElse(""));
   exchange.getResponseHeaders().set("Location", redirectUrl);
   exchange.sendResponseHeaders(302, 0);
   if ("HEAD".equals(exchange.getRequestMethod())) return;
   try (PrintStream out = new PrintStream(exchange.getResponseBody())) {
     HeaderResponse.send(out, SessionFilter.getSession(exchange), "Redirection to " + name);
     out.println("<DIV>");
     message.ifPresent(m -> out.printf("%s<BR>\n", m));
     out.printf("Go to: <A href=\"%s\"><B>%s</B></A>", redirectUrl, name);
     out.println("</DIV>");
   } catch (Exception e) {
     LOG.log(Level.SEVERE, e, () -> "Failed generating redirection to '" + name + "': ");
     throw (e);
   }
 }
 @Override
 @Transactional
 public UserDetails loadUserByUsername(final String login) {
   log.debug("Authenticating {}", login);
   String lowercaseLogin = login.toLowerCase();
   Optional<User> userFromDatabase = userRepository.findOneByLogin(lowercaseLogin);
   return userFromDatabase
       .map(
           user -> {
             if (!user.getActivated()) {
               throw new UserNotActivatedException(
                   "User " + lowercaseLogin + " was not activated");
             }
             List<GrantedAuthority> grantedAuthorities =
                 user.getAuthorities()
                     .stream()
                     .map(authority -> new SimpleGrantedAuthority(authority.getName()))
                     .collect(Collectors.toList());
             return new org.springframework.security.core.userdetails.User(
                 lowercaseLogin, user.getPassword(), grantedAuthorities);
           })
       .orElseThrow(
           () ->
               new UsernameNotFoundException(
                   "User " + lowercaseLogin + " was not found in the database"));
 }
예제 #6
0
  /**
   * Adds an all-in-one computer (combined with four freely customizable parts) to the cart.
   *
   * @param article requested all-in-one computer
   * @param number the amount of requested articles
   * @param cart contains a fresh initialized cart
   * @param success notification about adding an article to the cart
   * @return redirect to template "allinone"
   */
  @RequestMapping(value = "/cart2", method = RequestMethod.POST)
  public String addcomp(
      @RequestParam("pid") Computer article,
      @RequestParam("number") int number,
      @ModelAttribute Cart cart,
      RedirectAttributes success) {

    Optional<InventoryItem> item = inventory.findByProductIdentifier(article.getIdentifier());

    Quantity quantity = item.map(InventoryItem::getQuantity).orElse(NONE);
    BigDecimal amount1 = quantity.getAmount();
    int i = amount1.intValue();
    int amount = number;
    if (number <= 0) {
      amount = 1;
    }
    if (number >= i) {
      amount = i;
    }

    cart.addOrUpdateItem(article, Quantity.of(amount));
    cart.addOrUpdateItem(article.getProzessor().get(0), Quantity.of(amount));
    cart.addOrUpdateItem(article.getGraka().get(0), Quantity.of(amount));
    cart.addOrUpdateItem(article.getHdd().get(0), Quantity.of(amount));
    cart.addOrUpdateItem(article.getRam().get(0), Quantity.of(amount));

    article.getGraka().clear();
    article.getHdd().clear();
    article.getProzessor().clear();
    article.getRam().clear();

    success.addFlashAttribute(
        "success", "Der Artikel wurde erfolgreich Ihrem Warenkorb hinzugefügt.");
    return "redirect:allinone";
  }
예제 #7
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();
    }
  }
예제 #8
0
 @Provides
 @Singleton
 public Filter filter(
     final QueryParser parser, final FilterFactory filters, final ExtraParameters params) {
   return Optionals.pickOptional(
           filter.map(parser::parseFilter), params.getFilter(INGESTION_FILTER_PARAM, parser))
       .orElseGet(filters::t);
 }
예제 #9
0
  @Override
  public LocalizedText getToState() {
    Optional<VariableNode> component = getVariableComponent("ToState");

    return component
        .map(node -> (LocalizedText) node.getValue().getValue().getValue())
        .orElse(null);
  }
예제 #10
0
 @Override
 public Optional<Type> getCommonSuperType(List<? extends Type> types) {
   checkArgument(!types.isEmpty(), "types is empty");
   Optional<TypeSignature> commonSuperTypeSignature =
       getCommonSuperTypeSignature(
           types.stream().map(Type::getTypeSignature).collect(toImmutableList()));
   return commonSuperTypeSignature.map(this::getType);
 }
예제 #11
0
  @Override
  public ServerDiagnosticsSummaryDataType getServerDiagnosticsSummary() {
    Optional<VariableNode> component = getVariableComponent("ServerDiagnosticsSummary");

    return component
        .map(node -> (ServerDiagnosticsSummaryDataType) node.getValue().getValue().getValue())
        .orElse(null);
  }
예제 #12
0
  @Override
  public SubscriptionDiagnosticsDataType[] getSubscriptionDiagnosticsArray() {
    Optional<VariableNode> component = getVariableComponent("SubscriptionDiagnosticsArray");

    return component
        .map(node -> (SubscriptionDiagnosticsDataType[]) node.getValue().getValue().getValue())
        .orElse(null);
  }
예제 #13
0
 public Vec2 convertCoordinateSystem(Vec2 event) {
   Optional<Drawing> drawing = this.find(Drawing.drawing, both()).findFirst();
   return drawing
       .map(x -> x.windowSystemToDrawingSystem(event))
       .orElseThrow(
           () ->
               new IllegalArgumentException(
                   " cant mouse around something without drawing support (to provide coordinate system)"));
 }
 private void setConfirmResultConverter() {
   setResultConverter(
       (dialogButton) -> {
         List<PickerAssignee> finalUsers = state.getCurrentUsersList();
         Optional<PickerAssignee> selectedAssignee =
             PickerAssignee.getSelectedAssignee(finalUsers);
         return new AssigneePickerDialogResponse(
             dialogButton, selectedAssignee.map(PickerAssignee::getLoginName));
       });
 }
 private static <T> Optional<T> get(
     final JsonNode jsonResult, final String key, final Class<T> type) {
   final Optional<JsonNode> fieldNode = Optional.ofNullable(jsonResult.get(key));
   return fieldNode.map(
       f -> {
         try {
           return EVENT_PARAMETERS_READER.treeToValue(f, type);
         } catch (final JsonProcessingException e) {
           log.info("Unable to map field: " + key, e);
           return null;
         }
       });
 }
예제 #16
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) {

    }
  }
예제 #17
0
  @Override
  public void tweet() {
    // アカウントとテキストはnullにできない
    Objects.requireNonNull(twitter, "User is null.");
    Objects.requireNonNull(text, "TweetText is null.");

    StatusUpdate status = new StatusUpdate(text);
    reply.map(Tweet::getStatusId).ifPresent(status::setInReplyToStatusId);
    try {
      twitter.updateStatus(status);
    } catch (TwitterException e) {
      e.printStackTrace();
    }
  }
예제 #18
0
 @GET
 @Path("/entry/{entry-number}")
 @Produces({
   ExtraMediaType.TEXT_HTML,
   MediaType.APPLICATION_JSON,
   ExtraMediaType.TEXT_YAML,
   ExtraMediaType.TEXT_CSV,
   ExtraMediaType.TEXT_TSV,
   ExtraMediaType.TEXT_TTL
 })
 public AttributionView findByEntryNumber(@PathParam("entry-number") int entryNumber) {
   Optional<Entry> entry = entryDAO.findByEntryNumber(entryNumber);
   return entry.map(viewFactory::getEntryView).orElseThrow(NotFoundException::new);
 }
예제 #19
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));
    };
  }
예제 #20
0
  public SpritzOutputStream(final Optional<String> fname, final String key, final OutputStream out)
      throws IOException {
    internalName = fname;
    encrypter = new SpritzEncrypter(key, out);

    byte[] nameBytes =
        fname
            .map(n -> new File(n).getName())
            .orElse("")
            .getBytes(java.nio.charset.StandardCharsets.UTF_8);
    encrypter.write(nameBytes.length);
    encrypter.write(nameBytes);
    final Deflater zlibAlgo = new Deflater(Deflater.BEST_COMPRESSION);
    deflater = new DeflaterOutputStream(encrypter, zlibAlgo);
  }
  public void accept(ObjectMapper mapper) {

    JaxbAnnotationModule module = new JaxbAnnotationModule();
    // configure as necessary
    inc.map(include -> mapper.setSerializationInclusion(include));
    mapper.registerModule(module);
    PluginLoader.INSTANCE
        .plugins
        .get()
        .stream()
        .filter(m -> m.jacksonModules() != null)
        .flatMap(m -> m.jacksonModules().stream())
        .forEach(m -> mapper.registerModule(m));

    mapper.registerModule(new Jdk8Module());
  }
예제 #22
0
파일: App.java 프로젝트: rasika/carbon-uuf
 private Theme getRenderingTheme(API api) {
   Optional<String> sessionThemeName = api.getSession().map(Session::getThemeName);
   if (!sessionThemeName.isPresent()) {
     return defaultTheme;
   }
   return sessionThemeName
       .map(themes::get)
       .orElseThrow(
           () ->
               new IllegalArgumentException(
                   "Theme '"
                       + sessionThemeName.get()
                       + "' which is set as for the current session of app '"
                       + name
                       + "' does not exists."));
 }
예제 #23
0
  /**
   * Parse request and set logon user in request scope.
   *
   * @param request HttpServletRequest
   * @param response HttpServletResponse
   * @param chain FilterChain
   * @throws IOException IOException
   * @throws ServletException ServletException
   */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    if (isIgnored(httpServletRequest)) {
      logger.info("Ignore request by userAuthenticationFilter");
      chain.doFilter(httpServletRequest, httpServletResponse);
      return;
    }

    Optional<String> userIdOpt = getUserId(httpServletRequest);

    Optional<User> userOpt =
        userIdOpt
            .map(
                userId ->
                    Optional.of(
                        User.newBuilder()
                            .withEmail(userId)
                            .withUserId(userId)
                            .withUsername(userId)
                            .build()))
            .orElseGet(
                () -> {
                  if (Boolean.valueOf(testUserEnabled)) {
                    User user =
                        User.newBuilder()
                            .withEmail(testUserEmail)
                            .withUserId(testUserId)
                            .withUsername(testUsername)
                            .build();
                    return Optional.of(user);
                  } else {
                    return Optional.empty();
                  }
                });

    if (hasLogon(userOpt)) {
      authenticated(httpServletRequest, userOpt);
    } else {
      unauthenticated(httpServletResponse);
      return;
    }

    chain.doFilter(request, response);
  }
예제 #24
0
  @Override
  public VulnerabilityUpdateStatus updateForComponent(String componentId) throws TException {
    Optional<Component> component = vulnerabilityConnector.getComponent(componentId);

    return component
        .map(
            c ->
                c.isSetReleaseIds()
                    ? c.getReleaseIds()
                        .stream()
                        .map(this::updateForRelease)
                        .reduce(
                            getEmptyVulnerabilityUpdateStatus(),
                            (r1, r2) -> reduceVulnerabilityUpdateStatus(r1, r2))
                    : getEmptyVulnerabilityUpdateStatus())
        .orElse(getEmptyVulnerabilityUpdateStatus(RequestStatus.FAILURE));
  }
예제 #25
0
 /**
  * Attempts to parse the 'Authorization' header for Basic Authorization.
  *
  * @return a {@link LeoMap} with 'username' and 'password' properties
  */
 public LeoMap auth() {
   Optional<BasicAuthCredentials> auth = parseBasicAuth();
   return auth.map(
           b -> {
             LeoMap result = new LeoMap();
             result.putByString("username", LeoString.valueOf(b.getUsername()));
             result.putByString("password", LeoString.valueOf(b.getPassword()));
             return result;
           })
       .orElseGet(
           () -> {
             LeoMap result = new LeoMap();
             result.putByString("username", LeoString.valueOf(""));
             result.putByString("password", LeoString.valueOf(""));
             return result;
           });
 }
예제 #26
0
  /**
   * Sets the given AnnotationSet as the "selected" one. If null is passed then all AnnotationSets
   * will be unselected.
   *
   * <p>Note: Currently switching selection is not supported when the currently selected
   * AnnotationSet has collapsed clusters. It is the responsibility of the UI to expand all the
   * clusters before switching the AnnotationSet.
   *
   * <p>MKTODO: It would be better for the model to handle expanding the clusters, but for now we
   * will force the UI to do it.
   *
   * @throws IllegalStateException If the currently active AnnotationSet has collapsed clusters.
   */
  public void select(AnnotationSet annotationSet) {
    if (annotationSet == null || annotationSets.contains(annotationSet)) {

      if (Optional.ofNullable(annotationSet).equals(activeSet)) {
        return;
      }

      if (activeSet.map(AnnotationSet::hasCollapsedCluster).orElse(false)) {
        throw new IllegalStateException("Current AnnotationSet has collapsed clusters");
      }

      CyNetwork network = networkView.getModel();
      activeSet = Optional.ofNullable(annotationSet);

      // ModelManager.handle(AboutToRemoveNodesEvent) only removes nodes from the active annotation
      // set.
      // When switching to a new annotation set we need to "fix" the clusters to remove any nodes
      // that
      // were deleted previously.
      // MKTODO: probably need to test for deleted nodes when serializing the model

      if (annotationSet != null) {
        Set<Cluster> clusters = annotationSet.getClusters();
        for (Cluster cluster :
            new HashSet<>(
                clusters)) { // avoid ConcurrentModificationException because removeNodes() can call
          // delete()
          Set<CyNode> nodesToRemove =
              cluster
                  .getNodes()
                  .stream()
                  .filter(node -> !network.containsNode(node))
                  .collect(Collectors.toSet());

          // Fires ClusterChangedEvent, UI listeners should test if the cluster is part of the
          // active annotation set.
          if (!nodesToRemove.isEmpty()) {
            cluster.removeNodes(nodesToRemove);
          }
        }
      }

      parent.postEvent(new ModelEvents.AnnotationSetSelected(this, activeSet));
    }
  }
예제 #27
0
  @Override
  public VulnerabilityUpdateStatus updateForProject(String projectId) throws TException {
    Optional<Project> project = vulnerabilityConnector.getProject(projectId);

    return project
        .map(
            r ->
                r.isSetReleaseIdToUsage()
                    ? r.getReleaseIdToUsage()
                        .keySet()
                        .stream()
                        .map(this::updateForRelease)
                        .reduce(
                            getEmptyVulnerabilityUpdateStatus(),
                            (r1, r2) -> reduceVulnerabilityUpdateStatus(r1, r2))
                    : getEmptyVulnerabilityUpdateStatus())
        .orElse(getEmptyVulnerabilityUpdateStatus(RequestStatus.FAILURE));
  }
예제 #28
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    Optional<ContentFactoryPair> factoryOptional =
        inputConfig.getFactory(Optional.of(request.getContentType()).map(MediaType::valueOf));

    if (!factoryOptional.isPresent()) {
      response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
      String msg = "Unsupported Content-Type: " + request.getContentType();
      response.getOutputStream().write(msg.getBytes(StandardCharsets.UTF_8));
      return;
    }

    TTransport transport =
        new TIOStreamTransport(request.getInputStream(), response.getOutputStream());

    TProtocol inputProtocol = factoryOptional.get().getProtocol(transport);

    Optional<String> acceptHeader = Optional.ofNullable(request.getHeader(ACCEPT));
    Optional<MediaType> acceptType = Optional.empty();
    if (acceptHeader.isPresent()) {
      try {
        acceptType = acceptHeader.map(MediaType::valueOf);
      } catch (IllegalArgumentException e) {
        // Thrown if the Accept header contains more than one type or something else we can't
        // parse, we just treat is as no header (which will pick up the default value).
        acceptType = Optional.empty();
      }
    }

    ContentFactoryPair outputProtocolFactory = outputConfig.getFactory(acceptType);

    response.setContentType(outputProtocolFactory.getOutputType().toString());
    TProtocol outputProtocol = outputProtocolFactory.getProtocol(transport);
    try {
      processor.process(inputProtocol, outputProtocol);
      response.getOutputStream().flush();
    } catch (TException e) {
      throw new ServletException(e);
    }
  }
예제 #29
0
  public void update() {
    StringBuilder sb = new StringBuilder();
    ExportFormats.entryNumber =
        1; // Set entry number in case that is included in the preview layout.
    entry.ifPresent(
        entry ->
            layout.ifPresent(
                layout ->
                    sb.append(
                        layout.doLayout(
                            entry,
                            databaseContext.map(BibDatabaseContext::getDatabase).orElse(null),
                            highlightPattern))));
    String newValue = sb.toString();

    previewPane.setText(newValue);
    previewPane.revalidate();

    // Scroll to top:
    scrollToTop();
  }
    @Override
    public URL getResource(String name) {
      URL result = super.getResource(name);
      if (result == null) {
        Optional<byte[]> resourceAsBytes = getResourceAsBytes(name);
        if (resourceAsBytes.isPresent()) {}

        result =
            resourceAsBytes
                .map(
                    bb -> {
                      try {

                        return new URL(
                            "remoteUrl", "localhost", 0, "name", new RemoteURLStreamHandler(bb));
                      } catch (Exception e) {
                        throw new RuntimeException(e);
                      }
                    })
                .orElse(null);
      }
      return result;
    }