oracle.otnsamples.cmsxdb.admin.Externalizer (Java2HTML)
/*
 * @author  : Elangovan
 * @version : 1.0
 *
 * Development Environment : Oracle9i JDeveloper

 * Name of the File        : Externalizer.java
 *
 * Creation / Modification History
 *    Elangovan           12-Dec-2002        Created
 *
 */


package oracle.otnsamples.cmsxdb.admin;

import java.io.File;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.BufferedInputStream;

import java.net.URL;

import java.net.URLEncoder;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;

import oracle.otnsamples.cmsxdb.ConnParams;
import oracle.otnsamples.cmsxdb.exception.SiteGenerationException;

/**
 * This class generates files on the host file system. Calls TransformServlet to

 * generate content if its an XML resource.
 *
 * @see TransformServlet
 */
public class Externalizer  {

  /* Absolute path to root directory where files have to be generated */
  private String rootPath = null;

  /**

   * Constructs a new Externalizer with root path set to rootpath.
   *
   * @param rootpath Absolute path to root directory where files have to be generated.
   */
  public Externalizer(String rootpath ) {
    this.rootPath = rootpath;
  }

  /**
   * Generates file on host file system( where app server is running). Uses
   * TransformServlet (if xml resource) to get file content and writes it to disk.

   *
   * @param resourceUrl XDBUri of resource
   * @param xslLoc      XDBUri of XSL file to be applied on Resource
   * @param contentType Content type of resource after transformation
   *
   * @exception SiteGenerationException if generating file fails
   */
  public void generateFile(  String resourceUrl, String xslLoc,String contentType)
      throws SiteGenerationException {
      
      HttpURLConnection urlConn = null;


      // Basic Authentication string [ format:  username:password ]
      String userPassword =  ConnParams.dbUsername + ":" + ConnParams.dbPassword;

      // Encode using BASE64
      String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());

      String filePath = this.rootPath + resourceUrl;
      StringBuffer servletUrl = null;

      if( contentType == null || "".equals(contentType) ) {
        contentType = "text/xml";
      }  
      try {

      
        // Use TransformServlet, if XML resource
        if( resourceUrl.toLowerCase().endsWith(".xml") ) {
          servletUrl = new StringBuffer(ConnParams.dbTransServlet)
                                    .append("?resource=")
                                    .append(URLEncoder.encode(resourceUrl,"UTF-8"));

          if( xslLoc != null && !"".equals(xslLoc) ) {
            servletUrl.append( "&transform=" ).append(URLEncoder.encode(xslLoc,"UTF-8"));
          }  

          servletUrl.append( "&contenttype=" ).append( contentType );

        } else  {

          // Talk to XDB directly
          servletUrl = new StringBuffer(ConnParams.dbWebURL).append('/')
                                      .append(URLEncoder.encode(resourceUrl.substring(1),"UTF-8"));
        }

        // Generate file to relative path specified by the resource
        if( filePath.lastIndexOf('.') != -1 ) {
          filePath = filePath.substring( 0, filePath.lastIndexOf('.') + 1 ) +
                     this.getFileExtn( contentType );
        }
        URL url = new URL( servletUrl.toString( ) );
        urlConn = (HttpURLConnection) url.openConnection();

        urlConn.setDoInput(true);
        urlConn.setDoOutput(false);


        urlConn.setUseCaches(false);
        urlConn.setDefaultUseCaches(false);

        // Set Authentication headers
        urlConn.setRequestProperty ("Authorization", "Basic " + encoding);

        urlConn.connect();

        int buffsize = 1 * 1024;  // 1 KB buffer
        byte buffer[] = new byte[buffsize];
        int len = 0;
        BufferedInputStream servletin =   new BufferedInputStream(urlConn.getInputStream());

        // Create directory structure
        File dir = new File( filePath.substring(0, filePath.lastIndexOf('/') ) );

        dir.mkdirs( );

        FileOutputStream fileout = new FileOutputStream( filePath );

        // Read from Servlet and write to file
        while( (len = servletin.read( buffer,0, buffsize ) ) != -1 ) {
          fileout.write( buffer, 0, len );
        }  

        // Close input and output streams
        servletin.close();
        fileout.close();


      } catch( MalformedURLException invalidURLEx) {
        throw new SiteGenerationException(" Invalid Servlet URL to generate site : "+
                                           invalidURLEx.getMessage());

      } catch( IOException ioEx ) {
        throw new SiteGenerationException(" Could not generate file : "+
                                           ioEx.getMessage() );
      } finally {
        urlConn = null;
      }
  }

  /**
   * Returns file extension based on Content type.
   *
   * @param cType Content type
   *
   * @return File extension corresponding to Content type.
   */
  private String getFileExtn(String cType ) {

    String extn = null;

    if( cType.equals("application/msword") ) 
      extn = "doc";
    else if ( cType.equals("text/plain") )
      extn = "txt";
    else if ( cType.equals("image/jpeg") )
      extn = "jpg";
    else
      extn = cType.substring( cType.indexOf( '/') + 1 );

    return extn;
  }

}
E-mail this page
Printer View Printer View
Oracle Is The Information Company About Oracle | Oracle RSS Feeds | Careers | Contact Us | Site Maps | Legal Notices | Terms of Use | Privacy