BrowseArchiveController.java :  » Source-Control » sourcejammer » org » sourcejammer » web » servlet » Java Open Source

Java Open Source » Source Control » sourcejammer 
sourcejammer » org » sourcejammer » web » servlet » BrowseArchiveController.java
/*
 *  Copyright (C) 2001, 2002 Robert MacGrogan
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 *
 * $Archive: SourceJammer$
 * $FileName: BrowseArchiveController.java$
 * $FileID: 4407$
 *
 * Last change:
 * $AuthorName: Rob MacGrogan$
 * $Date: 8/25/03 9:16 PM$
 * $Comment: Made some static final fields public.$
 *
 * $KeyWordsOff: $
 */

package org.sourcejammer.web.servlet;

import javax.servlet.http.*;
import javax.servlet.*;
import org.sourcejammer.util.BadMethodArgumentException;
import org.sourcejammer.project.NodeList;
import org.sourcejammer.project.view.*;
import org.sourcejammer.server.ServerConfig;
import org.sourcejammer.server.make.EndOfSourceException;
import org.sourcejammer.server.source.TextLineReader;
import org.sourcejammer.project.NodeExistsException;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import java.util.Enumeration;
import org.sourcejammer.util.StringUtil;
import org.sourcejammer.project.NodeIterator;
import org.sourcejammer.project.view.NodeInfo;
import org.sourcejammer.project.view.*;
import org.sourcejammer.project.model.filesys.Util;
import org.sourcejammer.util.AppConfig;
import org.sourcejammer.util.ConfigurationException;
import org.sourcejammer.util.FileUtil;
import org.sourcejammer.util.TempDirectoryManager;


/**
 * Title:        SourceJammer 1.1
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:      SourceJammer
 * @author Robert MacGrogan
 * @version 1.0
 */

public class BrowseArchiveController extends HttpServlet implements SJRequestParams, SJResponseParams {

  private ServletConfig mConfig = null;
  public static final String BINARY_MIME_TYPE = "application/octet-stream";

  public static final String EXCEPTION_ATTR_NAME = "javax.servlet.jsp.jspException";
  public static final String ERROR_PAGE = "error.jsp";

  private static final class Commands{
    public static final String CONNECT_TO_ARCHIVE = "open_archive";
    public static final String GO_PARENT = "go_parent";
    public static final String GO_PROJECT = "go_project";
    public static final String GO_FILE = "go_file";
    public static final String GET_FILE = "get_file";
    public static final String GET_FILE_VERSION = "get_version";
    public static final String SHOW_FILE = "show_file";
  }

  public static final class Params{
    public static final String COMMAND = "Command";
    public static final String ARCHIVE_NAME = "archive_name";
    public static final String ID = "id";
    public static final String PARENT = "parent";
    public static final String CURRENT_PROJECT = "curr_project";
    public static final String PARENTS = "parents";
    public static final String FILE_NAME = "file_name";
    public static final String CURRENT_FILE = "curr_file";
    public static final String VERSION_NUMBER = "ver_num";
    public static final String EOL_TYPE = "eol";
    public static final String TYPE = "type";
    public static final String NO_FORMAT = "noformat";
    public static final String DOWNLOAD = "download";
  }

  private static final class SessionParams{
    public static final String SESSION_ID = "session_id";
    public static final String PARENT_LIST = "parent_list";
    public static final String ARCHIVE_NAME = "archive_name";
  }

  private static final class URLs{
    public static final String PROJECT = "project.jsp";
    public static final String FILE = "file.jsp";
  }

  public BrowseArchiveController() {
    super();
  }

  /**
   * Initialize global variables and load the configuration information.
   *
   * @param config configuration data for the servlet from the web.xml file.
   *
   * @exception ServletException thrown when there is an exception processing the
   *  configuration data.
   */
  public void init(ServletConfig config) throws ServletException{
    mConfig = config;
    super.init(config);
  }

  //Process the HTTP Get request
  public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException{
    process(request, response);
  }

  //Process the HTTP Post request
  public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException{
    process(request, response);
  }

  /**
   * Processes both post and get requests.
   */
  protected void process(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException{
    try{
      String command = request.getParameter(Params.COMMAND);
      if (command == null){
        throw new BadMethodArgumentException("No command found in request.");
      }
      String nextURL = null;
      if (command.equalsIgnoreCase(Commands.CONNECT_TO_ARCHIVE)){
        nextURL = connectToArchive(request);
        forward(request, response, nextURL);
      }
      else if (command.equalsIgnoreCase(Commands.GO_PROJECT)){
        nextURL = displayProject(request);
        forward(request, response, nextURL);
      }
      else if (command.equalsIgnoreCase(Commands.GO_PARENT)){
        nextURL = displayProjectParent(request);
        forward(request, response, nextURL);
      }
      else if (command.equalsIgnoreCase(Commands.GET_FILE)){
        getFile(request, response);
      }
      else if (command.equalsIgnoreCase(Commands.GET_FILE_VERSION)){
        getFileVersion(request, response);
      }
      else if (command.equalsIgnoreCase(Commands.GO_FILE)){
        nextURL = displayFile(request);
        forward(request, response, nextURL);
      }
      else if (command.equalsIgnoreCase(Commands.SHOW_FILE)){
        showFile(request, response);
      }
    }
    catch (Exception ex){
      displayException(request, response, ex);
    }
  }

  protected void showFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, EndOfSourceException{
    String sFileID = request.getParameter(Params.ID);
    if (sFileID == null || sFileID.equals("")){
      throw new BadMethodArgumentException("No file ID found in request.");
    }
    long lFileID = Long.parseLong(sFileID.trim());

    String sFileName = request.getParameter(Params.FILE_NAME);
    if (sFileName == null || sFileName.equals("")){
      throw new BadMethodArgumentException("No file name found in request.");
    }

    SJRequest sjRequest = getBaseRequest(request);
    sjRequest.putLong(REQUESTED_NODE_UNIQUE_ID, lFileID);
    SJResponse sjResponse = MasterControlProgram.getFileLatestVersion(sjRequest);
    if (sjResponse.getErrorEncountered()){
      throw new ServletException(sjResponse.getMessage());
    }
    DownloadFileIdentifier downloadID = sjResponse.downloadFileIdentifierValue();
    long lTempID = downloadID.getUniqueID();
    java.io.File flTemp = TempDirectoryManager.getTempFileById(lTempID);
    
    //Now let's read the file so we can display it.
//    FileInputStream stmIn = new FileInputStream(flTemp);
//    try{
//      BufferedInputStream stmBuff = new BufferedInputStream(stmIn);
//      TextLineReader reader = new TextLineReader(stmBuff);
//      reader.initIgnoreKeywords();

    byte[] fileBytes = FileUtil.readBytesFromFileSys(flTemp);
    String file = new String(fileBytes, AppConfig.getInstance().getTextEncodingCharset());
    file = StringUtil.replaceSubstring(file, "&", "&");
    file = StringUtil.replaceSubstring(file, "<", "&lt;");
    file = StringUtil.replaceSubstring(file, ">", "&gt;");
      PrintWriter out = new PrintWriter (response.getOutputStream());
      response.setContentType("text/html");
      out.println("<html><head><title>SourceJammer (" + sFileName + ")</title>");
      out.println("<body>\r\n<code><pre>");
      out.println(file);
//      while(reader.hasMoreLines()){  
//        String line = reader.getNextLine();
//        line = StringUtil.replaceSubstring(line, " ", "&nbsp;");
//        line = StringUtil.replaceSubstring(line, "\t", "&nbsp;&nbsp;");
//        line = StringUtil.replaceSubstring(line, "<", "&lt;");
//        line = StringUtil.replaceSubstring(line, ">", "&gt;");
//        out.println(line + "<br>");
//      }
      out.println("\r\n</pre></code>\r\n</body></html>");
      out.close();
//    }
//    finally{
//      stmIn.close();
//    }
  }

  /**
   * Called by post() to connect to an archive as anon user.
   */
  protected String connectToArchive(HttpServletRequest request)
        throws ServletException, NodeExistsException{
    String sArchiveName = request.getParameter(Params.ARCHIVE_NAME);
    if (sArchiveName == null || sArchiveName.equals("")){
      throw new BadMethodArgumentException("No archive name found in request.");
    }
    ServerConfig config = ServerConfig.getInstance();

    //First check if user is connected and disconnect him/her.
    HttpSession session = request.getSession(true);
    Long lngSessionId = (Long)session.getAttribute(SessionParams.SESSION_ID);
    if (lngSessionId != null){
      //There is a current session. Dicconnect it.
      SJRequest sjDisconnectRequest = getBaseRequest(request);
      MasterControlProgram.disconnect(sjDisconnectRequest);
    }

    SJRequest sjRequest = new SJRequest();
    sjRequest.setArchiveName(sArchiveName);
    sjRequest.setUserName(config.getAnonymousUserName());
    sjRequest.setPassword(config.getAnonymousUserName());
    SJResponse sjResponse = MasterControlProgram.connect(sjRequest);
    if (sjResponse.getErrorEncountered()){
      throw new ServletException(sjResponse.getMessage());
    }
    session.setAttribute(SessionParams.SESSION_ID, new Long(sjResponse.getSessionID()));
    Project rootProject = sjResponse.projectValue();
    try{
      rootProject.buildChildrenFromStrings();
    }
    catch (NodeExistsException ex){
      throw new ConfigurationException(ex.getMessage(), ex);
    }
    request.setAttribute(Params.CURRENT_PROJECT, rootProject);
    Vector parentList = new Vector();

    WebProjectPathElement thisElement = getPathElement(rootProject);
    thisElement.setIndex(0);
    parentList.add(thisElement);

    session.setAttribute(SessionParams.PARENT_LIST, parentList);
    session.setAttribute(SessionParams.ARCHIVE_NAME, sArchiveName);
    request.setAttribute(Params.PARENTS, parentList.elements());
    return URLs.PROJECT;
  }

  /**
   * Returns a new WebProjectPathElement based on the Project passed in.
   */
  protected WebProjectPathElement getPathElement(Project proj){
    WebProjectPathElement thisElement = new WebProjectPathElement();
    thisElement.setNodeName(proj.getNodeName());
    thisElement.setUniqueID(proj.getUniqueID());
    return thisElement;
  }

  /**
   * Displays info about a parent of the current project in the project page.
   */
  protected String displayProjectParent(HttpServletRequest request)
        throws ServletException, NodeExistsException {
    String sParentIndex = request.getParameter(Params.PARENT);
    if (sParentIndex ==  null || sParentIndex.equals("")){
      throw new BadMethodArgumentException("No parent ID found in request.");
    }
    int iParentIndex = Integer.parseInt(sParentIndex.trim());

    HttpSession session = request.getSession(true);
    Vector parentList = (Vector)session.getAttribute(SessionParams.PARENT_LIST);
    WebProjectPathElement element = (WebProjectPathElement)parentList.get(iParentIndex);
    long lProjectID = element.getUniqueID();
    //The new parent will be one before this one.
    iParentIndex = iParentIndex - 1;
    return displayProject(request, lProjectID, iParentIndex);
  }

  /**
   * Displays info about a project in the project page.
   */
  protected String displayProject(HttpServletRequest request)
        throws ServletException, NodeExistsException {
    String sProjectID = request.getParameter(Params.ID);
    if (sProjectID == null || sProjectID.equals("")){
      throw new BadMethodArgumentException("No project ID found in request.");
    }
    long lProjectID = Long.parseLong(sProjectID.trim());

    String sParentIndex = request.getParameter(Params.PARENT);
    if (sParentIndex ==  null || sParentIndex.equals("")){
      throw new BadMethodArgumentException("No parent ID found in request.");
    }
    int iParentIndex = Integer.parseInt(sParentIndex.trim());
    return displayProject(request, lProjectID, iParentIndex);
  }

  /**
   * Gets Project from the server.
   */
  protected String displayProject(HttpServletRequest request, long lProjectID, int iParentIndex)
        throws ServletException, NodeExistsException {
    SJRequest sjRequest = getBaseRequest(request);
    sjRequest.putLong(REQUESTED_NODE_UNIQUE_ID, lProjectID);
    SJResponse sjResponse = MasterControlProgram.getProjectInfo(sjRequest);
    if (sjResponse.getErrorEncountered()){
      throw new ServletException(sjResponse.getMessage());
    }
    Project proj = sjResponse.projectValue();
    try{
      proj.buildChildrenFromStrings();
    }
    catch (NodeExistsException ex){
      throw new ConfigurationException(ex.getMessage(), ex);
    }

    //Sort child nodes.
    NodeIterator children = proj.childNodes();
    children = StringUtil.sortNodeIterator(children);
    NodeInfo[] childrenArray = new NodeInfo[proj.childCount()];
    int iCounter = 0;
    while (children.hasMoreNodes()){
      childrenArray[iCounter] = (NodeInfo)children.getNextNode();
      iCounter++;
    }
    NodeList list = new NodeList();
    list.setContentsFromArray(childrenArray);
    
    proj.useChildNodeList(list);

    request.setAttribute(Params.CURRENT_PROJECT, proj);
    HttpSession session = request.getSession(true);

    Vector parentList = (Vector)session.getAttribute(SessionParams.PARENT_LIST);
    if (iParentIndex < parentList.size() - 1) {
      for (int i = parentList.size() - 1; i > iParentIndex; i--){
        parentList.remove(i);
      }
    }
    WebProjectPathElement thisElement = getPathElement(proj);
    thisElement.setIndex(parentList.size());
    parentList.add(thisElement);

    request.setAttribute(Params.CURRENT_PROJECT, proj);
    request.setAttribute(Params.PARENTS, parentList.elements());
    return URLs.PROJECT;
  }


  /**
   * Displays info about a file on the file page.
   */
  protected String displayFile(HttpServletRequest request)
        throws ServletException, NodeExistsException {
    String sFileID = request.getParameter(Params.ID);
    if (sFileID == null || sFileID.equals("")){
      throw new BadMethodArgumentException("No file ID found in request.");
    }
    long lFileID = Long.parseLong(sFileID.trim());

    String sParentIndex = request.getParameter(Params.PARENT);
    if (sParentIndex ==  null || sParentIndex.equals("")){
      throw new BadMethodArgumentException("No parent ID found in request.");
    }
    int iParentIndex = Integer.parseInt(sParentIndex.trim());
    SJRequest sjRequest = getBaseRequest(request);
    sjRequest.putLong(REQUESTED_NODE_UNIQUE_ID, lFileID);
    SJResponse sjResponse = MasterControlProgram.getFileInfo(sjRequest);
    if (sjResponse.getErrorEncountered()){
      throw new ServletException(sjResponse.getMessage());
    }
    File file = sjResponse.fileValue();
    try{
      file.buildChildrenFromStrings();
    }
    catch (NodeExistsException ex){
      throw new ConfigurationException(ex.getMessage(), ex);
    }

    
    request.setAttribute(Params.CURRENT_FILE, file);
    HttpSession session = request.getSession(true);

    Vector parentList = (Vector)session.getAttribute(SessionParams.PARENT_LIST);
    if (iParentIndex <= parentList.size() - 1) {
      for (int i = parentList.size() - 1; i > iParentIndex; i--){
        parentList.remove(i);
      }
    }
    request.setAttribute(Params.PARENTS, parentList.elements());
    return URLs.FILE;
  }


  /**
   * Returns a SJRequest object with initial parameters set.
   */
  protected SJRequest getBaseRequest(HttpServletRequest request){
    SJRequest sjRequest = new SJRequest();
    HttpSession session = request.getSession(true);
    String sArchiveName = (String)session.getAttribute(SessionParams.ARCHIVE_NAME);
    Long lngSessionId = (Long)session.getAttribute(SessionParams.SESSION_ID);
    if (sArchiveName == null ){
      throw new BadMethodArgumentException("Could not locate archive name. Session has expired.");
    }
    long lSessionID = -1;
    if (lngSessionId != null){
      lSessionID = lngSessionId.longValue();
    }
    sjRequest.setArchiveName(sArchiveName);
    sjRequest.setSessionID(lSessionID);
    ServerConfig conf = ServerConfig.getInstance();
    sjRequest.setUserName(conf.getAnonymousUserName());
    sjRequest.setPassword(conf.getAnonymousUserName());
    return sjRequest;
  }

  /**
   * Forwards to the error page, which displays info about the Exception.
   */
  protected void displayException(HttpServletRequest request, HttpServletResponse response, Exception ex)
        throws ServletException, IOException {
    request.setAttribute(EXCEPTION_ATTR_NAME, ex);
    forward(request, response, ERROR_PAGE);
  }//end displayException(request, response, Exception)


  /**
   * Downloads the requested file to the user's web browser.
   */
  protected void getFile(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException{

    String sFileID = request.getParameter(Params.ID);
    if (sFileID == null || sFileID.equals("")){
      throw new BadMethodArgumentException("No file ID found in request.");
    }
    long lFileID = Long.parseLong(sFileID.trim());

    String sFileName = request.getParameter(Params.FILE_NAME);
    if (sFileName == null || sFileName.equals("")){
      throw new BadMethodArgumentException("No file name found in request.");
    }

    SJRequest sjRequest = getBaseRequest(request);
    sjRequest.putLong(REQUESTED_NODE_UNIQUE_ID, lFileID);

    String sEOLType = request.getParameter(Params.EOL_TYPE);
    if (sEOLType != null && ! sEOLType.equals("")){
      int iEOLType = Integer.parseInt(sEOLType.trim());
      sjRequest.putInt(REQUESTED_EOL_TYPE, iEOLType);
    }

    SJResponse sjResponse = MasterControlProgram.getFileLatestVersion(sjRequest);
    if (sjResponse.getErrorEncountered()){
      throw new ServletException(sjResponse.getMessage());
    }
    DownloadFileIdentifier downloadID = sjResponse.downloadFileIdentifierValue();
    long lTempID = downloadID.getUniqueID();
    java.io.File flTemp = TempDirectoryManager.getTempFileById(lTempID);
    sendFile(request, response, flTemp, sFileName);
  }

  /**
   * Downloads the requested file version to the user's web browser.
   */
  protected void getFileVersion(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException{

    String sFileID = request.getParameter(Params.ID);
    if (sFileID == null || sFileID.equals("")){
      throw new BadMethodArgumentException("No file ID found in request.");
    }
    long lFileID = Long.parseLong(sFileID.trim());

    String sFileName = request.getParameter(Params.FILE_NAME);
    if (sFileName == null || sFileName.equals("")){
      throw new BadMethodArgumentException("No file name found in request.");
    }

    String sVersionNum = request.getParameter(Params.VERSION_NUMBER);
    if (sVersionNum == null || sVersionNum.equals("")){
      throw new BadMethodArgumentException("No version number found in request.");
    }
    int iVersionNumber = Integer.parseInt(sVersionNum.trim());


    SJRequest sjRequest = getBaseRequest(request);
    sjRequest.putLong(REQUESTED_NODE_UNIQUE_ID, lFileID);
    sjRequest.putInt(VERSION_NUMBER, iVersionNumber);

    String sEOLType = request.getParameter(Params.EOL_TYPE);
    if (sEOLType != null && ! sEOLType.equals("")){
      int iEOLType = Integer.parseInt(sEOLType.trim());
      sjRequest.putInt(REQUESTED_EOL_TYPE, iEOLType);
    }

    SJResponse sjResponse = MasterControlProgram.getFileVersion(sjRequest);
    if (sjResponse.getErrorEncountered()){
      throw new ServletException(sjResponse.getMessage());
    }
    DownloadFileIdentifier downloadID = sjResponse.downloadFileIdentifierValue();
    long tempID = downloadID.getUniqueID();
    java.io.File fl = TempDirectoryManager.getTempFileById(tempID);
    sendFile(request, response, fl, sFileName);
  }


  /**
   * Forwards control to the specified page.
   */
  protected void forward(HttpServletRequest request, HttpServletResponse response, String location)
        throws ServletException, IOException {
    RequestDispatcher dispatcher = mConfig.getServletContext().getRequestDispatcher("/" + location);
    if (dispatcher == null){
      throw new ServletException("Attempt to forward to the following URL failed: " + location);
    }
    dispatcher.forward(request, response);
  }

  /**
   * Sends the file as the response to the user's browser.
   */
  protected void sendFile(HttpServletRequest request, HttpServletResponse response,
          java.io.File fl, String fileName)
      throws IOException{
    byte[] file = FileUtil.readBytesFromFileSys(fl);
    ServletOutputStream out = response.getOutputStream();
    response.setContentType(BINARY_MIME_TYPE);
    response.setHeader("Content-disposition", "attachment; filename=" + fileName);
    out.write(file);
  }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.