Esempio n. 1
1
  public void createImage(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpg");

    /** 取得高度和宽度 */
    String width = request.getParameter("width");
    String height = request.getParameter("height");

    if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {

      w = NumberUtils.toInt(width);
      h = NumberUtils.toInt(height);
    }
    /** */
    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();
    createBackground(g);
    /** */
    String s = createCharacter(g);
    request.getSession().setAttribute(VALIDATE_CODE, s);
    g.dispose();
    OutputStream out = response.getOutputStream();
    ImageIO.write(image, "JPEG", out);
    out.close();
  }
  @Override
  protected void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {
    CsrfToken token = (CsrfToken) request.getAttribute("_csrf");

    // Spring Security will allow the Token to be included in this header name
    response.setHeader("X-CSRF-HEADER", token.getHeaderName());

    // Spring Security will allow the token to be included in this parameter name
    response.setHeader("X-CSRF-PARAM", token.getParameterName());

    // this is the value of the token to be included as either a header or an HTTP parameter
    response.setHeader("X-CSRF-TOKEN", token.getToken());

    // Cookie Base Approach for CSRF token

    //        String pCookieName = "XSRF-TOKEN";
    //
    //        try {
    //            Cookie cookie = new Cookie(pCookieName, token.getToken());
    //            URL url = new URL(request.getRequestURL().toString());
    //            cookie.setDomain(url.getHost());
    //            cookie.setComment("user is not eligible to take the survey this time");
    //            cookie.setMaxAge(-1);
    //            response.addCookie(cookie);
    //        } catch (MalformedURLException e) {
    //            e.printStackTrace();
    //        }

    filterChain.doFilter(request, response);
  }
  /**
   * This method is requesting the front page since that is all this servlet does (apart from config
   * initialisation and sharing). Return it here.
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse response)
      throws ServletException, IOException {
    /* HTTP 1.1 */
    response.setHeader("Cache-Control", "no-cache");
    /* HTTP 1.0 */
    response.setHeader("Pragma", "no-cache");
    /* Prevents caching at the proxy server */
    response.setDateHeader("Expires", 0);
    /*
     * Just return the front page. If we want some more (dynamic) web pages
     * available here, we need to do some extra handling of what the URL
     * actually says
     */
    Template template = velocityEngine.getTemplate("templates/index.vm");
    VelocityContext context = new VelocityContext();
    EventCartridge ec = new EventCartridge();
    ec.addEventHandler(new EscapeHtmlReference());
    ec.attachToContext(context);

    context.put("catalogue", catalogue);
    context.put("config", catalogue.getConfig());
    context.put("GISUtils", GISUtils.class);
    context.put("supportedImageFormats", ImageFormat.getSupportedMimeTypes());
    template.merge(context, response.getWriter());
  }
  /**
   * Performs the export.
   *
   * @param context the page context
   * @param i18n the internationalization package to use.
   */
  public void doExport(PageContext context, I18n i18n) {

    String filterId = new TopTotalEnqueuesFilter().getFilterId();

    RunningJobsInfoDAO dao = RunningJobsInfoDAO.getInstance();
    InMemoryFrontierReport report = dao.getFrontierReport(jobId, filterId);

    HttpServletResponse resp = (HttpServletResponse) context.getResponse();
    resp.setHeader("Content-Type", "text/plain");
    resp.setHeader(
        "Content-Disposition",
        "Attachment; filename=" + filterId + "-" + report.getJobName() + ".csv");

    PrintWriter pw;
    try {
      pw = new PrintWriter(resp.getOutputStream());
    } catch (IOException e) {
      HTMLUtils.forwardWithErrorMessage(
          context, i18n, e, "errorMsg;running.job.details.frontier.exportAsCsv");
      throw new ForwardedToErrorPage("Error in frontier report CSV export", e);
    }

    FrontierReportCsvExport.outputAsCsv(report, pw, ";");
    pw.close();
  }
  /** {@inheritDoc} */
  @Override
  public ActionForward execute(
      @SuppressWarnings("unused") ActionMapping mapping,
      @SuppressWarnings("unused") ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    HttpSession session = request.getSession();
    final InterMineAPI im = SessionMethods.getInterMineAPI(session);
    ObjectStore os = im.getObjectStore();
    WebConfig webConfig = SessionMethods.getWebConfig(request);
    Integer objectId = new Integer(request.getParameter("object"));
    String fieldName = request.getParameter("field");
    String fileType = request.getParameter("type");
    InterMineObject object = os.getObjectById(objectId);

    FieldExporter fieldExporter = null;

    Set classes = DynamicUtil.decomposeClass(object.getClass());

    Iterator classIter = classes.iterator();

    while (classIter.hasNext()) {
      Class c = (Class) classIter.next();

      Type thisTypeConfig = webConfig.getTypes().get(c.getName());

      FieldConfig fc = thisTypeConfig.getFieldConfigMap().get(fieldName);

      if (fc != null) {
        String fieldExporterClassName = fc.getFieldExporter();
        if (fieldExporterClassName != null) {
          fieldExporter = (FieldExporter) Class.forName(fieldExporterClassName).newInstance();
          break;
        }
      }
    }

    if (fieldExporter == null) {
      Object fieldValue = object.getFieldValue(fieldName);
      if (fileType == null || fileType.length() == 0) {
        response.setContentType("text/plain; charset=UTF-8");
        response.setHeader("Content-Disposition ", "inline; filename=" + fieldName + ".txt");
      } else {
        response.setContentType("text/" + fileType);
        response.setHeader(
            "Content-Disposition ", "inline; filename=" + fieldName + "." + fileType);
      }
      PrintStream out = new PrintStream(response.getOutputStream());
      if (fieldValue instanceof ClobAccess) {
        ((ClobAccess) fieldValue).drainToPrintStream(out);
      } else {
        out.print(fieldValue);
      }
      out.flush();
    } else {
      fieldExporter.exportField(object, fieldName, os, response);
    }
    return null;
  }
  @RequestMapping(value = "/getValidateCode.action", method = RequestMethod.GET)
  public void getValidateCode(HttpServletRequest req, HttpServletResponse resp) {
    try {
      // 设置响应的类型格式为图片格式
      resp.setContentType("image/jpeg");
      // 禁止图像缓存。
      resp.setHeader("Pragma", "no-cache");
      resp.setHeader("Cache-Control", "no-cache");
      resp.setDateHeader("Expires", 0);

      HttpSession session = req.getSession();

      ValidateCode vCode = new ValidateCode(60, 18, 4, 20);
      session.setAttribute("validateCode", vCode.getCode());
      // log.info("验证码为:[" + vCode.getCode() + "]");
      vCode.write(resp.getOutputStream());
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      log.error(e);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      log.error(e);
    }
  }
Esempio n. 7
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    resp.setHeader("Pragma", "no-cache");
    resp.setHeader("Cache-Control", "no-cache");
    String isPreviewStr = req.getParameter("isPreview");
    Boolean isPreview = null;
    if (isPreviewStr != null && !"null".equals(isPreviewStr))
      isPreview = Boolean.valueOf(isPreviewStr);

    String uid = (String) req.getSession().getAttribute("Uid");

    try {
      String sessionId;
      if (uid == null || isPreview != null && isPreview.booleanValue()) {
        sessionId = new UUID().toString();
      } else {
        sessionId = SessionService.getHandle().newSessionId(uid);

        // set lastAccessDate
        PreferenceService.getHandle().setAccessTime(uid);
      }
      resp.getWriter().println("is_sessionId = \"" + sessionId.replace("\\", "\\\\") + "\"");
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Esempio n. 8
0
 private void generateExpireResponseHeaders(HttpServletResponse res, boolean expireResponse) {
   if (expireResponse) {
     res.setHeader("Pragma", "no-cache");
     res.setDateHeader("Expires", 0);
     res.setHeader("Cache-Control", "no-cache");
   }
 }
  /* goodG2B() - use goodsource and badsink by moving BadSource and BadSink to after return */
  private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    {
      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");

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

      /* POTENTIAL FLAW: Input not verified before inclusion in header */
      response.setHeader("Location", "/author.jsp?lang=" + data);
    }

    if (true) return; /* INCIDENTAL: CWE 571 Expression is Always True.
		  We need the "if(true)" because the Java Language Spec requires that
		  unreachable code generate a compiler error */

    /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
    {
      Logger log_bad = Logger.getLogger("local-logger");

      /* read parameter from request */
      data = request.getParameter("name");

      /* POTENTIAL FLAW: Input not verified before inclusion in header */
      response.setHeader("Location", "/author.jsp?lang=" + data);
    }
  }
  protected void doProcess(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub

    // prevents direct access to the servlet
    String referer = request.getHeader("referer");
    if (referer == null) {
      response.sendRedirect("unauthorisedAccess.jsp");
      return;
    }

    HttpSession session = request.getSession();
    String tokenID = (String) session.getAttribute("tokenID");
    String userName = "******";
    response.setContentType("application/json");
    response.setHeader("Content-disposition", "attachment; filename=\"" + userName + ".json\"");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Expires", "-1");

    JSONObject tokenKey = new JSONObject();

    // actually send result bytes
    try {
      response.getWriter().write(tokenKey.put("tokenID", tokenID).toString());
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Esempio n. 11
0
 // Set an appropriate CORS header if requested and if allowed
 private void setCorsHeader(HttpServletRequest pReq, HttpServletResponse pResp) {
   String origin = requestHandler.extractCorsOrigin(pReq.getHeader("Origin"));
   if (origin != null) {
     pResp.setHeader("Access-Control-Allow-Origin", origin);
     pResp.setHeader("Access-Control-Allow-Credentials", "true");
   }
 }
Esempio n. 12
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds047752.mlab.com:47752/ase_lab7");
    MongoClient client = new MongoClient(uri);

    DB db = client.getDB(uri.getDatabase());
    DBCollection users = db.getCollection("users");

    BasicDBObject query = new BasicDBObject().append("username", "Ram");
    query.put("name", "Ram"); // request.getParameter("name"));
    query.put("password", "password"); // request.getParameter("password"));
    BasicDBObject newDocument = new BasicDBObject();
    newDocument.put("name", "SreeRam");
    users.update(query, newDocument);

    DBCursor docs = users.find(query);
    response.getWriter().write(docs.toArray().toString());

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
  }
Esempio n. 13
0
  public void doGetDDS(ReqState rs) throws Exception {
    HttpServletResponse response = rs.getResponse();

    GuardedDataset ds = null;
    try {
      ds = getDataset(rs);
      if (null == ds) return;

      response.setContentType("text/plain");
      response.setHeader("XDODS-Server", getServerVersion());
      response.setHeader("Content-Description", "dods-dds");

      OutputStream out = new BufferedOutputStream(response.getOutputStream());
      ServerDDS myDDS = ds.getDDS();

      if (rs.getConstraintExpression().equals("")) { // No Constraint Expression?
        // Send the whole DDS
        myDDS.print(out);
        out.flush();

      } else { // Otherwise, send the constrained DDS
        // Instantiate the CEEvaluator and parse the constraint expression
        CEEvaluator ce = new CEEvaluator(myDDS);
        ce.parseConstraint(rs);

        // Send the constrained DDS back to the client
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));
        myDDS.printConstrained(pw);
        pw.flush();
      }

    } finally { // release lock if needed
      if (ds != null) ds.release();
    }
  }
Esempio n. 14
0
  /** Sets mandatory headers, notably for anti-clickjacking. */
  @Override
  public void setCSPHeaders(DefDescriptor<?> top, HttpServletRequest req, HttpServletResponse rsp) {
    ContentSecurityPolicy csp =
        Aura.getConfigAdapter()
            .getContentSecurityPolicy(top == null ? null : top.getQualifiedName(), req);

    if (csp != null) {
      rsp.setHeader(CSP.Header.SECURE, csp.getCspHeaderValue());
      Collection<String> terms = csp.getFrameAncestors();
      if (terms != null) {
        // not open to the world; figure whether we can express an X-FRAME-OPTIONS header:
        if (terms.size() == 0) {
          // closed to any framing at all
          rsp.setHeader(HDR_FRAME_OPTIONS, HDR_FRAME_DENY);
        } else if (terms.size() == 1) {
          // With one ancestor term, we're either SAMEORIGIN or ALLOWFROM
          for (String site : terms) {
            if (site == null) {
              // Add same-origin headers and policy terms
              rsp.addHeader(HDR_FRAME_OPTIONS, HDR_FRAME_SAMEORIGIN);
            } else if (!site.contains("*") && !site.matches("^[a-z]+:$")) {
              // XFO can't express wildcards or protocol-only, so set only for a specific site:
              rsp.addHeader(HDR_FRAME_OPTIONS, HDR_FRAME_ALLOWFROM + site);
            } else {
              // When XFO can't express it, still set an ALLOWALL so filters don't jump in
              rsp.addHeader(HDR_FRAME_OPTIONS, HDR_FRAME_ALLOWALL);
            }
          }
        }
      }
    }
  }
  public String requestBearerToken() throws IOException {
    HttpsURLConnection connection = null;
    String encodedCredentials =
        encodeKeys(BUNDLE.getString("twt.client_id"), BUNDLE.getString("twt.secret"));
    String endPointUrl = "https://api.twitter.com/oauth2/token";
    try {
      HttpServletResponse response =
          (HttpServletResponse)
              FacesContext.getCurrentInstance().getExternalContext().getResponse();
      response.setHeader("Host", "api.twitter.com");
      response.setHeader("User-Agent", "Iclub");
      response.setHeader("Authorization", "Basic " + encodedCredentials);
      response.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
      response.setHeader("Content-Length", "29");
      ServletOutputStream fdsaf = response.getOutputStream();
      fdsaf.write("grant_type=client_credentials".getBytes());
      fdsaf.close();
      response.sendRedirect(endPointUrl);

      return new String();
    } catch (MalformedURLException e) {
      throw new IOException("Invalid endpoint URL specified.", e);
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
  }
  /* goodB2G() - use badsource and goodsink by switching statements around return */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;

    Logger log_bad = Logger.getLogger("local-logger");

    /* read parameter from request */
    data = request.getParameter("name");

    {

      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      data = URLEncoder.encode(data, "UTF-16");
      response.setHeader("Location", "/author.jsp?lang=" + data);
    }

    if (true) return; /* INCIDENTAL: CWE 571 Expression is Always True.
		  We need the "if(true)" because the Java Language Spec requires that
		  unreachable code generate a compiler error */

    /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
    {

      /* POTENTIAL FLAW: Input not verified before inclusion in header */
      response.setHeader("Location", "/author.jsp?lang=" + data);
    }
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    LOGGER.info("Cors Filter Entering");
    final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    String originHeader = httpServletRequest.getHeader("Origin");

    if (httpServletRequest.getMethod().equals(HttpMethod.OPTIONS.name())) {

      if (OriginsHelper.isValid(originHeader)) {
        LOGGER.info("Adding Header Allow Origin: " + originHeader);
        httpServletResponse.addHeader("Access-Control-Allow-Origin", originHeader);
      }

      httpServletResponse.setHeader(
          "Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
      httpServletResponse.setHeader(
          "Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");
      httpServletResponse.setHeader("Access-Control-Max-Age", "3600");

      LOGGER.info("Return OK status for OPTIONS method requests");
      httpServletResponse.setStatus(HttpServletResponse.SC_OK);

    } else {
      LOGGER.info("Continue filter processing");
      chain.doFilter(request, response);
    }
  }
Esempio n. 18
0
  /**
   * 导出整个
   *
   * @param request
   * @param response
   */
  @RequestMapping("/exportsql")
  public void exportsql(HttpServletRequest request, HttpServletResponse response) {
    try {
      String path = request.getSession().getServletContext().getRealPath("/export/");
      File file = new File(path + "/data.sql");
      if (!file.exists()) {
        file.createNewFile();
      }
      String exportPath = path + "/data.sql";
      MySqlImportAndExport.export(exportPath);

      long fileLength = file.length();
      //
      response.setContentType("application/octet-stream");
      response.setHeader(
          "Content-disposition",
          "attachment; filename=" + new String("data.sql".getBytes("utf-8"), "ISO8859-1"));
      response.setHeader("Content-Length", String.valueOf(fileLength));
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
      BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
      byte[] buff = new byte[2048];
      int bytesRead;
      while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
        bos.write(buff, 0, bytesRead);
      }
      bis.close();
      bos.close();

      file.delete();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 19
0
    private void sendHttpResponseFromOnem2mResponse(
        HttpServletResponse httpResponse, ResponsePrimitive onem2mResponse) throws IOException {

      // the content is already in the required format ...
      String content = onem2mResponse.getPrimitive(ResponsePrimitive.CONTENT);
      String rscString = onem2mResponse.getPrimitive(ResponsePrimitive.RESPONSE_STATUS_CODE);
      String rqi = onem2mResponse.getPrimitive(ResponsePrimitive.REQUEST_IDENTIFIER);
      if (rqi != null) {
        httpResponse.setHeader(Onem2m.HttpHeaders.X_M2M_RI, rqi);
      }

      int httpRSC = mapCoreResponseToHttpResponse(httpResponse, rscString);
      if (content != null) {
        httpResponse.setStatus(httpRSC);
        httpResponse.getWriter().println(content);
      } else {
        httpResponse.setStatus(httpRSC);
      }
      if (rscString.charAt(0) == '2') {
        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_OK);
      } else {
        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_ERROR);
      }

      String ct = onem2mResponse.getPrimitive(ResponsePrimitive.HTTP_CONTENT_TYPE);
      if (ct != null) {
        httpResponse.setContentType(ct);
      }
      String cl = onem2mResponse.getPrimitive(ResponsePrimitive.HTTP_CONTENT_LOCATION);
      if (cl != null) {
        httpResponse.setHeader("Content-Location", cl);
      }
    }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, java.io.IOException {
    // By the time we get here, the fileauthfilter has done the sanity
    // checking and authentication already. We can jump right into
    // serving the file.
    Conf conf = (Conf) getServletContext().getAttribute("conf");
    FileItem file = (FileItem) req.getAttribute("file");
    File fileOnDisk = new File(conf.getPathStore() + "/" + file.getFid().toString());

    logger.info("Preparing to stream file");
    resp.setContentType(file.getType());
    String disposition =
        req.getServletPath().equals("/file/get") && "image".equals(file.getType().substring(0, 5))
            ? "inline"
            : "attachment";
    resp.setHeader("Content-disposition", disposition + "; filename=\"" + file.getName() + "\"");
    resp.setHeader("Content-length", Long.toString(fileOnDisk.length()));

    FileInputStream instream = new FileInputStream(fileOnDisk);
    ServletOutputStream outstream = resp.getOutputStream();

    try {
      IOUtils.copyLarge(instream, outstream);
    } finally {
      if (instream != null) {
        instream.close();
      }
      if (outstream != null) {
        outstream.close();
      }
    }
    file.logDownload(ds, req.getRemoteAddr());
  }
  @RequestMapping(
      value = "/download",
      method = RequestMethod.POST,
      consumes = "application/x-www-form-urlencoded; charset=UTF-8")
  public String download(
      @RequestParam("path") String path, HttpServletRequest request, HttpServletResponse response)
      throws MessageException {
    try {
      if (path != null && path.endsWith("pdf")) {
        InputStream content = null;
        String fileName = path.substring(path.lastIndexOf("/") + 1);
        content = TestArtifactController.class.getResourceAsStream("/" + path);
        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        FileCopyUtils.copy(content, response.getOutputStream());
      } else if (path != null && path.endsWith("docx")) {
        InputStream content = null;
        String fileName = path.substring(path.lastIndexOf("/") + 1);
        if (!path.startsWith("/")) {
          content = TestArtifactController.class.getResourceAsStream("/" + path);
        } else {
          content = TestArtifactController.class.getResourceAsStream(path);
        }
        response.setContentType(
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        FileCopyUtils.copy(content, response.getOutputStream());
      }

      throw new IllegalArgumentException("Invalid Path Provided");
    } catch (IOException e) {
      logger.debug("Failed to download the test package ");
      throw new TestCaseException("Cannot download the artifact " + e.getMessage());
    }
  }
Esempio n. 22
0
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String createTypeFlag = request.getParameter("createTypeFlag"); // 接收客户端传递的createTypeFlag标识
   // 1.在内存中创建一张图片
   BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
   // 2.得到图片
   Graphics g = bi.getGraphics();
   // 3.设置图片的背影色
   setBackGround(g);
   // 4.设置图片的边框
   setBorder(g);
   // 5.在图片上画干扰线
   drawRandomLine(g);
   // 6.写在图片上随机数
   // String random = drawRandomNum((Graphics2D) g,"ch");//生成中文验证码图片
   // String random = drawRandomNum((Graphics2D) g,"nl");//生成数字和字母组合的验证码图片
   // String random = drawRandomNum((Graphics2D) g,"n");//生成纯数字的验证码图片
   // String random = drawRandomNum((Graphics2D) g,"l");//生成纯字母的验证码图片
   String random =
       drawRandomNum((Graphics2D) g, createTypeFlag); // 根据客户端传递的createTypeFlag标识生成验证码图片
   // 7.将随机数存在session中
   request.getSession().setAttribute("checkcode", random);
   // 8.设置响应头通知浏览器以图片的形式打开
   response.setContentType("image/jpeg"); // 等同于response.setHeader("Content-Type",
   // "image/jpeg");
   // 9.设置响应头控制浏览器不要缓存
   response.setDateHeader("expries", -1);
   response.setHeader("Cache-Control", "no-cache");
   response.setHeader("Pragma", "no-cache");
   // 10.将图片写给浏览器
   ImageIO.write(bi, "jpg", response.getOutputStream());
 }
  // method will call when user clicks on the link given in email
  @RequestMapping(value = "/logoutOutAction")
  public String getIssueDetails(
      HttpSession session, HttpServletRequest request, HttpServletResponse response) {

    logger.info("---- Entered getIssueDetails() of LogoutController ----");

    try {
      session = request.getSession(false);
      response.setHeader(
          "Cache-Control",
          "no-cache"); // Forces caches to obtain a new copy of the page from the origin server
      response.setHeader(
          "Cache-Control",
          "no-store"); // Directs caches not to store the page under any circumstance
      response.setDateHeader("Expires", 0); // Causes the proxy cache to see the page as "stale"
      response.setHeader("Pragma", "no-cache"); // HTTP 1.0 backward compatibility
      session.removeAttribute(IssueTrackerConstants.ISSUETRACKERCONSTANTS_LOGIN_USER_SESSION_NAME);
      session.setAttribute(
          IssueTrackerConstants.ISSUETRACKERCONSTANTS_LOGIN_USER_SESSION_NAME, null);
      session.invalidate();
    } catch (Exception e) {
      e.printStackTrace();
      StringWriter errors = new StringWriter();
      e.printStackTrace(new PrintWriter(errors));
      logger.error(errors.toString());
    }

    return "logout";
  }
Esempio n. 24
0
  /** {@inheritDoc} */
  @Override
  public void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    String requestURI = request.getRequestURI();

    if (requestURI.indexOf(".csv") > 0) {
      response.setContentType("Application/Octet-Stream");
      response.setHeader(
          "Content-Disposition",
          "attachment;filename=\"" + requestURI.substring(requestURI.lastIndexOf("/") + 1) + "\"");
    } else if (requestURI.indexOf(".xlsx") > 0) {
      response.setContentType("application/vnd.ms-excel");
      response.setHeader(
          "Content-Disposition",
          "attachment;filename=\"" + requestURI.substring(requestURI.lastIndexOf("/") + 1) + "\"");
    } else if (requestURI.indexOf(".xml") > 0) {
      response.setContentType("Application/Octet-Stream");
      response.setHeader(
          "Content-Disposition",
          "attachment;filename=\"" + requestURI.substring(requestURI.lastIndexOf("/") + 1) + "\"");
    }

    chain.doFilter(request, response);
  }
Esempio n. 25
0
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    // response.getWriter().append("Served at: ").append(request.getContextPath());
    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds019028.mlab.com:19028/asedb");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());
    DBCollection users = db.getCollection("UserRecords");
    BasicDBObject query = new BasicDBObject();

    String firstname = request.getParameter("FirstName");
    String lastname = request.getParameter("LastName");
    String email = request.getParameter("email");
    String password = request.getParameter("EnterPassword");
    String confpasswd = request.getParameter("ConfirmPassword");
    query.put("First Name", firstname);
    query.put("Last Name", lastname);
    query.put("Email", email);
    System.out.println(email);
    if (password == confpasswd) {
      query.put("Password", password);
    } else {

    }
    DBCursor docs = users.find(query);
    response.getWriter().write(docs.toArray().toString());

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
    System.out.println("Insert doget");
  }
Esempio n. 26
0
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String encoding = request.getHeader("Accept-Encoding");
   boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1);
   SessionTerminal st = (SessionTerminal) request.getSession(true).getAttribute("terminal");
   if (st == null || st.isClosed()) {
     st = new SessionTerminal();
     request.getSession().setAttribute("terminal", st);
   }
   String str = request.getParameter("k");
   String f = request.getParameter("f");
   String dump = st.handle(str, f != null && f.length() > 0);
   if (dump != null) {
     if (supportsGzip) {
       response.setHeader("Content-Encoding", "gzip");
       response.setHeader("Content-Type", "text/html");
       try {
         GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
         gzos.write(dump.getBytes());
         gzos.close();
       } catch (IOException ie) {
         // handle the error here
         ie.printStackTrace();
       }
     } else {
       response.getOutputStream().write(dump.getBytes());
     }
   }
 }
Esempio n. 27
0
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");

    System.out.println("*** Data tags");
    String sid = (String) request.getParameter("sid");
    if (sid == null) throw new IOException("Invalid session");

    String firstLetter = (String) request.getParameter("firstLetter");

    // Headers required by Internet Explorer
    response.setHeader("Pragma", "public");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0,pre-check=0");
    response.setHeader("Expires", "0");

    PrintWriter writer = response.getWriter();
    writer.write("<list>");
    for (int i = 0; i < 1000; i++) {
      writer.print("<tag>");
      writer.print("<index>" + i + "</index>");
      if (firstLetter != null) {
        writer.print("<word>" + firstLetter.charAt(0) + "tag" + i + "</word>");
        writer.print("<count>" + i + "</count>");
      } else {
        writer.print("<word>tag" + i + "</word>");
        writer.print("<count></count>");
      }
      writer.print("</tag>");
    }
    writer.write("</list>");
  }
Esempio n. 28
0
 @RequestMapping(value = "/file/{id}", method = RequestMethod.GET)
 public void showFileContent(@PathVariable Long id, HttpServletResponse response) {
   UploadedFileDTO uploadedFileDTO = getUploadedFileService().findById(id);
   response.setContentType("application/pdf");
   response.setHeader("Cache-Control", "private, max-age=5");
   response.setHeader("Pragma", "");
   byte[] file = uploadedFileDTO.getFile();
   if (file.length > 0) {
     response.setContentLength(file.length);
   }
   InputStream inputStream = new ByteArrayInputStream(file);
   ServletOutputStream outputStream = null;
   try {
     outputStream = response.getOutputStream();
     int b;
     while ((b = inputStream.read()) != -1) {
       outputStream.write(b);
     }
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       outputStream.flush();
       outputStream.close();
       inputStream.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
Esempio n. 29
0
 protected void service(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   res.setHeader("Pragma", "no-cache");
   res.setHeader("Cache-Control", "no-cache");
   res.setDateHeader("Expires", 0);
   super.service(req, res);
 }
Esempio n. 30
0
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub

    // response.getWriter().append("Served at: ").append(request.getContextPath());
    // JSONObject object = new JSONObject();
    // object.put("message", "Hello World");
    // response.getWriter().write(object.toString());

    response.getWriter().write("Read Users<br /><br />");

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");

    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds031611.mongolab.com:31611/testbeerdb");
    MongoClient client = new MongoClient(uri);

    DB db = client.getDB(uri.getDatabase());
    DBCollection songs = db.getCollection("users");

    DBCursor docs = songs.find();
    response.getWriter().write(docs.toArray().toString());

    doPost(request, response);
  }