ヘッダーをスキップ
Oracle® Virtual Assembly Builder開発者ガイド
11g リリース1(11.1.1.6)
B66716-01
  目次へ移動
目次
索引へ移動
索引

前
 
次
 

5 サンプル・アプリケーション

次の項では、WebサービスAPIを含むサンプル・アプリケーションについて説明します。

5.1 サンプル・アプリケーション

次のサンプル・アプリケーションは、一般的なOracle VM 3.0プラットフォームでアセンブリ・アーカイブをデプロイするための各手順の実行方法を示しています。

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Hashtable;
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedList;
import javax.net.SocketFactory;
import javax.net.ssl.*;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
 
public class OvabSamples
{
 
  private static final String OVM_URL = "https://myovm:7001";
  private static final String OVM_POOL_NAME = "mypool";
  private static final String OVM_ADMIN_NAME = "admin";
  private static final String OVM_ADMIN_PWD = "your ovm admin password";
  private static final String TARGET_NAME = "ovm-target";
 
  private static final String KEYSTORE_FILE = "/ab_home/ab_instance/config/deployer/DeployerTrust.jks";
  private static final String TRUSTSTORE_FILE = "/ab_home/ab_instance/config/deployer/DeployerTrust.jks";
  private static final String TRUSTSTORE_PASSWORD = "your truststore password";
 
  private static final String ASSEMBLY_NAME = "MyAssembly";
 
  private static final String OVA_FILE="/archives/BaseWLS.ova";
  private static final String PLAN_FILE="/plans/BaseWLSQAPlan.xml";
 
  private static final String DEPLOYER_URL = "https://localhost:7002";
  private static final String CLOUD_ADMIN_USERNAME="cloudAdmin";
  private static final String CLOUD_ADMIN_PASSWORD="cloud admin password";
  private static final String APPLICATION_ADMIN_USERNAME="applicationAdmin";
  private static final String APPLICATION_ADMIN_PASSWORD="application administrator";
 
  /*
   * This example shows how to deploy an OVA end-to-end on the standard OVAB Deployer.
   */
  public static void main(String[] args) throws Exception {
 
    createOvmTarget();
    addOvmTargetUser();
    uploadAssemblyArchive();
 
    int version = registerAssemblyArchive();
    if (version >= 0) {
      String assemblyInstanceId = createAssemblyInstance(version);
      if (deployAssemblyInstance(assemblyInstanceId)) {
        message("Creation of Assembly Instance Succeeded");
      } else {
        message("Creation of Assembly Instance Failed");
      }
    } else {
      message("Registration Failed");
    }
 
  }
 
  /*
   * When using the generic Deployer, you need to define a target.
   * The target includes configuration for the backend system. In
   * this example, the backend system is Oracle VM 3. 
   *
   * This operation is not used for the Oracle Exalogic Deployer as the
   * one target for Exalogic systems is pre-defined.
   */
  public static void createOvmTarget() throws Exception {
 
    message("CREATE Oracle VM target "+TARGET_NAME);
 
    // Set up connection
    HttpURLConnection conn = getConnection(DEPLOYER_URL+"/ovab/admin");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    String params = 
      "Action=CreateTarget" +
      "&target=" + TARGET_NAME +
      "&type=ovm" +
      "&default=false" +
      "&ovm.poolName=" + OVM_POOL_NAME +
      "&ovm.vmOperationTimeout=600000" +
      "&ovm.vmmversion=3.0" +
      "&ovm.user=" + OVM_ADMIN_NAME +
      "&ovm.url=" + OVM_URL +
      "&ovm.pwd=" + OVM_ADMIN_PWD;
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", "" + params.length());
 
    // Use Cloud Admin Credentials
    sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
    String encodedCredentials = 
      enc.encode(new String(CLOUD_ADMIN_USERNAME + ":" + CLOUD_ADMIN_PASSWORD).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + encodedCredentials);
 
    // Make the request
    try {
      conn.connect();
      // send the parameters
      OutputStream os = conn.getOutputStream();
      os.write(params.getBytes("UTF-8"));
      os.close();
 
      // Read the response
      Map<String, String> info = handleSuccessResponse(conn);
      for (Map.Entry<String, String> entry : info.entrySet()) {
        message("    "+entry.getKey()+"="+entry.getValue());
      }
      message("Create result: "+info);
      message("SUCCESS");
 
    } catch (Exception e) {
      Map<String, String> info = handleException(conn, e);
      for (Map.Entry<String, String> entry : info.entrySet()) {
        message("    "+entry.getKey()+"="+entry.getValue());
      }
    }
 
  }
  
  /*
   * For Oracle VM 3, users must be authorized by the administrator to use a target
   *
   * For Oracle Exalogic, the user calls this operation to provide  his or her own credentials
   */
  public static void addOvmTargetUser() throws Exception {
 
    message("ADD Oracle VM target user "+TARGET_NAME);
 
    // Set up connection
    HttpURLConnection conn = getConnection(DEPLOYER_URL+"/ovab/admin");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    String params = 
      "Action=AddTargetUser"+
      "&user=" + APPLICATION_ADMIN_USERNAME +
      "&target=" + TARGET_NAME;
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", "" + params.length());
 
    // Use Admin credentials
    sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
    String encodedCredentials = 
      enc.encode(new String(CLOUD_ADMIN_USERNAME + ":" + CLOUD_ADMIN_PASSWORD).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + encodedCredentials);
 
    // Make the request
    try {
      conn.connect();
      // send the parameters
      OutputStream os = conn.getOutputStream();
      os.write(params.getBytes("UTF-8"));
      os.close();
      // Read the response
      Map<String, String> info = handleSuccessResponse(conn);
      for (Map.Entry<String, String> entry : info.entrySet()) {
        message("    "+entry.getKey()+"="+entry.getValue());
      }
      message("SUCCESS");
 
    } catch (Exception e) {
      Map<String, String> info = handleException(conn, e);
      for (Map.Entry<String, String> entry : info.entrySet()) {
        message("    "+entry.getKey()+"="+entry.getValue());
      }
    }
 
  }
  
 
  /*
   * This is an example of how to upload an OVA from the client to the Deployer repository.
   */
  public static void uploadAssemblyArchive() throws Exception {
    message("UPLOAD OVA");
    // Set up connection
    HttpURLConnection conn = 
      getConnection(DEPLOYER_URL+
                    "/ovab/deployer"+
                    "?Action=UploadAssemblyArchive"+
                    "&assembly.name="+ASSEMBLY_NAME+
                    "&assembly.desc="+"my sample assembly");
 
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/octet-stream");
    conn.setChunkedStreamingMode(0);
 
    sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
    String encodedCredentials = 
      enc.encode(new String(APPLICATION_ADMIN_USERNAME + ":" + APPLICATION_ADMIN_PASSWORD).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + encodedCredentials);
 
    // Make the request
    try {
      conn.connect();
 
      int bytesRead, bufferSize;
      int maxBufferSize = 1 * 1024 * 1024;
      byte[] buffer;
      File f = new File(OVA_FILE);
      FileInputStream fis = new FileInputStream(f);
      bufferSize = Math.min(fis.available(), maxBufferSize);
      buffer = new byte[bufferSize];
      bytesRead = fis.read(buffer, 0, bufferSize);
 
      OutputStream os = conn.getOutputStream();
      while (bytesRead > 0) {
        os.write(buffer, 0, bufferSize);
        bufferSize = Math.min(fis.available(), maxBufferSize);
        bytesRead = fis.read(buffer, 0, bufferSize);
      }
      fis.close();
      os.flush();
      os.close();
 
      // Read the response
      Map<String, String> info = handleSuccessResponse(conn);
      for (Map.Entry<String, String> entry : info.entrySet()) {
        message("    "+entry.getKey()+"="+entry.getValue());
      }
      message("SUCCESS");
 
    } catch (Exception e) {
      Map<String, String> info = handleException(conn, e);
      for (Map.Entry<String, String> entry : info.entrySet()) {
        message("    "+entry.getKey()+"="+entry.getValue());
      }
    }
 
 
  }
  
  /*
   * This is an example of how to register an assembly archive from the Deployer
   * repository to the backend system
   *
   * Registration is an asynchronous task, so this method calls
   * another method to wait for the asynchronous request to complete
   * before returning.
   */
  public static int registerAssemblyArchive() throws Exception {
 
    message("REGISTER Assembly Archive");
 
    // Set up connection
    String params = 
      "Action=RegisterAssemblyArchive"+
      "&assembly.name="+ASSEMBLY_NAME+
      "&target="+TARGET_NAME;
    HttpURLConnection conn = getConnection(DEPLOYER_URL+"/ovab/deployer?"+params);
    conn.setDoInput(true);
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", "" + params.length());
 
    // Use Application Admin Credentials
    sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
    String encodedCredentials = 
      enc.encode(new String(APPLICATION_ADMIN_USERNAME + ":" + APPLICATION_ADMIN_PASSWORD).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + encodedCredentials);
 
    // Make the request
    try {
      conn.connect();
 
      // Read the response
      message("    Async Registration Request Initiated");
      Map<String, String> info = handleSuccessResponse(conn);
      String requestId =  info.get("RegisterAssemblyArchiveResult.requestId");
 
      // Wait for the request to complete
      if (waitForRequest(requestId)) {
        // return the version registered. This is used later for creating the deployment
        int version = Integer.parseInt(info.get("RegisterAssemblyArchiveResult.version"));
        return version;
      } else {
        return -1;
      }
 
    } catch (Exception e) {
      Map<String, String> info = handleException(conn, e);
      for (Map.Entry<String, String> entry : info.entrySet()) {
        message("    "+entry.getKey()+"="+entry.getValue());
      }
      return -1;
    }
 
  }
 
  /*
   * This method shows how to wait for the completion of an asynchronous Deployer request.
   * This is used by the examples for registration and deployment of an assembly archive.
   */
  public static boolean waitForRequest(String id) throws Exception {
 
    String status = "RUNNING";
 
    while ("RUNNING".equals(status)) {
      message("    Async request "+id+" is still in progress");
 
      // Set up connection
      String params = 
        "Action=DescribeRequests"+
        "&request.id="+id;
 
      HttpURLConnection conn = getConnection(DEPLOYER_URL+"/ovab/deployer?"+params);
      conn.setDoInput(true);
      conn.setRequestMethod("GET");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      conn.setRequestProperty("Content-Length", "" + params.length());
 
      // Use Application Admin Credentials
      sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
      String encodedCredentials = 
        enc.encode(new String(APPLICATION_ADMIN_USERNAME + ":" + APPLICATION_ADMIN_PASSWORD).getBytes());
      conn.setRequestProperty("Authorization", "Basic " + encodedCredentials);
 
      // Make the request
      try {
        conn.connect();
 
        // Read the response
        Map<String, String> info = handleSuccessResponse(conn);
        status = info.get("DescribeRequestsResult.requestInfo.requestStatus");
 
        try { Thread.sleep(30*1000); } catch (InterruptedException e) { }
 
      } catch (Exception e) {
        Map<String, String> info = handleException(conn, e);
        for (Map.Entry<String, String> entry : info.entrySet()) {
          message("    "+entry.getKey()+"="+entry.getValue());
        }
        return false;
      }
    }
 
    message("    Request status is "+status);
    if ("SUCCEEDED".equals(status)) {
      return true;
    } else {
      return false;
    }
  }
 
  /*
   * This is an example of creating an assembly instance. This is a POST
   * operation because the deployment plan is supplied in this step.
   */
  public static String createAssemblyInstance(int version) throws Exception {
    message("CREATE Deployment");
    // Set up connection
 
    String urlStr = 
      DEPLOYER_URL+
      "/ovab/deployer?"+
      "Action=CreateAssemblyInstance&assembly.name="+ASSEMBLY_NAME+
      "&assembly.version="+version+
      "&target="+TARGET_NAME;
 
    HttpURLConnection conn = 
      getConnection(urlStr);
 
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/octet-stream");
    conn.setChunkedStreamingMode(0);
 
    sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
    String encodedCredentials = 
      enc.encode(new String(APPLICATION_ADMIN_USERNAME + ":" + APPLICATION_ADMIN_PASSWORD).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + encodedCredentials);
 
    // Make the request
    try {
      conn.connect();
 
      // Read plan document from a file and write to the web service
      int bytesRead, bufferSize;
      int maxBufferSize = 1 * 1024 * 1024;
      byte[] buffer;
      File f = new File(PLAN_FILE);
      FileInputStream fis = new FileInputStream(f);
      bufferSize = Math.min(fis.available(), maxBufferSize);
      buffer = new byte[bufferSize];
      bytesRead = fis.read(buffer, 0, bufferSize);
      OutputStream os = conn.getOutputStream();
      while (bytesRead > 0) {
        os.write(buffer, 0, bufferSize);
        bufferSize = Math.min(fis.available(), maxBufferSize);
        bytesRead = fis.read(buffer, 0, bufferSize);
      }
      fis.close();
      os.flush();
      os.close();
 
      // Read the response
      Map<String, String> info = handleSuccessResponse(conn);
      message("Deployment Created");
      for (Map.Entry<String, String> entry : info.entrySet()) {
        message("    "+entry.getKey()+"="+entry.getValue());
      }
 
      String assemblyInstanceId = info.get("CreateAssemblyInstanceResult.assemblyInstanceId");
      return assemblyInstanceId;
 
    } catch (Exception e) {
      Map<String, String> info = handleException(conn, e);
      for (Map.Entry<String, String> entry : info.entrySet()) {
        message("    "+entry.getKey()+"="+entry.getValue());
      }
 
    }
 
    return null;
 
  }
 
  /*
   * This is an example of how to deploy an Assembly Instance
   *
   * Deployment is an asynchronous task, so this method calls
   * another method to wait for the asynchronous request to complete
   * before returning.
   *
   */
  public static boolean deployAssemblyInstance(String assemblyInstanceId) throws Exception {
 
    message("Deploy Assembly Instance");
 
    // Set up connection
    String params = 
      "Action=DeployAssemblyInstance"+
      "&assembly.instance.id="+assemblyInstanceId;
    HttpURLConnection conn = getConnection(DEPLOYER_URL+"/ovab/deployer?"+params);
    conn.setDoInput(true);
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", "" + params.length());
 
    // Use Application Admin Credentials
    sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
    String encodedCredentials = 
      enc.encode(new String(APPLICATION_ADMIN_USERNAME + ":" + APPLICATION_ADMIN_PASSWORD).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + encodedCredentials);
 
    // Make the request
    try {
      conn.connect();
 
      // Read the response
      message("    Async Deployment Request Initiated");
      Map<String, String> info = handleSuccessResponse(conn);
      for (Map.Entry<String, String> entry : info.entrySet()) {
        message("    "+entry.getKey()+"="+entry.getValue());
      }
 
      // Wait for the deployment to complete
      String requestId = info.get("DeployAssemblyInstanceResult.requestId");
      return waitForRequest(requestId);
 
    } catch (Exception e) {
      Map<String, String> info = handleException(conn, e);
      for (Map.Entry<String, String> entry : info.entrySet()) {
        message("    "+entry.getKey()+"="+entry.getValue());
      }
      return false;
    }
 
  }
 
 
  /*
   * This is a convenient method for creating an SSL connection to the Deployer
   */
  public static HttpURLConnection getConnection(String urlString) throws Exception {
    URL url = new URL(urlString);
 
    if (false) {
      return (HttpURLConnection) url.openConnection();
    }
 
    // Need to setup SSL connection
    SocketFactory sf = null;
    final String ALGORITHM = "sunx509";
    // For Testing
    // For testing
    String pw = TRUSTSTORE_PASSWORD;
    final char[] keystorePass = pw.toCharArray();
    final char[] truststorePass = pw.toCharArray();
 
    // create the private keyStore
    KeyStore ksPrivate;
    ksPrivate = KeyStore.getInstance("JKS");
    ksPrivate.load(new FileInputStream(KEYSTORE_FILE), keystorePass);
 
    // create the factory for the private key
    KeyManagerFactory keyManagerFactory;
    keyManagerFactory = KeyManagerFactory.getInstance(ALGORITHM);
    keyManagerFactory.init(ksPrivate, keystorePass);
 
    // create now the trusted keyStore
    KeyStore ksTrusted;
    ksTrusted = KeyStore.getInstance("JKS");
    ksTrusted.load(new FileInputStream(TRUSTSTORE_FILE), truststorePass);
 
    // create a trust manager factory using the same algorithm.
    TrustManagerFactory trustManagerFactory;
    trustManagerFactory = TrustManagerFactory.getInstance(ALGORITHM);
    trustManagerFactory.init(ksTrusted);
 
    SSLContext sslc = SSLContext.getInstance("TLS");
    sslc.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
 
    sf = sslc.getSocketFactory();
    HttpsURLConnection httpsURLConn = (HttpsURLConnection)url.openConnection();
    httpsURLConn.setSSLSocketFactory((SSLSocketFactory) sf);
 
    httpsURLConn.setHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String host, SSLSession sslsession) {
          return true;
        }
      });
    return (HttpURLConnection)httpsURLConn;
 
  }
 
  /*
   * This is a convenience method for extracting the information in the
   * response from a failed Deployer Web service call.
   */
  public static Map<String,String> handleException(HttpURLConnection conn, Exception e) throws IOException, SAXException {
 
    Map<String,String> result = new HashMap<String,String>();
 
    message("ERROR: "+e.getMessage());
    message("RESPONSE CODE: "+conn.getResponseCode());
    if (conn.getResponseCode() == (HttpURLConnection.HTTP_NOT_FOUND)) {
      message("Invalid request, web service not found");
      return result;
    } else if (conn.getResponseCode() == (HttpURLConnection.HTTP_UNAUTHORIZED)) {
      message("User is not authorized to perform this action");
      return result;
    } else if (conn.getResponseCode() == (HttpURLConnection.HTTP_FORBIDDEN)) {
      message("User is not authorized to perform this action");
      return result;
    }
 
    // Read the response
    DataInputStream input = new DataInputStream(conn.getErrorStream());
    String str;
    StringBuffer response = new StringBuffer();
    try {
      while (null != ((str = input.readLine()))) {
        response.append(str);
      }
      input.close();
 
      // Parse the response
      XMLReader reader = XMLReaderFactory.createXMLReader();
      reader.setContentHandler(new ResponseHandler(result));
      reader.parse(new InputSource(new StringReader(response.toString())));
 
    } catch (Exception e2) {
      message("Failure reading error stream: "+e2);
    }
 
    return result;
  }
 
  /*
   * This is a convenience method for extracting the information in the
   * response from a successful Deployer Web service call.
   */
  public static Map<String,String> handleSuccessResponse(HttpURLConnection conn) throws IOException, SAXException {
    HashMap<String,String> result = new HashMap<String,String>();
    DataInputStream input = new DataInputStream(conn.getInputStream());
    String str;
    StringBuffer response = new StringBuffer();
    while (null != ((str = input.readLine()))) {
      response.append(str);
    }
    input.close();
 
    // Parse the response
    XMLReader reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(new ResponseHandler(result));
    reader.parse(new InputSource(new StringReader(response.toString())));
 
    return result;
  }
 
  /*
   * The responses returned from the Deployer Web service are XML
   * documents. This handler translates the structure of the document
   * into a Map which is useful for picking out certain element.  It
   * also prints the entries to System.out.
   */
  public static class ResponseHandler extends DefaultHandler {
 
    private Map<String,String> info;
 
    public ResponseHandler(Map<String,String> info) {
      this.info = info;
    }
 
    LinkedList<String> elements = new LinkedList<String>();
 
    public void startElement(String namespaceURI, String elementName, String qName, Attributes attrs) {
      elements.add(elementName);
    }
 
    public void characters(char ch[], int start, int length) {
      String str = new String(ch,start,length);
 
      //message(String.format("    %s=%s", getCurrentKey(), str));
      info.put(getCurrentKey(), str);
    }
 
    private String getCurrentKey() {
      String result = null;
      for (String s : elements) {
        if (result != null) {
          result = result + "." +s;
        } else {
          result = s;
        }
      }
      return result;
    }
 
    public void endElement(String namespaceURI, String elementName, String qName) {
      elements.removeLast();
    }
  }
 
  private static void message(String msg) {
    System.out.println("["+new Date(System.currentTimeMillis())+"] "+msg);
 }
 
}