// post方式发送email
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		File file = doAttachment(request);
		EmailAttachment attachment = new EmailAttachment();
		attachment.setPath(file.getPath());
		attachment.setDisposition(EmailAttachment.ATTACHMENT);
		attachment.setName(file.getName());
		MultiPartEmail email = new MultiPartEmail();
		email.setCharset("UTF-8");
		email.setHostName("smtp.sina.com");
		email.setAuthentication("T-GWAP", "dangdang");
		try {
			email.addTo(parameters.get("to"));
			email.setFrom(parameters.get("from"));
			email.setSubject(parameters.get("subject"));
			email.setMsg(parameters.get("body"));
			email.attach(attachment);
			email.send();
			request.setAttribute("sendmail.message", "邮件发送成功!");
		} catch (EmailException e) {
			Logger logger = Logger.getLogger(SendAttachmentMailServlet.class);
			logger.error("邮件发送不成功", e);
			request.setAttribute("sendmail.message", "邮件发送不成功!");
		}
		request.getRequestDispatcher("/sendResult.jsp").forward(request,
				response);
	}
Esempio n. 2
0
  JxpSource getSource(File f) throws IOException {

    if (DEBUG) System.err.println("getSource\n\t " + f);

    File temp = _findFile(f);

    if (DEBUG) System.err.println("\t " + temp);

    if (!temp.exists()) return handleFileNotFound(f);

    //  if it's a directory (and we know we can't find the index file)
    //  TODO : at some point, do something where we return an index for the dir?
    if (temp.isDirectory()) return null;

    // if we are at init time, save it as an initializaiton file
    loadedFile(temp);

    // Ensure that this is w/in the right tree for the context
    if (_localObject != null && _localObject.isIn(temp)) return _localObject.getSource(temp);

    // if not, is it core?
    if (_core.isIn(temp)) return _core.getSource(temp);

    throw new RuntimeException("what?  can't find:" + f);
  }
Esempio n. 3
0
  /**
   * Maps a servlet-like URI to a jxp file.
   *
   * @param f File to check
   * @return new File with <root>.jxp if exists, orig file if not
   * @example /wiki/geir -> maps to wiki.jxp if exists
   */
  File tryServlet(File f) {
    if (f.exists()) return f;

    String uri = f.toString();

    if (uri.startsWith(_rootFile.toString())) uri = uri.substring(_rootFile.toString().length());

    if (_core != null && uri.startsWith(_core._base.toString()))
      uri = "/~~" + uri.substring(_core._base.toString().length());

    while (uri.startsWith("/")) uri = uri.substring(1);

    int start = 0;
    while (true) {

      int idx = uri.indexOf("/", start);
      if (idx < 0) break;
      String foo = uri.substring(0, idx);

      File temp = getFileSafe(foo + ".jxp");

      if (temp != null && temp.exists()) f = temp;

      start = idx + 1;
    }

    return f;
  }
	public File doAttachment(HttpServletRequest request)
			throws ServletException, IOException {
		File file = null;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<?> items = upload.parseRequest(request);
			Iterator<?> itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {
					parameters
							.put(item.getFieldName(), item.getString("UTF-8"));
				} else {
					File tempFile = new File(item.getName());
					file = new File(sc.getRealPath("/") + savePath, tempFile
							.getName());
					item.write(file);
				}
			}
		} catch (Exception e) {
			Logger logger = Logger.getLogger(SendAttachmentMailServlet.class);
			logger.error("邮件发送出了异常", e);
		}
		return file;
	}
Esempio n. 5
0
  private void _loadConfig() {
    try {

      _configScope.set("__instance__", this);

      _loadConfigFromCloudObject(getSiteObject());
      _loadConfigFromCloudObject(getEnvironmentObject());

      File f;
      if (!_admin) {
        f = getFileSafe("_config.js");
        if (f == null || !f.exists()) f = getFileSafe("_config");
      } else
        f =
            new File(
                Module.getModule("core-modules/admin").getRootFile(getVersionForLibrary("admin")),
                "_config.js");

      _libraryLogger.info("config file [" + f + "] exists:" + f.exists());

      if (f == null || !f.exists()) return;

      Convert c = new Convert(f);
      JSFunction func = c.get();
      func.setUsePassedInScope(true);
      func.call(_configScope);

      _logger.debug("config things " + _configScope.keySet());
    } catch (Exception e) {
      throw new RuntimeException("couldn't load config", e);
    }
  }
  public ReaderHandler(LowLevelDbAccess lowLevelDbAccess, String webDir) {

    loginInfoDb = new LoginInfo.DB(lowLevelDbAccess);
    userDb = new User.DB(lowLevelDbAccess);
    feedDb = new Feed.DB(lowLevelDbAccess);
    articleDb = new Article.DB(lowLevelDbAccess);
    readArticlesCollDb = new ReadArticlesColl.DB(lowLevelDbAccess);
    userHelpers = new UserHelpers(loginInfoDb, userDb);

    setContextPath("/");

    File warPath = new File(webDir);
    setWar(warPath.getAbsolutePath());

    if (isInJar) {
      for (Map.Entry<String, String> entry : PATH_MAPPING.entrySet()) {
        addPrebuiltJsp(entry.getKey(), "jsp." + entry.getValue().replaceAll("_", "_005f") + "_jsp");
      }
    } else {
      for (Map.Entry<String, String> entry : PATH_MAPPING.entrySet()) {
        addServlet(
            new ServletHolder(new RedirectServlet("/" + entry.getValue() + ".jsp")),
            entry.getKey());
      }
    }

    setErrorHandler(new ReaderErrorHandler());
  }
Esempio n. 7
0
  /**
   * @param context the Servlet context.
   * @deprecated Now handled in TdsContext.init().
   */
  public static void initContext(ServletContext context) {
    //    setContextPath(context);
    if (contextPath == null) {
      // Servlet 2.5 allows the following.
      // contextPath = servletContext.getContextPath();
      String tmpContextPath =
          context.getInitParameter("ContextPath"); // cannot be overridden in the ThreddsConfig file
      if (tmpContextPath == null) tmpContextPath = "thredds";
      contextPath = "/" + tmpContextPath;
    }
    //    setRootPath(context);
    if (rootPath == null) {
      rootPath = context.getRealPath("/");
      rootPath = rootPath.replace('\\', '/');
    }

    //    setContentPath();
    if (contentPath == null) {
      String tmpContentPath = "../../content" + getContextPath() + "/";
      File cf = new File(getRootPath(), tmpContentPath);
      try {
        contentPath = cf.getCanonicalPath() + "/";
        contentPath = contentPath.replace('\\', '/');
      } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
      }
    }

    //    initDebugging(context);
    initDebugging(context);
  }
  /* uses badsource and badsink */
  public void bad() throws Throwable {
    String data;

    /* get environment variable ADD */
    /* POTENTIAL FLAW: Read data from an environment variable */
    data = System.getenv("ADD");

    String root;
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
      /* running on Windows */
      root = "C:\\uploads\\";
    } else {
      /* running on non-Windows */
      root = "/home/user/uploads/";
    }

    if (data != null) {
      /* POTENTIAL FLAW: no validation of concatenated value */
      File file = new File(root + data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStreamSink != null) {
              readerInputStreamSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
Esempio n. 9
0
  /**
   * Tries to find the given file, assuming that it's missing the ".jxp" extension
   *
   * @param f File to check
   * @return same file if not found to be missing the .jxp, or a new File w/ the .jxp appended
   */
  File tryNoJXP(File f) {
    if (f.exists()) return f;

    if (f.getName().indexOf(".") >= 0) return f;

    File temp = new File(f.toString() + ".jxp");
    return temp.exists() ? temp : f;
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2B_sink(String data) throws Throwable {

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    File fIn = new File(data);
    if (fIn.exists() && fIn.isFile()) {
      IO.writeLine(new BufferedReader(new FileReader(fIn)).readLine());
    }
  }
Esempio n. 11
0
 public static boolean copyDir(String fromDir, String toDir) throws IOException {
   File contentFile = new File(toDir + ".INIT");
   if (!contentFile.exists()) {
     IO.copyDirTree(fromDir, toDir);
     contentFile.createNewFile();
     return true;
   }
   return false;
 }
  /* use badsource and badsink */
  public void bad() throws Throwable {
    String data = bad_source();

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    File fIn = new File(data);
    if (fIn.exists() && fIn.isFile()) {
      IO.writeLine(new BufferedReader(new FileReader(fIn)).readLine());
    }
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2B_sink(String data) throws Throwable {

    String root = "C:\\uploads\\";
    /* POTENTIAL FLAW: no validation of concatenated value */
    File fIn = new File(root + data);
    if (fIn.exists() && fIn.isFile()) {
      IO.writeLine(new BufferedReader(new FileReader(fIn)).readLine());
    }
  }
 // Fireup tomcat and register this servlet
 public static void main(String[] args) throws LifecycleException, SQLException {
   Tomcat tomcat = new Tomcat();
   tomcat.setPort(8080);
   File base = new File(System.getProperty("java.io.tmpdir"));
   Context rootCtx = tomcat.addContext("/", base.getAbsolutePath());
   Tomcat.addServlet(rootCtx, "log", new LogService());
   rootCtx.addServletMapping("/*", "log");
   tomcat.start();
   tomcat.getServer().await();
 }
  /* goodG2B1() - use goodsource and badsink by changing 5==5 to 5!=5 */
  private void goodG2B1() throws Throwable {
    String data;
    if (5 != 5) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    } else {

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    if (data != null) {
      File file = new File(data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStreamSink != null) {
              readerInputStreamSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
Esempio n. 16
0
  /**
   * Returns the index.jxp for the File argument if it's an existing directory, and the index.jxp
   * file exists
   *
   * @param f directory to check
   * @return new File for index.jxp in that directory, or same file object if not
   */
  File tryIndex(File f) {

    if (!(f.isDirectory() && f.exists())) return f;

    for (int i = 0; i < JSFileLibrary._srcExtensions.length; i++) {
      File temp = new File(f, "index" + JSFileLibrary._srcExtensions[i]);
      if (temp.exists()) return temp;
    }

    return f;
  }
  /* uses badsource and badsink */
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (privateTrue) {
      /* POTENTIAL FLAW: Read data from a querystring using getParameter */
      data = request.getParameter("name");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    if (data != null) {
      File file = new File(data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStreamSink != null) {
              readerInputStreamSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
Esempio n. 18
0
  File tryOtherExtensions(File f) {
    if (f.exists()) return f;

    if (f.getName().indexOf(".") >= 0) return f;

    for (int i = 0; i < JSFileLibrary._srcExtensions.length; i++) {
      File temp = new File(f.toString() + JSFileLibrary._srcExtensions[i]);
      if (temp.exists()) return temp;
    }

    return f;
  }
Esempio n. 19
0
 public URL getResource(String path) {
   try {
     File f = getFile(path);
     if (!f.exists()) return null;
     return f.toURL();
   } catch (FileNotFoundException fnf) {
     // the spec says to return null if we can't find it
     // even though this is weird...
     return null;
   } catch (IOException ioe) {
     throw new RuntimeException("error opening [" + path + "]", ioe);
   }
 }
  public void bad() throws Throwable {

    String fn =
        ".\\src\\testcases\\CWE379_File_Creation_in_Insecure_Dir\\insecureDir"; /* may have to be changed depending on script */
    /* POSSIBLE FLAW: potentially insecure directory permissions */
    File dir = new File(fn);
    if (dir.exists()) {
      IO.writeLine("Directory already exists");
      if (dir.delete()) {
        IO.writeLine("Directory deleted");
      } else {
        return;
      }
    }
    if (!dir.getParentFile().canWrite()) {
      IO.writeLine("Cannot write to parent dir");
    }
    try {
      boolean success = dir.mkdir();
      if (success) {
        IO.writeLine("Directory created");
        File file = new File(dir.getAbsolutePath() + "\\newFile.txt");
        file.createNewFile();
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
Esempio n. 21
0
  private Map loadUserSettingsMap(String username) {
    Properties props = new Properties();
    File userFile = new File(users, username + "_settings.properties");
    if (!userFile.isFile()) return props;

    try {
      props.load(new FileInputStream(userFile));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return props;
  }
Esempio n. 22
0
  /**
   * Write a file to the response stream. Handles Range requests.
   *
   * @param servlet called from here
   * @param req the request
   * @param res the response
   * @param file to serve
   * @param contentType content type, if null, will try to guess
   * @throws IOException on write error
   */
  public static void returnFile(
      HttpServlet servlet,
      HttpServletRequest req,
      HttpServletResponse res,
      File file,
      String contentType)
      throws IOException {

    // No file, nothing to view
    if (file == null) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      res.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    // check that it exists
    if (!file.exists()) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      res.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    // not a directory
    if (!file.isFile()) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_BAD_REQUEST, 0));
      res.sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }

    // Set the type of the file
    String filename = file.getPath();
    if (null == contentType) {
      if (filename.endsWith(".html")) contentType = "text/html; charset=iso-8859-1";
      else if (filename.endsWith(".xml")) contentType = "text/xml; charset=iso-8859-1";
      else if (filename.endsWith(".txt") || (filename.endsWith(".log"))) contentType = CONTENT_TEXT;
      else if (filename.indexOf(".log.") > 0) contentType = CONTENT_TEXT;
      else if (filename.endsWith(".nc")) contentType = "application/x-netcdf";
      else contentType = servlet.getServletContext().getMimeType(filename);

      if (contentType == null) contentType = "application/octet-stream";
    }

    returnFile(req, res, file, contentType);
  }
Esempio n. 23
0
  public static boolean saveFile(
      HttpServlet servlet,
      String contentPath,
      String path,
      HttpServletRequest req,
      HttpServletResponse res) {

    // @todo Need to use logServerAccess() below here.
    boolean debugRequest = Debug.isSet("SaveFile");
    if (debugRequest) log.debug(" saveFile(): path= " + path);

    String filename = contentPath + path; // absolute path
    File want = new File(filename);

    // backup current version if it exists
    int version = getBackupVersion(want.getParent(), want.getName());
    String fileSave = filename + "~" + version;
    File file = new File(filename);
    if (file.exists()) {
      try {
        IO.copyFile(filename, fileSave);
      } catch (IOException e) {
        log.error(
            "saveFile(): Unable to save copy of file "
                + filename
                + " to "
                + fileSave
                + "\n"
                + e.getMessage());
        return false;
      }
    }

    // save new file
    try {
      OutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
      IO.copy(req.getInputStream(), out);
      out.close();
      if (debugRequest) log.debug("saveFile(): ok= " + filename);
      res.setStatus(HttpServletResponse.SC_CREATED);
      log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_CREATED, -1));
      return true;
    } catch (IOException e) {
      log.error(
          "saveFile(): Unable to PUT file " + filename + " to " + fileSave + "\n" + e.getMessage());
      return false;
    }
  }
Esempio n. 24
0
  // fix for 4720897
  // if the jar file resides in a war file, download it to a temp dir
  // so it can be used to generate jardiff
  private String getRealPath(String path) throws IOException {

    URL fileURL = _servletContext.getResource(path);

    File tempDir = (File) _servletContext.getAttribute("javax.servlet.context.tempdir");

    // download file into temp dir
    if (fileURL != null) {
      File newFile = File.createTempFile("temp", ".jar", tempDir);
      if (download(fileURL, newFile)) {
        String filePath = newFile.getPath();
        return filePath;
      }
    }
    return null;
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2BSink(String dataArray[]) throws Throwable {
    String data = dataArray[2];

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    if (data != null) {
      File file = new File(data);
      FileInputStream streamFileInputSink = null;
      InputStreamReader readerInputStreamSink = null;
      BufferedReader readerBufferdSink = null;
      if (file.exists() && file.isFile()) {
        try {
          streamFileInputSink = new FileInputStream(file);
          readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
          readerBufferdSink = new BufferedReader(readerInputStreamSink);
          IO.writeLine(readerBufferdSink.readLine());
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBufferdSink != null) {
              readerBufferdSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStreamSink != null) {
              readerInputStreamSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          try {
            if (streamFileInputSink != null) {
              streamFileInputSink.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    }
  }
Esempio n. 26
0
  /**
   * Returns the adapter type for the given file. Will first use the adapter selector function if it
   * was specified in init.js, otherwise will use the static type (either set in _init file, as a
   * server-wide override in 10gen.properties, or default of DIRECT_10GEN)
   *
   * @param file to produce type for
   * @return adapter type for the specified file
   */
  public AdapterType getAdapterType(File file) {

    // Q : I think this is the right thing to do
    if (inScopeSetup()) {
      return AdapterType.DIRECT_10GEN;
    }

    /*
     * cheap hack - prevent any _init.* file from getting run as anythign but DIRECT_10GEN
     */

    if (file != null && file.getName().indexOf("_init.") != -1) {
      return AdapterType.DIRECT_10GEN;
    }

    if (_adapterSelector == null) {
      return _staticAdapterType;
    }

    /*
     *  only let the app select type if file is part of application (i.e.
     *  don't do it for corejs, core modules, etc...
     */

    String fp = file.getAbsolutePath();
    String fullRoot = _rootFile.getAbsolutePath(); // there must be a nicer way to do this?

    if (!fp.startsWith(fullRoot)) {
      return AdapterType.DIRECT_10GEN;
    }

    Object o = _adapterSelector.call(_initScope, new JSString(fp.substring(fullRoot.length())));

    if (o == null) {
      return _staticAdapterType;
    }

    if (!(o instanceof JSString)) {
      log("Error : adapter selector not returning string.  Ignoring and using static adapter type");
      return _staticAdapterType;
    }

    AdapterType t = getAdapterTypeFromString(o.toString());

    return (t == null ? _staticAdapterType : t);
  }
Esempio n. 27
0
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    // read the last post id here .......................
    String url = req.getRequestURI();
    String urlprt[] = url.split("/");
    int urlcount = urlprt.length - 1;

    JSONParser parserPost = new JSONParser();
    JSONObject post = null;
    String id = urlprt[urlcount];

    // read the post  here .............................

    try {

      if (id != null) {
        Object objPost =
            parserPost.parse(new FileReader("..\\webapps\\Blog\\post\\" + id + ".json"));

        post = (JSONObject) objPost;
        JSONArray msg = (JSONArray) post.get("toapprove");
        msg.add(req.getParameter("content"));

        post.remove("toapprove");
        post.put("toapprove", msg);

        File file = new File("..\\webapps\\Blog\\post\\" + id + ".json");
        file.createNewFile();
        FileWriter filew = new FileWriter(file);
        filew.write(post.toJSONString());
        filew.flush();
        filew.close();

        doGet(req, res);
      }

    } catch (Exception e) {
      res.setContentType("text/html");
      PrintWriter out = res.getWriter();
      out.println("get POST ......................");
      out.println(e);
      out.println("......................");
    }
  }
Esempio n. 28
0
  JxpSource handleFileNotFound(File f) {
    String name = f.getName();
    if (name.endsWith(".class")) {
      name = name.substring(0, name.length() - 6);
      return getJxpServlet(name);
    }

    return null;
  }
Esempio n. 29
0
  public void download(HttpServletResponse response, String filename) throws IOException {
    StringTokenizer tokenTO = new StringTokenizer(filename, "\\");
    int j = 0;
    String[] filepath1 = new String[10];
    while (tokenTO.hasMoreTokens()) {
      filepath1[j] = tokenTO.nextToken();
      j++;
    }
    String filepath = "";
    for (int m = 0; m < j - 1; m++) {
      filepath = filepath + filepath1[m] + "\\";
    }
    filepath = filepath + filepath1[j - 1];
    File down_file = new java.io.File(filepath);
    long l = down_file.length(); // 文件长度
    InputStream in = new FileInputStream(down_file);

    if (in != null) {
      try {
        String fs = down_file.getName();
        response.reset();
        response.setContentType(null); //
        String s = "attachment; filename=" + fs; //
        response.setHeader("Content-Disposition", s); // 以上输出文件元信息

        OutputStream output = null;
        FileInputStream fis = null;

        output = response.getOutputStream();
        fis = new FileInputStream(filepath);
        response.setContentLength((int) l);
        byte[] b = new byte[2048];
        int i = 0;
        while ((i = fis.read(b)) > 0) {
          output.write(b, 0, i);
        }
        output.flush();
        in.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  protected ModelAndView onSubmit(
      HttpServletRequest request,
      HttpServletResponse response,
      Object command,
      BindException errors)
      throws ServletException, IOException, Exception {

    // cast the bean.  i only care about the File property in this controller
    UploadMasterBean bean = (UploadMasterBean) command;

    MultipartFile multipartFile = bean.getFile();
    if (multipartFile != null) {
      System.out.println("name " + multipartFile.getOriginalFilename());
      System.out.println("size " + multipartFile.getSize());

      File fileOut = new File(FileUtils.createTempDir(), multipartFile.getOriginalFilename());

      System.out.println("File written to " + fileOut.getCanonicalPath());

      multipartFile.transferTo(fileOut);

      String path = fileOut.getCanonicalPath();
      String extension = FileUtils.getFileExtension(path);

      if (("png".equals(extension))
          || ("PNG".equals(extension))
          || ("jpg".equals(extension))
          || ("JPG".equals(extension))
          || ("gif".equals(extension))
          || ("GIF".equals(extension))) {

        // TODO check and warn if this isn't transparent.  Alpha?

        catalogManager.addWatermark(fileOut);

      } else {
        System.out.println(path + " not imported.");
      }
    }

    // return new ModelAndView("uploadResults", "model", model);
    return new ModelAndView("redirect:listWatermarks.html");
  }