Example #1
0
  public void downloadAndExtract(String name, Terminal terminal) throws IOException {
    if (name == null && url == null) {
      throw new IllegalArgumentException("plugin name or url must be supplied with install.");
    }

    if (!Files.exists(environment.pluginsFile())) {
      terminal.println(
          "Plugins directory [%s] does not exist. Creating...", environment.pluginsFile());
      Files.createDirectory(environment.pluginsFile());
    }

    if (!Environment.isWritable(environment.pluginsFile())) {
      throw new IOException("plugin directory " + environment.pluginsFile() + " is read only");
    }

    PluginHandle pluginHandle;
    if (name != null) {
      pluginHandle = PluginHandle.parse(name);
      checkForForbiddenName(pluginHandle.name);
    } else {
      // if we have no name but url, use temporary name that will be overwritten later
      pluginHandle = new PluginHandle("temp_name" + new Random().nextInt(), null, null);
    }

    Path pluginFile = download(pluginHandle, terminal);
    extract(pluginHandle, terminal, pluginFile);
  }
Example #2
0
  public static void main(String[] args) throws MessagingException, IOException {
    Properties props = new Properties();
    try (InputStream in = Files.newInputStream(Paths.get("mail", "mail.properties"))) {
      props.load(in);
    }
    List<String> lines = Files.readAllLines(Paths.get(args[0]), Charset.forName("UTF-8"));

    String from = lines.get(0);
    String to = lines.get(1);
    String subject = lines.get(2);

    StringBuilder builder = new StringBuilder();
    for (int i = 3; i < lines.size(); i++) {
      builder.append(lines.get(i));
      builder.append("\n");
    }

    Console console = System.console();
    String password = new String(console.readPassword("Password: "));

    Session mailSession = Session.getDefaultInstance(props);
    // mailSession.setDebug(true);
    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(builder.toString());
    Transport tr = mailSession.getTransport();
    try {
      tr.connect(null, password);
      tr.sendMessage(message, message.getAllRecipients());
    } finally {
      tr.close();
    }
  }
Example #3
0
  public static void main(String[] args) throws IOException {
    Path path = Paths.get("../alice.txt");
    String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);

    Stream<String> words = Stream.of(contents.split("[\\P{L}]+"));
    show("words", words);
    Stream<String> song = Stream.of("gently", "down", "the", "stream");
    show("song", song);
    Stream<String> silence = Stream.empty();
    silence = Stream.<String>empty(); // Explicit type specification
    show("silence", silence);

    Stream<String> echos = Stream.generate(() -> "Echo");
    show("echos", echos);

    Stream<Double> randoms = Stream.generate(Math::random);
    show("randoms", randoms);

    Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE));
    show("integers", integers);

    Stream<String> wordsAnotherWay = Pattern.compile("[\\P{L}]+").splitAsStream(contents);
    show("wordsAnotherWay", wordsAnotherWay);

    try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
      show("lines", lines);
    }
  }
Example #4
0
  public static void main(String args[]) {
    try {
      aServer asr = new aServer();

      // file channel.
      FileInputStream is = new FileInputStream("");
      is.read();
      FileChannel cha = is.getChannel();
      ByteBuffer bf = ByteBuffer.allocate(1024);
      bf.flip();

      cha.read(bf);

      // Path Paths
      Path pth = Paths.get("", "");

      // Files some static operation.
      Files.newByteChannel(pth);
      Files.copy(pth, pth);
      // file attribute, other different class for dos and posix system.
      BasicFileAttributes bas = Files.readAttributes(pth, BasicFileAttributes.class);
      bas.size();

    } catch (Exception e) {
      System.err.println(e);
    }

    System.out.println("hello ");
  }
Example #5
0
  /** Check that a cancelled key will never be queued */
  static void testCancel(Path dir) throws IOException {
    System.out.println("-- Cancel --");

    try (WatchService watcher = FileSystems.getDefault().newWatchService()) {

      System.out.format("register %s for events\n", dir);
      WatchKey myKey = dir.register(watcher, new WatchEvent.Kind<?>[] {ENTRY_CREATE});
      checkKey(myKey, dir);

      System.out.println("cancel key");
      myKey.cancel();

      // create a file in the directory
      Path file = dir.resolve("mars");
      System.out.format("create: %s\n", file);
      Files.createFile(file);

      // poll for keys - there will be none
      System.out.println("poll...");
      try {
        WatchKey key = watcher.poll(3000, TimeUnit.MILLISECONDS);
        if (key != null) throw new RuntimeException("key should not be queued");
      } catch (InterruptedException x) {
        throw new RuntimeException(x);
      }

      // done
      Files.delete(file);

      System.out.println("OKAY");
    }
  }
Example #6
0
  public Path[] getListInstalledPlugins() throws IOException {
    if (!Files.exists(environment.pluginsFile())) {
      return new Path[0];
    }

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(environment.pluginsFile())) {
      return Iterators.toArray(stream.iterator(), Path.class);
    }
  }
Example #7
0
 public static void remove() {
   Long id = Long.valueOf(params.get("id"));
   Files files = Files.findById(id);
   if (files.image.getFile().exists()) {
     files.image.getFile().delete();
   }
   files.delete();
   renderText("");
 }
Example #8
0
 private boolean checkAlter(Path quellDatei, Path zielDatei) {
   boolean retValue = false;
   try {
     if ((Files.getLastModifiedTime(quellDatei).compareTo(Files.getLastModifiedTime(zielDatei))
         > 0)) retValue = true;
   } catch (IOException e) {
     e.printStackTrace();
   }
   return retValue;
 }
Example #9
0
  /**
   * 以阻塞的方式立即下载一个文件,该方法会覆盖已经存在的文件
   *
   * @param task
   * @return "ok" if download success (else return errmessage);
   */
  static String download(DownloadTask task) {
    if (!openedStatus && show) openStatus();

    URL url;
    HttpURLConnection conn;
    try {
      url = new URL(task.getOrigin());
      conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout(30000);
      conn.setReadTimeout(30000);
      conn.setRequestProperty(
          "User-Agent",
          "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/"
              + Math.random());
      if ("www.imgjav.com".equals(url.getHost())) { // 该网站需要带cookie请求
        conn.setRequestProperty(
            "User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36");
        // conn.setRequestProperty("Cookie", "__cfduid=d219ea333c7a9b5743b572697b631925a1446093229;
        // cf_clearance=6ae62d843f5d09acf393f9e4eb130d9366840c82-1446093303-28800");
        conn.setRequestProperty(
            "Cookie",
            "__cfduid=d6ee846b378bb7d5d173a05541f8a2b6a1446090548; cf_clearance=ea10e8db31f8b6ee51570b118dd89b7e616d7b62-1446099714-28800");
        conn.setRequestProperty("Host", "www.imgjav.com");
      }
      Path directory = Paths.get(task.getDest()).getParent();
      if (!Files.exists(directory)) Files.createDirectories(directory);
    } catch (Exception e) {
      e.printStackTrace();
      return e.getMessage();
    }

    try (InputStream is = conn.getInputStream();
        BufferedInputStream in = new BufferedInputStream(is);
        FileOutputStream fos = new FileOutputStream(task.getDest());
        OutputStream out = new BufferedOutputStream(fos); ) {
      int length = conn.getContentLength();
      if (length < 1) throw new IOException("length<1");
      byte[] binary = new byte[length];
      byte[] buff = new byte[65536];
      int len;
      int index = 0;
      while ((len = in.read(buff)) != -1) {
        System.arraycopy(buff, 0, binary, index, len);
        index += len;
        allLen += len; // allLen有线程安全的问题 ,可能会不正确。无需精确数据,所以不同步了
        task.setReceivePercent(String.format("%.2f", ((float) index / length) * 100) + "%");
      }
      out.write(binary);
    } catch (IOException e) {
      e.printStackTrace();
      return e.getMessage();
    }
    return "ok";
  }
Example #10
0
 public static void upload(File[] files) throws FileNotFoundException {
   Files f = null;
   for (File file : files) {
     f = new Files();
     f.name = file.getName();
     f.path = "";
     f.image = new Blob();
     f.image.set(new FileInputStream(file), MimeTypes.getContentType(file.getName()));
     f.save();
     renderText(f.id);
   }
 }
Example #11
0
 /**
  * we check whether we need to remove the top-level folder while extracting sometimes (e.g.
  * github) the downloaded archive contains a top-level folder which needs to be removed
  */
 private Path findPluginRoot(Path dir) throws IOException {
   if (Files.exists(dir.resolve(PluginInfo.ES_PLUGIN_PROPERTIES))) {
     return dir;
   } else {
     final Path[] topLevelFiles = FileSystemUtils.files(dir);
     if (topLevelFiles.length == 1 && Files.isDirectory(topLevelFiles[0])) {
       Path subdir = topLevelFiles[0];
       if (Files.exists(subdir.resolve(PluginInfo.ES_PLUGIN_PROPERTIES))) {
         return subdir;
       }
     }
   }
   throw new RuntimeException(
       "Could not find plugin descriptor '" + PluginInfo.ES_PLUGIN_PROPERTIES + "' in plugin zip");
 }
 private static boolean exists(Path p) {
   Path base = p.getParent();
   String fileName = p.getFileName().toString();
   return Arrays.asList(extensions)
       .stream()
       .anyMatch(it -> Files.exists(base.resolve(fileName + it)));
 }
Example #13
0
 private static Stream<Path> walk(Path path) {
   try {
     return Files.walk(path);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Example #14
0
  public static void main(String[] args) throws Exception {
    Path dir = Paths.get(args[0]);

    Files.walkFileTree(
        dir,
        new SimpleFileVisitor<Path>() {
          @Override
          public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            check(dir);
            if (skip(dir)) return FileVisitResult.SKIP_SIBLINGS;
            return FileVisitResult.CONTINUE;
          }

          @Override
          public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            check(file);
            if (skip(file)) return FileVisitResult.SKIP_SIBLINGS;
            return FileVisitResult.CONTINUE;
          }

          @Override
          public FileVisitResult postVisitDirectory(Path dir, IOException x) {
            if (x != null) throw new RuntimeException(x);
            check(dir);
            return FileVisitResult.CONTINUE;
          }
        });
  }
Example #15
0
  private void initFrame() {
    this.setLocationRelativeTo(null);

    try {
      if (!Files.exists(saveName)) Files.createFile(saveName);

      laden(saveName);
    } catch (IOException e) {
      e.printStackTrace();
    }

    nUebSchr.setSelected(true);
    if (!quellListModel.isEmpty()) quellJList.setSelectedIndex(0);
    if (!zielListModel.isEmpty()) zielJList.setSelectedIndex(0);

    starteLaufwerkspruefung();
  }
Example #16
0
  public void removePlugin(String name, Terminal terminal) throws IOException {
    if (name == null) {
      throw new IllegalArgumentException("plugin name must be supplied with remove [name].");
    }
    PluginHandle pluginHandle = PluginHandle.parse(name);
    boolean removed = false;

    checkForForbiddenName(pluginHandle.name);
    Path pluginToDelete = pluginHandle.extractedDir(environment);
    if (Files.exists(pluginToDelete)) {
      terminal.println(VERBOSE, "Removing: %s", pluginToDelete);
      try {
        IOUtils.rm(pluginToDelete);
      } catch (IOException ex) {
        throw new IOException(
            "Unable to remove "
                + pluginHandle.name
                + ". Check file permissions on "
                + pluginToDelete.toString(),
            ex);
      }
      removed = true;
    }
    Path binLocation = pluginHandle.binDir(environment);
    if (Files.exists(binLocation)) {
      terminal.println(VERBOSE, "Removing: %s", binLocation);
      try {
        IOUtils.rm(binLocation);
      } catch (IOException ex) {
        throw new IOException(
            "Unable to remove "
                + pluginHandle.name
                + ". Check file permissions on "
                + binLocation.toString(),
            ex);
      }
      removed = true;
    }

    if (removed) {
      terminal.println("Removed %s", name);
    } else {
      terminal.println(
          "Plugin %s not found. Run \"plugin list\" to get list of installed plugins.", name);
    }
  }
Example #17
0
  public static void main(String[] args) throws Exception {
    boolean followLinks = false;
    boolean printCycles = false;
    int i = 0;
    while (i < (args.length - 1)) {
      switch (args[i]) {
        case "-follow":
          followLinks = true;
          break;
        case "-printCycles":
          printCycles = true;
          break;
        default:
          throw new RuntimeException(args[i] + " not recognized");
      }
      i++;
    }
    Path dir = Paths.get(args[i]);

    Set<FileVisitOption> options = new HashSet<FileVisitOption>();
    if (followLinks) options.add(FileVisitOption.FOLLOW_LINKS);

    final boolean follow = followLinks;
    final boolean reportCycles = printCycles;
    Files.walkFileTree(
        dir,
        options,
        Integer.MAX_VALUE,
        new FileVisitor<Path>() {
          @Override
          public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            System.out.println(dir);
            return FileVisitResult.CONTINUE;
          }

          @Override
          public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            System.out.println(file);
            return FileVisitResult.CONTINUE;
          }

          @Override
          public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            if (exc != null) throw exc;
            return FileVisitResult.CONTINUE;
          }

          @Override
          public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            if (follow && (exc instanceof FileSystemLoopException)) {
              if (reportCycles) System.out.println(file);
              return FileVisitResult.CONTINUE;
            } else {
              throw exc;
            }
          }
        });
  }
Example #18
0
  /** Register the given directory, and all its sub-directories, with the WatchService.f */
  private void registerAll(final Path start) throws IOException {
    Files.walkFileTree(
        start,
        new SimpleFileVisitor<Path>() {
          @Override
          public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            logger.debug("postVisitDir " + dir.toString());
            WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
            logger.debug("Adding key: " + key.toString() + " " + dir);
            keys.put(key, dir);
            return FileVisitResult.CONTINUE;
          }

          @Override
          public FileVisitResult preVisitDirectory(Path fullDir, BasicFileAttributes attrs)
              throws IOException {
            logger.debug("preVisitDirectory " + fullDir.toString());
            String dir = "/" + fixPath(startDir.relativize(fullDir).toString());
            if (!MetaHandler.isStored(dir) || MetaHandler.isModified(dir, fullDir.toFile())) {
              try {
                Entry folderEntry = null;
                try {
                  logger.debug("Creating folder: " + dir);
                  folderEntry = api.createFolder(dir);
                } catch (DropboxServerException ex) {
                  if (ex.error == DropboxServerException._403_FORBIDDEN) {
                    folderEntry = api.metadata(dir, 0, null, false, null);
                  } else {
                    logger.error(ex.getMessage());
                  }
                }

                MetaHandler.setFile(dir, fullDir.toFile(), folderEntry.rev);
              } catch (DropboxException ex) {
                ex.printStackTrace();
              }
            }

            return FileVisitResult.CONTINUE;
          }

          @Override
          public FileVisitResult visitFile(Path fullPath, BasicFileAttributes attrs)
              throws IOException {
            logger.debug("visitFile " + fullPath.toString());
            String file = "/" + fixPath(startDir.relativize(fullPath).toString());
            if (!MetaHandler.isStored(file) || MetaHandler.isModified(file, fullPath.toFile())) {
              logger.debug("Not stored or updated: " + file);
              try {
                uploadFile(file, fullPath);
              } catch (Exception ex) {
                ex.printStackTrace();
              }
            }
            return FileVisitResult.CONTINUE;
          }
        });
  }
 private static Set<ShardId> findAllShardsForIndex(Path indexPath) throws IOException {
   Set<ShardId> shardIds = new HashSet<>();
   if (Files.isDirectory(indexPath)) {
     try (DirectoryStream<Path> stream = Files.newDirectoryStream(indexPath)) {
       String currentIndex = indexPath.getFileName().toString();
       for (Path shardPath : stream) {
         if (Files.isDirectory(shardPath)) {
           Integer shardId = Ints.tryParse(shardPath.getFileName().toString());
           if (shardId != null) {
             ShardId id = new ShardId(currentIndex, shardId);
             shardIds.add(id);
           }
         }
       }
     }
   }
   return shardIds;
 }
Example #20
0
 public static void main(String[] args) throws IOException {
   Properties props = new Properties();
   try (InputStream in = Files.newInputStream(Paths.get(args[0]))) {
     props.load(in);
   }
   String url = props.remove("url").toString();
   String result = doPost(url, props);
   System.out.println(result);
 }
Example #21
0
 private static void setPosixFileAttributes(
     Path path, UserPrincipal owner, GroupPrincipal group, Set<PosixFilePermission> permissions)
     throws IOException {
   PosixFileAttributeView fileAttributeView =
       Files.getFileAttributeView(path, PosixFileAttributeView.class);
   fileAttributeView.setOwner(owner);
   fileAttributeView.setGroup(group);
   fileAttributeView.setPermissions(permissions);
 }
Example #22
0
    private int getNumberOfItems(Path quellOrdner) {
      int retValue = 0;

      try {
        DirectoryStream<Path> qstream = Files.newDirectoryStream(quellOrdner);
        for (Path qfile : qstream) {
          if (Files.isDirectory(qfile)) {
            getNumberOfItems(Paths.get(quellOrdner.toString() + "/" + qfile.getFileName()));
          }
          i++;
        }
        qstream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }

      retValue = i;
      return retValue;
    }
 @Override
 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
     throws IOException {
   Path targetPath = toPath.resolve(fromPath.relativize(dir));
   if (!Files.exists(targetPath)) {
     targetPath.toFile().mkdirs();
     // Files.createDirectory(targetPath);
   }
   return FileVisitResult.CONTINUE;
 }
Example #24
0
 private void create() {
   try {
     Messaging.log("Creating file: " + this.file.getName());
     Files.createParentDirs(this.file);
     this.file.createNewFile();
   } catch (IOException ex) {
     Messaging.severe("Could not create file: " + this.file.getName());
     ex.printStackTrace();
   }
 }
Example #25
0
  /**
   * In this method, all possible post hoc statistical test between more than three algorithms
   * results are executed, according to the configuration file
   *
   * @param code A double that identifies which methods will be applied
   * @param nfold A vector of int with fold number by algorithm
   * @param algorithms A vector of String with the names of the algorithms
   * @param fileName A String with the name of the output file
   */
  public static void doMultiple(double data[][], String algorithms[]) {

    String outputFileName = Configuration.getPath();

    String outputString = new String("");
    outputString = header();

    outputString += runMultiple(data, algorithms);

    Files.writeFile(outputFileName, outputString);
  } // end-method
 public Set<String> findAllIndices() throws IOException {
   if (nodePaths == null || locks == null) {
     throw new IllegalStateException("node is not configured to store local location");
   }
   assert assertEnvIsLocked();
   Set<String> indices = Sets.newHashSet();
   for (NodePath nodePath : nodePaths) {
     Path indicesLocation = nodePath.indicesPath;
     if (Files.isDirectory(indicesLocation)) {
       try (DirectoryStream<Path> stream = Files.newDirectoryStream(indicesLocation)) {
         for (Path index : stream) {
           if (Files.isDirectory(index)) {
             indices.add(index.getFileName().toString());
           }
         }
       }
     }
   }
   return indices;
 }
 /**
  * This method tries to write an empty file and moves it using an atomic move operation. This
  * method throws an {@link IllegalStateException} if this operation is not supported by the
  * filesystem. This test is executed on each of the data directories. This method cleans up all
  * files even in the case of an error.
  */
 public void ensureAtomicMoveSupported() throws IOException {
   final NodePath[] nodePaths = nodePaths();
   for (NodePath nodePath : nodePaths) {
     assert Files.isDirectory(nodePath.path) : nodePath.path + " is not a directory";
     final Path src = nodePath.path.resolve("__es__.tmp");
     Files.createFile(src);
     final Path target = nodePath.path.resolve("__es__.final");
     try {
       Files.move(src, target, StandardCopyOption.ATOMIC_MOVE);
     } catch (AtomicMoveNotSupportedException ex) {
       throw new IllegalStateException(
           "atomic_move is not supported by the filesystem on path ["
               + nodePath.path
               + "] atomic_move is required for elasticsearch to work correctly.",
           ex);
     } finally {
       Files.deleteIfExists(src);
       Files.deleteIfExists(target);
     }
   }
 }
  @Override
  public void parse() throws IOException {
    if (conservedRegionPath == null
        || !Files.exists(conservedRegionPath)
        || !Files.isDirectory(conservedRegionPath)) {
      throw new IOException(
          "Conservation directory whether does not exist, is not a directory or cannot be read");
    }

    Map<String, Path> files = new HashMap<>();
    String chromosome;
    Set<String> chromosomes = new HashSet<>();

    // Reading all files in phastCons folder
    DirectoryStream<Path> directoryStream =
        Files.newDirectoryStream(conservedRegionPath.resolve("phastCons"));
    for (Path path : directoryStream) {
      chromosome = path.getFileName().toString().split("\\.")[0].replace("chr", "");
      chromosomes.add(chromosome);
      files.put(chromosome + "phastCons", path);
    }

    // Reading all files in phylop folder
    directoryStream = Files.newDirectoryStream(conservedRegionPath.resolve("phylop"));
    for (Path path : directoryStream) {
      chromosome = path.getFileName().toString().split("\\.")[0].replace("chr", "");
      chromosomes.add(chromosome);
      files.put(chromosome + "phylop", path);
    }

    /** Now we can iterate over all the chromosomes found and process the files */
    logger.debug("Chromosomes found {}", chromosomes.toString());
    for (String chr : chromosomes) {
      logger.debug("Processing chromosome {}, file {}", chr, files.get(chr + "phastCons"));
      processFile(files.get(chr + "phastCons"), "phastCons");

      logger.debug("Processing chromosome {}, file {}", chr, files.get(chr + "phylop"));
      processFile(files.get(chr + "phylop"), "phylop");
    }
  }
Example #29
0
 /** Регистрация директории для WatchService. */
 private void registerAll(final Path start) throws IOException {
   // Регистрируем директорию
   Files.walkFileTree(
       start,
       new SimpleFileVisitor<Path>() {
         @Override
         public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
             throws IOException {
           register(dir);
           return FileVisitResult.CONTINUE;
         }
       });
 }
Example #30
0
 public static void load(Collection<FileDesc> files, Path root, int blocSize, Pattern pattern)
     throws IOException {
   root = root.toAbsolutePath().normalize();
   Visitor visitor = new Visitor(root, blocSize, pattern);
   Files.walkFileTree(root, visitor);
   for (Future<FileDesc> future : visitor.futures()) {
     try {
       files.add(future.get());
     } catch (Exception e) {
       log.error("", e);
     }
   }
 }