package com.oracle.ucm.generic;

import com.oracle.ucm.utils.data.FileAttributes;
import com.oracle.ucm.utils.data.docInfoContainer;

import com.oracle.ucm.utils.data.resultsContainer;
import com.oracle.ucm.utils.response.searchResponse;
import com.oracle.ucm.utils.response.ucmResponse;
import com.oracle.ucm.utils.response.fileResponse;
import com.oracle.ucm.utils.response.docInfoResponse;


import java.io.IOException;
import java.io.InputStream;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.xml.ws.WebServiceRef;
import weblogic.wsee.jws.jaxws.owsm.SecurityPoliciesFeature;

import java.util.List;
import java.util.Map;

import java.util.Set;

import javax.activation.DataHandler;

import javax.activation.FileDataSource;

import javax.mail.util.ByteArrayDataSource;

import javax.xml.ws.BindingProvider;

import oracle.webservices.ClientConstants;


// !THE CHANGES MADE TO THIS FILE WILL BE DESTROYED IF REGENERATED!
// This source file is generated by Oracle tools
// Contents may be subject to change
// For reporting problems, use the following
// Version = Oracle WebServices (11.1.1.0.0, build 111209.0821.28162)

public class WCCWSProxy
{
  @WebServiceRef
  private GenericSoapService genericSoapService;
  private GenericSoapPortType genericSoapPortType;

  
  
  private void init()
  {
      GenericSoapService genericSoapService = new GenericSoapService();

      
      // Configure security feature
      SecurityPoliciesFeature securityFeatures =
          new SecurityPoliciesFeature(new String[] {"oracle/wss11_saml_token_with_message_protection_client_policy" });
      //GenericSoapPortType genericSoapPortType = gen"ricSoapService.getGenericSoapPort(securityFeatures);
      // Add your code to call the desired methods.genericSoapService = new GenericSoapService();
      
     genericSoapPortType = genericSoapService.getGenericSoapPort(securityFeatures);
          
       
    //obtain request context from soap port
     
      Map<String, Object> requestContext = 
      ((BindingProvider)genericSoapPortType).getRequestContext();
     
      //Example of how to Set username and password if using user name token OWSM Policy
     //requestContext.put(BindingProvider.USERNAME_PROPERTY, "weblogic"); 
     //requestContext.put(BindingProvider.PASSWORD_PROPERTY, "welcome1");
      
      //setting location of keystore used for OWSM SAML policy
      requestContext.put(ClientConstants.WSSEC_KEYSTORE_LOCATION, "d:\\keystore\\default-keystore.jks");
      requestContext.put(ClientConstants.WSSEC_KEYSTORE_PASSWORD, "welcome");
      requestContext.put(ClientConstants.WSSEC_KEYSTORE_TYPE, "JKS");
      requestContext.put(ClientConstants.WSSEC_SIG_KEY_ALIAS, "orakey");
      requestContext.put(ClientConstants.WSSEC_SIG_KEY_PASSWORD, "welcome");
      
  }
  
  public searchResponse executeSearch(String ftxcriteria)
  {
      //public search interface method called by clients
     init();
     Generic request = new Generic();
     request.setWebKey("cs");
     return executeSearch(request, genericSoapPortType, ftxcriteria);
  }
  
  private searchResponse executeSearch(Generic req, GenericSoapPortType port, String ftxcriteria)
  {
    //private search interface which uses objects generated from   
    Service svc = new Service();
    resultsContainer rscont = new resultsContainer();
    
    //create service document object
    Service.Document doc = new Service.Document();
    
        
    //set service to be executed in service object
    svc.setIdcService("GET_SEARCH_RESULTS");
    
    //bind document container to service
    svc.setDocument(doc);
    
    //bind service to request object
    req.setService(svc);
    
    //create request field container from document object
    List <Field> fldlst = doc.getField();
    
    //start creating fields that will contain parameter data required for service request and add to field container
    Field qTxt = new Field();
    qTxt.setName("QueryText");
    if (ftxcriteria.length() > 0)
    {
        qTxt.setValue("<ftx>" + ftxcriteria + "</ftx>");
        Field ftxind = new Field();
        ftxind.setName("ftx");
        ftxind.setValue("1");
    }
    else
    {
      qTxt.setValue("");  
    }
    fldlst.add(qTxt);
    Field sortfld = new Field();
    sortfld.setName("SortField");
    sortfld.setValue("dInDate");
    fldlst.add(sortfld);
    Field sortorder = new Field();
    sortorder.setName("SortOrder");
    sortorder.setValue("Desc");
    fldlst.add(sortorder);
    Field rsltcnt = new Field();
    rsltcnt.setName("ResultCount");
    rsltcnt.setValue("200");
    fldlst.add(rsltcnt);
    
    searchResponse rsp = null;
    try
    {
        //execute search request to server that returns response as a Service ojbect
        Generic resp = port.genericSoapOperation(req);
        
        
        //get Response back
        Service rspsvc = resp.getService();
        
        //Get document object from service object
        //Document object wraps all container objects (e.g. ResultSets, local data,etc) returned in response
        Service.Document rspdoc = rspsvc.getDocument();
        
        rsp = new searchResponse(rspdoc.getField());
        if ("0".equals(rsp.getStatusCode()))
        {
            //Get Results Sets from document
            List<ResultSet> rsets = rspdoc.getResultSet();
            
            for (ResultSet rset : rsets) 
            { 
              //handle processing only SearchResults result set in this method
              if ("searchresults".equals(rset.getName().toLowerCase()))
              {
                List<Row> rsrows = rset.getRow();
                if (rsrows.size() > 0) 
                { 
                  // Get column headers returned in first row of a result set or ResultSet  
                  Row cols = rsrows.get(0);
                  List<Field> rscols = cols.getField();
                  rscont.init(rscols.size(), rsrows.size());
                  String colhdrs[] = new String[rscont.getNumCols()];
                  int colidx = 0;
                  for (Field col : rscols)
                  { 
                    colhdrs[colidx] = col.getName();
                    ++colidx;
                  }
                  
                  rscont.setCols(colhdrs);
                  
                  // Print out the row data
                  String rows[][] = new String[rscont.getNumRows()][rscont.getNumCols()];
                  int rowidx = 0;
                  for (Row currow : rsrows) 
                  { 
                    colidx = 0;
                    rscols = currow.getField(); 
                    for (Field val : rscols) 
                    { 
                     
                      rows[rowidx][colidx] = val.getValue();
                      ++colidx;
                    }
                    ++rowidx;
                   
                  } 
                  rscont.setRows(rows);
                } 
                rsp.setResults(rscont);  
              }
            }
        }
    }
    
    catch (Exception e) 
    {
        //catch exception to handle formatting response
        List <Field> exfields = new ArrayList();
        Field statuscode = new Field();
        statuscode.setName("StatusCode");
        statuscode.setValue("-1");
        Field statusmsg = new Field();
        statusmsg.setName("StatusMessage");
        statusmsg.setValue(e.getMessage());
        exfields.add(statuscode);
        exfields.add(statusmsg);
        rsp = new searchResponse(exfields);
        
        
    }
   
    return rsp;
  }
  
  public docInfoResponse executeDocInfo(String docname, String did)
  {
     init();
     Generic request = new Generic();
     request.setWebKey("cs");
     return executeDocInfo(request, genericSoapPortType, docname, did);
  }
  
  private docInfoResponse executeDocInfo(Generic req, GenericSoapPortType port, String docname, String did)
  {
    Service svc = new Service();
    docInfoContainer dinfocont = new docInfoContainer();
    Service.Document doc = new Service.Document();
    List <Field> fldlst = doc.getField();
    svc.setIdcService("DOC_INFO");
    svc.setDocument(doc);
    req.setService(svc);
    if (docname != null)
    {
        Field dDocName = new Field();
        dDocName.setName("dDocName");
        dDocName.setValue(docname);
        fldlst.add(dDocName);
    }
    Field dID = new Field();
    dID.setName("dID");
    dID.setValue(did);
    fldlst.add(dID);
    //execute search request to server
    docInfoResponse dir = null;
    try
    {
        //submit request
        Generic resp = port.genericSoapOperation(req);
        
        //get Response back
        Service rspsvc = resp.getService();
        
        //Document object wraps all container objects (e.g. ResultSets, local data,etc) returned in response
        Service.Document rspdoc = rspsvc.getDocument();
        dir = new docInfoResponse(rspdoc.getField());
        if ("0".equals(dir.getStatusCode()))
        {
            List<ResultSet> rsets = rspdoc.getResultSet();
            for (ResultSet rset:rsets)
            {
              String name = rset.getName();
              if ("DOC_INFO".equals(name))
              {
                List<Row> currow = rset.getRow();
                if (currow.size() > 0) 
                { 
                  // Get column headers returned in first row of a result set or ResultSet  
                  Row cols = currow.get(0);
                  List<Field> rscols = cols.getField();
                  dinfocont.initDocInfo(rscols.size(), currow.size());
                  String colhdrs[] = new String[dinfocont.getDocInfoNumCols()];
                  int colidx = 0;
                  for (Field col : rscols)
                  { 
                    colhdrs[colidx] = col.getName();
                    ++colidx;
                  }
                  
                  dinfocont.setDocInfoCols(colhdrs);
                           
                  // Print out the row data
                  String rows[][] = new String[dinfocont.getDocInfoNumRows()][dinfocont.getDocInfoNumCols()];
                  int rowidx = 0;
                  //traverse rows
                  for (Row row : currow) 
                  { 
                    colidx = 0;
                    rscols = row.getField(); 
                    //traverse columns within current row
                    for (Field val : rscols) 
                    { 
                     
                      rows[rowidx][colidx] = val.getValue();
                      ++colidx;
                    }
                    ++rowidx;
                   
                  } 
                  dinfocont.setDocInfoRows(rows);
                } //if DOCINFO has rows
                
              } //if resultset id DOC_INFO
                
              if ("REVISION_HISTORY".equals(name))
              {
                List<Row> currow = rset.getRow();
                if (currow.size() > 0) 
                { 
                  // Get column headers returned in first row of a result set or ResultSet  
                  Row cols = currow.get(0);
                  List<Field> rscols = cols.getField();
                  dinfocont.initRevHistory(rscols.size(), currow.size());
                  String colhdrs[] = new String[dinfocont.getRevHistoryNumCols()];
                  int colidx = 0;
                  for (Field col : rscols)
                  { 
                    colhdrs[colidx] = col.getName();
                    ++colidx;
                  }
                  
                  dinfocont.setRevHistoryCols(colhdrs);
                           
                  // Print out the row data
                  String rows[][] = new String[dinfocont.getRevHistoryNumRows()][dinfocont.getRevHistoryNumCols()];
                  int rowidx = 0;
                  for (Row row : currow) 
                  { 
                    colidx = 0;
                    rscols = row.getField(); 
                    for (Field val : rscols) 
                    { 
                     
                      rows[rowidx][colidx] = val.getValue();
                      ++colidx;
                    }
                    ++rowidx;
                   
                  } 
                  dinfocont.setRevHistoryRows(rows);
                } //if RevHistory has rows 
              } //if resultset id REV_HISTORY       
            
            } //for
            dir.setResults(dinfocont);
        }
    }
    
    catch (Exception e) 
    {
        List <Field> exfields = new ArrayList();
        Field statuscode = new Field();
        statuscode.setName("StatusCode");
        statuscode.setValue("-1");
        Field statusmsg = new Field();
        statusmsg.setName("StatusMessage");
        statusmsg.setValue(e.getMessage());
        exfields.add(statuscode);
        exfields.add(statusmsg);
        dir = new docInfoResponse(exfields);
    }
    return dir;
    
  }
  
    public ucmResponse executeDeleteRev(String docname, String did)
    {
       init();
       Generic request = new Generic();
       request.setWebKey("cs");
       return executeDeleteRev(request, genericSoapPortType, docname, did);
    }
    
    private ucmResponse executeDeleteRev(Generic req, GenericSoapPortType port, String docname, String did)
    {
      Service svc = new Service();
      docInfoContainer dinfocont = new docInfoContainer();
      Service.Document doc = new Service.Document();
      List <Field> fldlst = doc.getField();
      svc.setIdcService("DELETE_REV");
      svc.setDocument(doc);
      req.setService(svc);
      Field dDocName = new Field();
      dDocName.setName("dDocName");
      dDocName.setValue(docname);
      fldlst.add(dDocName);
      Field dID = new Field();
      dID.setName("dID");
      dID.setValue(did);
      fldlst.add(dID);
      ucmResponse rsp = null;
      try
      {
          //execute delete request to server
          Generic resp = port.genericSoapOperation(req);
          
          //get Response back
          Service rspsvc = resp.getService();
          Service.Document rspdoc = rspsvc.getDocument();
          rsp = new ucmResponse(rspdoc.getField());
          if ("-64".equals(rsp.getStatusCode())) 
          {
              //ucm server returns an error code 0f -64 when the final revision of a document is deleted this is not an error
              //set status code to zero so normal response is rendered
              rsp.setStatusCode("0");
          }
      }
      
      catch (Exception e)
      {
          List <Field> exfields = new ArrayList();
          Field statuscode = new Field();
          statuscode.setName("StatusCode");
          statuscode.setValue("-1");
          Field statusmsg = new Field();
          statusmsg.setName("StatusMessage");
          statusmsg.setValue(e.getMessage());
          exfields.add(statuscode);
          exfields.add(statusmsg);
          rsp = new ucmResponse(exfields);
          
      }
      return rsp;
      
    }
  
  public ucmResponse executeCheckin(HashMap metaFields, String fName, String contentType, InputStream is) 
  {
      init();
      Generic request = new Generic();
      request.setWebKey("cs");
      return executeCheckin(request, genericSoapPortType, metaFields, fName, contentType, is);
  }
  
  private ucmResponse executeCheckin(Generic req, GenericSoapPortType port, HashMap metafields, String fName, String contentType, InputStream fis)
  {
      Service svc = new Service();
      
        //create service document object
      Service.Document doc = new Service.Document();
      
      //bind service object to request
      req.setService(svc);
      
      //get request field container from document
      List <Field> fields = doc.getField();
      
      //set service to be executed in service object
      svc.setIdcService("CHECKIN_NEW");
      
      //bind document object to servcie object
      svc.setDocument(doc);
      
      
      Set fldset = metafields.keySet();
      Iterator fldnames = fldset.iterator();
      //build up list of fields for metadata on checkin
      while (fldnames.hasNext()) 
      {
          String fldname = (String)fldnames.next();
          String val = (String)metafields.get(fldname);
          Field f = new Field();
          f.setName(fldname);
          f.setValue(val);
          fields.add(f);
      }
      //create field for primary file
      Field f_primary = new Field();
      f_primary.setName("primaryFile");
      f_primary.setValue(fName);
      fields.add(f_primary);
      ucmResponse rsp = null;
      try
      {
        //create file container object from document object  
        List <com.oracle.ucm.generic.File> f = doc.getFile();
        
        //create file object, not file object is generated from WSDL and not a stadard java.io.File object
        com.oracle.ucm.generic.File pfile = new com.oracle.ucm.generic.File();
        
        //bind name of file being uploaded to file object
        pfile.setHref(fName);
          
        //retrieve file right from data stream passed in from servlet client using ByteArrayDataSource to reduce I/O for this example.  Note: ByteArrayDataSource
        //reads everything into memory so this will not work for larger files and FileDataSource should be used which means some intermediate I/O needs  to occur
        //to write the incoming stream (fis) to local disk and have FileDataSource pick it up from there.
        pfile.setContents(new DataHandler(new ByteArrayDataSource(fis, contentType)));
        
        //add file object to file container
        f.add(pfile);
          
        //Submit WebService request to UCM server over Soap Port
        Generic response= port.genericSoapOperation(req);
          
        //Get response Service object from response
        Service rspsvc = response.getService();
          
        //Get Document object from response service object
        Service.Document rspdoc = rspsvc.getDocument();
          
        //Get localdata area of response by callign getField() method and store in fied list
        List<Field> rspfields = rspdoc.getField();
        rsp =  new ucmResponse(rspfields);
        
          
      }
      
      catch(Exception ioe)
      {
          List <Field> exfields = new ArrayList();
          Field statuscode = new Field();
          statuscode.setName("StatusCode");
          statuscode.setValue("-1");
          Field statusmsg = new Field();
          statusmsg.setName("StatusMessage");
          statusmsg.setValue(ioe.getMessage());
          exfields.add(statuscode);
          exfields.add(statusmsg);
          rsp = new ucmResponse(exfields);
                  
      }
      
      return rsp;
      
    }
  
    public fileResponse executeGetFile(String dID) 
    {
        init();
        Generic request = new Generic();
        request.setWebKey("cs");
        return executeGetFile(request, genericSoapPortType, dID);
    }
    
    private fileResponse executeGetFile(Generic req, GenericSoapPortType port, String dID) 
    {
        Service svc = new Service();
        Service.Document doc = new Service.Document();
        req.setService(svc);
        List <Field> fields = doc.getField();
        svc.setIdcService("GET_FILE");
        svc.setDocument(doc);
        Field did = new Field();
        did.setName("dID");
        did.setValue(dID);
        fields.add(did);
        fileResponse frsp = null;
        try
        {
            Generic svcrsp = port.genericSoapOperation(req);
            Service rspsvc = svcrsp.getService();
            Service.Document rspdoc = rspsvc.getDocument();
            frsp = new fileResponse(rspdoc.getField());
            if ("0".equals(frsp.getStatusCode()))
            {
                List<File> flst = rspdoc.getFile();
                InputStream retis = null;
                for (File fcur:flst)
                {
                   DataHandler dh = fcur.getContents();
                   retis =  dh.getInputStream();
                   break; 
                }
                frsp.setInputStream(retis);
                    
            }
        }
            
        catch (Exception ioe)
        {
            //catch exception to handle formatting response
            List <Field> exfields = new ArrayList();
            Field statuscode = new Field();
            statuscode.setName("StatusCode");
            statuscode.setValue("-1");
            Field statusmsg = new Field();
            statusmsg.setName("StatusMessage");
            statusmsg.setValue(ioe.getMessage());
            exfields.add(statuscode);
            exfields.add(statusmsg);
            frsp = new fileResponse(exfields);
        }
       
        return frsp;
       
        
    }
    
    public FileAttributes getFileAttributes(String dID) 
    {
        FileAttributes fattrib = null;
        int nameidx = 0;
        int formatidx = 0;
        int sizeidx = 0;
        
        init();
        Generic request = new Generic();
        request.setWebKey("cs");
        docInfoResponse dir = executeDocInfo(request, genericSoapPortType, null, dID);
        if ("0".equals(dir.getStatusCode()))
        {
            fattrib = new FileAttributes();
            docInfoContainer di = dir.getResults();
            for (int curcol = 0; curcol < di.getDocInfoNumCols(); ++curcol)
            {
                if ("dFormat".equals(di.getDocInfoCols()[curcol]))
                    formatidx = curcol;
                
                if ("dOriginalName".equals(di.getDocInfoCols()[curcol]))
                    nameidx = curcol;
                
                if ("dFileSize".equals(di.getDocInfoCols()[curcol]))
                    sizeidx = curcol;
            }
            
            fattrib.setFformat(di.getDocInfoRows()[0][formatidx]);
            fattrib.setFname(di.getDocInfoRows()[0][nameidx]);
            fattrib.setFsize(Integer.parseInt(di.getDocInfoRows()[0][sizeidx]));
        } 
        return fattrib;
        
    }
}
