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;
    }
  }
Пример #2
0
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String fileName = request.getParameter("file");
    if (fileName == null || fileName.length() == 0) {
      // 设置返回的内容格式
      response.setHeader("Content-Type", "text/html; charset=utf-8");
      response.getOutputStream().print("Need to specify a file! Using 'file' parameter.");
      return;
    }
    String savedFilePath =
        request.getServletContext().getRealPath("/") + "downloads/" + fileName + "/~main";
    File savedFile = new File(savedFilePath);

    // 发送
    String rangeStr = request.getHeader("Range");
    // 是否是断续请求
    if (rangeStr != null && rangeStr.length() != 0) {
      // 如果为分段的请求
      // 设置响应代码
      response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
      response.setHeader("Accept-Ranges", "bytes");
      rangeStr = rangeStr.substring(rangeStr.indexOf("=") + 1);
      String[] ranges = rangeStr.split("-");
      // 获取请求的长度
      long startPos = Long.parseLong(ranges[0]);
      long endPos = savedFile.length();
      // 获取文件总大小
      long fileSize = endPos;
      if (ranges.length > 1) {
        endPos = Long.parseLong(ranges[1]);
      }

      // 头
      response.setHeader("Content-Range", "bytes " + startPos + "-" + endPos + "/" + fileSize);
      long sendSize = endPos - startPos + 1;
      response.setHeader("Content-Length", "" + sendSize);

      // 开始传输
      OutputStream os = response.getOutputStream();
      try (InputStream is = new BufferedInputStream(new FileInputStream(savedFile))) {
        // 传输
        fsu.streamFile(is, os, startPos, sendSize);
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else {
      // 如果为第一次请求
      long fileSize = savedFile.length();
      response.setHeader("Accept-Ranges", "bytes");
      response.setHeader("Content-Type", "text/html; charset=utf-8");
      response.setHeader("Content-Length", "" + fileSize);
      OutputStream os = response.getOutputStream();
      try (InputStream is = new BufferedInputStream(new FileInputStream(savedFile))) {
        // 传输
        fsu.streamFile(is, os);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Пример #3
0
  public void serviceGetPerfilturnoDetallePdf(
      HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    utf8RequestService(request);
    String[] getMethodos =
        new String[] {
          PerfilturnoHelper.IDTP_GET_METHOD_NAME,
          PerfilturnoHelper.IDPERFIL_GET_METHOD_NAME + "PerfilturnoParsed",
          PerfilturnoHelper.IDTURNO_GET_METHOD_NAME + "PerfilturnoParsed",
          PerfilturnoHelper.VALORCOSTE_GET_METHOD_NAME + "PerfilturnoParsed"
        };

    PerfilturnoGroupBean tgb = new PerfilturnoGroupBean();
    try {
      tgb.setElemento(PerfilturnoHelper.getPerfilturno(request));
    } catch (TorqueException e) {
      logger.severe(e.getMessage());
    }

    byte[] content =
        PdfUtils.getBytes(
            replaceStringBuffer(tgb.buildXml(getMethodos, null, "ISO-8859-1"), "n/a", " "),
            perfilturno_transformer,
            "ISO-8859-1");
    response.addHeader("content-disposition", "attachment;filename=Perfilturno.pdf");
    response.setContentType("application/pdf");
    response.setHeader("Cache-Control", ""); // para que funcione en IE
    response.setContentLength(content.length);
    response.getOutputStream().write(content);
    response.getOutputStream().flush();
    response.getOutputStream().close();
  }
Пример #4
0
  public void servicePerfilturnoTableContentPdf(
      HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    utf8RequestService(request);
    Criteria c = new Criteria();
    String paramQuery = WebUtils.getStringParam(request, "query");
    if ((paramQuery != null) && (paramQuery.compareTo("") != 0))
      c = PerfilturnoManager.buildSearchCriteria(paramQuery);
    c = criteriaPerfilturnoTableContent(request, c);
    PerfilturnoGroupBean tgb = PerfilturnoManager.getPerfilturnos(c);

    String[] methodos =
        new String[] {
          PerfilturnoHelper.IDPERFIL_GET_METHOD_NAME + "PerfilturnoParsed",
          PerfilturnoHelper.IDTURNO_GET_METHOD_NAME + "PerfilturnoParsed",
          PerfilturnoHelper.VALORCOSTE_GET_METHOD_NAME + "PerfilturnoParsed"
        };

    byte[] content =
        PdfUtils.getBytes(
            replaceStringBuffer(tgb.buildXml(methodos, null, "ISO-8859-1"), "n/a", " "),
            perfilturnos_transformer,
            "ISO-8859-1");
    response.addHeader("content-disposition", "attachment;filename=ListaPerfilturno.pdf");
    response.setContentType("application/pdf");
    response.setHeader("Cache-Control", ""); // para que funcione en IE
    response.setContentLength(content.length);
    response.getOutputStream().write(content);
    response.getOutputStream().flush();
    response.getOutputStream().close();
  }
Пример #5
0
  /** Generates a PDF with the list of registered members in the event. */
  public void print() {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    response.setContentType("application/pdf");
    response.setHeader("Content-disposition", "inline=filename=file.pdf");

    try {
      Document document = new Document();
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      PdfWriter.getInstance(document, baos);
      document.open();

      EventAttendeeReport eventAttendeeReport = new EventAttendeeReport(document);
      eventAttendeeReport.printReport(this.attendees);

      document.close();

      response.getOutputStream().write(baos.toByteArray());
      response.getOutputStream().flush();
      response.getOutputStream().close();
      context.responseComplete();
    } catch (IOException | DocumentException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
  }
Пример #6
0
  /** {@inheritDoc} */
  public ActionForward execute(
      @SuppressWarnings("unused") ActionMapping mapping,
      @SuppressWarnings("unused") ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    String type = request.getParameter("type");
    if (type == null) {
      type = "webapp";
    }

    if ("webapp".equals(type)) {
      response.getOutputStream().print("OK");
    } else if ("query".equals(type)) {
      final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
      ObjectStore os = im.getObjectStore();
      Query q = new Query();
      QueryClass c = new QueryClass(InterMineObject.class);
      q.addFrom(c);
      q.addToSelect(c);
      // Add a unique value to the select to avoid caching the query
      QueryValue token = new QueryValue(System.currentTimeMillis());
      q.addToSelect(token);
      Results r = os.execute(q, 1, false, false, false);
      if (r.get(0) != null) {
        response.getOutputStream().print("OK");
      } else {
        response.getOutputStream().print("NO RESULTS");
      }
    }
    return null;
  }
Пример #7
0
  protected void generateXLSOutput(
      String reportName,
      JasperPrint jasperPrint,
      HttpServletResponse resp,
      HashMap<String, Object> params)
      throws IOException, JRException {
    String reportfilename = (reportName) + ".xls";
    JRXlsExporter exporterXLS = new JRXlsExporter();
    exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
    // exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,Boolean.TRUE);
    exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
    exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
    exporterXLS.setParameter(
        JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.FALSE);
    exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, resp.getOutputStream());
    for (Iterator<?> iterator = params.keySet().iterator(); iterator.hasNext(); ) {
      String key = (String) iterator.next();
      try {
        PdfReportParam.class.getDeclaredField(key);
        Field field = JRXlsExporterParameter.class.getDeclaredField(key);
        field.setAccessible(true);
        exporterXLS.setParameter(
            (JRExporterParameter) field.get(JRPdfExporterParameter.class), params.get(key));
      } catch (Exception e) {
        // Xls Param will only valid in report param
      }
    }
    resp.setHeader("Content-Disposition", "inline;filename=" + reportfilename);
    resp.setContentType("application/vnd.ms-excel");

    exporterXLS.exportReport();
    resp.getOutputStream().close();
    // clear();
  }
Пример #8
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);
  }
  protected void doGet(final HttpServletRequest req, final HttpServletResponse res)
      throws ServletException, IOException {

    final String uuid = req.getParameter("uuid");

    if (uuid == null) {
      res.sendError(SC_BAD_REQUEST);
    }

    final AssetItem asset = repository.loadAssetByUUID(uuid);

    if (asset == null) {
      res.sendError(SC_NO_CONTENT);
      return;
    }

    final ServiceConfig serviceConfig =
        ServiceConfigPersistence.getInstance().unmarshal(asset.getContent());

    try {
      res.setContentType("application/x-download");
      res.setHeader("Content-Disposition", "attachment; filename=drools-service.war;");
      buildWar(serviceConfig, repository, res.getOutputStream());
    } catch (Throwable e) {
      ((OutputStream) res.getOutputStream()).close();
      res.sendError(SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
    }
  }
Пример #10
0
  private void handleRSS(HttpServletRequest req, HttpServletResponse res, Site site, String slug)
      throws IOException, XMLStreamException, ServletException {
    slug = slug.replaceFirst("/", "");

    Locale locale =
        Strings.isNullOrEmpty(req.getParameter("locale"))
            ? I18N.getLocale()
            : new Locale.Builder().setLanguageTag(req.getParameter("locale")).build();

    String[] parts = slug.split("/");

    if (parts.length == 1) {
      res.setContentType("application/rss+xml;charset=UTF-8");
      res.getOutputStream()
          .write(RSSService.generateRSSForSite(site, locale).getBytes(StandardCharsets.UTF_8));
    } else {
      Category category = site.categoryForSlug(parts[1]);
      if (category == null) {
        errorPage(req, res, site, 404);
      } else {
        res.setContentType("application/rss+xml;charset=UTF-8");
        res.getOutputStream()
            .write(
                RSSService.generateRSSForCategory(category, locale)
                    .getBytes(StandardCharsets.UTF_8));
      }
    }
  }
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String uri = request.getParameter("uri");
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    String rLastEdit = request.getParameter("lastEdit");
    if (rLastEdit == null) return;
    long userLastEdit = Long.parseLong(rLastEdit);
    if (clipStatus.hasAccess(request.getSession().getId(), uri)) {
      Connection con = dbCon.getConnection();
      try {
        Clip clip = ClipAgent.getInstance().loadClip(uri, con);
        if (clip != null) {
          DateFormat df = DateFormat.getDateTimeInstance();
          String textAreaValue = clip.getValue();
          Pattern p = Pattern.compile("</\\s*textarea", Pattern.CASE_INSENSITIVE);
          Matcher m = p.matcher(textAreaValue);

          textAreaValue = m.replaceAll("textarea");
          response.getOutputStream().write(textAreaValue.getBytes("UTF-8"));
        }
      } finally {
        dbCon.returnConnection(con);
      }
    } else {

      response.getOutputStream().print("");
    }
    response.getOutputStream().flush();
  }
Пример #12
0
 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   String query = req.getParameter("query");
   ServiceResponse<Meeting> response;
   Type responseType = new TypeToken<ServiceResponse<Meeting>>() {}.getType();
   switch (query) {
     case RestApi.GET_MEETING:
       String title = req.getParameter("title");
       Meeting meeting = restService.getMeeting(title);
       if (meeting != null) {
         response = new ServiceResponse<>(meeting);
         GsonHelper.write(response, responseType, resp.getOutputStream());
       } else {
         response =
             new ServiceResponse<>(
                 ServiceResponse.FAIL, ServiceResponse.MEETING_NOT_FOUND_MASSAGE);
         GsonHelper.write(response, resp.getOutputStream());
       }
       break;
     case RestApi.FIND_MEETING:
       String fragment = req.getParameter("fragment");
       Meeting findMeeting = restService.getMeetingByDescriptionFragment(fragment);
       if (findMeeting != null) {
         response = new ServiceResponse<>(findMeeting);
         GsonHelper.write(response, responseType, resp.getOutputStream());
       } else {
         response =
             new ServiceResponse<>(
                 ServiceResponse.FAIL, ServiceResponse.MEETING_NOT_FOUND_MASSAGE);
         GsonHelper.write(response, resp.getOutputStream());
       }
       break;
   }
 }
Пример #13
0
 @Override
 protected void doPut(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   String query = req.getParameter("query");
   ServiceResponse response;
   switch (query) {
     case RestApi.CREATE_MEETING:
       Meeting newMeeting = GsonHelper.read(Meeting.class, req.getInputStream());
       restService.addMeeting(newMeeting);
       response = new ServiceResponse(ServiceResponse.SUCCESS, "Meeting created");
       GsonHelper.write(response, resp.getOutputStream());
       break;
     case RestApi.ACCEPT_MEETING:
       String title = req.getParameter("title");
       Participant participant = GsonHelper.read(Participant.class, req.getInputStream());
       Meeting acceptMeeting = restService.acceptMeeting(participant, title);
       if (acceptMeeting != null) {
         response = new ServiceResponse(ServiceResponse.SUCCESS, "You accept meeting");
         GsonHelper.write(response, resp.getOutputStream());
       } else {
         response =
             new ServiceResponse(
                 ServiceResponse.FAIL,
                 "Accept error: " + ServiceResponse.MEETING_NOT_FOUND_MASSAGE);
         GsonHelper.write(response, resp.getOutputStream());
       }
       break;
   }
 }
Пример #14
0
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   String query = req.getParameter("query");
   switch (query) {
     case RestApi.AUTHENTICATION:
       String userPassword = req.getParameter("password");
       boolean result = restService.checkPassword(userPassword);
       ServiceResponse response;
       if (result) {
         response = new ServiceResponse(ServiceResponse.SUCCESS, "Success connect");
       } else {
         response = new ServiceResponse(ServiceResponse.FAIL, "Authentication error");
       }
       GsonHelper.write(response, resp.getOutputStream());
       break;
     case RestApi.GET_MEETINGS:
       ServiceResponse<Collection<String>> meetingsResponse =
           new ServiceResponse<>(restService.getMeetings());
       GsonHelper.write(
           meetingsResponse,
           new TypeToken<ServiceResponse<Collection<String>>>() {}.getType(),
           resp.getOutputStream());
       break;
   }
 }
    public void handle(
        String s, Request r, HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws IOException, ServletException {

      Enumeration<?> e = httpRequest.getHeaderNames();
      String param;
      while (e.hasMoreElements()) {
        param = e.nextElement().toString();
        httpResponse.addHeader("X-" + param, httpRequest.getHeader(param));
      }

      int size = 10 * 1024;
      if (httpRequest.getContentLength() > 0) {
        size = httpRequest.getContentLength();
      }
      byte[] bytes = new byte[size];
      if (bytes.length > 0) {
        final InputStream in = httpRequest.getInputStream();
        final OutputStream out = httpResponse.getOutputStream();
        int read;
        while ((read = in.read(bytes)) != -1) {
          out.write(bytes, 0, read);
        }
      }

      httpResponse.setStatus(200);
      httpResponse.getOutputStream().flush();
      httpResponse.getOutputStream().close();
    }
Пример #16
0
 public void marshalResult(final HttpServletResponse pResponse)
     throws TransformerException, IOException, XmlException {
   if (mResult instanceof XmlSerializable) {
     // By default don't use JAXB
     setContentType(pResponse, "text/xml");
     OutputStreamWriter writer =
         new OutputStreamWriter(pResponse.getOutputStream(), pResponse.getCharacterEncoding());
     XmlUtil.serialize((XmlSerializable) mResult, writer);
     writer.close();
     return;
   }
   final XmlRootElement xmlRootElement =
       mResult == null ? null : mResult.getClass().getAnnotation(XmlRootElement.class);
   if (xmlRootElement != null) {
     try {
       final JAXBContext jaxbContext = JAXBContext.newInstance(getReturnType());
       final JAXBSource jaxbSource = new JAXBSource(jaxbContext, mResult);
       setContentType(pResponse, "text/xml");
       Sources.writeToStream(jaxbSource, pResponse.getOutputStream());
     } catch (final JAXBException e) {
       throw new MessagingException(e);
     }
   } else {
     serializeValue(pResponse, this.mResult);
   }
 }
Пример #17
0
  /**
   * Writes an output of a GetView request to the <code>httpResponse</code> using the <code>mime
   * </code> type.
   *
   * @param output the image to be sent back
   * @param httpResponse the response to pipe the image
   * @param mime the type of image
   */
  private void writeImage(Image output, HttpServletResponse httpResponse, String mime) {
    try {

      OutputStream os = httpResponse.getOutputStream();
      httpResponse.setContentType(mime);

      if (mime.equalsIgnoreCase("image/jpg") || mime.equalsIgnoreCase("image/jpeg")) {

        OGCWebService service = WPVServiceFactory.createInstance();
        WPVSConfiguration config = (WPVSConfiguration) ((WPVService) service).getCapabilities();
        float quality = config.getDeegreeParams().getViewQuality();
        Encoders.encodeJpeg(os, (BufferedImage) output, quality);

        // TODO png accepted?
      } else if (mime.equalsIgnoreCase("image/png")) {
        Encoders.encodePng(os, (BufferedImage) output);
      } else if (mime.equalsIgnoreCase("image/tif") || mime.equalsIgnoreCase("image/tiff")) {
        Encoders.encodeTiff(os, (BufferedImage) output);
      } else if (mime.equalsIgnoreCase("image/bmp")) {
        Encoders.encodeBmp(os, (BufferedImage) output);
      } else {
        httpResponse.setContentType("text/xml");
        os = httpResponse.getOutputStream();
        OGCWebServiceException exce =
            new OGCWebServiceException("WMS:writeImage", "unsupported image format: " + mime);
        os.write(((Marshallable) exce).exportAsXML().getBytes());
      }

      os.close();
    } catch (Exception e) {
      LOG.logError("-", e);
    }
  }
Пример #18
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());
     }
   }
 }
Пример #19
0
 public ModelAndView downloadFile(
     HttpServletRequest request, HttpServletResponse response, DataObject para) throws Exception {
   response.setContentType("application/octet-stream; charset=ISO-8859-1");
   StringBuffer contentDisposition = new StringBuffer("\"attachment; filename=\"");
   try {
     DataObject result = NoticeMngBPO.downloadFile(para);
     String fileName = result.getString("fileName", "");
     byte[] fileByte = (byte[]) result.getObject("fileByte");
     if (fileName.length() > 150) // 解决IE 6.0 bug
     {
       fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
     } else {
       fileName = URLEncoder.encode(fileName, "UTF-8");
     }
     contentDisposition.append(fileName);
     response.setHeader("Content-disposition", contentDisposition.toString());
     OutputStream os = response.getOutputStream();
     os.write(fileByte);
   } catch (ApplicationException e) {
     response.getOutputStream().close();
     LogHandler.saveBizLog(request, e.getMessage());
     return this.showErrorMessage(e.getMessage());
   }
   response.getOutputStream().close();
   return null;
 }
Пример #20
0
  /**
   * Return the specified logs
   *
   * @param request The HTTP servlet request.
   * @param response The HTTP servlet response.
   */
  protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
      throws ServletException, IOException {
    final String logName = request.getPathInfo();
    if ((logName == null) || (logName.length() == 0)) {
      response.sendRedirect("logs/");
      return;
    } else if ("/".equals(logName)) {
      response.setContentType("text/html");
      response.setStatus(HttpServletResponse.SC_OK);
      response.setContentLength(directoryContents.length());
      response.getOutputStream().print(directoryContents);
    } else {
      final String contents;
      try {
        contents = TestLogController.readLog(logName);
      } catch (final Throwable th) {
        log("Error reading log file", th);
        response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.setContentLength(notFoundResponse.length());
        response.getOutputStream().print(notFoundResponse);
        return;
      }

      response.setContentType("text/xml");
      response.setStatus(HttpServletResponse.SC_OK);
      response.setContentLength(contents.length());
      response.getOutputStream().print(contents);
    }
  }
Пример #21
0
 @RequestMapping(value = "exportExcel")
 public String exportExcel(HttpServletRequest request, HttpServletResponse response)
     throws Exception {
   String operator = request.getParameter("filter_LIKES_operator");
   String time = request.getParameter("filter_LIKES_time");
   StringBuilder builder = new StringBuilder("from OptLog where 1=1");
   if (StringUtils.isNotBlank(operator)) {
     builder.append(" and operator like '%").append(operator).append("%'");
     request.setAttribute("filter_LIKES_operator", operator);
   }
   if (StringUtils.isNotBlank(time)) {
     builder.append(" and time like '%").append(time).append("%'");
     request.setAttribute("filter_LIKES_time", time);
   }
   builder.append(" order by id desc");
   List<OptLog> data = optLogManager.findOptLogOrderby(builder.toString());
   // 生成Excel文件.
   Workbook wb = new ExcelExporter().export("操作日志", data);
   // 输出Excel文件.
   // HttpServletResponse response = Struts2Utils.getResponse();
   response.setContentType(ServletUtils.EXCEL_TYPE);
   ServletUtils.setFileDownloadHeader(response, "操作日志.xls");
   wb.write(response.getOutputStream());
   response.getOutputStream().flush();
   return null;
 }
Пример #22
0
  @Override
  public void getResource(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    String pathInfo = request.getPathInfo().substring(getResourcePath().length());

    InputStream in =
        Resources.getResourceAsStream(
            "org/betaconceptframework/astroboa/portal/resource/web" + pathInfo,
            getServletContext());

    try {
      if (in != null) {
        byte[] buffer = new byte[1024];
        int read = in.read(buffer);
        while (read != -1) {
          response.getOutputStream().write(buffer, 0, read);
          read = in.read(buffer);
        }
        response.getOutputStream().flush();
      } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
      }
    } finally {
      Resources.closeStream(in);
    }
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    String communityLogo = "PoweredByOpenbravo.png";
    String opsLogo = "PoweredByOpenbravoOPS.png";

    // get instance active status from db
    boolean active = false;
    OBContext.setAdminMode();
    try {
      active = ActivationKey.getInstance().isActive();
      log4j.debug("GetOpsLogo: activated: " + active);
    } finally {
      OBContext.restorePreviousMode();
    }

    String activeLogo;
    if (active) {
      activeLogo = opsLogo;
    } else {
      activeLogo = communityLogo;
    }

    FileUtility f =
        new FileUtility(this.globalParameters.prefix + "web/images", activeLogo, false, true);
    response.setContentType("image/png");
    // mark response as cache-forever
    response.addHeader("Expires", "Sun, 17 Jan 2038 19:14:07 GMT");
    response.addHeader("Cache-Control", "public");

    f.dumpFile(response.getOutputStream());
    response.getOutputStream().flush();
    response.getOutputStream().close();
  }
  public void onExpectedRequest(
      String target, HttpServletRequest request, HttpServletResponse response) throws Exception {

    assertTrue(request.getPathInfo().endsWith("/api/rest/getLatestBuildResults.action"));

    final String[] authTokens = request.getParameterValues("auth");
    final String[] buildKeys = request.getParameterValues("buildKey");

    assertEquals(1, authTokens.length);
    assertEquals(1, buildKeys.length);

    final String authToken = authTokens[0];
    final String myBuildKey = buildKeys[0];

    assertEquals(LoginCallback.AUTH_TOKEN, authToken);
    assertEquals(buildKey, myBuildKey);

    VelocityEngine velocityEngine = new VelocityEngine();
    Properties props = new Properties();
    props.setProperty("resource.loader", "class");
    props.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());
    velocityEngine.init(props);
    final VelocityContext context = new VelocityContext();
    context.put("buildKey", buildKey);
    context.put("buildNumber", buildNumber);

    final OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
    velocityEngine.mergeTemplate(
        "/mock/bamboo/1_2_4/api/rest/latestBuildResultResponse.vm", "UTF-8", context, writer);
    writer.flush();
    response.getOutputStream().flush();
  }
Пример #25
0
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String name = request.getParameter("name");
    String phonenumber = request.getParameter("phonenumber");
    response.getOutputStream().write(("此次填写的是" + name + "的手机号是:" + phonenumber + "").getBytes());
    String url = "jdbc:mysql://127.0.0.1:3306/haust_cs_113?user=root&password=root";

    try {
      // 创建一个数据库driver?
      Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    try {
      // 通过制定的url建立数据库连接
      Connection conn = DriverManager.getConnection(url);
      if (conn != null) System.out.println("数据库连接成功!");
      else System.out.println("数据库连接失败!");
      // 创建一个 Statement 对象来将 SQL 语句发送到数据库。
      Statement stm = conn.createStatement();
      // 执行给定 SQL 语句,该语句可能为 INSERT、UPDATE 或 DELETE 语句,或者不返回任何内容的 SQL 语句(如 SQL DDL 语句)。
      stm.executeUpdate("insert into user value('" + name + "','" + phonenumber + "');");
      response.getOutputStream().write("插入成功".getBytes());
      conn.close();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Пример #26
0
 private void doGet(HttpServletResponse response, XcapResourceImpl resource) throws IOException {
   response.setContentType(resource.getMimeType());
   if (resource.isAllDocument()) {
     response.getOutputStream().write(resource.getDocument().getBytes());
   } else {
     XmlResource selectedResource = resource.getSelectedResource();
     switch (resource.getNodeType()) {
       case ATTRIBUTE:
         response
             .getOutputStream()
             .write(((Attr) selectedResource.getDom()).getValue().getBytes());
         break;
       case ELEMENT:
         response.getOutputStream().write(selectedResource.getBytes());
         break;
       case NAMESPACE:
         Node node = selectedResource.getDom();
         String prefix = "<" + node.getNodeName() + " ";
         response.getOutputStream().write(prefix.getBytes());
         response.getOutputStream().write(node.getNamespaceURI().getBytes());
         response.getOutputStream().write("/>".getBytes());
         break;
       default:
         break;
     }
   }
 }
  @RequestMapping("download")
  public void download(ReportVo reportVo, HttpServletResponse response, HttpServletRequest request)
      throws IOException {
    if (reportVo != null) {
      String template = "config/templates/" + reportVo.getReportType() + ".html";
      PdfDocumentGenerator pdfGenerator = new PdfDocumentGenerator();
      List<User> users = userService.findAll();
      if (users != null) {
        List<DocumentVo> employeeReportVos = new ArrayList<DocumentVo>();
        for (User user : users) {
          EmployeeReportVo employeeReportVo = new EmployeeReportVo(user, reportVo.getReportType());
          if (employeeReportVo.getIsEmployee() != null && employeeReportVo.getIsEmployee()) {
            employeeReportVos.add(employeeReportVo);
          }
        }
        try {
          if (reportVo.getReportType().equals(ReportType.TimeCardReport.name())
              || reportVo.getReportType().equals(ReportType.ExceptionsReport.name())) {
            try {
              pdfGenerator.generate(
                  createTimeCardReport(reportVo, employeeReportVos), response.getOutputStream());
            } catch (Exception e) {
              e.printStackTrace();
            }
          } else {
            pdfGenerator.generate(template, employeeReportVos, response.getOutputStream());
          }

        } catch (DocumentGeneratingException e) {
          e.printStackTrace();
        }
      }
    }
  }
  @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());
    }
  }
    /* @Override */
    public void handle(
        String pathInContext,
        org.eclipse.jetty.server.Request request,
        HttpServletRequest httpRequest,
        HttpServletResponse httpResponse)
        throws IOException, ServletException {

      final boolean expectGet = (httpRequest.getHeader("x-expect-get") != null);
      final boolean expectPost = (httpRequest.getHeader("x-expect-post") != null);
      if (expectGet) {
        final String method = request.getMethod();
        if (!"GET".equals(method)) {
          httpResponse.sendError(500, "Incorrect method.  Expected GET, received " + method);
          return;
        }
        httpResponse.setStatus(200);
        httpResponse.getOutputStream().write("OK".getBytes());
        httpResponse.getOutputStream().flush();
        return;
      } else if (expectPost) {
        final String method = request.getMethod();
        if (!"POST".equals(method)) {
          httpResponse.sendError(500, "Incorrect method.  Expected POST, received " + method);
          return;
        }
        httpResponse.setStatus(200);
        httpResponse.getOutputStream().write("OK".getBytes());
        httpResponse.getOutputStream().flush();
        return;
      }

      String header = httpRequest.getHeader("x-redirect");
      if (header != null) {
        // format for header is <status code>|<location url>
        String[] parts = header.split("@");
        int redirectCode;
        try {
          redirectCode = Integer.parseInt(parts[0]);
        } catch (Exception ex) {
          ex.printStackTrace();
          httpResponse.sendError(500, "Unable to parse redirect code");
          return;
        }
        httpResponse.setStatus(redirectCode);
        if (httpRequest.getHeader("x-negative") == null) {
          httpResponse.addHeader("x-expect-get", "true");
        } else {
          httpResponse.addHeader("x-expect-post", "true");
        }
        httpResponse.setContentLength(0);
        httpResponse.addHeader("Location", parts[1] + counter.getAndIncrement());
        httpResponse.getOutputStream().flush();
        return;
      }

      httpResponse.sendError(500);
      httpResponse.getOutputStream().flush();
      httpResponse.getOutputStream().close();
    }
Пример #30
0
  /*
   * (non-Javadoc)
   *
   * @see javax.servlet.http.HttpServlet#service(javax.servlet.ServletRequest,
   * javax.servlet.ServletResponse)
   */
  @Override
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {
      String messageId = request.getParameter("messageId");
      String attachmentIndex = request.getParameter("attachmentIndex");
      boolean isThumbnail = Boolean.valueOf(request.getParameter("thumbnail")).booleanValue();

      if (messageId != null) {
        IMailbox mailbox = SessionManager.get().getMailbox();
        Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

        if (isThumbnail) {
          List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg);
          int index = Integer.valueOf(attachmentIndex);

          MimePart retrievePart = attachmentList.get(index);

          ContentType contentType = new ContentType(retrievePart.getContentType());
          response.setContentType(contentType.getBaseType());

          BufferedInputStream bufInputStream =
              new BufferedInputStream(retrievePart.getInputStream());
          OutputStream outputStream = response.getOutputStream();

          writeScaledImage(bufInputStream, outputStream);

          bufInputStream.close();
          outputStream.flush();
          outputStream.close();
        } else {
          Part imagePart = findImagePart(msg);
          if (imagePart != null) {
            ContentType contentType = new ContentType(imagePart.getContentType());
            response.setContentType(contentType.getBaseType());

            BufferedInputStream bufInputStream =
                new BufferedInputStream(imagePart.getInputStream());
            OutputStream outputStream = response.getOutputStream();

            byte[] inBuf = new byte[1024];
            int len = 0;
            int total = 0;
            while ((len = bufInputStream.read(inBuf)) > 0) {
              outputStream.write(inBuf, 0, len);
              total += len;
            }

            bufInputStream.close();
            outputStream.flush();
            outputStream.close();
          }
        }
      }
    } catch (Exception ex) {
      log.error(ex.getMessage(), ex);
    }
  }