Android Open Source - ASQLDatabase Php Executor






From Project

Back to project page ASQLDatabase.

License

The source code is released under:

GNU General Public License

If you think the Android project ASQLDatabase listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.mptr.asqldatabase;
/*from ww w .j a  v a2  s.  com*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

import android.content.Intent;
import android.util.Log;


/**
 * Executes a PHP files stored on a remote server.
 * The PHP file can be executed with additional POST messages.
 * 
 * @author Michal Poteralski <michalpoteralski@gmail.com>
 * @version 0.1
 */

public class PhpExecutor implements Runnable {
  private URL phpURLAddress;
  private HashSet<PhpExecutorListener> phpExecutorListenerList;
  private List<String> postMessagesQueue;
  private PhpExecutorRequest currentRequest;
  private URLConnection urlConnection;
  private Proxy proxyToUse;

  /**
   * Stores enumerators which represent {@link PhpExecutor} requests.
   *
   * @author Michal Poteralski <michalpoteralski@gmail.com>
   */
  public enum PhpExecutorRequest {
    OPEN_CONNECTION(0),
    OPEN_CONNECTION_WITH_PROXY(1),
    CLOSE_CONNECTION(2),
    CHECK_CONNECTION_OR_CONNECT(3),
    SEND(4);

    private final int value;

      private PhpExecutorRequest(int value) {
          this.value = value;
      }

      public int getValue() {
          return value;
      }
  }

  /**
   * Stores enumerator which represent results of {@link PhpExecutor} requests.
   *
   * @author Michal Poteralski <michalpoteralski@gmail.com>
   *
   */
  public enum PhpExecutorResult {
    RESULT_OK(0),
    RESULT_FAILED(1),
    RESULT_NOT_FINISHED(3);

    private final int value;

      private PhpExecutorResult(int value) {
          this.value = value;
      }

      public int getValue() {
          return value;
      }
  }
  
  /**
   * Creates {@link PhpExecutor} object.
   * 
   * @param phpAddress {@link URL} object which specifies address to PHP file.
   */
  public PhpExecutor(URL phpAddress) {
    this.setPhpAddress(phpAddress);
    this.phpExecutorListenerList = new HashSet<PhpExecutorListener>();
    this.postMessagesQueue = new LinkedList<String>();
  }
  
  /**
   * Synchronous method which gets PHP file address.
   *
   * @return {@link URL} object which represents PHP file URL address.
   */
  public URL getPhpAddress() {
    return phpURLAddress;
  }

  /**
   * Synchronous method which sets PHP file address.
   *
   * @param phpAddress {@link URL} object which represents PHP file URL address.
   */
  public void setPhpAddress(URL phpAddress) {
    this.phpURLAddress = phpAddress;
  }

  /**
   * Synchronous method which registers a listener which will be invoked after PHP file execution.
   * 
   * @param listener {@link PhpExecutorListener} object which represents listener.
   * @return True if listener has been successfully registered, otherwise returns false.
   */
  public boolean registerListener(PhpExecutorListener listener) {
    if (listener == null)
      return false;

    this.phpExecutorListenerList.add(listener);
    return true;
  }
  
  /**
   * Synchronous method which unregisters a listener.
   * 
   * @param listener {@link PhpExecutorListener} object which represents listener.
   * @return True if listener has been successfully unregistered, otherwise returns false.
   */
  public boolean unregisterListener(PhpExecutorListener listener) {
    if (listener == null)
      return false;
    return this.phpExecutorListenerList.remove(listener);
  }
  
  /**
   * Synchronous method which checks if listener has been registered.
   * 
   * @param listener {@link PhpExecutorListener} object which represents listener.
   * @return True is listener has been registered, otherwise returns false.
   */
  public boolean isListenerRegistered(PhpExecutorListener listener) {
    if (listener == null)
      return false;
    return this.phpExecutorListenerList.contains(listener);
  }

  /**
   * Synchronous method which adds a POST message to the queue which will be sent to PHP file.
   * 
   * @param message String which represent a POST message.
   * @return True if message has been added to the queue, otherwise returns false.
   *
   * @see #addPostMessageToQueue(String[])
   * @see #cleanPostMessagesQueue()
   * @see #getPostMessagesQueue()
   */
  
  public boolean addPostMessageToQueue(String message) {
    if (message == null || message.isEmpty())
      return false;
    return this.postMessagesQueue.add(message);
  }

  /**
   * Synchronous method which adds an array of POST message to the queue which will be sent to PHP file.
   *
   * @param messages String array which represent a POST messages.
   * @return True if all messages has been added to the queue, otherwise returns false.
   *
   * @see #addPostMessageToQueue(String)
   * @see #cleanPostMessagesQueue()
   * @see #getPostMessagesQueue()
   */
  public boolean addPostMessageToQueue(String[] messages) {
    if (messages.length == 0)
      return false;

    List<String> temporaryList = new LinkedList<String>();
    for(int itr = 0; itr < messages.length; ++itr) {
      if (messages[itr] != null || !messages[itr].isEmpty())
        temporaryList.add(messages[itr]);
      else
        return false;
    }

    return this.postMessagesQueue.addAll(temporaryList);
  }
  
  /**
   * Synchronous method which cleans up all POST messages which has been added to the POST queue.
   * 
   * @see #addPostMessageToQueue(String)
   * @see #addPostMessageToQueue(String[])
   * @see #getPostMessagesQueue()
   */
  public void cleanPostMessagesQueue() {
    this.postMessagesQueue.clear();
  }
  
  
  /**
   * Synchronous method which returns all POST messages which has been added to the POST queue.
   * @return String array which POST messages, if array is empty then return an empty String array.
   * 
   * @see #addPostMessageToQueue(String)
   * @see #addPostMessageToQueue(String[])
   * @see #cleanPostMessagesQueue()e
   */
  public String[] getPostMessagesQueue() {
    String[] strArray = new String[this.postMessagesQueue.size()];
    return this.postMessagesQueue.toArray(strArray);
  }
  
  /**
   * Asynchronous method which opens connection to PHP file.
   */
  public void openConnection() {
    // TODO Add a mutex
    this.currentRequest = PhpExecutorRequest.OPEN_CONNECTION;
    this.run();
  }
  
  /**
   * Asynchronous method which opens connection to PHP file with specified proxy.
   */
  public void openConnectioWithProxy(Proxy proxy) {
    // TODO Add a mutex
    this.currentRequest = PhpExecutorRequest.OPEN_CONNECTION_WITH_PROXY;
    this.proxyToUse = proxy;
    this.run();
  }
  
  /**
   * Asynchronous method which closes connection to PHP file.
   */
  public void closeConnection() {
    // TODO Add a mutex
    this.currentRequest = PhpExecutorRequest.CLOSE_CONNECTION;
    this.run();
  }
  
  /**
   * Asynchronous method which checks if connection can be established.
   * If connection open then open connection and check if can be established.
   */
  public void checkConnectionOrConnect() {
    // TODO Add a mutex
    this.currentRequest = PhpExecutorRequest.CHECK_CONNECTION_OR_CONNECT;
    this.run();
  }

  /**
   * Asynchronous method which sends POST messages (if specified) to the PHP file.
   * 
   * If POST messages has not been specified then just PHP file will being invoked.
   */
  public void send() {
    // TODO Add a mutex
    this.currentRequest = PhpExecutorRequest.SEND;
    this.run();
  }

  private boolean notifyAllListeners(PhpExecutorRequest requestCode, int resultCode, Intent data) {
    if (requestCode == null)
      return false;
    for (PhpExecutorListener listener : this.phpExecutorListenerList)
      listener.onPhpExecutorResult(requestCode, resultCode, data);
    return true;
  }

  private String getPostDataToSend() {
    // TODO
    return "";
  }

  @Override
  public void run() {
    switch(this.currentRequest) {
    case OPEN_CONNECTION:
      try {
        this.urlConnection = this.phpURLAddress.openConnection();
        urlConnection.setDoInput(true);
        notifyAllListeners(PhpExecutorRequest.OPEN_CONNECTION, PhpExecutorResult.RESULT_OK.value, null);
      } catch (Exception e) {
        Log.v(ASqlDatabase.ASQLDATABASE_DEBUG_TAG, "PhpExecutor: OPEN_CONNECTION failed");
        notifyAllListeners(PhpExecutorRequest.OPEN_CONNECTION, PhpExecutorResult.RESULT_FAILED.value, null);
      }
      break;
    case OPEN_CONNECTION_WITH_PROXY:
      try {
        this.urlConnection = this.phpURLAddress.openConnection(this.proxyToUse);
        this.urlConnection.setDoInput(true);
        notifyAllListeners(PhpExecutorRequest.OPEN_CONNECTION_WITH_PROXY, PhpExecutorResult.RESULT_OK.value, null);
      } catch (Exception e) {
        Log.v(ASqlDatabase.ASQLDATABASE_DEBUG_TAG, "PhpExecutor: OPEN_CONNECTION_WITH_PROXY failed");
        notifyAllListeners(PhpExecutorRequest.OPEN_CONNECTION_WITH_PROXY, PhpExecutorResult.RESULT_FAILED.value, null);
      }
      break;
    case CHECK_CONNECTION_OR_CONNECT:
      try {
        if (this.urlConnection == null)
          notifyAllListeners(PhpExecutorRequest.CHECK_CONNECTION_OR_CONNECT, PhpExecutorResult.RESULT_FAILED.value, null);
        this.urlConnection.connect();
        this.urlConnection.setDoInput(true);
        notifyAllListeners(PhpExecutorRequest.CHECK_CONNECTION_OR_CONNECT, PhpExecutorResult.RESULT_FAILED.value, null);
      } catch (Exception e) {
        Log.v(ASqlDatabase.ASQLDATABASE_DEBUG_TAG, "PhpExecutor: CHECK_CONNECTION_OR_CONNECT failed");
        notifyAllListeners(PhpExecutorRequest.CHECK_CONNECTION_OR_CONNECT, PhpExecutorResult.RESULT_FAILED.value, null);
      }
      break;
    case SEND:
      try {
        // Write and flush POST data to PHP script.
        OutputStreamWriter writer = new OutputStreamWriter(this.urlConnection.getOutputStream());
        writer.write(getPostDataToSend());
        writer.flush();

        // Read data got from PHP Script
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(
                this.urlConnection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null) {
          sb.append(line);
          break;
        }

        Intent i = new Intent();
        i.putExtra(PhpExecutorListener.INTENT_RECEIVED_DATA,
            sb.toString());
        notifyAllListeners(PhpExecutorRequest.SEND, PhpExecutorResult.RESULT_OK.value, i);
      } catch (Exception e) {
        Log.v(ASqlDatabase.ASQLDATABASE_DEBUG_TAG, "PhpExecutor: OPEN_CONNECTION failed");
        notifyAllListeners( PhpExecutorRequest.CHECK_CONNECTION_OR_CONNECT, PhpExecutorResult.RESULT_FAILED.value, null);
      }
      break;
    default:
      Log.v(ASqlDatabase.ASQLDATABASE_DEBUG_TAG, "PhpExecutor: Invalid run request");
    }
  }
}




Java Source Code List

com.mptr.asqldatabase.ASqlDatabaseListener.java
com.mptr.asqldatabase.ASqlDatabase.java
com.mptr.asqldatabase.JsonFieldName.java
com.mptr.asqldatabase.PhpExecutorListener.java
com.mptr.asqldatabase.PhpExecutor.java
com.mptr.asqldatabase.SecurityWriter.java