@Override
  public HTTPResponse update(HTTPRequest request, HTTPResponse response) {
    Key key = Key.create(request, response);
    Connection connection = getConnection();

    PreparedStatement statement = null;
    try {
      JdbcUtil.startTransaction(connection);
      statement =
          connection.prepareStatement(
              "update response set headers = ?, cachetime = ? where uri = ? and vary = ?");
      statement.setString(1, response.getHeaders().toJSON());
      statement.setTimestamp(2, new Timestamp(DateTimeUtils.currentTimeMillis()));
      statement.setString(3, key.getURI().toString());
      statement.setString(4, key.getVary().toJSON());
      statement.executeUpdate();
      connection.commit();
      return getImpl(connection, key);
    } catch (SQLException e) {
      JdbcUtil.rollback(connection);
      JdbcUtil.close(connection);
      throw new DataAccessException(e);
    } finally {
      JdbcUtil.endTransaction(connection);
      JdbcUtil.close(statement);
    }
  }
Beispiel #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();
  }
  @Override
  public HTTPResponse insert(HTTPRequest request, HTTPResponse response) {
    Key key = Key.create(request, response);
    Connection connection = getConnection();

    String sql =
        "insert into response(uri, vary, status, headers, payload, mimeType, cachetime) values (?, ?, ?, ?, ?, ?, ?)";
    PreparedStatement statement = null;
    try {
      JdbcUtil.startTransaction(connection);
      invalidate(key, connection);
      statement = connection.prepareStatement(sql);
      statement.setString(1, key.getURI().toString());
      statement.setString(2, key.getVary().toJSON());
      statement.setInt(3, response.getStatus().getCode());
      statement.setString(4, response.getHeaders().toJSON());
      InputStream inputStream = null;
      if (response.hasPayload() && response.getPayload().isAvailable()) {
        statement.setString(6, response.getPayload().getMimeType().toString());
        inputStream = response.getPayload().getInputStream();
        statement.setBinaryStream(5, inputStream);
      } else {
        statement.setNull(5, Types.BLOB);
        statement.setNull(6, Types.VARCHAR);
      }
      statement.setTimestamp(7, new Timestamp(DateTimeUtils.currentTimeMillis()));
      try {
        statement.executeUpdate();
      } finally {
        IOUtils.closeQuietly(inputStream);
      }
      connection.commit();
      return getImpl(connection, key);
    } catch (SQLException e) {
      JdbcUtil.rollback(connection);
      JdbcUtil.close(connection);
      throw new DataAccessException(e);
    } finally {
      JdbcUtil.endTransaction(connection);
      JdbcUtil.close(statement);
    }
  }
  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;
  }