connection.java

来自「J2ME MIDP_Example_Applications」· Java 代码 · 共 229 行

JAVA
229
字号
// Copyright 2003 Nokia Corporation.
//
// THIS SOURCE CODE IS PROVIDED 'AS IS', WITH NO WARRANTIES WHATSOEVER,
// EXPRESS OR IMPLIED, INCLUDING ANY WARRANTY OF MERCHANTABILITY, FITNESS
// FOR ANY PARTICULAR PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE
// OR TRADE PRACTICE, RELATING TO THE SOURCE CODE OR ANY WARRANTY OTHERWISE
// ARISING OUT OF ANY PROPOSAL, SPECIFICATION, OR SAMPLE AND WITH NO
// OBLIGATION OF NOKIA TO PROVIDE THE LICENSEE WITH ANY MAINTENANCE OR
// SUPPORT. FURTHERMORE, NOKIA MAKES NO WARRANTY THAT EXERCISE OF THE
// RIGHTS GRANTED HEREUNDER DOES NOT INFRINGE OR MAY NOT CAUSE INFRINGEMENT
// OF ANY PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OWNED OR CONTROLLED
// BY THIRD PARTIES
//
// Furthermore, information provided in this source code is preliminary,
// and may be changed substantially prior to final release. Nokia Corporation
// retains the right to make changes to this source code at
// any time, without notice. This source code is provided for informational
// purposes only.
//
// Nokia and Nokia Connecting People are registered trademarks of Nokia
// Corporation.
// Java and all Java-based marks are trademarks or registered trademarks of
// Sun Microsystems, Inc.
// Other product and company names mentioned herein may be trademarks or
// trade names of their respective owners.
//
// A non-exclusive, non-transferable, worldwide, limited license is hereby
// granted to the Licensee to download, print, reproduce and modify the
// source code. The licensee has the right to market, sell, distribute and
// make available the source code in original or modified form only when
// incorporated into the programs developed by the Licensee. No other
// license, express or implied, by estoppel or otherwise, to any other
// intellectual property rights is granted herein.
package example.mesql;

import java.io.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;

public class Connection
  implements HttpPosterListener
{

  private final String proxyUrl;
  private final HttpPoster poster;
  private DBListener listener = null;


  public Connection(Display display, String proxyUrl)
  {
    this.proxyUrl = proxyUrl;
    this.poster = new HttpPoster(display, proxyUrl);
  }

  // set the listnener. Only one at a time can be used
  public void setListener(DBListener listener)
  {
    this.listener = listener;
  }

  // stops the HTTP thread
  public void destroy()
  {
    poster.abort();
  }

  // used by other classes in the package to send queries
  void sendSimpleQuery(String query,
                       int maxrows,
                       Vector variables)
  {
    try
    {
      StringBuffer postContent = createPost(query, variables);
      if (maxrows > 0)
      {
        postContent.append("&maxrows=").append(maxrows);
      }
      poster.sendRequest(HttpConnection.POST,
                         "application/x-www-form-urlencoded",
                         postContent.toString(),
                         this);
    }
    catch (IOException e)
    {
      if (listener != null)
      {
        listener.receiveSQLException(new SQLException(e.getMessage()));
      }
    }
  }

  // used by other classes in the package to send updates
  void sendUpdate(String query, Vector variables)
  {
    try
    {
      StringBuffer postContent = createPost(query, variables);
      poster.sendRequest(HttpConnection.POST,
                         "application/x-www-form-urlencoded",
                         postContent.toString(),
                         this);
    }
    catch (IOException e)
    {
      if (listener != null)
      {
        listener.receiveSQLException(new SQLException(e.getMessage()));
      }
    }
  }

  // creates the variables included in the post's body
  private StringBuffer createPost(String query, Vector variables)
  {
    StringBuffer postContent = new StringBuffer("query=");
    postContent.append(Codec.encode(query));
    if (variables != null && variables.size() > 0)
    {
      for (int i = 0; i < variables.size(); i++)
      {
        Parameter p = (Parameter) variables.elementAt(i);
        postContent.append("&value").append(p.index).append("=");
        postContent.append(Codec.encode(p.content.toString()));
        postContent.append("&type").append(p.index).append("=");
        postContent.append(p.type);
      }
    }
    return postContent;
  }


  // parses the result of an update
  private int parseUpdate(String response)
    throws SQLException
  {
    // sanity checks
    Tokenizer t = new Tokenizer(response, '\n');
    if (!"OK".equals(t.nextElement()))
    {
      throw new SQLException("Update response incorrect");
    }
    if (!"UPDATE".equals(t.nextElement()))
    {
      throw new SQLException("Update response incorrect");
    }
    try {
      return Integer.parseInt((String) t.nextElement());
    } catch (NumberFormatException e) {
      throw new SQLException(e.getMessage());
    }
  }

  // builds a statement object
  public Statement createStatement()
  {
    return new Statement(this);
  }

  // builds a prepared statement object based on a sql command
  public PreparedStatement prepareStatement(String sql)
  {
    return new PreparedStatement(this, sql);
  }

  // parses the server's response
  public void receiveHttpResponse(String response)
  {
    if (listener != null)
    {
      if (response.startsWith("ERROR"))
      {
        // report an error in the server side
        listener.receiveSQLException(
          new SQLException(response.substring(6)));
      }
      else if (response.startsWith("OK\nSELECT"))
      {
        // report a result
        try {
          listener.receiveQueryResponse(new ResultSet(response));
        } catch (SQLException e) {
          // parsing failed
          listener.receiveSQLException(e);
        }
      }
      else
      {
        // report an update
        response = response.substring(3);
        try {
          if (response.startsWith("UPDATE"))
          {
            int count = Integer.parseInt(response.substring(7));
            listener.receiveUpdateResponse(count,
                                           SQLConstants.UPDATE);
          }
          else if (response.startsWith("INSERT"))
          {
            int count = Integer.parseInt(response.substring(7));
            listener.receiveUpdateResponse(count,
                                           SQLConstants.INSERT);
          }
          if (response.startsWith("DELETE"))
          {
            int count = Integer.parseInt(response.substring(7));
            listener.receiveUpdateResponse(count,
                                           SQLConstants.DELETE);
          }
        } catch (NumberFormatException e) {
         listener.receiveSQLException(new SQLException(e.getMessage()));
        }
      }
    }
  }


  public void handleHttpError(String errorStr)
  {
    // report the error to the listener, otherwise ignore
    if (listener != null)
    {
      listener.receiveSQLException(new SQLException(errorStr));
    }
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?