Example #1
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());
    }
  }
Example #2
0
  /**
   * Writes the query results to the HTTP response output stream.
   *
   * @param resp
   * @param writer
   * @param request
   * @param response
   * @param updateCountsFor
   * @throws IOException
   */
  protected final void stringResponse(
      ServiceResponse resp,
      Writer writer,
      HttpServletRequest request,
      HttpServletResponse response,
      Set<LogEvent> updateCountsFor)
      throws IOException {
    if (resp instanceof ErrorResponse) {

      errorResponse(
          ((ErrorResponse) resp).getStatus(),
          ((ErrorResponse) resp).toString(),
          request,
          response,
          updateCountsFor);

    } else if (resp.isEmpty()) {
      log.warn(
          "stringResponse: I got an empty ServiceResponce "
              + "(must be already converted to the ErrorResponse)");

      errorResponse(NO_RESULTS_FOUND, "no results found", request, response, updateCountsFor);

    } else {
      response.setContentType("text/plain");
      DataResponse dresp = (DataResponse) resp;

      log.debug("QUERY RETURNED " + dresp.getData().toString().length() + " chars");

      // take care to count provider's data accessed events
      Set<String> providers = dresp.getProviders();
      updateCountsFor.addAll(LogEvent.fromProviders(providers));

      // log to the db (for analysis and reporting)
      // problems with logging subsystem should not fail the entire service
      try {
        service.log(updateCountsFor, clientIpAddress(request));
      } catch (Throwable ex) {
        log.error("LogUtils.log failed", ex);
      }

      if (dresp.getData() instanceof Path) {
        File resultFile = ((Path) dresp.getData()).toFile(); // this is some temp. file
        response.setHeader("Content-Length", String.valueOf(resultFile.length()));
        FileReader reader = new FileReader(resultFile);
        IOUtils.copyLarge(reader, writer);
        response.flushBuffer();
        reader.close();
        resultFile.delete();
      } else {
        writer.write(dresp.getData().toString());
        response.flushBuffer();
      }
    }
  }
 protected void startSend(HttpServletResponse response) throws IOException {
   response.setContentType(contentType);
   response.setHeader("Connection", "keep-alive");
   ServletOutputStream os = response.getOutputStream();
   os.print(boundarySeperator);
   response.flushBuffer();
 }
Example #4
0
  /**
   * 下載Server端的檔案。
   *
   * @param response HttpServletResponse
   * @param realName Server端待下載檔案實際的檔名
   * @param fileName 下載後的檔名
   * @throws IOException
   */
  public static void downloadFile(HttpServletResponse response, String realName, String fileName)
      throws IOException {

    response.setHeader("Content-disposition", "attachment; filename=" + fileName);
    response.setContentType("application/x-download");
    // File exportFile = new File(realName);
    // response.setContentLength((int) exportFile.length());
    ServletOutputStream servletOutputStream = response.getOutputStream();
    ;
    try {
      byte[] b = new byte[1024];
      int i = 0;
      FileInputStream fis = new java.io.FileInputStream(realName);
      while ((i = fis.read(b)) > 0) {
        servletOutputStream.write(b, 0, i);
      }
    } catch (IOException e) {
      throw e;
    } finally {
      try {
        servletOutputStream.flush();
        servletOutputStream.close();
      } catch (IOException e) {
        throw e;
      } finally {
        response.setStatus(HttpServletResponse.SC_OK);
        response.flushBuffer();
      }
    }
  }
Example #5
0
 @Override
 @RequestMapping(method = RequestMethod.GET)
 public File compileSass(
     @RequestParam(value = "variables", required = false) String variables,
     @RequestParam(value = "entrypoints", required = false) String entrypoints,
     @RequestParam(value = "output", required = false) String output)
     throws Exception {
   SCSSProcessorBase processor = null;
   File inputFile = writeInputStreamToFile(getClass().getResourceAsStream("/default-theme.zip"));
   try {
     Map<String, String> mapping = convertFields(variables);
     Map<String, String> entryPoints = convertFields(entrypoints);
     processor = new SCSSProcessorJsass(inputFile.getAbsolutePath(), mapping, entryPoints);
     processor.compileAll();
     if (response != null) {
       OutputStream outputStream = response.getOutputStream();
       if ("css".equals(output)) {
         serveCss(processor, outputStream, "theme.css");
       } else {
         serveZip(processor, outputStream, "theme.zip");
       }
       IOUtils.closeQuietly(outputStream);
       response.flushBuffer();
     }
   } finally {
     if (processor != null) processor.cleanup();
     if (inputFile.exists()) inputFile.delete();
   }
   return null;
 }
 @Override
 public void handle(
     String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
     throws IOException, ServletException {
   String method = request.getMethod();
   // Handle statements post requests
   if ("POST".equals(method) && target.startsWith("/enonce/")) {
     new StatementResource().handle(request, response);
   }
   // Handle flight optimization requests (Statement 2 - Jajascript)
   else if ("POST".equals(method) && target.equals("/jajascript/optimize")) {
     new OptimizeResource().handle(request, response);
   }
   // Handle questions
   else if ("GET".equals(method)
       && "/".equals(target)
       && request.getParameter(QuestionResource.QUESTION_PARAMETER) != null) {
     new QuestionResource().handle(request, response);
   }
   // Handle change requests (Statement 1 - Scalaskel)
   else if ("GET".equals(method) && target.startsWith("/scalaskel/change/")) {
     new ScalaskelChangeResource().handle(request, response);
   }
   // Unknown request ...
   else {
     System.out.println("Unmanaged request : " + target);
     response.setStatus(HttpServletResponse.SC_NOT_FOUND);
     response.flushBuffer();
   }
 }
  public static void write(HttpServletResponse response, File file) throws IOException {

    if (response instanceof ByteBufferServletResponse) {
      ByteBufferServletResponse byteBufferResponse = (ByteBufferServletResponse) response;

      ByteBuffer byteBuffer = ByteBuffer.wrap(FileUtil.getBytes(file));

      byteBufferResponse.setByteBuffer(byteBuffer);
    } else if (response instanceof StringServletResponse) {
      StringServletResponse stringResponse = (StringServletResponse) response;

      String s = FileUtil.read(file);

      stringResponse.setString(s);
    } else {
      FileInputStream fileInputStream = new FileInputStream(file);

      FileChannel fileChannel = fileInputStream.getChannel();

      try {
        int contentLength = (int) fileChannel.size();

        response.setContentLength(contentLength);

        response.flushBuffer();

        fileChannel.transferTo(0, contentLength, Channels.newChannel(response.getOutputStream()));
      } finally {
        fileChannel.close();
      }
    }
  }
  public static void write(HttpServletResponse response, byte[][] bytesArray) throws IOException {

    try {

      // LEP-3122

      if (!response.isCommitted()) {
        int contentLength = 0;

        for (byte[] bytes : bytesArray) {
          contentLength += bytes.length;
        }

        response.setContentLength(contentLength);

        response.flushBuffer();

        ServletOutputStream servletOutputStream = response.getOutputStream();

        for (byte[] bytes : bytesArray) {
          servletOutputStream.write(bytes);
        }
      }
    } catch (IOException ioe) {
      if (ioe instanceof SocketException
          || ioe.getClass().getName().equals(_CLIENT_ABORT_EXCEPTION)) {

        if (_log.isWarnEnabled()) {
          _log.warn(ioe);
        }
      } else {
        throw ioe;
      }
    }
  }
Example #9
0
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    Set<String> keys = sampler.get().keys();

    PrintWriter writer = response.getWriter();
    writer.write("<html>");
    writer.write("<head>");
    writer.write("<title>VarZ</title>");
    writer.write("</head>");
    writer.write("<body>");
    writer.write("<h1>VarZ</h1>");

    writer.write("<table border=1>");
    writer.write("<tr><td>VarZ</td><td>Values</td></tr>");

    for (String key : keys) {
      writer.write("<tr>");
      writer.write("<td>");
      writer.write("<a href='/varz" + key + "'>");
      writer.write(key);
      writer.write("<a>");
      writer.write("</td>");
      writer.write("<td> ... </td>");
      writer.write("</tr>");
    }
    writer.write("</table>");

    writer.write("</body>");
    writer.write("</html>");

    response.flushBuffer();
  }
 @RequestMapping(
     value = "staff/{id}/{type}",
     method = RequestMethod.GET,
     produces = "application/pdf")
 public void getReport(
     @PathVariable("id") Integer id,
     @RequestParam("start") String s,
     @RequestParam("end") String e,
     @PathVariable("type") String type,
     HttpServletResponse response)
     throws IOException {
   DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
   if (type.equals("pdf")) gen = new PDFGenerator();
   else gen = new SheetGenerator();
   try {
     Date start = formatter.parse(s);
     Date end = formatter.parse(e);
     String dateHeader = start + " - " + end;
     Collection<Activity> acts =
         activityRepository.findByDateBetweenAndEmplIdAndSubmittedTrue(start, end, id);
     InputStream is = new FileInputStream(gen.getDocumentByStaff(acts, dateHeader));
     if (type.equals("pdf")) response.setContentType("application/pdf");
     else
       response.setContentType(
           "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
     OutputStream os = response.getOutputStream();
     int n = 0;
     byte[] byteBuffer = new byte[16384];
     while ((n = is.read(byteBuffer)) > -1) {
       os.write(byteBuffer, 0, n); // Don't allow any extra bytes to creep in, final write
     }
     response.flushBuffer();
   } catch (Exception ex) {
   }
 }
Example #11
0
  public ActionForward exportInfoToExcel(
      ActionMapping mapping,
      ActionForm actionForm,
      HttpServletRequest request,
      HttpServletResponse response)
      throws IOException {

    final CerimonyInquiry cerimonyInquiry = getDomainObject(request, "cerimonyInquiryId");
    if (cerimonyInquiry != null) {
      Collection<CerimonyInquiryPerson> requests = cerimonyInquiry.getCerimonyInquiryPersonSet();

      String inquiryName =
          (cerimonyInquiry.getDescription() != null
                  ? cerimonyInquiry.getDescription()
                  : "UnnamedInquiry")
              .replaceAll(" ", "_");
      final String filename =
          BundleUtil.getString(
                  Bundle.ALUMNI, "label.publicRelationOffice.alumniCerimony.inquiry.report")
              + "_"
              + inquiryName
              + "_"
              + new DateTime().toString("ddMMyyyyHHmmss");

      response.setContentType("application/vnd.ms-excel");
      response.setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");
      ServletOutputStream writer = response.getOutputStream();

      exportToXls(requests, writer);
      writer.flush();
      response.flushBuffer();
    }

    return null;
  }
Example #12
0
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    HttpServletResponse resp = (HttpServletResponse) servletResponse;

    String uri = req.getRequestURI();
    String path = uri.substring(0, uri.lastIndexOf("/") + 1);
    String name = uri.substring(uri.lastIndexOf("/") + 1);

    File testFile = new File("src/main/resources/tests" + path + "test-" + name);
    if (req.getParameter("skiptest") == null && testFile.exists() && testFile.isFile()) {
      Wrapper wrapper = new Wrapper(resp);
      filterChain.doFilter(req, wrapper);
      resp.flushBuffer();

      if (wrapper.isWrapped()) {
        String content = new String(wrapper.toByteArray(), "utf-8");
        String test = IOUtils.toString(testFile.toURI().toURL(), "utf-8");
        content = content.replace("</body>", test + "</body>");
        resp.getOutputStream().print(content);
      }
    } else {
      filterChain.doFilter(req, resp);
    }
  }
 @Override
 public void handle(
     final String target,
     final Request jettyRequest,
     final HttpServletRequest request,
     final HttpServletResponse response)
     throws IOException, ServletException {
   if (target.length() < 2) {
     response.setStatus(HttpStatus.BadRequest);
     response.getWriter().write("Invalid request");
   } else {
     final char command = target.charAt(1);
     switch (command) {
       case 'g':
         this.getMessage(jettyRequest, response);
         break;
       case 'p':
         this.putMessage(jettyRequest, response);
         break;
       case 'o':
         this.getOffset(jettyRequest, response);
         break;
       default:
         response.setStatus(HttpStatus.BadRequest);
         response.getWriter().write("Invalid request");
         break;
     }
   }
   response.flushBuffer();
 }
Example #14
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    final ImageSize size = ImageSize.fromString(req.getParameter(SIZE_PARAM));

    URL url = null;
    try {
      url = new URL(req.getParameter(URL_PARAM));
      Preconditions.checkNotNull(url);
    } catch (Exception e) {
      LOG.error("Invalid image url requested", e);
      resp.sendError(
          HttpServletResponse.SC_BAD_REQUEST, "Please provide a valid image url parameter");
      return;
    }

    try {
      CachedImage img = cache.get(url, size);
      resp.setHeader(HttpHeaders.CONTENT_TYPE, img.getMimeType());
      ByteStreams.copy(img, resp.getOutputStream());
    } catch (IOException e) {
      String errMsg = String.format("No image found for url '%s'", url);
      LOG.error(errMsg, e);
      resp.sendError(HttpServletResponse.SC_NOT_FOUND, errMsg);
    } finally {
      resp.flushBuffer();
    }
  }
 protected void sendResponseAppropriately(
     CallingContext context, HttpServletRequest req, HttpServletResponse resp, String response)
     throws IOException {
   String encoding = req.getHeader("Accept-Encoding");
   resp.setContentType("application/json");
   if (encoding != null && encoding.indexOf("gzip") >= 0) {
     resp.setHeader("Content-Encoding", "gzip");
     OutputStream o = null;
     GZIPOutputStream gz = null;
     try {
       o = resp.getOutputStream();
       gz = new GZIPOutputStream(o);
       gz.write(response.getBytes("UTF-8"));
     } finally {
       if (gz != null) {
         gz.close();
       }
       if (o != null) {
         o.close();
       }
     }
   } else {
     resp.getWriter().append(response);
     resp.flushBuffer();
   }
 }
 public static void sendString(String s, HttpServletResponse response) throws Exception {
   byte[] bytes = s.getBytes();
   response.setStatus(HttpServletResponse.SC_OK);
   response.setContentLength(bytes.length);
   response.getOutputStream().write(bytes);
   response.flushBuffer();
 }
Example #17
0
  /**
   * Process the user's http get request. Process the template that maps to the URI that was hit.
   *
   * @param request the user's http request
   * @param response the user's http response
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (processStatus(request, response)) {
      return;
    }

    if (!isRunning()) {
      int errorCode = mProperties.getInt("startup.codes.error", 503);
      response.sendError(errorCode);
      return;
    }

    if (mUseSpiderableRequest) {
      request =
          new SpiderableRequest(request, mQuerySeparator, mParameterSeparator, mValueSeparator);
    }

    // start transaction
    TeaServletTransaction tsTrans = getEngine().createTransaction(request, response, true);

    // load associated request/response
    ApplicationRequest appRequest = tsTrans.getRequest();
    ApplicationResponse appResponse = tsTrans.getResponse();

    // process template
    processTemplate(appRequest, appResponse);
    appResponse.finish();

    // flush the output
    response.flushBuffer();
  }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
      resp.getWriter().write("DispatchingServletGet-");
      resp.flushBuffer();

      final boolean first = TrackingServlet.first;
      TrackingServlet.first = false;

      final AsyncContext ctxt = req.startAsync();
      TrackingListener listener = new TrackingListener(false, true, null);
      ctxt.addListener(listener);
      ctxt.setTimeout(3000);

      Runnable run =
          new Runnable() {
            @Override
            public void run() {
              if (first) {
                ctxt.dispatch("/stage1");
              } else {
                ctxt.dispatch("/stage2");
              }
            }
          };
      if ("y".equals(req.getParameter("useThread"))) {
        new Thread(run).start();
      } else {
        run.run();
      }
    }
  /* ------------------------------------------------------------ */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    String[] method = request.getParameterValues("ajax");
    String[] message = request.getParameterValues("message");

    if (method != null && method.length > 0) {
      HttpServletRequest srequest = (HttpServletRequest) request;
      HttpServletResponse sresponse = (HttpServletResponse) response;

      StringWriter sout = new StringWriter();
      PrintWriter out = new PrintWriter(sout);

      out.println("<ajax-response>");
      AjaxResponse aResponse = new AjaxResponse(srequest, out);

      for (int i = 0; i < method.length; i++) {
        handle(method[i], message[i], srequest, aResponse);
      }

      out.println("</ajax-response>");
      byte[] ajax = sout.toString().getBytes("UTF-8");
      sresponse.setHeader("Pragma", "no-cache");
      sresponse.addHeader("Cache-Control", "must-revalidate,no-cache,no-store");
      sresponse.setDateHeader("Expires", 0);
      sresponse.setContentType("text/xml; charset=UTF-8");
      sresponse.setContentLength(ajax.length);
      sresponse.getOutputStream().write(ajax);
      sresponse.flushBuffer();
    } else chain.doFilter(request, response);
  }
  /**
   * Restart the NTLM logon process
   *
   * @param context ServletContext
   * @param req HttpServletRequest
   * @param res SessHttpServletResponse
   * @throws IOException
   */
  public void restartLoginChallenge(
      ServletContext context, HttpServletRequest req, HttpServletResponse res) throws IOException {
    if (getLogger().isDebugEnabled()) getLogger().debug("restartLoginChallenge...");

    // Remove any existing session and NTLM details from the session
    HttpSession session = req.getSession(false);
    if (session != null) {
      clearSession(session);
    }

    String userAgent = req.getHeader("user-agent");
    if (userAgent != null && userAgent.indexOf("Safari") != -1) {
      final PrintWriter out = res.getWriter();
      out.println("<html><head></head>");
      out.println(
          "<body><p>Login authentication failed. Please close and re-open Safari to try again.</p>");
      out.println("</body></html>");
      out.close();
    } else {
      // Force the logon to start again
      res.setHeader(WWW_AUTHENTICATE, AUTH_NTLM);
      res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      writeLoginPageLink(context, req, res);
    }

    if (isFallbackEnabled()) {
      includeFallbackAuth(context, req, res);
    }

    res.flushBuffer();
  }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
      if (request.getParameter("session") != null) request.getSession(true);
      if (request.getParameter("sleep") != null) {
        try {
          Thread.sleep(Long.parseLong(request.getParameter("sleep")));
        } catch (InterruptedException e) {
        }
      }

      if (request.getParameter("lines") != null) {
        int count = Integer.parseInt(request.getParameter("lines"));
        for (int i = 0; i < count; ++i) {
          response.getWriter().append("Line: " + i + "\n");
          response.flushBuffer();

          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
          }
        }
      }

      response.setContentType("text/plain");
    }
 /**
  * Returns an error message in the given Response object. The response number is still 200 (SC_OK)
  * so the message goes through cleanly.
  *
  * @param response write the error message here
  * @param errMsg error message to return
  * @throws IOException if writing to the response object throws one
  */
 private void sendErrMsg(HttpServletResponse response, String errMsg) throws IOException {
   response.setStatus(HttpServletResponse.SC_OK);
   response.setContentType("text/html;charset=UTF-8");
   PrintWriter respWriter = response.getWriter();
   respWriter.println(errMsg);
   response.flushBuffer();
 }
Example #23
0
 /**
  * @param aStatusCode
  * @param aMessage
  * @param aResp
  * @throws IOException
  */
 protected static void sendMessage(int aStatusCode, String aMessage, HttpServletResponse aResp)
     throws IOException {
   aResp.setStatus(aStatusCode);
   aResp.getWriter().print(aMessage);
   aResp.flushBuffer();
   aResp.getWriter().close();
 }
Example #24
0
  private void handlePartialPlayback(
      HttpServletRequest request,
      HttpServletResponse response,
      Vertex artifactVertex,
      String fileName,
      User user)
      throws IOException {
    String type = getRequiredParameter(request, "type");

    InputStream in;
    Long totalLength = null;
    long partialStart = 0;
    Long partialEnd = null;
    String range = request.getHeader("Range");

    if (range != null) {
      response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

      Matcher m = RANGE_PATTERN.matcher(range);
      if (m.matches()) {
        partialStart = Long.parseLong(m.group(1));
        if (m.group(2).length() > 0) {
          partialEnd = Long.parseLong(m.group(2));
        }
      }
    }

    response.setCharacterEncoding(null);
    response.setContentType(type);
    response.addHeader("Content-Disposition", "attachment; filename=" + fileName);

    StreamingPropertyValue mediaPropertyValue = getStreamingPropertyValue(artifactVertex, type);

    totalLength = mediaPropertyValue.getLength();
    in = mediaPropertyValue.getInputStream();

    if (partialEnd == null) {
      partialEnd = totalLength;
    }

    // Ensure that the last byte position is less than the instance-length
    partialEnd = Math.min(partialEnd, totalLength - 1);
    long partialLength = totalLength;

    if (range != null) {
      partialLength = partialEnd - partialStart + 1;
      response.addHeader(
          "Content-Range", "bytes " + partialStart + "-" + partialEnd + "/" + totalLength);
      if (partialStart > 0) {
        in.skip(partialStart);
      }
    }

    response.addHeader("Content-Length", "" + partialLength);

    OutputStream out = response.getOutputStream();
    copy(in, out, partialLength);

    response.flushBuffer();
  }
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   resp.getWriter().write("ErrorServletGet-");
   resp.flushBuffer();
   throw new ServletException("Opps.");
 }
  public ActionForward exportResultsToFile(
      ActionMapping mapping,
      ActionForm actionForm,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    String degreeTypeString = (String) getFromRequest(request, "degreeType");
    DegreeType degreeType = DegreeType.valueOf(degreeTypeString);
    ExecutionYear executionYear = getDomainObject(request, "executionYearOID");
    StyledExcelSpreadsheet spreadsheet =
        YearDelegateElection.exportElectionsResultsToFile(
            Degree.readAllByDegreeType(degreeType), executionYear);

    final ServletOutputStream writer = response.getOutputStream();
    spreadsheet.getWorkbook().write(writer);
    response.setContentType("application/txt");
    final String filename =
        String.format(
            "electionsResults_%s_%s.xls",
            degreeType.getLocalizedName(), executionYear.getYear().replace("/", "-"));
    response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    writer.flush();
    response.flushBuffer();
    return null;
  }
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   resp.getWriter().write("DispatchingServletGet-");
   resp.flushBuffer();
   final int iter = Integer.parseInt(req.getParameter(ITER_PARAM)) - 1;
   final AsyncContext ctxt = req.startAsync();
   if (addTrackingListener) {
     TrackingListener listener = new TrackingListener(completeOnError, true, null);
     ctxt.addListener(listener);
   }
   Runnable run =
       new Runnable() {
         @Override
         public void run() {
           if (iter > 0) {
             ctxt.dispatch("/stage1?" + ITER_PARAM + "=" + iter);
           } else {
             ctxt.dispatch("/stage2");
           }
         }
       };
   if ("y".equals(req.getParameter("useThread"))) {
     new Thread(run).start();
   } else {
     run.run();
   }
 }
 @RequestMapping(value = "projects/{id}/{type}")
 public void getProjectReport(
     @PathVariable("id") Integer id,
     @RequestParam(value = "start", required = false) String b,
     @RequestParam(value = "end", required = false) String e,
     @PathVariable("type") String type,
     HttpServletResponse response)
     throws IOException {
   if (type.equals("pdf")) gen = new PDFGenerator();
   else gen = new SheetGenerator();
   if (b != null && e != null) {
     DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
     try {
       Date begin = formatter.parse(b);
       Date end = formatter.parse(e);
       Collection<Activity> col = activityRepository.findByDateBetweenAndProjId(begin, end, id);
       InputStream is = new FileInputStream(gen.getDocumentByProject(col, begin + "-" + end));
       if (type.equals("pdf")) response.setContentType("application/pdf");
       else
         response.setContentType(
             "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
       OutputStream os = response.getOutputStream();
       int n = 0;
       byte[] byteBuffer = new byte[16384];
       while ((n = is.read(byteBuffer)) > -1) {
         os.write(byteBuffer, 0, n); // Don't allow any extra bytes to creep in, final write
       }
       response.flushBuffer();
     } catch (Exception ex) {
     }
   } else {
     try {
       Collection<Activity> col = activityRepository.findByProjId(id);
       InputStream is = new FileInputStream(gen.getDocumentByProject(col, "Whole period"));
       response.setContentType("application/pdf");
       OutputStream os = response.getOutputStream();
       int n = 0;
       byte[] byteBuffer = new byte[16384];
       while ((n = is.read(byteBuffer)) > -1) {
         os.write(byteBuffer, 0, n); // Don't allow any extra bytes to creep in, final write
       }
       response.flushBuffer();
     } catch (Exception ex) {
     }
   }
 }
Example #29
0
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
      String host = req.getParameter("host");
      if (!isLegalHost(host)) {
        LOG.error("from=" + req.getRemoteAddr() + "errHost=" + host);
        return;
      }

      String action = req.getParameter("action");
      if ("reload".equals(action)) {
        resp.getWriter().println("old size=" + dns.size() + " reloading...");
        resp.flushBuffer();

        loadIPs();

        resp.getWriter().println("new size=" + dns.size());
        resp.flushBuffer();
        return;
      } else if ("count".equals(action)) {
        resp.getWriter().println("dns=" + dns.size());
        resp.getWriter().println("unknownHosts=" + unknownHosts.size());
        resp.getWriter().println("querying=" + querying.size());
        resp.flushBuffer();
        return;
      } else if ("cleanUnknown".equals(action)) { // ���� unknownhost����
        resp.getWriter().println("unknownHosts=" + unknownHosts.size());
        resp.flushBuffer();
        unknownHosts = new HashMap(1000000);
        return;
      }

      try {
        if (dns.containsKey(host)) {
          resp.getWriter().print(dns.get(host));
          resp.flushBuffer();
          return;
        } else if (unknownHosts.containsKey(host)) {
          resp.getWriter().print(ipUnknown);
          resp.flushBuffer();
          return;
        } else { // ֱ�ӷ��أ�����
          queryQueue.add(host); // doing

          resp.getWriter().print(ipPend); // ��ȷ��
          resp.flushBuffer();
          return;
        }
      } catch (Exception e) {
        LOG.error("from=" + e.toString());

        resp.getWriter().print(ipPend);
        resp.flushBuffer();
        return;
      }
    }
Example #30
0
 @Override
 public void close() {
   try {
     r.flushBuffer();
   } catch (Throwable ex) {
     log.trace("exception closing and flushing", ex);
   }
 }