public static SyncFile addFolderSyncFile(
      Path filePath, long parentFolderId, long repositoryId, long syncAccountId) throws Exception {

    // Local sync file

    if (Files.notExists(filePath)) {
      return null;
    }

    String name = String.valueOf(filePath.getFileName());

    SyncFile syncFile =
        addSyncFile(
            null,
            null,
            null,
            filePath.toString(),
            Files.probeContentType(filePath),
            name,
            parentFolderId,
            repositoryId,
            SyncFile.STATE_SYNCED,
            syncAccountId,
            SyncFile.TYPE_FOLDER);

    // Remote sync file

    FileEventUtil.addFolder(parentFolderId, repositoryId, syncAccountId, name, syncFile);

    return syncFile;
  }
Example #2
0
  public static FileInfo pathToFileInfo(Path filePath, Path start) {
    FileInfo fileInfo = new FileInfo();
    if (!Files.exists(filePath)) {
      fileInfo.setName("Unknown");
      return fileInfo;
    }

    fileInfo.setName(start.relativize(filePath).toString());

    if (Files.isDirectory(filePath)) {
      fileInfo.setDir(true);
    } else {
      fileInfo.setDir(false);
      try {
        fileInfo.setSize(Files.size(filePath));
      } catch (IOException e) {
        fileInfo.setSize(0);
      }
      try {
        fileInfo.setMimeType(Files.probeContentType(filePath));
      } catch (IOException e) {
        fileInfo.setMimeType("application/octet-stream");
      }
      if (fileInfo.getMimeType() == null) {
        fileInfo.setMimeType("application/octet-stream");
      }
    }

    return fileInfo;
  }
  public static SyncFile addFileSyncFile(
      Path filePath, long folderId, long repositoryId, long syncAccountId) throws Exception {

    // Local sync file

    if (Files.notExists(filePath)) {
      return null;
    }

    String checksum = FileUtil.getChecksum(filePath);
    String name = String.valueOf(filePath.getFileName());
    String mimeType = Files.probeContentType(filePath);

    SyncFile syncFile =
        addSyncFile(
            null,
            checksum,
            null,
            filePath.toString(),
            mimeType,
            name,
            folderId,
            repositoryId,
            SyncFile.STATE_SYNCED,
            syncAccountId,
            SyncFile.TYPE_FILE);

    // Remote sync file

    FileEventUtil.addFile(
        filePath, folderId, repositoryId, syncAccountId, checksum, name, mimeType, syncFile);

    return syncFile;
  }
 public static String getFileMimeType(File f) {
   String fileType = "application/octet-stream";
   try {
     fileType = Files.probeContentType(f.toPath());
     System.out.println("Read File Type as " + fileType + " " + f.getName());
   } catch (IOException e) {
     // TODO Auto-generated catch block
     fileType = "unknown";
   }
   return fileType;
 }
Example #5
0
 public static String getMimeType(String fileName) {
   try {
     return Files.probeContentType(Paths.get(fileName));
   } catch (IOException e) {
     return "application/octet-stream";
   }
   /*
    * Collection types = MimeUtil.getMimeTypes(fileName); return
    * MimeUtil2.getMostSpecificMimeType(types).toString();
    */
 }
Example #6
0
 @Override
 public boolean accept(File file) {
   if (file.isDirectory()) return true;
   else {
     try {
       return Files.probeContentType(file.toPath()).indexOf("video") == 0;
     } catch (IOException e) {
       e.printStackTrace();
       return false;
     }
   }
 }
  public String getAttachmentContentType(String defaultType, String filename) {
    if (filename != null && fileContentTypes.containsKey(filename))
      return fileContentTypes.get(filename);

    File file = new File(filename);
    String contentType = defaultType;
    try {
      contentType = Files.probeContentType(file.toPath());
    } catch (IOException e) {
      log.info("Failed to determine content type of attachment [" + filename + "]: ", e);
    }
    return contentType;
  }
 /**
  * Get file mime type
  *
  * @param filepath
  * @return mime filetype
  */
 public String getMimeFileType(String filepath) {
   try {
     String mimeType = Files.probeContentType(new File(filepath).toPath());
     if (mimeType == null) {
       // handle special case when OS cannot detect file type
       // get file extension
       int i = filepath.lastIndexOf('.');
       mimeType = filepath.substring(i + 1);
       mimeType = "application/" + mimeType;
     }
     return mimeType;
   } catch (IOException e) {
     return null;
   }
 }
Example #9
0
  /** Process all events for the key queued to the watcher. */
  void processEvents() {
    for (; ; ) {

      // wait for key to be signaled
      WatchKey key;
      try {
        key = watcher.take();
      } catch (InterruptedException x) {
        return;
      }

      for (WatchEvent<?> event : key.pollEvents()) {
        WatchEvent.Kind kind = event.kind();

        if (kind == OVERFLOW) {
          continue;
        }

        // The filename is the context of the event.
        WatchEvent<Path> ev = (WatchEvent<Path>) event;
        Path filename = ev.context();

        // Verify that the new file is a text file.
        try {
          Path child = dir.resolve(filename);
          if (!Files.probeContentType(child).equals("text/plain")) {
            System.err.format("New file '%s' is not a plain text file.%n", filename);
            continue;
          }
        } catch (IOException x) {
          System.err.println(x);
          continue;
        }

        // Email the file to the specified email alias.
        System.out.format("Emailing file %s%n", filename);
      }

      // Reset the key -- this step is critical if you want to receive
      // further watch events. If the key is no longer valid, the directory
      // is inaccessible so exit the loop.
      boolean valid = key.reset();
      if (!valid) {
        break;
      }
    }
  }
 public static String probeContentType(Path path) {
   String mimeType = null;
   try {
     mimeType = Files.probeContentType(path);
   } catch (IOException e) {
     // if any exception they try Apache Tika, ignore this exception
     // do nothing
   }
   if (null == mimeType || mimeType.trim().length() == 0) {
     try {
       mimeType = tika.detect(path.toFile());
     } catch (IOException ex) {
       Log.exception(ex);
       throw new RuntimeException(ex);
     }
   }
   return mimeType;
 }
Example #11
0
  @GET
  @Path("{url : .+}")
  public Response get(@PathParam("url") String url) throws IOException {

    java.nio.file.Path path = LocalImageCache.getInstance().resolveLocal(url);
    if (!Files.isReadable(path) || Files.size(path) == 0) {

      if (url.endsWith(".jpg")) {

        String[] groups = RegExp.parseGroups(url, "([\\w]+)/([\\d]+)\\.[\\w]+");
        if (groups != null) {
          String type = groups[0];
          Long downloadableId = Long.parseLong(groups[1]);
          Downloadable instance = DownloadableFactory.getInstance().createInstance(downloadableId);

          if (instance != null) {
            FindDownloadableImageTask instanceTask =
                DynamoObjectFactory.createInstance(FindDownloadableImageTask.class, instance);
            if (instanceTask != null) {
              BackLogProcessor.getInstance().schedule(instanceTask, false);
            }
          }
        }

        InputStream in = this.getClass().getResourceAsStream("/ring.svg");
        return Response.ok(in).header("Content-Type", "image/svg+xml").build();
      }

      return Response.status(404).build();
    } else {

      Calendar calendar = Calendar.getInstance();
      calendar.add(Calendar.DAY_OF_MONTH, 2);

      InputStream in = Files.newInputStream(path, StandardOpenOption.READ);
      return Response.ok(in)
          .header("Content-Length", Files.size(path))
          .header("Content-Type", Files.probeContentType(path))
          .header("Expires", calendar.getTimeInMillis())
          .build();
    }
  }
  /** {@inheritDoc} */
  @Override
  public Message process(Message message) {
    String directoryAsString = ExpressionUtils.evaluateNoFail(this.directory, message, "/");
    File directory = new File(directoryAsString);

    if (directory.isDirectory()) {
      String fileAsString = ExpressionUtils.evaluateNoFail(this.filePath, message, "");
      File file = new File(directory, fileAsString);
      try {
        FileInputStream io = new FileInputStream(file);
        message.setPayload(IOUtils.toByteArray(io));

        String contentType = Files.probeContentType(file.toPath());
        message.putProperty(MessageUtils.FILE_BASE_PROPERTY + ".contentType", contentType);
      } catch (IOException e) {
        log.error("Error reading the file", e);
      }
    }

    return message;
  }
  @Action(
      value = "/viewResultFile",
      results = {
        @Result(name = "success", location = "/file_view.jsp"),
        @Result(name = "error", location = "/file_view.jsp")
      })
  public String viewFileData() {
    String uuid = getUuid();
    String project = getProject();
    if (absolutePath != null) {
      try {
        String realPath = context.getRealPath("/tmp-files");
        String id = UUID.randomUUID().toString();
        File dir = new File(realPath, id);
        dir.mkdir();

        String[] parentsArr = PortEnginUtils.convertAbsolutePathToArray(absolutePath, true, true);
        fileName = PortEnginUtils.retrieveFileNameFromAbsolutePath(absolutePath);
        InputStream is = jobMonitoringService.download(uuid, project, jobId, parentsArr, fileName);

        File file = new File(dir, fileName);
        PortEnginUtils.convertInputStreamToFile(is, file);
        String mime = Files.probeContentType(file.toPath());
        FileViewer viewer = FileViewerFactory.createFileViewer(mime);
        relativePath = "tmp-files/" + id + "/" + fileName;
        view = viewer.createView(relativePath);
        file.deleteOnExit();
      } catch (MonitoringServiceException e) {
        PortEnginUtils.handleException(e, logger);
      } catch (IOException e) {
        PortEnginUtils.handleException(e, logger);
      } catch (UserNotAuthorizedException e) {
        PortEnginUtils.handleException(e, logger);
      }
      return SUCCESS;
    }
    close = true;
    return ERROR;
  }
  /**
   * Tell the kernel to stream a file as specified by {@code filename} directly from disk to the
   * outgoing connection, bypassing userspace altogether (where supported by the underlying
   * operating system. This is a very efficient way to serve files.
   *
   * <p>
   */
  public HttpServerResponse sendFile(String filename) {
    if (headWritten) {
      throw new IllegalStateException("Head already written");
    }
    checkWritten();

    File file = new File(filename);

    if (!file.exists()) {
      HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_FOUND);
      writeFuture = conn.write(response);
    } else {
      HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
      response.setHeader(Names.CONTENT_LENGTH, String.valueOf(file.length()));
      try {
        String contenttype = Files.probeContentType(Paths.get(filename));
        if (contenttype != null) {
          response.setHeader(Names.CONTENT_TYPE, contenttype);
        }
      } catch (IOException e) {
        e.printStackTrace();
      }

      conn.write(response);

      writeFuture = conn.sendFile(file);
    }

    // Close the non-keep-alive connection after the write operation is done.
    if (!keepAlive) {
      writeFuture.addListener(ChannelFutureListener.CLOSE);
    }
    headWritten = written = true;
    conn.responseComplete();

    return this;
  }