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();
    }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletInputStream is = request.getInputStream();
    ServletOutputStream os = response.getOutputStream();

    System.out.println(request.getContentLength());
    System.out.println(request.getContentType());
    int clength = request.getContentLength();
    byte[] data = new byte[clength];
    int offset = 0;
    do {
      int rc = is.read(data, offset, data.length - offset);
      if (-1 == rc) {
        break;
      }
      offset += rc;
    } while (offset < data.length);

    // Echo input stream to output stream
    os.println(header);
    os.print(new String(data, 0, offset));
    os.println();
    os.println(footer);

    response.setContentType("text/html");

    is.close();
    os.close();
  }
 /**
  * Create a new listener for this session.
  *
  * @param request
  * @return the appropriate listener
  */
 protected AbstractUploadListener createNewListener(HttpServletRequest request) {
   if (isAppEngine()) {
     return new MemoryUploadListener(uploadDelay, request.getContentLength());
   } else {
     return new UploadListener(uploadDelay, request.getContentLength());
   }
 }
 /**
  * Override this method if you want to check the request before it is passed to commons-fileupload
  * parser.
  *
  * @param request
  * @throws RuntimeException
  */
 public void checkRequest(HttpServletRequest request) {
   logger.debug(
       "UPLOAD-SERVLET ("
           + request.getSession().getId()
           + ") procesing a request with size: "
           + request.getContentLength()
           + " bytes.");
   if (request.getContentLength() > maxSize) {
     throw new UploadSizeLimitException(maxSize, request.getContentLength());
   }
 }
示例#5
0
 /**
  * Deserialize an object from an HttpServletRequest input stream. Does not throw any exceptions;
  * instead, exceptions are logged and null is returned.
  *
  * @param req An HttpServletRequest that contains a serialized object.
  * @return An object instance, or null if an exception occurred.
  */
 private static Object deserialize(HttpServletRequest req) {
   if (req.getContentLength() == 0) {
     log.severe("request content length is 0");
     return null;
   }
   try {
     byte[] bytesIn = new byte[req.getContentLength()];
     req.getInputStream().readLine(bytesIn, 0, bytesIn.length);
     return deserialize(bytesIn);
   } catch (IOException e) {
     log.log(Level.SEVERE, "Error deserializing task", e);
     return null; // don't retry task
   }
 }
 private HttpResponse forward(
     HttpClient httpclient,
     String verb,
     String uri,
     HttpServletRequest request,
     MultiValueMap<String, String> headers,
     MultiValueMap<String, String> params,
     InputStream requestEntity)
     throws Exception {
   Map<String, Object> info = this.helper.debug(verb, uri, headers, params, requestEntity);
   URL host = RequestContext.getCurrentContext().getRouteHost();
   HttpHost httpHost = getHttpHost(host);
   uri = StringUtils.cleanPath(host.getPath() + uri);
   HttpRequest httpRequest;
   switch (verb.toUpperCase()) {
     case "POST":
       HttpPost httpPost = new HttpPost(uri + getQueryString());
       httpRequest = httpPost;
       httpPost.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
       break;
     case "PUT":
       HttpPut httpPut = new HttpPut(uri + getQueryString());
       httpRequest = httpPut;
       httpPut.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
       break;
     case "PATCH":
       HttpPatch httpPatch = new HttpPatch(uri + getQueryString());
       httpRequest = httpPatch;
       httpPatch.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
       break;
     default:
       httpRequest = new BasicHttpRequest(verb, uri + getQueryString());
       log.debug(uri + getQueryString());
   }
   try {
     httpRequest.setHeaders(convertHeaders(headers));
     log.debug(httpHost.getHostName() + " " + httpHost.getPort() + " " + httpHost.getSchemeName());
     HttpResponse zuulResponse = forwardRequest(httpclient, httpHost, httpRequest);
     this.helper.appendDebug(
         info,
         zuulResponse.getStatusLine().getStatusCode(),
         revertHeaders(zuulResponse.getAllHeaders()));
     return zuulResponse;
   } finally {
     // When HttpClient instance is no longer needed,
     // shut down the connection manager to ensure
     // immediate deallocation of all system resources
     // httpclient.getConnectionManager().shutdown();
   }
 }
 /**
  * @param request
  * @throws IOException
  */
 public CapturedRequest(HttpServletRequest request) throws IOException {
   for (Enumeration<?> names = request.getHeaderNames(); names.hasMoreElements(); ) {
     String name = (String) names.nextElement();
     headers.put(name, request.getHeader(name));
   }
   contentType = request.getContentType();
   if (request.getContentLength() > 0) {
     byteBody = new byte[request.getContentLength()];
     InputStream in = request.getInputStream();
     in.read(byteBody);
     requestBody = new String(byteBody);
   }
   method = request.getMethod();
 }
示例#8
0
 private void copyContentToCGI(final HttpServletRequest req, final OutputStream dst)
     throws IOException {
   final int contentLength = req.getContentLength();
   final InputStream src = req.getInputStream();
   new Thread(
           new Runnable() {
             @Override
             public void run() {
               try {
                 try {
                   final byte[] buf = new byte[bufferSize];
                   int remaining = contentLength;
                   while (0 < remaining) {
                     final int max = Math.max(buf.length, remaining);
                     final int n = src.read(buf, 0, max);
                     if (n < 0) {
                       throw new EOFException("Expected " + remaining + " more bytes");
                     }
                     dst.write(buf, 0, n);
                     remaining -= n;
                   }
                 } finally {
                   dst.close();
                 }
               } catch (IOException e) {
                 log.debug("Unexpected error copying input to CGI", e);
               }
             }
           },
           "Gitweb-InputFeeder")
       .start();
 }
示例#9
0
  @Override
  @VarZ("/dht/messages/incoming")
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    int length = request.getContentLength();
    byte[] data = new byte[length];
    DataInputStream dataIs = new DataInputStream(request.getInputStream());
    dataIs.readFully(data);
    dataIs.close();

    String hostname = request.getHeader("X-Node-Host");
    String port = request.getHeader("X-Node-Port");

    InetSocketAddress src = InetSocketAddress.createUnresolved(hostname, Integer.valueOf(port));

    try {
      DHTMessage destination =
          context.getMessageFactory().createMessage(src, ByteBuffer.wrap(data));

      varZ.log("/dht/messages/incoming/" + destination.getOpCode().name().toLowerCase());

      dispatcher.get().handleMessage(destination);
    } catch (Exception e) {
      logger.error(e);
    }
  }
    public void handle(
        String s, Request r, HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws IOException, ServletException {

      int size = 10 * 1024;
      if (httpRequest.getContentLength() > 0) {
        size = httpRequest.getContentLength();
      }
      byte[] bytes = new byte[size];
      if (bytes.length > 0) {
        final int read = httpRequest.getInputStream().read(bytes);
        httpResponse.getOutputStream().write(bytes, 0, read);
      }

      httpResponse.setStatus(200);
      httpResponse.getOutputStream().flush();
    }
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    System.out.println("开始!" + fileName);

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(maxPostSize);

    try {
      String rootPath = request.getRealPath("/");
      String filePath = rootPath + uploadPath;

      // 若该路径目录不存在,则创建
      File f = new File(filePath);
      if (!f.exists()) {
        f.mkdirs();
      }

      File f2 = new File(filePath + File.separator + fileName + ".jpg");
      if (f2.exists()) {
        out.print("文件已存在");
      } else {
        InputStream inputStream = request.getInputStream();
        FileOutputStream outputStream = new FileOutputStream(f2);

        try {
          int formlength = request.getContentLength();
          byte[] formcontent = new byte[formlength];
          int totalread = 0;
          int nowread = 0;
          while (totalread < formlength) {
            nowread = inputStream.read(formcontent, totalread, formlength);
            totalread += nowread;
          }

          outputStream.write(formcontent);
          outputStream.flush();
        } catch (IOException e) {
          e.printStackTrace();
          out.print("错误:" + e.getMessage());
        } finally {
          outputStream.close();
          inputStream.close();
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
      out.print("错误:" + e.getMessage());
    } finally {
      out.close();
    }
    System.out.println("结束");
  }
  @Test
  public void shouldProxyTheRequestMethodUriBodyAndContentType()
      throws ServletException, IOException, URISyntaxException {
    CloseableHttpClient mockHttpClient =
        mock(CloseableHttpClient.class, Mockito.RETURNS_DEEP_STUBS);

    AbstractLightblueProxyServlet servlet =
        getTestServlet(mockHttpClient, null, "http://myservice.com", null);

    HttpServletRequest stubRequest =
        new StubHttpServletRequest(
            "http://my.site.com/app/get/the/thing?foo=bar",
            "GET",
            "{test:0}",
            "application/json",
            "/get/*");

    HttpServletResponse mockResponse = mock(HttpServletResponse.class);
    ServletOutputStream outputStream = new FakeServletOutputStream(new ByteArrayOutputStream());
    when(mockResponse.getOutputStream()).thenReturn(outputStream);

    servlet.service(stubRequest, mockResponse);

    ArgumentCaptor<HttpUriRequest> requestCaptor = ArgumentCaptor.forClass(HttpUriRequest.class);

    verify(mockHttpClient).execute(requestCaptor.capture());

    HttpUriRequest request = requestCaptor.getValue();

    assertEquals("GET", request.getMethod());
    assertEquals(new URI("http://myservice.com/the/thing?foo=bar"), request.getURI());
    assertThat(request, instanceOf(HttpEntityEnclosingRequest.class));
    assertEquals(1, request.getHeaders("content-type").length);
    assertEquals("application/json", request.getHeaders("content-type")[0].getValue());

    HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) request;
    ByteArrayOutputStream entityOutStream = new ByteArrayOutputStream();
    entityEnclosingRequest.getEntity().writeTo(entityOutStream);

    byte[] expectedEntityBytes = new byte[stubRequest.getContentLength()];
    stubRequest.getInputStream().read(expectedEntityBytes, 0, stubRequest.getContentLength());

    assertEquals(new String(expectedEntityBytes), entityOutStream.toString());
  }
示例#13
0
 /** Redirect to HTTP port. */
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   HttpClient client = HttpConnectionUtil.getClient(connectionTimeout);
   // setup POST
   HttpPost post = null;
   try {
     post = new HttpPost(postAcceptorURL);
     String path = req.getContextPath();
     if (path == null) {
       path = "";
     }
     log.debug("Path: {}", path);
     if (req.getPathInfo() != null) {
       path += req.getPathInfo();
     }
     log.debug("Path 2: {}", path);
     int reqContentLength = req.getContentLength();
     if (reqContentLength > 0) {
       log.debug("Request content length: {}", reqContentLength);
       IoBuffer reqBuffer = IoBuffer.allocate(reqContentLength);
       ServletUtils.copy(req, reqBuffer.asOutputStream());
       reqBuffer.flip();
       post.setEntity(new InputStreamEntity(reqBuffer.asInputStream(), reqContentLength));
       post.addHeader("Content-Type", REQUEST_TYPE);
       // get.setPath(path);
       post.addHeader("Tunnel-request", path);
       // execute the method
       HttpResponse response = client.execute(post);
       int code = response.getStatusLine().getStatusCode();
       log.debug("HTTP response code: {}", code);
       if (code == HttpStatus.SC_OK) {
         HttpEntity entity = response.getEntity();
         if (entity != null) {
           resp.setContentType(REQUEST_TYPE);
           // get the response as bytes
           byte[] bytes = EntityUtils.toByteArray(entity);
           IoBuffer resultBuffer = IoBuffer.wrap(bytes);
           resultBuffer.flip();
           ServletUtils.copy(resultBuffer.asInputStream(), resp.getOutputStream());
           resp.flushBuffer();
         }
       } else {
         resp.sendError(code);
       }
     } else {
       resp.sendError(HttpStatus.SC_BAD_REQUEST);
     }
   } catch (Exception ex) {
     log.error("", ex);
     if (post != null) {
       post.abort();
     }
   }
 }
示例#14
0
  @Test
  public void testContentLength() {

    final int contentLength = 500;

    when(servletRequest.getContentLength()).thenReturn(contentLength);

    assertEquals(
        "The content length the underlying servlet request should be returned",
        contentLength,
        request.contentLength());
  }
示例#15
0
  public Hashtable getParts(HttpServletRequest request) throws IOException, MultipartException {
    this.parts = new Hashtable();

    // Copy all parameters coming from the request URI to the parts table.
    // This happens when a form's action attribute has some parameters
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      String[] values = request.getParameterValues(name);
      Vector v = new Vector(values.length);
      for (int i = 0; i < values.length; i++) {
        v.add(values[i]);
      }
      this.parts.put(name, v);
    }

    // upload progress bar support
    this.session = request.getSession();
    this.hasSession = this.session != null;
    if (this.hasSession) {
      this.uploadStatus = new Hashtable();
      this.uploadStatus.put("started", Boolean.FALSE);
      this.uploadStatus.put("finished", Boolean.FALSE);
      this.uploadStatus.put("sent", new Integer(0));
      this.uploadStatus.put("total", new Integer(request.getContentLength()));
      this.uploadStatus.put("filename", "");
      this.uploadStatus.put("error", Boolean.FALSE);
      this.uploadStatus.put("uploadsdone", new Integer(0));
      this.session.setAttribute(UPLOAD_STATUS_SESSION_ATTR, this.uploadStatus);
    }

    parseParts(request.getContentLength(), request.getContentType(), request.getInputStream());

    if (this.hasSession) {
      this.uploadStatus.put("finished", Boolean.TRUE);
    }

    return this.parts;
  }
示例#16
0
 public MultiPartRequest getMultiPartRequest(int maxLen)
     throws FormDataTooLongException, IOException {
   if (req.getContentType() == null || !req.getContentType().startsWith("multipart/form-data")) {
     return null;
   }
   if (req.getContentLength() > maxLen) {
     throw new FormDataTooLongException(req.getContentLength() + " bytes, " + maxLen + " allowed");
   }
   MultiPartRequest multi = new MultiPartRequest(req);
   if (log.isDebug2()) {
     String[] parts = multi.getPartNames();
     log.debug3("Multipart request, " + parts.length + " parts");
     if (log.isDebug3()) {
       for (int p = 0; p < parts.length; p++) {
         String name = parts[p];
         String cont = multi.getString(parts[p]);
         log.debug3(name + ": " + cont);
       }
     }
   }
   multiReq = multi;
   return multi;
 }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    int flowChunkNumber = getFlowChunkNumber(request);

    FlowInfo info = getFlowInfo(request);

    RandomAccessFile raf = new RandomAccessFile(info.flowFilePath, "rw");

    // Seek to position
    long offset = ((long) (flowChunkNumber - 1)) * info.flowChunkSize;

    raf.seek(offset);

    // Save to file
    InputStream is = request.getInputStream();
    long readed = 0;
    long content_length = request.getContentLength();
    byte[] bytes = new byte[1024 * 100];
    while (readed < content_length) {
      int r = is.read(bytes);
      if (r < 0) {
        break;
      }
      raf.write(bytes, 0, r);
      readed += r;
    }
    raf.close();

    // Mark as uploaded.
    info.uploadedChunks.add(new FlowInfo.FlowChunkNumber(flowChunkNumber));

    // Print the number
    System.out.println(
        "Chunk #" + flowChunkNumber + " of " + info.flowFilename + " has been uploaded.");

    if (info.checkIfUploadFinished()) { // Check if all chunks uploaded, and change filename
      FlowInfoStorage.getInstance().remove(info);
      response.getWriter().print("All finished.");

      getOptionIsoName = GetIso();
      list(info.flowFilename, getOptionIsoName);

      // System.out.println(info.flowFilename + " is completed.");

    } else {
      response.getWriter().print("Upload");
    }
  }
示例#18
0
  private void exec(
      final HttpServletRequest req, final HttpServletResponse rsp, final ProjectControl project)
      throws IOException {
    final Process proc =
        Runtime.getRuntime()
            .exec(
                new String[] {gitwebCgi.toAbsolutePath().toString()},
                makeEnv(req, project),
                gitwebCgi.toAbsolutePath().getParent().toFile());

    copyStderrToLog(proc.getErrorStream());
    if (0 < req.getContentLength()) {
      copyContentToCGI(req, proc.getOutputStream());
    } else {
      proc.getOutputStream().close();
    }

    try (InputStream in = new BufferedInputStream(proc.getInputStream(), bufferSize)) {
      readCgiHeaders(rsp, in);

      try (OutputStream out = rsp.getOutputStream()) {
        final byte[] buf = new byte[bufferSize];
        int n;
        while ((n = in.read(buf)) > 0) {
          out.write(buf, 0, n);
        }
      }
    } catch (IOException e) {
      // The browser has probably closed its input stream. We don't
      // want to continue executing this request.
      //
      proc.destroy();
      return;
    }

    try {
      proc.waitFor();

      final int status = proc.exitValue();
      if (0 != status) {
        log.error("Non-zero exit status (" + status + ") from " + gitwebCgi);
        if (!rsp.isCommitted()) {
          rsp.sendError(500);
        }
      }
    } catch (InterruptedException ie) {
      log.debug("CGI: interrupted waiting for CGI to terminate");
    }
  }
示例#19
0
  private int readInRequest(
      QueueSession session, HttpServletRequest request, HttpServletResponse response) {
    try {

      BufferedReader reader = request.getReader();
      if (!reader.ready()) return 0;
      StringAppender sb = new StringAppender(request.getContentLength());
      CharBuffer buffer = CharBuffer.allocate(10);
      int read;
      while ((read = reader.read(buffer)) > 0) {
        buffer.rewind();
        for (; read > 0; read--) {
          sb.append(buffer.get());
        }
        buffer.rewind();
      }

      Message msg =
          createCommandMessage(
              sessionProvider.getSession(
                  request.getSession(), request.getHeader(ClientMessageBus.REMOTE_QUEUE_ID_HEADER)),
              request,
              sb.toString());
      if (msg != null) {
        try {
          service.store(msg);
        } catch (Exception e) {
          if (!e.getMessage().contains("expired")) {
            writeExceptionToOutputStream(response, e);
            return 0;
          }
        }

        return 1;
      } else {
        return 0;
      }
    } catch (IOException e) {
      MessageQueue queue = service.getBus().getQueue(session);
      if (queue != null) {
        queue.stopQueue();
      }
      e.printStackTrace();
      return -1;
    }
  }
  @Override
  protected void proxy(
      String targetUrl, final HttpServletRequest request, final HttpServletResponse response)
      throws IOException {

    final HttpMethod proxyRequest = createProxyRequest(targetUrl, request);

    if (proxyRequest instanceof EntityEnclosingMethod) {
      EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) proxyRequest;
      RequestEntity requestEntity =
          new InputStreamRequestEntity(
              request.getInputStream(), request.getContentLength(), request.getContentType());
      entityEnclosingMethod.setRequestEntity(requestEntity);
    }
    int code = httpClient.executeMethod(proxyRequest);
    response.setStatus(code);
    copyProxyReponse(proxyRequest, response);
  }
示例#21
0
  Request(HttpServletRequest request) {
    raw = request;
    scheme = request.getScheme();
    method = request.getMethod();
    port = request.getServerPort();
    uri = request.getRequestURI();
    url = request.getRequestURL().toString();
    ip = request.getRemoteAddr();
    userAgent = request.getHeader(USER_AGENT);
    pathInfo = request.getPathInfo();
    protocol = request.getProtocol();
    servletPath = request.getServletPath();
    contextPath = request.getContextPath();
    contentType = request.getContentType();
    contentLength = request.getContentLength();
    queryParams = request.getParameterMap().keySet();

    cookies = cookies();
    attributes = attributes();
    headers = headers();
  }
示例#22
0
 public static String toString(HttpServletRequest request) {
   StringBuilder sb = new StringBuilder();
   String user = "******";
   Principal principal = request.getUserPrincipal();
   if (principal != null) {
     user = principal.getName();
   }
   sb.append('[')
       .append(user)
       .append("] ")
       .append(request.getMethod())
       .append(" ")
       .append(request.getRequestURI())
       .append('?')
       .append(request.getQueryString())
       .append(" ")
       .append(request.getContentType())
       .append(" ")
       .append(request.getContentLength());
   return sb.toString();
 }
示例#23
0
  public Status makeCollection(WebDAVRequest webDavRequest) throws WebDAVException {

    try {
      HttpServletRequest request = webDavRequest.getHttpServletRequest();

      if (request.getContentLength() > 0) {
        return new Status(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
      }

      String[] pathArray = webDavRequest.getPathArray();

      long companyId = webDavRequest.getCompanyId();
      long groupId = webDavRequest.getGroupId();
      long parentFolderId = getParentFolderId(companyId, pathArray);
      String name = WebDAVUtil.getResourceName(pathArray);
      String description = StringPool.BLANK;

      ServiceContext serviceContext = new ServiceContext();

      serviceContext.setAddCommunityPermissions(isAddCommunityPermissions(groupId));
      serviceContext.setAddGuestPermissions(true);
      serviceContext.setPlid(getPlid(webDavRequest.getGroupId()));
      serviceContext.setScopeGroupId(webDavRequest.getGroupId());

      IGFolderServiceUtil.addFolder(parentFolderId, name, description, serviceContext);

      String location = StringUtil.merge(pathArray, StringPool.SLASH);

      return new Status(location, HttpServletResponse.SC_CREATED);
    } catch (DuplicateFolderNameException dfne) {
      return new Status(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } catch (NoSuchFolderException nsfe) {
      return new Status(HttpServletResponse.SC_CONFLICT);
    } catch (PrincipalException pe) {
      return new Status(HttpServletResponse.SC_FORBIDDEN);
    } catch (Exception e) {
      throw new WebDAVException(e);
    }
  }
示例#24
0
  public String getPost(HttpServletRequest req) throws ServletException {
    /*    List<Object> lf = new LinkedList<Object>();
        if (isMultipartContent(req)) {
          try {
            Collection<Part> p = req.getParts();
            for (Part z : p) {
              String n = z.getName();
              Object o = readObject(z);
              // lf.set(Integer.valueOf(z.getName().substring(1)), readObject(z));
              lf.add(o);
            }
            return lf.toArray();
          } catch (ServletException sx) {
            throw new BrijjException(sx);
          } catch (IOException ix) {
            throw new BrijjException(ix);
          }
        } else {
    */

    try {
      String ce = req.getCharacterEncoding();
      InputStream is = req.getInputStream();
      InputStreamReader isr =
          ce != null ? new InputStreamReader(is, ce) : new InputStreamReader(is);
      int n = req.getContentLength();
      StringWriter sos = new StringWriter();
      char cb[] = new char[1024];
      while (true) {
        int z = isr.read(cb);
        if (z == -1) break;
        sos.write(cb, 0, z);
      }
      return sos.toString();
    } catch (Exception ex) {
      throw new ServletException("Failed to read input", ex);
    }
  }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    //		LogEvent.logFatal("IndicatorAggregationReportingServlet", "size",
    // String.valueOf(request.getContentLength()));
    ServletInputStream inputStream = request.getInputStream();

    List<ReportExternalImport> insertableImportReports = new ArrayList<ReportExternalImport>();
    List<ReportExternalImport> updatableImportReports = new ArrayList<ReportExternalImport>();

    Document sentIndicators = getDocument(inputStream, request.getContentLength());

    if (sentIndicators == null) {
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      return;
    }

    if (!authenticated(sentIndicators)) {
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      return;
    }

    /*
    This is too handle the problem where either
    1. The same lab sends a report quickly enough to cause a race condition
    2. Two different labs send a report at the same time but one is miss-configured and uses the same site id

     In both cases createReportItems considers the report a new one rather than a modification of an existing report
     */
    synchronized (this) {
      createReportItems(sentIndicators, insertableImportReports, updatableImportReports);

      updateReports(insertableImportReports, updatableImportReports);
    }

    response.setStatus(HttpServletResponse.SC_OK);
  }
示例#26
0
 private void logRequestParams(HttpServletRequest request) {
   // logger.info("Empty service specified, request originating from "
   // + request.getRemoteHost());
   logger.info("thread = " + Thread.currentThread().hashCode());
   logger.info("path = " + request.getPathInfo());
   logger.info("query = " + request.getQueryString());
   logger.info("protocol = " + request.getProtocol());
   logger.info("agent = " + request.getRemoteUser());
   logger.info("uri = " + request.getRequestURI());
   logger.info("method = " + request.getMethod());
   logger.info("contenttype = " + request.getContentType());
   logger.info("scheme = " + request.getScheme());
   logger.info("server = " + request.getServerName());
   logger.info("port = " + request.getServerPort());
   logger.info("contentlength = " + request.getContentLength());
   Enumeration<String> enm = request.getHeaderNames();
   while (enm.hasMoreElements()) {
     String key = enm.nextElement();
     String header = request.getHeader(key);
     logger.info(">>" + key + "=" + header);
   }
   return;
 }
示例#27
0
  /**
   * Returns a String with all basic request information in an HTML table.
   *
   * @return A String with all basic request information in an HTML table.
   */
  public String getRequestInfo() {
    Map info = new TreeMap();
    HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();

    info.put("authType", nullToString(req.getAuthType()));
    info.put("characterEncoding", nullToString(req.getCharacterEncoding()));
    info.put("contentLength", Integer.toString(req.getContentLength()));
    info.put("contentType", nullToString(req.getContentType()));
    info.put("contextPath", nullToString(req.getContextPath()));
    info.put("pathInfo", nullToString(req.getPathInfo()));
    info.put("protocol", nullToString(req.getProtocol()));
    info.put("queryString", nullToString(req.getQueryString()));
    info.put("remoteAddr", nullToString(req.getRemoteAddr()));
    info.put("remoteHost", nullToString(req.getRemoteHost()));
    info.put("remoteUser", nullToString(req.getRemoteUser()));
    info.put("requestURI", nullToString(req.getRequestURI()));
    info.put("scheme", nullToString(req.getScheme()));
    info.put("serverName", nullToString(req.getServerName()));
    info.put("serverPort", Integer.toString(req.getServerPort()));
    info.put("servletPath", nullToString(req.getServletPath()));

    return toHTMLTable("request properties", info);
  }
  public static String extractRequest(ServletRequest request) {
    StringBuilder str = new StringBuilder("Request received: ");

    if (request instanceof HttpServletRequest) {
      HttpServletRequest httpRequest = (HttpServletRequest) request;

      str.append(httpRequest.getMethod()).append(horizontalSeparator);
      str.append(httpRequest.getRequestURL()).append(horizontalSeparator);
      String queryString = httpRequest.getQueryString();
      if (hasText(queryString)) {
        str.append("Query string - ").append(queryString).append(horizontalSeparator);
      }
      str.append("Content length - ")
          .append(httpRequest.getContentLength())
          .append(horizontalSeparator);
      str.append("Parameters - ")
          .append(extractParameters(httpRequest.getParameterMap()))
          .append(horizontalSeparator);
      str.append("Headers - ").append(extractHeaders(httpRequest)).append(horizontalSeparator);
    }

    return str.toString();
  }
示例#29
0
  /** XCAP 8.2.2. Verifying Document Content */
  private String getContent(HttpServletRequest request, XcapResourceImpl resource)
      throws XcapException {
    if (request.getContentLength() <= 0) {
      throw new XcapException(
          "No content received ", HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
    }

    // If the MIME type in the Content-Type header field of the request is
    // not equal to the MIME type defined for the application usage, the
    // server MUST reject the request with a 415.
    if (!resource.getMimeType().equals(request.getContentType())) {
      throw new XcapException(
          "Bad content type: " + request.getContentType() + " should be:" + resource.getMimeType(),
          HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
    }

    try {
      InputStream is = request.getInputStream();
      ByteArrayOutputStream os = new ByteArrayOutputStream();
      int read;
      byte[] buffer = new byte[128];
      while ((read = is.read(buffer)) != -1) {
        os.write(buffer, 0, read);
      }
      return new String(new String(os.toByteArray()));
    } catch (Throwable e) {
      XcapException e1 =
          new XcapException("Unable to read content", HttpServletResponse.SC_CONFLICT);
      StringBuffer sb = new StringBuffer();
      sb.append(XcapException.XCAP_ERROR_HEADER);
      sb.append("<not-xml-att-value/>");
      sb.append(XcapException.XCAP_ERROR_FOOTER);

      e1.setContent(XcapException.XCAP_ERROR_CONTENT_TYPE, sb.toString().getBytes());
      throw e1;
    }
  }
示例#30
0
 /**
  * Prepare text.
  *
  * @param request The HTTP request
  * @return Builder of text
  */
 private StringBuilder text(final HttpServletRequest request) {
   final StringBuilder text = new StringBuilder();
   text.append(Logger.format("date: %s\n", new Date()));
   this.append(text, request, "code");
   this.append(text, request, "message");
   this.append(text, request, "exception_type");
   this.append(text, request, "request_uri");
   final ServletContext ctx = this.getServletContext();
   text.append(Logger.format("servlet context path: \"%s\"\n", request.getContextPath()));
   text.append(
       Logger.format(
           "requested: %s (%s) at %s:%d\n",
           request.getRequestURL().toString(),
           request.getMethod(),
           request.getServerName(),
           request.getServerPort()));
   text.append(
       Logger.format(
           "request: %s, %d bytes\n", request.getContentType(), request.getContentLength()));
   text.append(
       Logger.format(
           "remote: %s:%d (%s)\n",
           request.getRemoteAddr(), request.getRemotePort(), request.getRemoteHost()));
   text.append(
       Logger.format(
           "servlet: \"%s\" (API %d.%d) at \"%s\"\n",
           ctx.getServletContextName(),
           ctx.getMajorVersion(),
           ctx.getMinorVersion(),
           ctx.getServerInfo()));
   text.append("headers:\n").append(ExceptionTrap.headers(request)).append('\n');
   text.append(
       Logger.format(
           "exception: %[exception]s\n", request.getAttribute("javax.servlet.error.exception")));
   return text;
 }