package com.oracle.ucm.wsdemoservlet;


//import com.oracle.ucm.wsproxy.File;
import com.oracle.ucm.utils.data.FileAttributes;
import com.oracle.ucm.utils.data.docInfoContainer;
import com.oracle.ucm.utils.response.ucmResponse;
import com.oracle.ucm.utils.data.resultsContainer;
import com.oracle.ucm.utils.response.searchResponse;
import com.oracle.ucm.utils.response.fileResponse;
import com.oracle.ucm.utils.response.docInfoResponse;

import com.oracle.ucm.generic.WCCWSProxy;
import com.oracle.ucm.nativews.NativeProxy;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;

import javax.servlet.*;
import javax.servlet.http.*;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import java.util.HashMap;
import java.util.List;
import java.io.InputStream;

public class IdcWSServletDemo
  extends HttpServlet
{
    private static final String CONTENT_TYPE = "text/html; charset=utf-8";
    private static final String DEFAULT_API = "GenericWS";
    private static final String GEN_API = "GenericWS";
    private static final String NATIVE_API = "NativeWS";
    private static final String RIDC_API = "RIDC";
    
    @SuppressWarnings("compatibility:-3580001000023056041")
    private static final long serialVersionUID = 1L;

    public void init(ServletConfig config)
    throws ServletException
  {
    super.init(config);
  }

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
    throws ServletException, IOException
  {
    
    String idcsvc = "";
    resultsContainer searchresults = null;
    try
    {
      idcsvc = request.getParameter("IdcService");
      if ((idcsvc == null) || (idcsvc.length() == 0))
      {
        splashPage(request, response);
      }
      else
      {
        if ("Search".equals(idcsvc))
        {
            String qStr = request.getQueryString();
            String qparts[] = qStr.split("&");
            String apiopt = request.getParameter("SelectedAPI");
            renderSearchFrm(request, response, apiopt);
        }
        else if ("SearchSubmit".equals(idcsvc)) 
        {
            String ftxcriteria = request.getParameter("ftx");
            String apiopt = request.getParameter("SelectedAPI");
            getSearchResults(request, response, ftxcriteria, apiopt);
        }
        else if ("Info".equals(idcsvc))
        {
          String qStr = request.getQueryString();
          String qparts[] = qStr.split("&");
          String apiopt = request.getParameter("SelectedAPI");
         
          getDocInfo(request, response, qparts[1].split("=")[1],qparts[2].split("=")[1], apiopt);
        }
        else if ("CheckinFrm".equals(idcsvc)) 
        {
            String apiopt = request.getParameter("SelectedAPI");
            renderCheckinFrm(request, response, apiopt); 
                        
        }
        else if ("GetFile".equals(idcsvc)) 
        {
            String qStr = request.getQueryString();
            String qparts[] = qStr.split("&");
            String apiopt = request.getParameter("SelectedAPI");
            getFile(request, response, qparts[1].split("=")[1], apiopt);           
        }
        else if ("Delete".equals(idcsvc))
        {
            String qStr = request.getQueryString();
            String qparts[] = qStr.split("&");
            String apiopt = request.getParameter("SelectedAPI");
            deleteDocRev(request, response, qparts[1].split("=")[1],qparts[2].split("=")[1], apiopt);
        }
        else 
        {
            response.getWriter().println("<b>Invalid Service Request Specified");
        }
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
      throw new ServletException(e.getMessage());
    }
   
  }

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
    throws ServletException, IOException
  {
      
    String UPLOAD_DIRECTORY = "upload";
    int THRESHOLD_SIZE = 1024 * 1024 * 1; // 3MB
    int MAX_FILE_SIZE = 1024 * 1024 * 2000; // 2g
    int REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
    HashMap metafields = new HashMap();
    String uploadfilename = "";
    InputStream is = null;
    String apiopt = null;
    String UPLOAD_PATH = "c:/temp/servletupload/";
    try
    {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart)
        {
            File file;
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(THRESHOLD_SIZE);
            // Location to save data that is larger than maxMemSize.
            File f_upload = new File(UPLOAD_PATH);
            if (!f_upload.exists())
                f_upload.mkdir();
            
            factory.setRepository(f_upload);

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(-1);
            upload.setFileSizeMax(MAX_FILE_SIZE);

            // Parse the request to get file items.
            List<FileItem> fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            //Iterator i = fileItems.iterator();

            String contentType = null;
            for (FileItem fi:fileItems)
            {
                //it is a file
                if ( !fi.isFormField () )      
                {
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    String fileName = fi.getName();
                    uploadfilename = fi.getName();
                    is = fi.getInputStream();
                    contentType = fi.getContentType();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    
                    // Write the file
                    if( fileName.lastIndexOf("\\") >= 0 )
                    {
                        file = new File(UPLOAD_PATH + 
                        fileName.substring( fileName.lastIndexOf("\\"))) ;
                    }
                    else
                    {
                        file = new File( UPLOAD_PATH + 
                        fileName.substring(fileName.lastIndexOf("\\")+1)) ;
                    }
                   
                }//if
                else
                {
                    if ("SelectedAPI".equals(fi.getFieldName()))
                        apiopt = fi.getString();
                    else
                        metafields.put(fi.getFieldName(), fi.getString());
                                            
                }
            }//for
            
            ucmResponse rsp = null;
            //submit checkin over web service proxy API build from GenericSoapPort WSDL
            if (GEN_API.equals(apiopt))
            {
                WCCWSProxy wccp = new WCCWSProxy();
                rsp = wccp.executeCheckin(metafields, uploadfilename, contentType, is);
            }
            else
            {
                NativeProxy nw = new NativeProxy(apiopt, request.getUserPrincipal().getName());
                rsp = nw.executeCheckInService(metafields, uploadfilename, contentType, is);
            }
            
            
            is.close();
            if (!"0".equals(rsp.getStatusCode())) 
            {
              reportError(request, response, rsp.getStatusCode(), rsp.getStatusMsg());  
            }
            else
            {
              reportCheckinSuccess(request, response, rsp, apiopt);
                  
            }
           
            
        }//if isMultiPart
        else
        {
            doGet(request,response);
        }

    }//try
    catch (Exception e)
    {
        is.close();
        throw new ServletException(e.getMessage());
    }
    
  }
  
  private void splashPage(HttpServletRequest request, HttpServletResponse response)
  {
    try
    {
      String url = request.getRequestURI();
      response.setContentType(CONTENT_TYPE);
      PrintWriter out = response.getWriter();
      out.println("<html>");
      out.println("<head><title>WebCenter Content WebServices 11g Demo</title><script type=\"text/javascript\" src=\"" + request.getContextPath() + "/script/wsdemo.js\"></script>\r\n</head>");
      out.println("<body>");
      out.println("<p><b><img src=" + request.getContextPath() + "/images/oraclelogo.png> WebCenter Content WebServices 11g Demo (" + request.getUserPrincipal() + ")</b></p>");
      out.println("<form name=\"apifrm\"><input type=\"radio\" checked name=\"api\" id=\"genws\" value=\"GenericWS\">Generic WebService&nbsp;<input type=\"radio\" name=\"api\" id=\"nativews\" value=\"NativeWS\">Native WebService&nbsp;<input type=\"radio\" name=\"api\" id=\"RIDC\" value=\"RIDC\">RIDC</form>");
      out.println("<p>Options:</p>");
      out.println("<p><a href=javascript:appendAPI('" + url + "?IdcService=CheckinFrm')>Check-in</a></p>");
      out.println("<p><a href=javascript:appendAPI('" + url + "?IdcService=Search')>Search</a></p>");
      out.println("</body></html>");
      out.close();
    }
    catch (IOException ioe)
    {
      ioe.printStackTrace();
    }
  }//splashpage()
  
  private void getSearchResults(HttpServletRequest request, HttpServletResponse response, String Criteria, String apiopt)
  throws IOException
  {
    resultsContainer searchresults = null;
    searchResponse sr = null;
    //Call to WebService Proxy to submit search
    if (GEN_API.equals(apiopt))
    {
        WCCWSProxy wcc = new WCCWSProxy();
        sr  = wcc.executeSearch(Criteria);
    }
    else if (NATIVE_API.equals(apiopt) || RIDC_API.equals(apiopt)) 
    {
        NativeProxy npws = new NativeProxy(apiopt, request.getUserPrincipal().getName());
        sr = npws.executeSearch(Criteria);
    }
    
    if ("0".equals(sr.getStatusCode()))
    {
        searchresults = sr.getResults();
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Search Results</title></head>");
        out.println("<body>");
        out.println("<p><img src=" + request.getContextPath() + "/images/oraclelogo.png><b>Search Results</b></p>");
        out.println("<table border=1>");
        String[] cols = searchresults.getCols();
        out.println("<tr bgcolor=cyan>");
        out.print("<td>&nbsp;</td>");
        for (int curcol = 0; curcol < cols.length; ++curcol)
        {
          out.print("<td><b>");
          out.print(cols[curcol]);
          out.print("</td>");
        }
        out.print("\r\n</tr>");
        
        String rows[][] = searchresults.getRows();
        for (int currow = 0; currow < searchresults.getNumRows(); ++currow)
        {
          String dDocName = "";
          String dID = "";
          StringBuffer row = new StringBuffer();
          StringBuffer hrefcol = new StringBuffer();
          out.println("<tr>");
          for (int curcol = 0; curcol < searchresults.getNumCols(); ++curcol)
          {
            //row.append("<td>");
              //out.print("<td>");
            if ("dDocName".equalsIgnoreCase(searchresults.getCols()[curcol]))
            {
              dDocName = rows[currow][curcol];
              //row.append(dDocName);
             
            }
            else if ("dID".equals(searchresults.getCols()[curcol]))
            {
                
                row.append("<td>");
                dID = rows[currow][curcol];
                row.append(dID);
                row.append("</td>");
            }
            else
            {
                row.append("<td>");
                String rowval = rows[currow][curcol];
                if ((rowval == null) || (rowval.length() == 0))
                    rowval = "&nbsp;";
                row.append(rowval);
                row.append("</td>");
                
            }
            //row.append("</td>");
            
          }//columns
          //output buffered row
          hrefcol.append("<td><a href=\"" + request.getRequestURI() + "?IdcService=GetFile&dID=" + dID + "&SelectedAPI=" + apiopt + "\"><img src=\"" + request.getContextPath() + "/images/download.jpg\"></a></td><td><a href=\"" + request.getRequestURI() + "?IdcService=Info&dDocName=" + dDocName + "&dID=" + dID + "&SelectedAPI=" + apiopt + "\">" + dDocName + "</a></td>");
          hrefcol.append(row.toString());
          out.println(hrefcol.toString());
          out.println("\r\n</tr>");
        }//rows
        
        out.println("</table>");
        out.println("<br><a href=" + request.getRequestURL() + ">Back</a>");
        out.println("</body></html>");
        out.close();
    }
    else
    {
        reportError(request, response, sr.getStatusCode(), sr.getStatusMsg());  
    }
  }
  
  private void getDocInfo(HttpServletRequest request, HttpServletResponse response, String docname, String dID, String apiopt)
  throws IOException
  {
    docInfoContainer docinfo = null;
    docInfoResponse dir = null;
    if (GEN_API.equals(apiopt))
    {
        WCCWSProxy wccp = new WCCWSProxy();
        dir = wccp.executeDocInfo(docname,dID);
    }
    else if (NATIVE_API.equals(apiopt) || RIDC_API.equals(apiopt)) 
    {
        NativeProxy npws = new NativeProxy(apiopt, request.getUserPrincipal().getName());
        dir = npws.executeDocInfo(docname, dID);
    }
    
    if ("0".equals(dir.getStatusCode()))
    {
        docinfo = dir.getResults();
        String dinfocols[] = docinfo.getDocInfoCols();
        String dinforows[][] = docinfo.getDocInfoRows();
        String did = "0";
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Document Information</title></head>");
        out.println("<body>");
        out.println("<p><img src=\"" + request.getContextPath() + "/images/oraclelogo.png\"><b>Document Information For " + docname + "</b></p>");
        out.println("<table border=1>");
        
        //output document information
        for (int curcol = 0; curcol < docinfo.getDocInfoNumCols(); ++curcol)
        {
          out.println("<tr>");
          out.print("<td align=\"right\"><b>" + dinfocols[curcol] + ":</b></td><td>" + dinforows[0][curcol] + "</td>");
          out.println("</tr>");
        }
        
        out.println("</table>");
        
        //output revision history
        String revhistcols[] = docinfo.getRevHistoryCols();
        String revhistrows[][] = docinfo.getRevHistoryRows();
        int docnamecolidx = 0;
        int didcolidx = 0;
        out.println("</br>");
        out.println("<b>Revision History</b>");
        out.println("<table border=1>");
        out.println("<tr bgcolor=cyan>");
        for (int curcol = 0; curcol < docinfo.getRevHistoryNumCols(); ++curcol)
        {
          if ("dID".equals(revhistcols[curcol]))
              didcolidx = curcol;
          out.print("<td><b>");
          out.print(revhistcols[curcol]);
          out.print("</td>");
        }
        out.println("<td>&nbsp;</td>");
        out.println("<td>&nbsp;</td>");
        out.print("\r\n</tr>");
         
        for (int currow = 0; currow < docinfo.getRevHistoryNumRows(); ++currow)
        {
          String dDocName = "";
          String revdID = "";
          out.println("<tr>");
          for (int curcol = 0; curcol < docinfo.getRevHistoryNumCols(); ++curcol)
          {
            
            if (curcol == docnamecolidx)
                dDocName = revhistrows[currow][curcol];
            if (curcol == didcolidx)
                revdID = revhistrows[currow][curcol];
            out.print("<td>");
            out.print(revhistrows[currow][curcol]);
            out.print("</td>");
          }//columns
          out.println("<td><a href=\"" + request.getRequestURI() + "?IdcService=Info&dDocName=" + docname + "&dID=" + revdID +  "&SelectedAPI=" +apiopt + "\"><img src=\"" + request.getContextPath() + "/images/InfoIcon_sm.gif\"></a></td>");
          out.println("<td><a href=\"" + request.getRequestURI() + "?IdcService=Delete&dDocName=" + docname + "&dID=" + revdID +  "&SelectedAPI=" +apiopt + "\">Delete</a></td>");
          out.println("\r\n</tr>");
        }//rows
          
        out.println("</table>");
        
        //output footer
        out.println("<br><a href=" + request.getRequestURL() + ">Back</a>");
        out.println("</body></html>");
        out.close();
    }
    else
    {
        reportError(request, response, dir.getStatusCode(), dir.getStatusMsg());   
    }
  }
  
    private void deleteDocRev(HttpServletRequest request, HttpServletResponse response, String docname, String dID, String apiopt)
    throws IOException
    {
        docInfoContainer docinfo = null;
        ucmResponse rsp = null;
        if (GEN_API.equals(apiopt))
        {
            WCCWSProxy wccp = new WCCWSProxy();
            rsp = wccp.executeDeleteRev(docname,dID);
        }
        else if (NATIVE_API.equals(apiopt) || RIDC_API.equals(apiopt)) 
        {
            NativeProxy nwp = new NativeProxy(apiopt, request.getUserPrincipal().getName());
            rsp = nwp.executeDeleteRev(docname, dID);
        }
        
        if ("0".equals(rsp.getStatusCode()))
        {
            response.setContentType(CONTENT_TYPE);
            PrintWriter out = response.getWriter();
         
            out.println("<b>Content Item " + docname + " Sucessfully Deleted</b>");
            //output footer
            out.println("<br><a href=" + request.getRequestURL() + ">Back</a>");
            out.println("</body></html>");
            out.close();
        }
        else
        {
            reportError(request, response, rsp.getStatusCode(), rsp.getStatusMsg());
            
        }
    }
  
  private void renderCheckinFrm(HttpServletRequest request, HttpServletResponse response, String apiopt) 
  throws IOException
  {
      response.setContentType(CONTENT_TYPE);
      PrintWriter out = response.getWriter();
      out.println("<html>");
      out.println("<head><title>Check-in</title></head>");
      out.println("<body>");
      out.println("<p><img src=" + request.getContextPath() + "/images/oraclelogo.png><b>Check-in Form</b></p>");
      out.println("<form name=\"Checkin\"  enctype=\"multipart/form-data\" method=post action=" + request.getRequestURI() + ">\n");
      out.println("<input type=\"hidden\" name=\"SelectedAPI\" value=\"" + apiopt + "\">");
      out.println("<table>");     
      out.println("<tr>");
      out.println("<td align=\"right\">Document Type:</td>");
      out.println("<td><input type=\"text\" name=\"dDocType\"></td></tr>");
      out.println("<tr>");
      out.println("<td align=\"right\">Title:</td>");
      out.println("<td><input type=\"text\" name=\"dDocTitle\"></td></tr>");
      out.println("<tr>");
      out.println("<tr>");
      out.println("<td align=\"right\">Security Group:</td>");
      out.println("<td><input type=\"text\" name=\"dSecurityGroup\"></td></tr>");
      out.println("<tr>");
      out.println("<td align=\"right\">Author:</td>");
      out.println("<td><input type=\"text\" name=\"dDocAuthor\" value=\"" + request.getUserPrincipal() + "\"></td></tr>");
      out.println("<tr>");
      out.println("<td align=\"right\">Primary File</td>");
      out.println("<td><input type=\"file\" name=\"pFile\"></td></tr>");
      out.println("<td>&nbsp;</td>");
      out.println("<td><input type=\"submit\" value=\"Submit\"></td></tr>");
      out.println("</table>");
      out.println("</form>");
      out.println("</body></html>");
      out.flush();
      out.close();
  }
  
    private void renderSearchFrm(HttpServletRequest request, HttpServletResponse response, String apiopt) 
    throws IOException
    {
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Search</title></head>");
        out.println("<body>");
        out.println("<p><img src=" + request.getContextPath() + "/images/oraclelogo.png><b>Search Form</b></p>");
        out.println("<form name=\"search\"  method=\"GET\" action=" + request.getRequestURI() + ">\n");
        out.println("<input type=\"hidden\" name=\"IdcService\" value=\"SearchSubmit\">");
        out.println("<input type=\"hidden\" name=\"SelectedAPI\" value=\"" + apiopt + "\">");
        out.println("<table>");     
        out.println("<tr>");
        out.println("<td align=\"right\">Full Text:</td>");
        out.println("<td><input type=\"text\" name=\"ftx\"></td></tr>");
        out.println("<tr>");
        out.println("<td>&nbsp;</td>");
        out.println("<td><input type=\"submit\" value=\"Submit\"></td></tr>");
        out.println("</table>");
        out.println("</form>");
        out.println("</body></html>");
        out.flush();
        out.close();
    }
  
   private void getFile(HttpServletRequest request, HttpServletResponse response, String dID, String apiopt) throws IOException 
   {
        FileAttributes fattrib = null; 
        if (GEN_API.equals(apiopt))
        {
            WCCWSProxy wccp = new WCCWSProxy();
            fattrib = wccp.getFileAttributes(dID);
        }
        else if (NATIVE_API.equals(apiopt) || RIDC_API.equals(apiopt)) 
        {
            NativeProxy nwp = new NativeProxy(apiopt, request.getUserPrincipal().getName());
            fattrib = nwp.getFileAttributes(dID);
        }
           
        if (fattrib != null)
        {
            //response.setContentType(CONTENT_TYPE);
            response.setContentType(fattrib.getFformat());
            response.setContentLength(fattrib.getFsize());
            response.setHeader("Content-Transfer-Encoding", "binary");
            response.setHeader("Content-Disposition","attachment; filename=\"" + fattrib.getFname() + "\"");
            InputStream is = null;
            fileResponse fr = null;
            if (GEN_API.equals(apiopt))
            {
                WCCWSProxy wccp = new WCCWSProxy();
                fr = wccp.executeGetFile(dID);
            }
            else if (NATIVE_API.equals(apiopt) || RIDC_API.equals(apiopt))
            {
                NativeProxy nwp = new NativeProxy(apiopt, request.getUserPrincipal().getName());
                fr = nwp.executeGetFile(dID);
            }
            
            if ("0".equals(fr.getStatusCode()))
            {
                byte b[] = new byte[1024];
                int bytesread = 0;
                is = fr.getInputStream();
                while ((bytesread = is.read(b, 0, b.length)) != -1) {
                    response.getOutputStream().write(b, 0, bytesread);
                }
                
                response.getOutputStream().flush();
                is.close();
            }
            else 
            {
                reportError(request, response, fr.getStatusCode(), fr.getStatusMsg());
            }
        }
        else 
        {
            reportError(request, response, "-1", "Error retriving file attributes required for file download");  
        }
    }
    
    private void reportError(HttpServletRequest request, HttpServletResponse response, String errCode, String errmsg) 
    {
        try
        {
          String url = request.getRequestURI();
          response.setContentType(CONTENT_TYPE);
          StringBuffer rspbuf = new StringBuffer();
          rspbuf.append("<html>");
          rspbuf.append("<head><title>WebCenter Content Error</title></head>");
          rspbuf.append("<body>");
          rspbuf.append("<p><b><img src=" + request.getContextPath() + "/images/oraclelogo.png> WebCenter Content Error</b></p>");
          rspbuf.append("<p>Error : " + errCode + "-" + errmsg + " while integrating with Oracle WebCenter Content Over WebService Call</p>");
          rspbuf.append(("<p><a href=" + request.getRequestURL() + ">Back</a>"));
          rspbuf.append("</body></html>");
          response.setContentLength(rspbuf.toString().length());
          PrintWriter out = response.getWriter();
          out.write(rspbuf.toString());
          out.close();
        }
        catch (IOException ioe)
        {
          ioe.printStackTrace();
        }
    }
    
    private void reportCheckinSuccess(HttpServletRequest request, HttpServletResponse response, ucmResponse ucmrsp, String apiopt) 
    {
        try
        {
          String url = request.getRequestURI();
          response.setContentType(CONTENT_TYPE);
          StringBuffer rspbuf = new StringBuffer();
          HashMap meta = ucmrsp.getMetaFields();
          String contentid = (String)meta.get("dDocName");
          String did = (String)meta.get("dID");
          String title = (String)meta.get("dDocTitle");
          String author = (String)meta.get("dDocAuthor");
          rspbuf.append("<html>\r\n");
          rspbuf.append("<head><title>WebCenter Content Checkin Confirmation</title></head>\r\n");
          rspbuf.append("<body>");
          rspbuf.append("<p><b><img src=" + request.getContextPath() + "/images/oraclelogo.png> WebCenter Content Checkin Confirmation</b></p>\r\n");
          rspbuf.append("<p><u>Check-In Confirmation for '" + title + "'</u></p>\r\n");
          rspbuf.append("<p><b>Content ID:</b> " + contentid + " <a href=\"" + request.getRequestURI() + "?IdcService=Info&dDocName=" + contentid + "&dID=" + did + "&SelectedAPI=" + apiopt + "\">[Content Info]</a></p>\r\n");
          rspbuf.append("<p><b>Title:</b> " + title + "</p>\r\n");
          rspbuf.append("<p><b>Checked In By: </b>" + author + "</p>\r\n");
          rspbuf.append("</body>\r\n</html>");
          int length = rspbuf.toString().length();
          response.setContentLength(length);
          PrintWriter out = response.getWriter();
          out.write(rspbuf.toString());
          out.close();
        }
        catch (IOException ioe)
        {
          ioe.printStackTrace();
        }
    }
}
