Exemple #1
0
  /** @param args */
  public static void main(String[] args) {
    FileTypeMap fileTypeMap = FileTypeMap.getDefaultFileTypeMap();

    String path = ".";
    File dir = new File(path);
    File[] listFiles = dir.listFiles();
    for (File file : listFiles) {
      System.out.println(file.getName() + ":" + fileTypeMap.getContentType(file));
    }
  }
 /**
  * Use the specified file as the content for this part.
  *
  * @param file the file
  * @since JavaMail 1.4
  */
 public void attachFile(File file) throws IOException, MessagingException {
   FileTypeMap map = FileTypeMap.getDefaultFileTypeMap();
   String contentType = map.getContentType(file);
   if (contentType == null)
     throw new MessagingException("Unable to determine MIME type of " + file);
   /*GPL->GNU@03/15/2011 - Fix for adding attachments into MimeBodyPart start*/
   // setContent(new FileInputStream(file), contentType);
   setContent(file);
   /*GPL->GNU@03/15/2011 - Fix for adding attachments into MimeBodyPart end*/
   setFileName(file.getName());
 }
  public ModelAndView downloadDocuments(HttpServletRequest request, HttpServletResponse response)
      throws ServletException {
    JSONObject jobj = new JSONObject();
    JSONObject myjobj = new JSONObject();
    KwlReturnObject kmsg = null;
    String details = "";
    String auditAction = "";
    try {
      String url = request.getParameter("url");
      url = StringUtil.checkForNull(url);
      String applicant = request.getParameter("applicant");
      applicant = StringUtil.checkForNull(applicant);
      Hashtable ht;
      if (applicant.equalsIgnoreCase("applicant")) {
        kmsg = hrmsExtApplDocsDAOObj.downloadDocument(url);
        ht = getExtDocumentDownloadHash(kmsg.getEntityList());
      } else {
        kmsg = documentDAOObj.downloadDocument(url);
        ht = getDocumentDownloadHash(kmsg.getEntityList());
      }

      String src = storageHandlerImplObj.GetDocStorePath();
      //            String src = "/home/trainee/";
      if (request.getParameter("mailattch") != null) {
        src = src + ht.get("svnname");
      } else {
        src = src + ht.get("userid").toString() + "/" + ht.get("svnname");
      }

      File fp = new File(src);
      byte[] buff = new byte[(int) fp.length()];
      FileInputStream fis = new FileInputStream(fp);
      int read = fis.read(buff);
      javax.activation.FileTypeMap mmap = new javax.activation.MimetypesFileTypeMap();
      response.setContentType(mmap.getContentType(src));
      response.setContentLength((int) fp.length());
      response.setHeader(
          "Content-Disposition",
          request.getParameter("dtype") + "; filename=\"" + ht.get("Name") + "\";");
      response.getOutputStream().write(buff);
      response.getOutputStream().flush();
      response.getOutputStream().close();
      String map = ht.get("relatedto").toString();
      String refid = ht.get("recid").toString();

      myjobj.put("success", true);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    return new ModelAndView("jsonView", "model", myjobj.toString());
  }
 private static FileTypeMap loadFileTypeMapFromContextSupportModule() {
   // see if we can find the extended mime.types from the context-support module
   Resource mappingLocation =
       new ClassPathResource("org/springframework/mail/javamail/mime.types");
   if (mappingLocation.exists()) {
     if (logger.isTraceEnabled()) {
       logger.trace("Loading Java Activation Framework FileTypeMap from " + mappingLocation);
     }
     InputStream inputStream = null;
     try {
       inputStream = mappingLocation.getInputStream();
       return new MimetypesFileTypeMap(inputStream);
     } catch (IOException ex) {
       // ignore
     } finally {
       if (inputStream != null) {
         try {
           inputStream.close();
         } catch (IOException ex) {
           // ignore
         }
       }
     }
   }
   if (logger.isTraceEnabled()) {
     logger.trace("Loading default Java Activation Framework FileTypeMap");
   }
   return FileTypeMap.getDefaultFileTypeMap();
 }
Exemple #5
0
  // 处理参数
  public static void process(ImgObject image) {

    String key = image.getGomefsKey() == null ? image.getSourceKey() : image.getGomefsKey();
    //        if (!(image.getIsPressed() == 0 && image.getIsThumbNail() == 0   &&
    // image.getWaterMark() == WaterMarkEnum.WATERMARK_NONE)) {
    //            String zoomPara = image.toParaString();
    //            image.getHeaders().add(HttpHeaders.ETAG, zoomPara);
    //        }
    if (!image.isOriginal()) {
      String zoomPara = image.toParaString();
      image.getHeaders().add(HttpHeaders.ETAG, zoomPara);
    } else {
      image.getHeaders().add(HttpHeaders.ETAG, image.toNullString());
    }
    image.getHeaders().add(HttpHeaders.CONTENT_LENGTH, String.valueOf(image.getZoomData().length));
    image.getHeaders().add(HttpHeaders.CONTENT_TYPE, fileTypeMap.getContentType(key.toLowerCase()));
    if (image.isHtml()) {
      // html 编码
      MediaType mediaType = new MediaType("text", "html", Charset.forName("UTF-8"));
      image.getHeaders().setContentType(mediaType);
    }
    //        long lastModified = image.gomefsKey == null ? 0 :
    // KeyUtils.getCreateTime(image.gomefsKey);
    //        image.headers.setLastModified(lastModified * 1000);
    image.getHeaders().setCacheControl("max-age=315360000"); // year 10
    long time = System.currentTimeMillis() + YEAR_30;
    image.getHeaders().setExpires(time);
  }
  @Override
  protected ModelAndView svnHandle(
      final SVNConnection connection,
      final BaseCommand cmd,
      final long headRevision,
      final UserRepositoryContext userRepositoryContext,
      final HttpServletRequest request,
      final HttpServletResponse response,
      final BindException exception)
      throws Exception {

    final MultipleEntriesCommand command = (MultipleEntriesCommand) cmd;

    final Map<String, Object> model = new HashMap<String, Object>();
    final List<PathRevision> imageEntries = new ArrayList<PathRevision>();

    logger.debug("Showing thumbnail images");
    // Check what entries are image files - and add them to the list of thumbnails.
    for (final PathRevision entry : command.getEntries()) {
      logger.debug("entry: " + entry);
      if (mimeFileTypeMap.getContentType(entry.getPath()).startsWith("image")) {
        imageEntries.add(entry);
      }
    }
    logger.debug(
        imageEntries.size()
            + " entries out of "
            + command.getEntries().length
            + " are image files");
    model.put("thumbnailentries", imageEntries);
    return new ModelAndView(getViewName(), model);
  }
 /** Find extended mime.types from the spring-context-support module. */
 private static FileTypeMap initFileTypeMap() {
   Resource resource = new ClassPathResource("org/springframework/mail/javamail/mime.types");
   if (resource.exists()) {
     if (logger.isTraceEnabled()) {
       logger.trace("Loading JAF FileTypeMap from " + resource);
     }
     InputStream inputStream = null;
     try {
       inputStream = resource.getInputStream();
       return new MimetypesFileTypeMap(inputStream);
     } catch (IOException ex) {
       // ignore
     } finally {
       if (inputStream != null) {
         try {
           inputStream.close();
         } catch (IOException ex) {
           // ignore
         }
       }
     }
   }
   if (logger.isTraceEnabled()) {
     logger.trace("Loading default Java Activation Framework FileTypeMap");
   }
   return FileTypeMap.getDefaultFileTypeMap();
 }
  /**
   * @param request the <code>HttpRequest</code>
   * @param response the <code>HttpResponse</code>
   * @param hasBody <code>true</code> to write the message body; <code>false</code> otherwise.
   */
  private void perform(final HttpRequest request, final HttpResponse response, boolean hasBody) {

    final String path = request.getRequestedPath();
    final File file = new File(path.substring(1)); // remove the leading '/'
    if (!file.exists()) {
      throw new HttpException(HttpStatus.CLIENT_ERROR_NOT_FOUND);
    } else if (!file.isFile()) {
      throw new HttpException(HttpStatus.CLIENT_ERROR_FORBIDDEN, path + "is not a file");
    }

    final long lastModified = file.lastModified();
    response.setHeader("Last-Modified", DateUtil.parseToRFC1123(lastModified));
    response.setHeader("Cache-Control", "public");
    String mimeType = mimeTypeMap.getContentType(file);
    if ("text/plain".equals(mimeType)) {
      mimeType += "; charset=utf-8";
    }
    response.setHeader("Content-Type", mimeType);
    final String ifModifiedSince = request.getHeader("If-Modified-Since");
    if (ifModifiedSince != null) {
      final long ims = DateUtil.parseToMilliseconds(ifModifiedSince);
      if (lastModified <= ims) {
        response.setStatus(HttpStatus.REDIRECTION_NOT_MODIFIED);
        logger.debug("not modified");
        return;
      }
    }

    if (hasBody) {
      response.write(file);
    }
  }
  /* (non-Javadoc)
   * @see uk.ac.ox.oucs.oxam.logic.PaperFileService#deposit(uk.ac.ox.oucs.oxam.logic.PaperFile, uk.ac.ox.oucs.oxam.logic.Callback)
   */
  public void deposit(PaperFile paperFile, InputStream in) {
    PaperFileImpl impl = castToImpl(paperFile);
    String path = impl.getPath();
    ContentResourceEdit resource = null;
    try {

      try {
        contentHostingService.checkResource(path);
        resource = contentHostingService.editResource(path);
        // Ignore PermissionException, IdUnusedException, TypeException
        // As they are too serious to continue.
      } catch (IdUnusedException iue) {
        // Will attempt to create containing folders.

        resource = contentHostingService.addResource(path);
        // Like the basename function.
        String filename = StringUtils.substringAfterLast(path, "/");
        ResourceProperties props = resource.getPropertiesEdit();
        props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, filename);
        resource.setContentType(mimeTypes.getContentType(filename));
      }
      resource.setContent(in);
      contentHostingService.commitResource(resource, NotificationService.NOTI_NONE);
      LOG.debug("Sucessfully copied file to: " + path);
    } catch (OverQuotaException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ServerOverloadException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (PermissionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InUseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TypeException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IdUsedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IdInvalidException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InconsistentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      // Close the stream here as this is where it's created.
      if (resource.isActiveEdit()) {
        contentHostingService.cancelResource(resource);
      }
    }
  }
Exemple #10
0
  public static String jsFunction_getContentType(
      Context cx, Scriptable thisObj, Object[] args, Function funObj) throws ScriptException {
    String functionName = "getContentType";
    int argsCount = args.length;
    if (argsCount != 0) {
      HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
    }
    FileHostObject fho = (FileHostObject) thisObj;

    if (!mimeMapLoaded) {
      FileTypeMap.setDefaultFileTypeMap(loadMimeMap());
      mimeMapLoaded = true;
    }

    return fho.file.getContentType();
  }
Exemple #11
0
    /**
     * 添付ファイルのDataSourceインスタンスを生成して返します。
     *
     * @return 添付ファイルのDataSourceインスタンス
     */
    public DataSource getDataSource() {
      if (file != null) {
        return new FileDataSource(file);
      }

      if (url != null) {
        return new URLDataSource(url);
      }

      // InputStreamからDataSourceを生成
      String contentType = FileTypeMap.getDefaultFileTypeMap().getContentType(name);
      if (is != null) {
        // InputStreamからDataSourceを生成
        return new ByteArrayDataSource(is, contentType);
      } else {
        // byte配列からDataSourceを生成
        return new ByteArrayDataSource(bytes, contentType);
      }
    }
 public static MediaType getMediaType(String filename) {
   String mediaType = fileTypeMap.getContentType(filename);
   return (StringUtils.hasText(mediaType) ? MediaType.parseMediaType(mediaType) : null);
 }
 public static String getMimeType(String filePath) {
   return FileTypeMap.getDefaultFileTypeMap().getContentType(filePath);
 }
/**
 * A RequestHandler that serves static content (files) from a predefined directory.
 *
 * <p>"Cache-Control: public" indicates that the response MAY be cached by any cache, even if it
 * would normally be non-cacheable or cacheable only within a non- shared cache.
 */
public class StaticContentHandler extends RequestHandler {

  private static final Logger logger = LoggerFactory.getLogger(StaticContentHandler.class);

  private static final StaticContentHandler instance = new StaticContentHandler();

  private final FileTypeMap mimeTypeMap = FileTypeMap.getDefaultFileTypeMap();

  public static StaticContentHandler getInstance() {
    return instance;
  }

  /** {inheritDoc} */
  @Override
  public void get(HttpRequest request, HttpResponse response) {
    perform(request, response, true);
  }

  /** {inheritDoc} */
  @Override
  public void head(final HttpRequest request, final HttpResponse response) {
    perform(request, response, false);
  }

  /**
   * @param request the <code>HttpRequest</code>
   * @param response the <code>HttpResponse</code>
   * @param hasBody <code>true</code> to write the message body; <code>false</code> otherwise.
   */
  private void perform(final HttpRequest request, final HttpResponse response, boolean hasBody) {

    final String path = request.getRequestedPath();
    final File file = new File(path.substring(1)); // remove the leading '/'
    if (!file.exists()) {
      throw new HttpException(HttpStatus.CLIENT_ERROR_NOT_FOUND);
    } else if (!file.isFile()) {
      throw new HttpException(HttpStatus.CLIENT_ERROR_FORBIDDEN, path + "is not a file");
    }

    final long lastModified = file.lastModified();
    response.setHeader("Last-Modified", DateUtil.parseToRFC1123(lastModified));
    response.setHeader("Cache-Control", "public");
    String mimeType = mimeTypeMap.getContentType(file);
    if ("text/plain".equals(mimeType)) {
      mimeType += "; charset=utf-8";
    }
    response.setHeader("Content-Type", mimeType);
    final String ifModifiedSince = request.getHeader("If-Modified-Since");
    if (ifModifiedSince != null) {
      final long ims = DateUtil.parseToMilliseconds(ifModifiedSince);
      if (lastModified <= ims) {
        response.setStatus(HttpStatus.REDIRECTION_NOT_MODIFIED);
        logger.debug("not modified");
        return;
      }
    }

    if (hasBody) {
      response.write(file);
    }
  }
}