Exemple #1
0
  /**
   * This adds a single file to the parser
   *
   * @param rootPath The root path to the source folder
   * @param relativeFilePath The relative path inside the root path to the file. The file will be
   *     added to the map with the key of the entire relative path so that lookups from within
   *     Sorbet do not have any ambiguity
   * @return 0 if success, 1 if failed
   */
  private int addFile(String rootPath, String relativeFilePath) {
    try {
      // Open file
      FileInputStream file = new FileInputStream(rootPath + File.separator + relativeFilePath);

      // Setup parser
      CompilationUnit cu = JavaParser.parse(file);

      // Visit the file with our visitor
      VariableVisitor<Object> variableVisitor = new VariableVisitor<Object>();
      variableVisitor.visit(cu, null);

      Lines lines = variableVisitor.getLines();

      if (files.containsKey(relativeFilePath)) {
        // Already contains this file, return failed
        return 1;
      } else {
        files.put(relativeFilePath, lines);
      }

    } catch (FileNotFoundException e) {
      // File doesn't exist, return failed
      return 1;
    } catch (ParseException e) {
      // File isn't valid, return failed
      return 1;
    }

    // Return success
    return 0;
  }
Exemple #2
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);
  }
Exemple #3
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");
    }
  }
  public static void main(String[] args) throws IOException {
    Closer closer = Closer.create();
    // copy a file
    File origin = new File("join_temp");
    File copy = new File("target_temp");

    try {
      BufferedReader reader = new BufferedReader(new FileReader("join_temp"));
      BufferedWriter writer = new BufferedWriter(new FileWriter("target_temp"));

      closer.register(reader);
      closer.register(writer);

      String line;

      while ((line = reader.readLine()) != null) {
        writer.write(line);
      }
    } catch (IOException e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }

    Files.copy(origin, copy);

    File moved = new File("moved");

    // moving renaming
    Files.move(copy, moved);

    // working files as string
    List<String> lines = Files.readLines(origin, Charsets.UTF_8);

    HashCode hashCode = Files.hash(origin, Hashing.md5());
    System.out.println(hashCode);

    // file write and append
    String hamlet = "To be, or not to be it is a question\n";
    File write_and_append = new File("write_and_append");

    Files.write(hamlet, write_and_append, Charsets.UTF_8);

    Files.append(hamlet, write_and_append, Charsets.UTF_8);

    //        write_and_append.deleteOnExit();

    Files.write("OverWrite the file", write_and_append, Charsets.UTF_8);

    // ByteSource ByteSink
    ByteSource fileBytes = Files.asByteSource(write_and_append);
    byte[] readBytes = fileBytes.read();
    // equals to pre line -> Files.toByteArray(write_and_append) == readBytes

    ByteSink fileByteSink = Files.asByteSink(write_and_append);
    fileByteSink.write(Files.toByteArray(write_and_append));

    BaseEncoding base64 = BaseEncoding.base64();
    System.out.println(base64.encode("123456".getBytes()));
  }
  public void event(WatchEvent.Kind kind, Path path) {
    // System.out.println("Log event");

    File file = new File(path.toString());
    String ip = "0.0.0.0", owner = "unknown";
    try {
      ip = Inet4Address.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
    try {
      FileOwnerAttributeView ownerAttributeView =
          Files.getFileAttributeView(path, FileOwnerAttributeView.class);
      owner = ownerAttributeView.getOwner().getName();
    } catch (IOException e) {
      e.printStackTrace();
    }

    String entry =
        String.format(
            "[%s] \"%s\" copied on \"%s\" by \"%s\"\n",
            new SimpleDateFormat("dd/MMM/YYYY HH:mm:ss").format(new Date()),
            path.toString(),
            ip,
            owner);

    try {
      Files.write(Paths.get(logFile), entry.getBytes(), StandardOpenOption.APPEND);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemple #6
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);
    }
  }
  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();
    }
  }
Exemple #8
0
 public static void setLocation(String type, Location loc) {
   Files.getDataFile().set(type + ".world", loc.getWorld().getName());
   Files.getDataFile().set(type + ".x", loc.getBlockX());
   Files.getDataFile().set(type + ".y", loc.getBlockY());
   Files.getDataFile().set(type + ".z", loc.getBlockZ());
   Files.saveDataFile();
 }
  /**
   * It selects the best solution according to objective 0 and generates the given RB
   *
   * @return the RB with the best value for objective 0
   */
  private ArrayList<String> getAllSolutions() {
    ArrayList<String> solutions = new ArrayList<String>();
    // This procedure can be updated in order to select any other desirable solution
    Files function = new Files();
    String funcionStr = function.readFile(header + ".var");
    StringTokenizer lines = new StringTokenizer(funcionStr, "\n");

    while (lines.hasMoreTokens()) {
      StringTokenizer token = new StringTokenizer(lines.nextToken(), " ");
      String solutionFS = token.nextToken();
      solutionFS = solutionFS.replace("\t", "");
      if (solutionFS.contains("1")) {
        String solutionIS = token.nextToken();
        solutionIS = solutionIS.replace("\t", "");
        if (solutionIS.contains("1")) {
          solutions.add(solutionFS); // 111010110101
          solutions.add(solutionIS); // 111010110101
        } else {
          System.err.println("Skipping empty solution (FS)");
        }
      } else {
        System.err.println("Skipping empty solution (FS)");
      }
    }
    return solutions;
  }
Exemple #10
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 ");
  }
Exemple #11
0
  @Override
  public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
    checkCreate(qc);

    final Path path = toPath(0, qc);
    final B64 archive = toB64(exprs[1], qc, false);
    final TokenSet hs = entries(2, qc);

    try (ArchiveIn in = ArchiveIn.get(archive.input(info), info)) {
      while (in.more()) {
        final ZipEntry ze = in.entry();
        final String name = ze.getName();
        if (hs == null || hs.delete(token(name)) != 0) {
          final Path file = path.resolve(name);
          if (ze.isDirectory()) {
            Files.createDirectories(file);
          } else {
            Files.createDirectories(file.getParent());
            Files.write(file, in.read());
          }
        }
      }
    } catch (final IOException ex) {
      throw ARCH_FAIL_X.get(info, ex);
    }
    return null;
  }
  @After
  public void tearDown() throws Exception {

    // Удаляем тестовый фаил
    Files.delete(Paths.get(pathTempFile));

    // Удаляем тестовые папки и файлы
    Files.walkFileTree(
        Paths.get(storagePath),
        new SimpleFileVisitor<Path>() {

          @Override
          public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
              throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
          }

          @Override
          public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
          }
        });
  }
  /**
   * Check uploading files and create attachments
   *
   * @throws Exception
   */
  @Test
  public void testCreateAttachment() throws Exception {

    List<MultipartFile> files = new ArrayList<>();
    files.add(multipartFile);

    Mockito.when(attachmentFactory.newAttachment()).thenReturn(null);

    attachmentService.setAttachment(new Attachment());
    attachmentService.setMessageResponse(new MessageResponse());

    MessageResponse messageResponse = attachmentService.createAttachment(files);

    Mockito.verify(attachmentDao, Mockito.times(1)).createAttachments(argumentCaptor.capture());

    Attachment attachment = argumentCaptor.getValue().get(0);

    boolean isExistPreview = Files.exists(Paths.get(storagePath + attachment.getPreviewPath()));
    boolean isExistImage = Files.exists(Paths.get(storagePath + attachment.getFilePathInStorage()));

    Files.delete(Paths.get(storagePath + attachment.getPreviewPath()));
    Files.delete(Paths.get(storagePath + attachment.getFilePathInStorage()));

    Assert.assertTrue(
        attachment.getMimeType().equals("image/png")
            && messageResponse.getCode() == 0
            && isExistPreview
            && isExistImage);
  }
  @Test
  public void testRemoveAttachment() throws Exception {

    // CREATING ATTACHMENT FOR REMOVE
    List<MultipartFile> files = new ArrayList<>();
    files.add(multipartFile);

    Mockito.when(attachmentFactory.newAttachment()).thenReturn(null);

    attachmentService.setAttachment(new Attachment());
    attachmentService.setMessageResponse(new MessageResponse());

    MessageResponse messageResponse1 = attachmentService.createAttachment(files);

    Mockito.verify(attachmentDao, Mockito.times(1)).createAttachments(argumentCaptor.capture());

    Attachment attachment = argumentCaptor.getValue().get(0);

    // REMOVE ATTACHMENT
    Mockito.when(attachmentDao.removeAttachment(attachment.getAttachmentId()))
        .thenReturn(attachment);

    MessageResponse messageResponse =
        attachmentService.removeAttachment(attachment.getAttachmentId());

    boolean isExistPreview = Files.exists(Paths.get(storagePath + attachment.getPreviewPath()));
    boolean isExistImage = Files.exists(Paths.get(storagePath + attachment.getFilePathInStorage()));

    Assert.assertTrue(!isExistPreview && !isExistImage && messageResponse.getCode() == 1);
  }
Exemple #15
0
 public static Location getLocation(String type) {
   Location loc =
       new Location(
           Bukkit.getWorld(Files.getDataFile().getString(type + ".world")),
           Files.getDataFile().getInt(type + ".x"),
           Files.getDataFile().getInt(type + ".y"),
           Files.getDataFile().getInt(type + ".z"));
   return loc;
 }
  @Override
  protected void doDelete() throws SQLException {
    final Files theFile = getFile();

    if (theFile != null) {
      theFile.scheduleDeletion();
    }
    super.doDelete();
  }
Exemple #17
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);
    }
  }
Exemple #18
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("");
 }
Exemple #19
0
  public static char[] readCharBuffer(Path path) {
    try {

      long bufSize = Files.size(path);
      return readCharBuffer(Files.newBufferedReader(path, DEFAULT_CHARSET), (int) bufSize);

    } catch (IOException ex) {
      return Exceptions.handle(char[].class, ex);
    }
  }
Exemple #20
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;
 }
Exemple #21
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";
  }
 private void setLocationAndTrackBack(MavenVersion version) {
   try {
     Files files = getFiles(version);
     version.setLocation(files.getArtifactLocation());
     version.setTrackBackUrl(files.getTrackBackUrl());
   } catch (Exception ex) {
     LOGGER.error("Error getting location for " + version.getRevisionLabel(), ex);
     version.setErrorMessage(
         "Plugin could not determine location/trackback. Please see plugin log for details.");
   }
 }
Exemple #23
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);
   }
 }
  public static MapGraph createMapGraphFromFile(String filename) throws IOException {
    Path infilePath = Paths.get(filename);
    MapGraph newMap;

    if (Files.exists(infilePath)) {
      newMap = MapGraphCreator.createMapGraphFromText(Files.readAllLines(infilePath));

    } else {
      throw new IOException(String.format("The file {0} does not exist!", filename));
    }
    return newMap;
  }
 // Set type of file as name of the element
 private void setType(Element element, Path path) {
   if (Files.isDirectory(path)) {
     element.setLocalName(FileType.DIR.getName());
     return;
   } else if (Files.isRegularFile(path)) {
     element.setLocalName(FileType.FILE.getName());
     return;
   } else if (Files.isSymbolicLink(path)) {
     element.setLocalName(FileType.SYMLINK.getName());
     return;
   } else element.setLocalName(FileType.OTHER.getName());
 }
Exemple #26
0
  /**
   * Save network weights to a file
   *
   * @param file_name Output file name
   * @param header header of the data set for which the network has been adjusted to
   */
  protected void printNetworkToFile(String file_name, String header) {
    // write the header to the file
    Files.writeFile(file_name, header);

    Files.addToFile(file_name, "Number of neurons: " + nSel + "\n");
    for (int i = 0; i < nSel; i++) {
      Files.addToFile(file_name, "\nNeuron " + i + "\n");
      for (int j = 0; j < conjS[i].length; j++) {
        Files.addToFile(file_name, Double.toString(conjS[i][j]) + " ");
      }
      Files.addToFile(file_name, " Class = " + clasesS[i] + "\n");
    }
  }
Exemple #27
0
 public static void main(String[] args) throws IOException {
   Path jarfile = Paths.get("/home/punki/test.zip");
   FileSystem fs = FileSystems.newFileSystem(jarfile, null);
   Path path = fs.getPath("tekst.txt");
   System.out.println("path.toString() = " + path.toString());
   ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
   Files.copy(path, outputStream);
   System.out.println("bytes = " + new String(outputStream.toByteArray()));
   List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
   for (String line : lines) {
     System.out.println("line = " + line);
   }
 }
 @Override
 public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
   if (currentDepth >= 0) {
     if (!Files.isReadable(file) || Files.isSymbolicLink(file)) return FileVisitResult.CONTINUE;
     try {
       addPathToTree(file, currentDepth);
       return FileVisitResult.CONTINUE;
     } catch (IOException e) {
       LOG.info(e.getMessage());
       return FileVisitResult.CONTINUE;
     }
   } else return FileVisitResult.SKIP_SIBLINGS;
 }
Exemple #29
0
 public static boolean write(String fullyNamedPath, String content) {
   Path file = Paths.get(fullyNamedPath);
   try {
     Files.deleteIfExists(file);
     Files.write(
         file, Arrays.asList(content), Charset.forName("UTF-8"), StandardOpenOption.CREATE_NEW);
   } catch (IOException ioEx) {
     if (LOGGER.isDebugEnabled()) {
       LOGGER.debug("", ioEx);
     }
   }
   return Files.exists(file, LinkOption.NOFOLLOW_LINKS);
 }
Exemple #30
0
  public static Path createDirectory(Path dir) {

    try {

      if (!Files.exists(dir)) {
        return Files.createDirectory(dir);
      } else {
        return null;
      }

    } catch (Exception ex) {
      return Exceptions.handle(Path.class, ex);
    }
  }