示例#1
0
  /**
   * Test concurrent reader and writer (GH-458).
   *
   * <p><b>Test case:</b>
   *
   * <ol>
   *   <li/>start a long running reader;
   *   <li/>try to start a writer: it should time out;
   *   <li/>stop the reader;
   *   <li/>start the writer again: it should succeed.
   * </ol>
   *
   * @throws Exception error during request execution
   */
  @Test
  @Ignore("There is no way to stop a query on the server!")
  public void testReaderWriter() throws Exception {
    final String readerQuery = "?query=(1%20to%20100000000000000)%5b.=1%5d";
    final String writerQuery = "/test.xml";
    final byte[] content = Token.token("<a/>");

    final Get readerAction = new Get(readerQuery);
    final Put writerAction = new Put(writerQuery, content);

    final ExecutorService exec = Executors.newFixedThreadPool(2);

    // start reader
    exec.submit(readerAction);
    Performance.sleep(TIMEOUT); // delay in order to be sure that the reader has started
    // start writer
    Future<HTTPResponse> writer = exec.submit(writerAction);

    try {
      final HTTPResponse result = writer.get(TIMEOUT, TimeUnit.MILLISECONDS);

      if (result.status.isSuccess()) fail("Database modified while a reader is running");
      throw new Exception(result.toString());
    } catch (final TimeoutException e) {
      // writer is blocked by the reader: stop it
      writerAction.stop = true;
    }

    // stop reader
    readerAction.stop = true;

    // start the writer again
    writer = exec.submit(writerAction);
    assertEquals(HTTPCode.CREATED, writer.get().status);
  }
示例#2
0
  /**
   * This method takes care of some special generic Maui events. It should be called before the Maui
   * application handles the event.
   *
   * @param mauiApp Reference to the MauiApplication associated with the events
   * @param eventVector The same event vector that is passed to the Maui app.
   * @param paramHash Hashtable of HTTP parameters
   * @param response The HTTPResponse object which will be sent back to the client
   */
  private void processEvent(
      MauiApplication mauiApp,
      Vector eventVector,
      Hashtable paramHash,
      HTTPRequest request,
      HTTPResponse response) {
    boolean passEventToMauiApp = true;

    try {
      if (eventVector != null && !eventVector.isEmpty()) {
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // Component events
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        String componentID = (String) eventVector.lastElement();

        // If there are parentheses...
        if (componentID.startsWith("(") && componentID.endsWith(")")) {
          // ... strip them off!
          componentID = componentID.substring(1, componentID.length() - 1);
        }

        //
        //	Strip off prefix - some wml browsers don't like variables that begin with a digit
        //
        if (componentID.startsWith("IDz")) {
          componentID = componentID.substring(3);
        }
        {
          System.err.println("componentID: " + componentID);
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // Pass events to Maui application
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        // Check for a content-type override
        String contentType = null;
        {
          if ((contentType = request.getQueryValue("contentType")) != null) {
            response.setContentType(contentType);
          } else {
            response.setContentType("x-wap.wml");
          }
        }
        response.setContent(mauiApp.render().getBytes());
      } else {
        response.setContentType("text/vnd.wap.wml");
        response.setContent(mauiApp.render().getBytes());
      }
    } catch (Exception e) {
      response.setContentType(getBaseContentType());
      response.setContent((generateExceptionMessage(e)).getBytes());
      e.printStackTrace(System.err);
    }
  }
  public boolean post(HTTPResponse httpRes) {
    HTTPSocket httpSock = getSocket();
    long offset = 0;
    long length = httpRes.getContentLength();
    if (hasContentRange() == true) {
      long firstPos = getContentRangeFirstPosition();
      long lastPos = getContentRangeLastPosition();

      // Thanks for Brent Hills (10/26/04)
      if (lastPos <= 0) lastPos = length - 1;
      if ((firstPos > length) || (lastPos > length))
        return returnResponse(HTTPStatus.INVALID_RANGE);
      httpRes.setContentRange(firstPos, lastPos, length);
      httpRes.setStatusCode(HTTPStatus.PARTIAL_CONTENT);

      offset = firstPos;
      length = lastPos - firstPos + 1;
    }
    return httpSock.post(httpRes, offset, length, isHeadRequest());
    // httpSock.close();
  }
示例#4
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    int index;

    DatastoreService ds;
    MemcacheService ms;
    BlobstoreService bs;
    URLFetchService us;
    FileService fs;

    Map<String, List<BlobKey>> blobMap;
    BlobKey blobKey;
    BlobInfoFactory blobInfoFactory;
    BlobInfo blobInfo;

    int postCount;
    int postIndex;
    String postType;
    String postText;
    String postDelpw;
    String postShowgallery;
    DataObj dataObj;
    String filelink;

    String picUrl;
    HTTPResponse picRes;
    List<HTTPHeader> headerList;
    String picMime;
    String[] fileNamePart;
    AppEngineFile picFile;
    FileWriteChannel writeChannel;

    PostObj postObj;
    List<PostObj> postObjList;
    String linkID;

    resp.setCharacterEncoding("UTF-8");
    resp.setContentType("text/plain");

    try {
      ds = DatastoreServiceFactory.getDatastoreService();
      ms = MemcacheServiceFactory.getMemcacheService();
      bs = BlobstoreServiceFactory.getBlobstoreService();
      us = URLFetchServiceFactory.getURLFetchService();
      fs = FileServiceFactory.getFileService();
      blobInfoFactory = new BlobInfoFactory(ds);

      blobMap = bs.getUploads(req);
      postCount = Integer.valueOf(req.getParameter("input_post_count"));
      postObjList = new ArrayList<PostObj>();

      for (postIndex = 0; postIndex < postCount; postIndex++) {
        try {
          postType = req.getParameter("input_post_type_" + postIndex);
          if (postType == null) {
            continue;
          }

          postText = req.getParameter("input_post_text_" + postIndex);
          postDelpw = req.getParameter("input_post_delpw_" + postIndex);
          postShowgallery = req.getParameter("input_post_showgallery_" + postIndex);
          if (postShowgallery == null) {
            postShowgallery = "";
          }

          if (postType.equals("file") == true) {
            blobKey = blobMap.get("input_post_file_" + postIndex).get(0);
            if (blobKey == null) {
              throw new Exception();
            }

            dataObj = new DataObj();
            dataObj.fileid = createUID();
            dataObj.posttime = new Date().getTime();
            dataObj.delpw = postDelpw;
            dataObj.blobkey = blobKey;
            dataObj.putDB(ds);

            blobInfo = blobInfoFactory.loadBlobInfo(dataObj.blobkey);
            filelink =
                "http://"
                    + req.getServerName()
                    + "/down/"
                    + dataObj.fileid
                    + "/"
                    + blobInfo.getFilename();
            postObj =
                new PostObj(
                    dataObj.fileid,
                    filelink,
                    blobInfo.getSize(),
                    dataObj.posttime,
                    dataObj.delpw,
                    postShowgallery);
            postObjList.add(postObj);
          } else if (postType.equals("url") == true) {
            picUrl = postText;

            picRes = us.fetch(new URL(picUrl));
            headerList = picRes.getHeaders();
            picMime = "application/octet-stream";
            for (index = 0; index < headerList.size(); index++) {
              if (headerList.get(index).getName().compareToIgnoreCase("Content-Type") == 0) {
                picMime = headerList.get(index).getValue();
                break;
              }
            }

            fileNamePart = picUrl.split("/");

            picFile = fs.createNewBlobFile(picMime, fileNamePart[fileNamePart.length - 1]);
            writeChannel = fs.openWriteChannel(picFile, true);
            writeChannel.write(ByteBuffer.wrap(picRes.getContent()));
            writeChannel.closeFinally();

            dataObj = new DataObj();
            dataObj.fileid = createUID();
            dataObj.posttime = new Date().getTime();
            dataObj.delpw = postDelpw;
            dataObj.blobkey = fs.getBlobKey(picFile);
            dataObj.putDB(ds);

            blobInfo = blobInfoFactory.loadBlobInfo(dataObj.blobkey);
            filelink =
                "http://"
                    + req.getServerName()
                    + "/down/"
                    + dataObj.fileid
                    + "/"
                    + blobInfo.getFilename();
            postObj =
                new PostObj(
                    dataObj.fileid,
                    filelink,
                    blobInfo.getSize(),
                    dataObj.posttime,
                    dataObj.delpw,
                    postShowgallery);
            postObjList.add(postObj);
          }
        } catch (Exception e) {
        }
      }

      linkID = postFile(us, postObjList);

      if (req.getParameter("specflag") != null) {
        resp.getWriter().print("http://tnfshmoe.appspot.com/link.jsp?linkid=" + linkID);
      } else {
        resp.sendRedirect("http://tnfshmoe.appspot.com/link.jsp?linkid=" + linkID);
      }
    } catch (Exception e) {
    }
  }
 public boolean returnResponse(int statusCode) {
   HTTPResponse httpRes = new HTTPResponse();
   httpRes.setStatusCode(statusCode);
   httpRes.setContentLength(0);
   return post(httpRes);
 }
  public HTTPResponse post(String host, int port, boolean isKeepAlive) {
    HTTPResponse httpRes = new HTTPResponse();

    setConnection((isKeepAlive == true) ? HTTP.KEEP_ALIVE : HTTP.CLOSE);

    boolean isHeaderRequest = isHeadRequest();

    OutputStream out = null;
    InputStream in = null;

    try {
      if (postSocket == null) postSocket = new Socket(host, port);

      out = postSocket.getOutputStream();
      PrintStream pout = new PrintStream(out);
      pout.print(getHeader());
      pout.print(HTTP.CRLF);

      boolean isChunkedRequest = isChunked();

      String content = getContentString();
      int contentLength = 0;
      if (content != null) contentLength = content.length();

      if (0 < contentLength) {
        if (isChunkedRequest == true) {
          String chunSizeBuf = Long.toString(contentLength);
          pout.print(chunSizeBuf);
          pout.print(HTTP.CRLF);
        }
        pout.print(content);
        if (isChunkedRequest == true) pout.print(HTTP.CRLF);
      }

      if (isChunkedRequest == true) {
        pout.print("0");
        pout.print(HTTP.CRLF);
      }

      pout.flush();

      in = postSocket.getInputStream();
      httpRes.set(in, isHeaderRequest);
    } catch (Exception e) {
      httpRes.setStatusCode(HTTPStatus.INTERNAL_SERVER_ERROR);
    } finally {
      if (isKeepAlive == false) {
        try {
          in.close();
        } catch (Exception e) {
        }
        ;
        if (in != null)
          try {
            out.close();
          } catch (Exception e) {
          }
        ;
        if (out != null)
          try {
            postSocket.close();
          } catch (Exception e) {
          }
        ;
        postSocket = null;
      }
    }

    return httpRes;
  }