public static void main(String[] args) {
    AccessIdentifiers2 ac = new AccessIdentifiers2();
    System.out.println(ac.getClass().getName());
    System.out.println(
        Arrays.stream(ac.getClass().getDeclaredFields())
            .map(Field::getName)
            .collect(Collectors.joining(" || ")));
    ;
    System.out.println(
        Arrays.stream(ac.getClass().getDeclaredMethods())
            .map(Method::getName)
            .collect(Collectors.joining(" || ")));
    System.out.println(
        Arrays.stream(ac.getClass().getDeclaredMethods())
            .map(Method::getReturnType)
            .map(Class::getName)
            .collect(Collectors.joining(" || ")));
    System.out.println(
        Arrays.stream(ac.getClass().getInterfaces())
            .map(Class::getName)
            .collect(Collectors.joining(" || ")));

    System.out.println(ac.getClass().getDeclaredFields().length);
    System.out.println(ac.getClass().getDeclaredMethods().length);
  }
Example #2
0
 @Override
 public final Double apply(
     final Stream<? extends ITerm> p_first, final Stream<? extends ITerm> p_second) {
   return this.ncd(
       p_first.map(Object::toString).collect(Collectors.joining("")),
       p_second.map(Object::toString).collect(Collectors.joining("")));
 }
Example #3
0
  public static void main(String[] args) throws IOException {
    try (Stream<Path> stream = Files.list(Paths.get(""))) {
      String joined =
          stream
              .map(String::valueOf)
              .filter(path -> !path.startsWith("."))
              .sorted()
              .collect(Collectors.joining("; "));
      System.out.println("List: " + joined);
    }

    Path start = Paths.get("");
    int maxDepth = 5;
    try (Stream<Path> stream =
        Files.find(start, maxDepth, (path, attr) -> String.valueOf(path).endsWith(".java"))) {
      String joined = stream.sorted().map(String::valueOf).collect(Collectors.joining("; "));
      System.out.println("Found: " + joined);
    }

    try (Stream<Path> stream = Files.walk(start, maxDepth)) {
      String joined =
          stream
              .map(String::valueOf)
              .filter(path -> path.endsWith(".java"))
              .sorted()
              .collect(Collectors.joining("; "));
      System.out.println("walk(): " + joined);
    }

    List<String> lines = Files.readAllLines(Paths.get("src/golf.sh"));
    lines.add("puts 'foobar'");
    Path path = Paths.get("src/golf-modified.sh");
    Files.write(path, lines);

    try (Stream<String> stream = Files.lines(path)) {
      stream.filter(line -> line.contains("puts")).map(String::trim).forEach(System.out::println);
    }

    System.out.println("a" == "a");
    System.out.println("a" != new String("a"));
    System.out.println(null != "a");
    System.out.println("a".equals("a"));

    try (BufferedReader reader = Files.newBufferedReader(path)) {
      while (reader.ready()) System.out.println(reader.readLine());
    }

    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("hello-world.sh"))) {
      writer.write("puts 'Hello world'");
    }

    try (BufferedReader reader = Files.newBufferedReader(path)) {
      long countPuts = reader.lines().filter(line -> line.contains("put")).count();
      System.out.println(countPuts);
    }
  }
 public boolean contentLongText(String selector, String text) {
   String shrinkText =
       Arrays.stream(text.split("\n")).map(v -> v.trim()).collect(Collectors.joining());
   Elements es = document().select(selector);
   for (Element e : es) {
     String fullText =
         Arrays.stream(e.html().trim().split("<(br|BR|Br|bR) */?>"))
             .map(v -> Arrays.stream(v.trim().split("\n")).collect(Collectors.joining()))
             .collect(Collectors.joining(""));
     if (fullText.equals(shrinkText)) return wrap(true);
   }
   addViolation(String.format("入力されたはずのテキストがDOM要素 '%s' に表示されていません", selector));
   return wrap(false);
 }
 @Override
 public String createExistenceQuery(List<Metadata> metadatas) throws QueryCreationError {
   StringBuilder query = new StringBuilder("SELECT ");
   if (fetchAmount > 0) {
     query.append("TOP ").append(fetchAmount).append(" ");
   }
   query.append(
       metadatas
           .stream()
           .filter(Metadata::isPk)
           .map(Metadata::getColumnSelectStr)
           .collect(Collectors.joining(",")));
   // These lines append any columns that are needed in the where clauses so that the query is
   // valid.
   if (!testType.equals(TestType.FULL)) {
     String whereClauseColumns =
         whereClauses
             .stream()
             .map(WhereClause::getColumn)
             .filter(Objects::nonNull)
             .filter(
                 wc ->
                     metadatas
                         .stream()
                         .anyMatch(md -> md.getColumnLabel().equalsIgnoreCase(wc) && md.isPk()))
             .collect(Collectors.joining(","));
     if (!whereClauseColumns.isEmpty()) {
       query.append(",").append(whereClauseColumns);
     }
   }
   query.append(" FROM ");
   query.append(getFrom());
   if (!testType.equals(TestType.FULL)) {
     String whereClause =
         whereClauses
             .stream()
             .map(wc -> wc.constructClause(this))
             .filter(Objects::nonNull)
             .collect(Collectors.joining(" AND "));
     if (!whereClause.isEmpty()) {
       query.append(" WHERE ").append(whereClause);
     }
   }
   if (orderDirection != null) {
     query.append(" ORDER BY ").append(getOrderBy(metadatas));
   }
   return query.toString();
 }
Example #6
0
 private static String unescapeKeywords(String term) {
   return splitIdentifiers
       .splitAsStream(term + " ") // add space such that the ending "::" is not lost
       .map(BaseRascalREPL::unescapeKeyword)
       .collect(Collectors.joining("::"))
       .trim();
 }
  @Override
  public void FilesRecursiveSaving(post post, Set<part> neededParts) {
    try {
      Files.walk(Paths.get(post.getPath()))
          .filter(Files::isRegularFile)
          .map(
              path ->
                  new part()
                      .setName(path.toString().replace(post.getPath(), ""))
                      .setPath(path.toString()))
          .filter(
              part ->
                  neededParts.stream().anyMatch(part1 -> part.getName().equals(part1.getName())))
          .map(
              part2 -> {
                String collect = "";
                try {

                  collect =
                      Files.lines(Paths.get(part2.getPath(), "")).collect(Collectors.joining("\n"));
                } catch (IOException e) {
                }
                return part2.setContent(collect);
              })
          .map(p -> p.setPost(post))
          .forEach(pa3 -> partRepository.save(pa3));

    } catch (IOException e) {
    }
  }
  @Override
  public String getTaxNumber(String firmokpo, String docnum, String docdate) {
    TaxNumberParameter params = new TaxNumberParameter(firmokpo, docnum, docdate);

    StringBuilder outputBuffer = new StringBuilder();

    // here we should validate parameters, that have been passed with query
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<TaxNumberParameter>> constraintViolations = validator.validate(params);

    StringBuilder validationBuffer = new StringBuilder();

    validationBuffer.append(
        constraintViolations
            .stream()
            .map(ConstraintViolation::getMessage)
            .collect(Collectors.joining("\n")));

    String validationMessage = validationBuffer.toString();
    if (!validationMessage.isEmpty()) {

      // outputBuffer.append(validationMessage);
      // Throwing Exception with contents.
      throw new IllegalArgumentException("Invalid input parameters: " + validationMessage);
    }

    String taxNumber = taxNumberDAO.getTaxNumber(params);

    return taxNumber;
  }
Example #9
0
  public static void createCreative(Creative creative) throws Exception {
    int status = 0;
    String jsonString = null;
    CloseableHttpClient client = HttpClientBuilder.create().build();

    HttpPost post = new HttpPost("https://rest.emaildirect.com/v1/Creatives?ApiKey=apikey");
    List<NameValuePair> params = creative.getParams();

    post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    HttpResponse response = client.execute(post);

    HttpEntity entity = response.getEntity();
    if (entity != null) {
      BufferedReader rd =
          new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

      try {
        jsonString = rd.lines().collect(Collectors.joining()).toString();
        System.out.println("JSON ->" + jsonString);
      } finally {
        rd.close();
      }
    }

    JSONObject jObj = new JSONObject(jsonString);

    if (status == 201) {
      creative.setCreativeID(jObj.getString("CreativeID"));
      creative.setCreativeTimestamp(jObj.getString("Created"));
      dbUpdate(creative);
    }
  }
Example #10
0
  protected void postConstruct() throws Exception {
    api.ongoingRequests.addListener(
        (ListChangeListener<HttpRequestBase>)
            c -> {
              int size = c.getList().size();

              Platform.runLater(
                  () -> {
                    ProgressBar indicator = getNode();

                    String tooltip =
                        c.getList()
                            .stream()
                            .map(r -> String.format("%s %s", r.getMethod(), r.getURI()))
                            .collect(Collectors.joining("\n"));

                    indicator.setTooltip(new Tooltip(tooltip));
                    indicator.setVisible(size > 0);

                    if (size == 0) {
                      indicator.setProgress(100);
                    } else if (size == 1) {
                      indicator.setProgress(ProgressBar.INDETERMINATE_PROGRESS);
                    } else {
                      double pct = 1d / (double) size;
                      indicator.setProgress(pct);
                    }
                  });
            });
  }
 private MongoCredentials getMongoCredentials(String mongoDbName) {
   try { // TODO: Use user and password
     String hosts =
         configuration
             .getStorageEngine(STORAGE_ENGINE_ID)
             .getAlignment()
             .getDatabase()
             .getHosts()
             .stream()
             .map(String::toString)
             .collect(Collectors.joining(","));
     String mongodbUser =
         configuration.getStorageEngine(STORAGE_ENGINE_ID).getAlignment().getDatabase().getUser();
     String mongodbPassword =
         configuration
             .getStorageEngine(STORAGE_ENGINE_ID)
             .getAlignment()
             .getDatabase()
             .getPassword();
     return new MongoCredentials(
         MongoCredentials.parseDataStoreServerAddresses(hosts),
         mongoDbName,
         mongodbUser,
         mongodbPassword);
   } catch (IllegalOpenCGACredentialsException e) {
     logger.error(e.getMessage(), e);
     return null;
   }
 }
 private static String readFileFromArchive(Archive archive, String path) throws IOException {
   try (InputStream manifest = archive.get(path).getAsset().openStream()) {
     BufferedReader reader =
         new BufferedReader(new InputStreamReader(manifest, StandardCharsets.UTF_8));
     return reader.lines().collect(Collectors.joining());
   }
 }
 @Override
 public String toString() {
   StringBuilder strBuilder = new StringBuilder(entityType.getName()).append('{');
   strBuilder.append(
       stream(entityType.getAtomicAttributes().spliterator(), false)
           .map(
               attr -> {
                 StringBuilder attrStrBuilder = new StringBuilder(attr.getName()).append('=');
                 if (EntityTypeUtils.isSingleReferenceType(attr)) {
                   Entity refEntity = getEntity(attr.getName());
                   attrStrBuilder.append(refEntity != null ? refEntity.getIdValue() : null);
                 } else if (EntityTypeUtils.isMultipleReferenceType(attr)) {
                   attrStrBuilder
                       .append('[')
                       .append(
                           stream(getEntities(attr.getName()).spliterator(), false)
                               .map(Entity::getIdValue)
                               .map(Object::toString)
                               .collect(joining(",")))
                       .append(']');
                 } else {
                   attrStrBuilder.append(get(attr.getName()));
                 }
                 return attrStrBuilder.toString();
               })
           .collect(Collectors.joining("&")));
   strBuilder.append('}');
   return strBuilder.toString();
 }
    @Override
    public TimeZoneMap getWorkflowTimeZonesByIdList(List<Long> defIdList) {
      if (defIdList.isEmpty()) {
        return TimeZoneMap.empty();
      }

      List<IdTimeZone> list =
          autoCommit(
              (handle, dao) ->
                  handle
                      .createQuery(
                          "select wd.id, wc.timezone from workflow_definitions wd"
                              + " join revisions rev on rev.id = wd.revision_id"
                              + " join projects proj on proj.id = rev.project_id"
                              + " join workflow_configs wc on wc.id = wd.config_id"
                              + " where wd.id in ("
                              + defIdList
                                  .stream()
                                  .map(it -> Long.toString(it))
                                  .collect(Collectors.joining(", "))
                              + ")"
                              + " and site_id = :siteId")
                      .bind("siteId", siteId)
                      .map(new IdTimeZoneMapper())
                      .list());

      Map<Long, ZoneId> map = IdTimeZone.listToMap(list);
      return new TimeZoneMap(map);
    }
  // TODO extract configured Mapping to FacesServlet
  @Override
  public String getRequestPath() {
    final FacesContext facesContext = FacesContext.getCurrentInstance();

    List<String> optionalParameters = new ArrayList<>(5);
    if (getLibraryName() != null) {
      optionalParameters.add("ln=" + getLibraryName());
    }
    if (!facesContext.isProjectStage(ProjectStage.Production)) {
      // append stage for all ProjectStages except Production
      optionalParameters.add("stage=" + facesContext.getApplication().getProjectStage().toString());
    }

    StringBuilder sb =
        new StringBuilder(30)
            .append(ResourceHandler.RESOURCE_IDENTIFIER)
            .append('/')
            .append(getResourceName())
            // the mapping has to be added, otherwise resources are not dispatched by the
            // FacesServlet
            .append(".xhtml");

    String parameterString = optionalParameters.stream().collect(Collectors.joining("&"));
    if (StringUtils.isNotBlank(parameterString)) {
      sb.append("?").append(parameterString);
    }

    return facesContext
        .getApplication()
        .getViewHandler()
        .getResourceURL(facesContext, sb.toString());
  }
Example #16
0
 @Override
 public String createDataQuery(List<Metadata> metadatas) throws QueryCreationError {
   Collections.sort(metadatas);
   StringBuilder query = new StringBuilder("SELECT ");
   if (fetchAmount > 0) {
     query.append("TOP ").append(fetchAmount).append(" ");
   }
   query.append(generateSelectStatement(metadatas));
   query.append(" FROM ");
   query.append(getFrom());
   if (whereClauses != null) {
     String whereClause =
         whereClauses
             .stream()
             .map(wc -> wc.constructClause(this))
             .filter(Objects::nonNull)
             .collect(Collectors.joining(" AND "));
     if (!whereClause.isEmpty()) {
       query.append(" WHERE ").append(whereClause);
     }
   }
   if (orderDirection != null && fetchAmount > 0) {
     query.append(" ORDER BY ").append(getOrderBy(metadatas));
   }
   return query.toString();
 }
Example #17
0
 /**
  * Executes a process, waits for it to finish, prints the process output to stdout and returns the
  * process output.
  *
  * <p>The process will have exited before this method returns.
  *
  * @param pb The ProcessBuilder to execute.
  * @return The {@linkplain OutputAnalyzer} instance wrapping the process.
  */
 public static OutputAnalyzer executeCommand(ProcessBuilder pb) throws Throwable {
   String cmdLine = pb.command().stream().collect(Collectors.joining(" "));
   System.out.println("Command line: [" + cmdLine + "]");
   OutputAnalyzer analyzer = ProcessTools.executeProcess(pb);
   System.out.println(analyzer.getOutput());
   return analyzer;
 }
Example #18
0
 /**
  * Executes a process, waits for it to finish, prints the process output to stdout, and returns
  * the process output.
  *
  * <p>The process will have exited before this method returns.
  *
  * @param cmds The command line to execute.
  * @return The {@linkplain OutputAnalyzer} instance wrapping the process.
  */
 public static OutputAnalyzer executeCommand(String... cmds) throws Throwable {
   String cmdLine = Arrays.stream(cmds).collect(Collectors.joining(" "));
   System.out.println("Command line: [" + cmdLine + "]");
   OutputAnalyzer analyzer = ProcessTools.executeProcess(cmds);
   System.out.println(analyzer.getOutput());
   return analyzer;
 }
Example #19
0
  /**
   * Starts the Ping Service on a specified port and stores connection parameters (host and port) of
   * the Pong service.
   *
   * <p>All parameters are passed via command line parameters args
   *
   * @param args Own port, IP of the pong service, Port of the pong service
   */
  public static void main(String[] args) {

    if (args.length < 3) {
      System.out.println("Sorry, you have to specify");
      System.out.println("- a port for the ping service as first command line parameter");
      System.out.println("- a host/ip for the pong service as second command line parameter");
      System.out.println("- a port for the pong service as third command line parameter");
      System.out.println("");
      System.out.println("It seems, you started ping like that");
      System.out.println("java Ping " + Arrays.stream(args).collect(Collectors.joining(", ")));
      System.out.println("So please use: java Ping <pingport> <ponghost> <pongport>");
      System.exit(1);
    }

    try {
      int pingPort = Integer.parseInt(args[0]);
      String pongHost = args[1];
      int pongPort = Integer.parseInt(args[2]);

      HttpServer httpServer = HttpServer.create(new InetSocketAddress(pingPort), 0);
      httpServer.setExecutor(Executors.newCachedThreadPool());

      registerPingHandlerWith(httpServer, pongHost, pongPort);
      registerMPingHandlerWith(httpServer, pongHost, pongPort);

      httpServer.start();
      System.out.println("Ping Service Started ...");

    } catch (Exception ex) {
      System.out.println("We got the following exception" + ex);
      System.out.println("while starting the Ping Service.");
      System.out.println("Aborting program execution.");
    }
  }
Example #20
0
 @Override
 public String genSql() {
   String result = "";
   LinkedList<SqlNode<?>> children = getChildren();
   int len = children.size();
   if (len > 0) {
     String indent = getStartSelectIndent();
     result =
         "ON "
             + IntStream.range(0, len)
                 .boxed()
                 .map(
                     i -> {
                       SqlNode<?> n = children.get(i);
                       if (i == 0) {
                         return n.genSql();
                       }
                       if (Operator.class.isInstance(n)) {
                         return "\n" + indent + n.genSql();
                       }
                       return " " + n.genSql();
                     })
                 .collect(Collectors.joining());
   }
   return result;
 }
Example #21
0
  public String declaredName() {
    StringBuilder res = new StringBuilder();
    String space = "";

    Optional<TypeVariableInfo> maybeTypeVariableInfo = typeVariableInfo();
    if (maybeTypeVariableInfo.isPresent()) {
      TypeVariableInfo typeVariableInfo = maybeTypeVariableInfo.get();
      res.append(typeVariableInfo.declaredName());
      space = " ";
    }

    Optional<NameInfo> maybeType = type();
    if (maybeType.isPresent()) {
      res.append(space);
      String type = maybeType.get().simpleName();
      res.append(type);
    }

    List<TypeParameterInfo> typeParameterInfoList = typeParameterInfoList();
    if (!typeParameterInfoList.isEmpty()) {
      res.append("<");
      res.append(
          typeParameterInfoList.stream().map(Object::toString).collect(Collectors.joining(", ")));
      res.append(">");
    }

    return res.toString();
  }
 private void saveFile() {
   try {
     saveHandler.accept(Files.lines(tmpfile).collect(Collectors.joining("\n", "", "\n")));
   } catch (IOException ex) {
     errorHandler.accept("Failure in read edit file: " + ex.getMessage());
   }
 }
 public static String threadName(Settings settings, String... names) {
   String namePrefix =
       Arrays.stream(names)
           .filter(name -> name != null)
           .collect(Collectors.joining(".", "[", "]"));
   return threadName(settings, namePrefix);
 }
Example #24
0
 @Override
 public String toString() {
   return Stream.of(numero, emissor, emissao)
       .filter(o -> o != null)
       .map(Object::toString)
       .collect(Collectors.joining(", "));
 }
Example #25
0
  /**
   * Exercise 3
   *
   * <p>Join the second, third and forth strings of the list into a single string, where each word
   * is separated by a hyphen (-). Print the resulting string.
   */
  private void exercise3() {
    List<String> list =
        Arrays.asList("The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog");

    String result = list.stream().skip(1).limit(3).collect(Collectors.joining("-"));
    System.out.println(result);
  }
Example #26
0
 @Override
 public String toString() {
   return "while("
       + condition
       + "\n"
       + body.exprs().stream().map(Expr::toString).collect(Collectors.joining("\n", "", "\n)"));
 }
  public void sendNicklist(User target) {
    ArrayList<User> users = Globals.server.getChannelUsers(this.name);

    String nicklist = users.stream().map(u -> u.getName()).collect(Collectors.joining(" "));

    target.sendMessage(353, target.getName() + " @ " + this.name, nicklist);
    target.sendMessage(366, target.getName() + " " + this.name, "END of /NAMES list.");
  }
Example #28
0
  private void saveHistory() {
    try (Writer out = Files.newBufferedWriter(historyFile.toPath())) {
      String lineSeparator = System.getProperty("line.separator");

      out.write(getHistory().save().stream().collect(Collectors.joining(lineSeparator)));
    } catch (final IOException exp) {
    }
  }
Example #29
0
 @RequestMapping("/api/stats")
 public String getStats() {
   return activeUsersRepository
       .findAll()
       .stream()
       .map(record -> record.getDate() + "," + record.getUserIDs().size())
       .collect(Collectors.joining("\n"));
 }
Example #30
0
 @JsonIgnore
 public String getAllLyrics() {
   return notes
       .stream()
       .sorted()
       .map(Note::getPronunciationAliasString)
       .collect(Collectors.joining(","));
 }