Example #1
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    // String id = request.getParameter("id");
    PrintWriter out = response.getWriter();
    String id = request.getParameter("id");
    // out.print(id);
    PreparedStatement pstat = null;
    ResultSet rs = null;
    String sql = null;
    try {
      Connection conn = DbUtil.getConnection();
      sql = "delete from `news` where id ='" + id + " '";
      pstat = conn.prepareStatement(sql);
      pstat.executeUpdate();
      // out.close();
      // rs.close();
      pstat.close();
      conn.close();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    response.sendRedirect("indexmanager.jsp");
  }
Example #2
0
 private void generaReporte(String tipo, List<Entrada> entradas, HttpServletResponse response)
     throws JRException, IOException {
   log.debug("Generando reporte {}", tipo);
   byte[] archivo = null;
   switch (tipo) {
     case "PDF":
       archivo =
           reporteUtil.generaPdf(entradas, "/mx/edu/um/mateo/inventario/reportes/entradas.jrxml");
       response.setContentType("application/pdf");
       response.addHeader("Content-Disposition", "attachment; filename=entradas.pdf");
       break;
     case "CSV":
       archivo =
           reporteUtil.generaCsv(entradas, "/mx/edu/um/mateo/inventario/reportes/entradas.jrxml");
       response.setContentType("text/csv");
       response.addHeader("Content-Disposition", "attachment; filename=entradas.csv");
       break;
     case "XLS":
       archivo =
           reporteUtil.generaXls(entradas, "/mx/edu/um/mateo/inventario/reportes/entradas.jrxml");
       response.setContentType("application/vnd.ms-excel");
       response.addHeader("Content-Disposition", "attachment; filename=entradas.xls");
   }
   if (archivo != null) {
     response.setContentLength(archivo.length);
     try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
       bos.write(archivo);
       bos.flush();
     }
   }
 }
  /** {@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;
  }
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    HttpSession session = req.getSession();
    if (session == null) {
      resp.setStatus(401);
      return;
    }
    String username = (String) session.getAttribute("username");
    if (username == null) {
      resp.setStatus(401);
      return;
    }

    Map userMap = loadUserSettingsMap(username);
    if (userMap == null) {
      resp.setStatus(401);
      return;
    }
    if (pathInfo.equals("/")) {
      resp.setContentType("application/json; charset=UTF-8");
      resp.getWriter().write(JSONUtil.write(userMap));
      return;
    }

    String key = pathInfo.substring(1);
    String value = (String) userMap.get(key);

    Map jsonObject = new HashMap();
    jsonObject.put(key, value);
    resp.setContentType("application/json; charset=UTF-8");
    resp.getWriter().write(JSONUtil.write(jsonObject));
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
      throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    try {
      Authentication authentication = authenticationService.getAuthentication(httpRequest);
      SecurityContextHolder.getContext().setAuthentication(authentication);
      filterChain.doFilter(httpRequest, httpResponse);

    } catch (SignatureException exception) {
      httpResponse.setCharacterEncoding("UTF-8");
      httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
      httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

      ObjectMapper mapper = new ObjectMapper();

      FailureResponse error =
          new FailureResponse(
              httpRequest.getMethod(),
              httpRequest.getRequestURI(),
              "unauthorized JWT (invalid signature or expired token). Please use auth api to take another valid token.");
      httpResponse.getWriter().println(mapper.writeValueAsString(error));

      SecurityContextHolder.clearContext();

    } catch (MalformedJwtException exception) {
      httpResponse.setCharacterEncoding("UTF-8");
      httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
      httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

      ObjectMapper mapper = new ObjectMapper();

      FailureResponse error =
          new FailureResponse(
              httpRequest.getMethod(),
              httpRequest.getRequestURI(),
              "malformed token. Please use auth api to take another valid token.");
      httpResponse.getWriter().println(mapper.writeValueAsString(error));

      SecurityContextHolder.clearContext();

    } catch (Exception exception) {
      httpResponse.setCharacterEncoding("UTF-8");
      httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
      httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      ObjectMapper mapper = new ObjectMapper();

      FailureResponse error =
          new FailureResponse(
              httpRequest.getMethod(),
              httpRequest.getRequestURI(),
              "Internal server error, please contact the backend team.");
      httpResponse.getWriter().println(mapper.writeValueAsString(error));
      LOGGER.error(exception.getMessage(), exception);
      SecurityContextHolder.clearContext();
    }
  }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String prenom = request.getParameter("prenom");
    String pseudo = request.getParameter("pseudo");
    String mdp = request.getParameter("mdp");

    Map<String, Object> config = new HashMap<String, Object>();
    config.put("javax.json.stream.JsonGenerator.prettyPrinting", Boolean.valueOf(true));
    JsonBuilderFactory factory = Json.createBuilderFactory(config);
    JsonObject value;

    try {
      gestionJoueurs.creerJoueur(prenom, pseudo, mdp);
    } catch (JoueurDejaExistantException e) {
      value =
          factory.createObjectBuilder().add("success", "0").add("message", e.getMessage()).build();
      response.setContentType("application/json");
      response.getWriter().write(value.toString());
      return;
    }

    HttpSession session = request.getSession();
    Joueur nouveauJoueur = new Joueur(prenom, pseudo, mdp);

    session.setAttribute("joueur", nouveauJoueur);

    value =
        factory
            .createObjectBuilder()
            .add("success", "1")
            .add("message", "Inscription avec succès!")
            .build();
    response.setContentType("application/json");
    response.getWriter().write(value.toString());
  }
  /** {@inheritDoc} */
  @Override
  protected ModelAndView onSubmit(
      HttpServletRequest request,
      HttpServletResponse response,
      Object command,
      BindException errors)
      throws Exception {
    ReportParameters parameters = (ReportParameters) command;
    if ((parameters.getFormat() == ReportFormat.PDF)
        || (parameters.getFormat() == ReportFormat.SVG)) {
      response.setContentType("application/pdf;charset=UTF-8");
      response.setHeader("Content-disposition", "inline; filename=report.pdf");
      response.setHeader("Pragma", "public");
      response.setHeader("Cache-Control", "cache");
      response.setHeader("Cache-Control", "must-revalidate");
    }

    if (parameters.getFormat() == ReportFormat.CSV) {
      response.setContentType("text/csv;charset=UTF-8");
      response.setHeader("Content-disposition", "inline; filename=report.csv");
      response.setHeader("Pragma", "public");
      response.setHeader("Cache-Control", "cache");
      response.setHeader("Cache-Control", "must-revalidate");
    }
    m_reportWrapperService.runAndRender(
        parameters, ReportMode.IMMEDIATE, response.getOutputStream());
    return null;
  }
Example #8
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    String uid = request.getParameter("uid");
    String i = request.getParameter("counter");
    Pairtree pt = new Pairtree();

    String perfectName =
        Constants.PAIRTREE_ROOT
            + pt.mapToPPath(uid)
            + File.separator
            + "obj"
            + File.separator
            + "images"
            + File.separator
            + "image"
            + i
            + ".png";
    FileInputStream is = new FileInputStream(perfectName);

    byte data[] = new byte[is.available()];
    is.read(data);
    is.close();
    response.setContentType("image/png");
    OutputStream toClient1 = response.getOutputStream();
    toClient1.write(data);
    toClient1.close();
  }
Example #9
0
  private void manageRequest(HttpServletRequest req, HttpServletResponse res) throws IOException {
    PrintWriter out = res.getWriter();
    req.setCharacterEncoding("ISO-8859-1");
    String actionType = null;
    if (req.getParameter("actionType") != null) {
      actionType = req.getParameter("actionType").toString();
    }
    RecommendationManager recommendationManager =
        (RecommendationManager) appContext.getBean("recommendationManager");

    if (actionType != null && actionType.equalsIgnoreCase("getRecommendationToolbar")) {
      String json = recommendationManager.makeRecommendationToolbar();
      out.write(json);
      res.setContentType(CONTENT_TYPE_JSON);
    }

    if (actionType != null && actionType.equalsIgnoreCase("saveRecommendation")) {
      String saveRecommendationJson = req.getParameter("saveRecommendationJson");
      // System.out.println(saveRecommendationJson);
      String json = recommendationManager.saveRecommendation(saveRecommendationJson);
      out.write(json);
      res.setContentType(CONTENT_TYPE_JSON);
    }

    out.flush();
    out.close();
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");

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

    ItemVO itemVO = new ItemVO();
    itemVO.setItemClassNo(Integer.valueOf(request.getParameter("itemClassNo")));
    itemVO.setItemNo(Integer.valueOf(request.getParameter("itemNo")));
    itemVO.setItemName(request.getParameter("itemName"));
    itemVO.setDiscount(Double.valueOf(request.getParameter("discount")));
    itemVO.setItemDscrp(request.getParameter("itemDscrp"));
    itemVO.setPrice(Double.valueOf(request.getParameter("price")));
    ExportProcess ep = new ExportProcess();

    if (fileType.equals("doc")) {
      response.setContentType(
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
      XWPFDocument dFile = ep.exportWord(itemVO, request.getHeader("referer"));

      dFile.write(response.getOutputStream());
      return;
    }

    if (fileType.equals("pdf")) {
      response.setContentType("application/pdf");
      ServletOutputStream out = response.getOutputStream();
      Document pdfFile = ep.ExportPDF(itemVO, request.getHeader("referer"), out);

      out.flush();
      out.close();

      return;
    }
  }
  /**
   * Copy the response headers into the response.
   *
   * @param message the current message
   * @param headers the current set of headers
   */
  protected void copyResponseHeaders(Message message, HttpServletResponse response) {
    String ct = (String) message.get(Message.CONTENT_TYPE);
    String enc = (String) message.get(Message.ENCODING);

    if (null != ct
        && null != enc
        && ct.indexOf("charset=") == -1
        && !ct.toLowerCase().contains("multipart/related")) {
      ct = ct + "; charset=" + enc;
    }

    Map<?, ?> headers = (Map<?, ?>) message.get(Message.PROTOCOL_HEADERS);
    if (null != headers) {

      if (!headers.containsKey(Message.CONTENT_TYPE)) {
        response.setContentType(ct);
      }

      for (Iterator<?> iter = headers.keySet().iterator(); iter.hasNext(); ) {
        String header = (String) iter.next();
        List<?> headerList = (List<?>) headers.get(header);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < headerList.size(); i++) {
          sb.append(headerList.get(i));
          if (i + 1 < headerList.size()) {
            sb.append(',');
          }
        }
        response.addHeader(header, sb.toString());
      }
    } else {
      response.setContentType(ct);
    }
  }
 private void innerGet(String path, HttpServletResponse response) throws IOException {
   path = path.replace("/static/", "");
   if (FilenameUtils.isExtension(path, "js")) {
     path = "js/" + path;
     response.setContentType("text/javascript; charset=UTF-8");
   } else if (FilenameUtils.isExtension(path, "css") || FilenameUtils.isExtension(path, "less")) {
     path = "css/" + path;
     response.setContentType("text/css; charset=UTF-8");
   } else if (FilenameUtils.isExtension(path, IMG_EXTENSION)) {
     path = "img/" + path;
     response.setContentType("image/" + FilenameUtils.getExtension(path));
   }
   path = "view/" + path;
   if (path.endsWith(".handlebars.js")) {
     // handlebars
     response.setContentType("text/javascript; charset=UTF-8");
     path = path.substring(0, path.length() - 3);
     File file = new File(getWebInf(), path);
     String content = FileUtils.readFileToString(file, "UTF-8");
     try {
       content = HandlebarsObj.toJavaScript(content);
       IOUtils.write(content.getBytes("UTF-8"), response.getOutputStream());
     } catch (Exception e) {
       throw new ServerError(e);
     }
   } else {
     sendFile(response, path);
   }
 }
Example #13
0
 public void exportDataByHssf(HttpServletRequest request, HttpServletResponse response)
     throws IOException, ExcelPortException, DbPropertyException, SQLException {
   String header = request.getParameter("header") == null ? null : request.getParameter("header");
   String where = request.getParameter("where") == null ? null : request.getParameter("where");
   Date date = new Date();
   DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
   String filename = format.format(date);
   HSSFWorkbook web = customerMgm.exportExcelByHeaderAndWhere(header, where);
   if (web != null) {
     response.setContentType("text/html");
     response.setContentType("application/octet-stream");
     response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".xls");
     OutputStream out = response.getOutputStream();
     web.write(out);
     out.flush();
     out.close();
   } else {
     response.setContentType("text/html");
     PrintWriter out = response.getWriter();
     out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
     out.println("<HTML>");
     out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
     out.println("  <BODY>");
     out.println("excel数据导出失败!");
     out.println("  </BODY>");
     out.println("</HTML>");
     out.flush();
     out.close();
   }
 }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String action = req.getParameter("action");
    String uuid = req.getParameter("uuid");
    String profileName = req.getParameter("profile");
    String taskName = req.getParameter("taskname");
    String taskFormValue = req.getParameter("tfvalue");

    IDiagramProfile profile = ServletUtil.getProfile(req, profileName, getServletContext());
    String[] packageAssetInfo = ServletUtil.findPackageAndAssetInfo(uuid, profile);
    String packageName = packageAssetInfo[0];
    // String assetName = packageAssetInfo[1];

    if (action != null && action.equals(ACTION_LOAD)) {
      resp.setContentType("text/html");
      resp.setCharacterEncoding("UTF-8");
      PrintWriter pw = resp.getWriter();
      pw.write(getTaskFormFromGuvnor(taskName, packageName, profile));
    } else if (action != null && action.equals(ACTION_SAVE)) {
      resp.setContentType("text/plain");
      resp.setCharacterEncoding("UTF-8");
      PrintWriter pw = resp.getWriter();
      try {
        pw.write(storeTaskFormToGuvnor(taskName, packageName, profile, taskFormValue));
      } catch (Exception e) {
        pw.write("error: " + e.getMessage());
      }
    }
  }
Example #15
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    logger.info("get: " + req.getQueryString());

    String sessionId = req.getParameter("sessionId");
    if (!Utils.isNullOrEmpty(sessionId)) {
      Session session = getSessionCache().getSessionForSessionId(sessionId);
      if (session.getUserProfile() != null) {
        String picture = req.getParameter("picture");
        if ("tmp".equals(picture)) {
          String fileName = req.getParameter("filename");
          if (fileName.contains("..")) return;
          System.out.println("fnis:" + fileName);
          File picFile = new File(Backend.getWorkDir() + "tmpfiles" + File.separator + fileName);

          OutputStream out = resp.getOutputStream();
          FileInputStream fi = new FileInputStream(picFile);
          resp.setContentType("image");
          IOUtils.copy(fi, out);
          fi.close();
          out.close();

        } else if ("user".equals(picture)) {
          try {
            byte[] rawPicture = null;
            String fromUniqueUserId = req.getParameter("uniqueUserId");

            if (session.getUserProfile().getUniqueUserID().equals(fromUniqueUserId)) {
              if (Boolean.parseBoolean(req.getParameter("bigPicture"))) {
                logger.info("sending big user picture");
                rawPicture = session.getUserProfile().getUserCredentials().getPicture();
              } else {
                logger.info("sending small user picture");
                rawPicture = session.getUserProfile().getUserCredentials().getSmallPicture();
              }
            }
            OutputStream out = resp.getOutputStream();
            if (rawPicture == null) {
              FileInputStream fi =
                  new FileInputStream(
                      Backend.getWebContentFolder().getAbsolutePath()
                          + File.separator
                          + "images"
                          + File.separator
                          + "replacement_user_image.png");
              resp.setContentType("image");
              IOUtils.copy(fi, out);
              fi.close();
            } else {
              out.write(rawPicture);
            }
            out.close();
          } catch (Exception e) {
            logger.error("error sending user picture", e);
          }
        }
      }
    } else super.doGet(req, resp);
  }
Example #16
0
 public static void inlinePic(HttpServletResponse res, String path) {
   BufferedInputStream bis = null;
   BufferedOutputStream bos = null;
   if (path != null) {
     if (path.toLowerCase().endsWith(".jpg") || path.toLowerCase().endsWith(".jpeg")) {
       res.setContentType("image/jpeg");
       res.setHeader("Content-disposition", "inline; filename=\"license.jpg\";");
     } else if (path.toLowerCase().endsWith(".gif")) {
       res.setContentType("image/gif");
       res.setHeader("Content-disposition", "inline; filename=\"license.gif\";");
     } else if (path.toLowerCase().endsWith(".png")) {
       res.setContentType("image/png");
       res.setHeader("Content-disposition", "inline; filename=\"license.png\";");
     }
     res.setHeader("Content-Length", String.valueOf(new File(path).length()));
     try {
       bis = new BufferedInputStream(new FileInputStream(path));
       bos = new BufferedOutputStream(res.getOutputStream());
       IOUtils.copy(bis, bos);
     } catch (IOException e) {
       logger.error(ExceptionUtils.getStackTrace(e));
       throw new RuntimeException(e);
     } finally {
       IOUtils.closeQuietly(bis);
       IOUtils.closeQuietly(bos);
     }
   }
 }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

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

    if (logica.equals("Cadastrar")) {
      Veiculo veiculo =
          new Veiculo(
              request.getParameter("placa"),
              request.getParameter("modelo"),
              request.getParameter("ano"),
              request.getParameter("motor"));
      Dao dao = new Dao();
      try {
        dao.cadastrar(veiculo);
        PrintWriter w = response.getWriter();
        response.setContentType("text/html");
        w.append("<html>");
        w.append("<body>");
        w.append("<h3 style='color:green'>VEÍCULO CADASTRADO COM SUCESSO!!</h3>");
        w.append("</body>");
        w.append("</html>");
      } catch (SQLException e) {
        PrintWriter w = response.getWriter();
        response.setContentType("text/html");
        w.append("<html>");
        w.append("<body>");
        w.append("<h3 style='color:red'>ERRO AO TENTAR INCLUIR VEÍCULO!!</h3>");
        w.append("</body>");
        w.append("</html>");
      }
    }
  }
Example #18
0
  public static void download(
      HttpServletRequest request, HttpServletResponse response, String contentType, String filePath)
      throws Exception {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;

    System.out.println("path=" + filePath);
    long fileLength = new File(filePath).length();

    response.setContentType(contentType);
    response.setHeader(
        "Content-disposition",
        "attachment; filename="
            + new String(
                filePath.split("/")[filePath.split("/").length - 1].getBytes("utf-8"),
                "ISO8859-1"));
    response.setHeader("Content-Length", String.valueOf(fileLength));

    bis = new BufferedInputStream(new FileInputStream(filePath));
    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();
  }
  private void write() {
    if (Constants.FORMAT_JSON.equals(action.getFormat())) {
      response.setCharacterEncoding("UTF-8");
      response.setContentType("text/plain");
      try {
        PrintWriter out = response.getWriter();
        out.write(getActionJSON());
        out.flush();
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }

    } else if (Constants.FORMAT_XML.equals(action.getFormat())) {
      response.setCharacterEncoding("UTF-8");
      response.setContentType("text/xml");
      try {
        PrintWriter out = response.getWriter();
        out.write(getActionXML());
        out.flush();
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    HttpSession sess = request.getSession();
    session se = (session) sess.getAttribute("actualsession");
    response.setContentType("text/html;charset=UTF-8");

    if (se == null) {

      response.sendRedirect(request.getContextPath());

    } else {

      if (se.getUs().getTipo().equals("aluno") && se.isvalid()) {
        HtmlCoder d = new HtmlCoder();
        String resposta = d.relatorioProva(se, se.getListaPerguntas());
        se.setListaPerguntas(null);
        try (PrintWriter out = response.getWriter()) {
          out.print(resposta);
        }

      } else {

        response.sendRedirect(request.getContextPath());
      }
    }
  }
  /** {@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);
  }
Example #22
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    try {

      String id = req.getParameter("id");

      if ((id != null) && (id.length() > 0)) {
        MemberDocument doc =
            CouchDBD3LeaderboardsDatabase.getInstance().get(MemberDocument.class, id);

        if (doc != null) {
          String text = gson.toJson(doc);

          resp.setContentType("text/json");
          resp.getWriter().println(text);
          resp.flushBuffer();
        }
      } else {
        List<MemberDocument> list =
            CouchDBD3LeaderboardsDatabase.getInstance().findAll(MemberDocument.class);

        String text = gson.toJson(list);

        resp.setContentType("text/json");
        resp.getWriter().println(text);
        resp.flushBuffer();
      }

    } catch (Exception e) {
      resp.setContentType("text/plain");
      e.printStackTrace(resp.getWriter());
    }
  }
  protected void streamOperationOutcome(
      BaseServerResponseException theE,
      RestfulServer theServer,
      EncodingEnum theEncodingNotNull,
      HttpServletResponse theResponse,
      RequestDetails theRequest)
      throws IOException {
    theResponse.setStatus(theE.getStatusCode());

    theServer.addHeadersToResponse(theResponse);

    if (theE.getOperationOutcome() != null) {
      theResponse.setContentType(theEncodingNotNull.getResourceContentType());
      IParser parser = theEncodingNotNull.newParser(theServer.getFhirContext());
      parser.setPrettyPrint(RestfulServerUtils.prettyPrintResponse(theServer, theRequest));
      Writer writer = theResponse.getWriter();
      try {
        parser.encodeResourceToWriter(theE.getOperationOutcome(), writer);
      } finally {
        writer.close();
      }
    } else {
      theResponse.setContentType(Constants.CT_TEXT);
      Writer writer = theResponse.getWriter();
      try {
        writer.append(theE.getMessage());
      } finally {
        writer.close();
      }
    }
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {

      ApplicationContext appContext =
          WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
      ceaService = appContext.getBean(ICountryEnvironmentApplicationService.class);
      factoryCea = appContext.getBean(IFactoryCountryEnvironmentApplication.class);
      PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

      String id = policy.sanitize(request.getParameter("id"));
      String system = id.split("System&#61;")[1].split("&amp;")[0];
      String country = id.split("Country&#61;")[1].split("&amp;")[0];
      String env = id.split("Env&#61;")[1].split("&amp;")[0];
      String app = id.split("App&#61;")[1].split("&amp;")[0];

      response.setContentType("text/html");
      ceaService.delete(factoryCea.create(system, country, env, app, null, null, null, null));
    } catch (CerberusException ex) {
      Logger.getLogger(DeleteCountryEnvironmentParameter.class.getName())
          .log(Level.SEVERE, null, ex);
    }
  }
  @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());
    }
  }
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String captchaId = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
   String parm = (String) request.getParameter("txtResponse");
   if (captchaId != null && parm != null) {
     if (captchaId.equals(parm)) {
       response.setContentType("text/html");
       PrintWriter out = response.getWriter();
       out.write(
           "document.getElementById('imagen_captcha').src='KaptchaServlet#"
               + Math.floor(Math.random() * 1100000)
               + "';");
       out.write("document.getElementById('captcha_response').value='';");
       out.write("f_grabarDatos();");
       out.flush();
       out.close();
     } else {
       response.setContentType("text/html");
       PrintWriter out = response.getWriter();
       out.write(
           "document.getElementById('imagen_captcha').src='KaptchaServlet#"
               + Math.floor(Math.random() * 1100000)
               + "';");
       out.write("alert('Codigo incorrecto,registra nuevamente el codigo de la imagen');");
       out.write("document.getElementById('captcha_response').value='';");
       out.write("document.getElementById('captcha_response').focus();");
       out.write("return false;");
       out.flush();
       out.close();
     }
   }
 }
  public static ModelAndView Render(
      Object obj, String jsonpCallback, HttpServletResponse response) {
    PrintWriter out = null;
    try {
      StringBuffer jsonp = new StringBuffer();
      if (StringUtils.isBlank(jsonpCallback)) {
        jsonp.append(JsonUtil.Object2JsonStr(obj));
        response.setContentType("application/json");
      } else {
        jsonp.append(jsonpCallback + "(" + JsonUtil.Object2JsonStr(obj) + ")");
        response.setContentType("application/javascript");
      }
      response.setCharacterEncoding("utf-8");
      Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
      Matcher m = p.matcher(jsonp.toString());
      StringBuffer res = new StringBuffer();
      while (m.find()) {
        m.appendReplacement(res, "\\" + toUnicode(m.group()));
      }
      m.appendTail(res);

      out = response.getWriter();
      out.write(res.toString());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (null != out) out.close();
    }

    return null;
  }
Example #28
0
 /* 避免中文乱码 */
 private void setContentType(HttpServletResponse res) {
   String contentType = res.getContentType();
   if (Strings.isNullOrEmpty(contentType)) {
     contentType = "text/html; charset=UTF-8";
   }
   final String iso = "iso-8859-1";
   if (!contentType.toLowerCase().contains("charset")) {
     String encoding = res.getCharacterEncoding();
     if (Strings.isNullOrEmpty(encoding) || encoding.toLowerCase().equals(iso)) {
       encoding = "UTF-8";
     }
     contentType += "; charset=" + encoding;
     res.setContentType(contentType);
   } else {
     int pos = contentType.toLowerCase().lastIndexOf(iso);
     if (pos > 0) {
       String mime = contentType.substring(0, pos) + "UTF-8";
       int start = pos + iso.length() + 1;
       if (start < contentType.length()) {
         mime += contentType.substring(start);
       }
       res.setContentType(mime);
     }
   }
 }
Example #29
0
  @Override
  public final void doFilter(
      final ServletRequest req, final ServletResponse res, final FilterChain chain)
      throws ServletException {
    try {
      HttpServletRequest request = (HttpServletRequest) req;
      HttpServletResponse response = (HttpServletResponse) res;
      HttpSession session = request.getSession(false);

      if (session == null) {
        response.setContentType("application/json");
        response.getWriter().write("{\"error\":\"No active session\"}");
      } else {
        User user = (User) session.getAttribute("user");
        if (user == null) {
          response.setContentType("application/json");
          response.getWriter().write("{\"error\":\"User session not found\"}");
        } else {
          chain.doFilter(req, res);
        }
      }
    } catch (Throwable t) {
      throw new ServletException("Error: " + t.getMessage(), t);
    }
  }
Example #30
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String login = request.getParameter("login");
    String pass = request.getParameter("password");

    if (login == null || pass == null) {
      response.setContentType("text/html;charset=utf-8");
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }

    UserProfile profile = accountService.getUserByLogin(login);

    if (profile == null || !profile.getPass().equals(pass)) {
      response.setContentType("text/html;charset=utf-8");
      response.setStatus(401);
      response.getWriter().print("Unauthorized");
    } else {
      accountService.addSession(request.getSession().getId(), profile);
      Gson gson = new Gson();
      String json = gson.toJson(profile);
      // response.getWriter().println(json);
      response.setContentType("text/html;charset=utf-8");
      response.setStatus(200);
      response.getWriter().print("Authorized: " + login);
    }
  }