学习uportal-1

org.jasig.portal下的PortalSessionManager是uportal的入口类


package  org.jasig.portal;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jasig.portal.channels.portlet.CPortletAdapter;
import org.jasig.portal.jndi.JNDIManager;
import org.jasig.portal.services.LogService;
import org.jasig.portal.utils.ResourceLoader;

扩展HttpServlet,作为portal container
public class PortalSessionManager extends HttpServlet {

  public static final String INTERNAL_TAG_VALUE=Long.toHexString((new Random()).nextLong());
  public static final String IDEMPOTENT_URL_TAG="idempotent";

  private static boolean initialized = false; 是否初始化
  private static ServletContext servletContext = null;
  private static PortalSessionManager instance = null;
  private static boolean fatalError = false;
 
  public static final ErrorID initPortalContext = new ErrorID("config","JNDI","Cannot initialize JNDI context");

  /**
 返回实例
   */
  public static final PortalSessionManager getInstance() {
     return instance;
  }

  // Following flag allows to disable features that prevent
  // repeated requests from going through. This is useful
  // when debugging and typing things in on a command line.
  // Otherwise, the flag should be set to false.
  private static final boolean ALLOW_REPEATED_REQUESTS = PropertiesManager.getPropertyAsBoolean("org.jasig.portal.PortalSessionManager.allow_repeated_requests");

  //  产生随机数
  private static final Random randomGenerator = new Random();

  static {
    LogService.log(LogService.INFO, "uPortal started");
  }

  /**
   * Initialize the PortalSessionManager servlet
   * @throws ServletException
   */
  public void init() throws ServletException {
    if(!initialized) {
      instance = this;
      // Retrieve the servlet configuration object from the servlet container
      // and make sure it's available
      ServletConfig sc = getServletConfig();
      if (sc == null) {
        throw new ServletException("PortalSessionManager.init(): ServletConfig object was returned as null");
      }
     
      // Supply PortletContainer with ServletConfig
      CPortletAdapter.setServletConfig(sc);
     
      servletContext = sc.getServletContext();

      try {
          JNDIManager.initializePortalContext();
      } catch (Exception pe) {
         ExceptionHelper.genericTopHandler(initPortalContext,pe);
         fatalError=true;
      }
     
      // Turn off URL caching if it has been requested
      if (!PropertiesManager.getPropertyAsBoolean("org.jasig.portal.PortalSessionManager.url_caching")) {
         // strangely, we have to instantiate a URLConnection to turn off caching, so we'll get something we know is there
         try {
            URL url = ResourceLoader.getResourceAsURL(PortalSessionManager.class, "/properties/portal.properties");
            URLConnection conn = url.openConnection();
            conn.setDefaultUseCaches(false);
         } catch (Exception e) {
            LogService.log(LogService.WARN, "PortalSessionManager.init(): Caught Exception trying to disable URL Caching");
         }
      }

      // Log orderly shutdown time
      Runtime.getRuntime().addShutdownHook(new Thread("uPortal shutdown hook") {
          public void run() {
            LogService.log(LogService.INFO, "uPortal stopped");
          }
        });


      // Flag that the portal has been initialized
      initialized = true;

      // Get the SAX implementation
      if (System.getProperty("org.xml.sax.driver") == null) {
          System.setProperty("org.xml.sax.driver", PropertiesManager.getProperty("org.xml.sax.driver"));
      }
    }
  }


    /**
     * Process HTTP POST request
     *
     * @param req an incoming <code>HttpServletRequest</code> value
     * @param res an outgoing <code>HttpServletResponse</code> value
     * @exception ServletException if an error occurs
     * @exception IOException if an error occurs
     */
    public void doPost(HttpServletRequest req, HttpServletResponse res)  {
        doGet(req, res);
    }

    /**
     * Process HTTP GET request.
     *
     * @param req an incoming <code>HttpServletRequest</code>
     * @param res an outgoing <code>HttpServletResponse</code>
     * @exception ServletException if an error occurs
     * @exception IOException if an error occurs
     */
    public void doGet(HttpServletRequest req, HttpServletResponse res) {
        // Send the uPortal version in a header
        res.setHeader("uPortal-version", "uPortal_rel-2-3-3");
       
        if (fatalError) {
            try {
                res.sendRedirect("error/fatal.htm");
            } catch (IOException e) {
                ExceptionHelper.genericTopHandler(Errors.bug,e);
            }
            return;
        }
       
        HttpSession session = req.getSession();

        if (session != null) {
            Set requestTags=null;
            boolean request_verified=false;

            if(!ALLOW_REPEATED_REQUESTS) {
                // obtain a tag table
                synchronized(session) {
                    requestTags=(Set)session.getAttribute("uP_requestTags");
                    if(requestTags==null) {
                        requestTags=Collections.synchronizedSet(new HashSet());
                        session.setAttribute("uP_requestTags",requestTags);
                    }
                }
                // determine current tag
                UPFileSpec upfs=new UPFileSpec(req);

                String tag=upfs.getTagId();

                // see if the tag was registered
                if(tag!=null) {
                    request_verified=(tag.equals(IDEMPOTENT_URL_TAG) || requestTags.remove(tag));
                }

                LogService.log(LogService.DEBUG, "PortalSessionManager::doGet() : request verified: "+request_verified);
            }

            try {
                UserInstance userInstance = null;
                try {
                    // Retrieve the user's UserInstance object
                    userInstance = UserInstanceManager.getUserInstance(req);
                } catch(Exception e) {
                 ExceptionHelper.genericTopHandler(Errors.bug,e);
                 ExceptionHelper.generateErrorPage(res,e);
                 return;
                }


                // fire away
                if(ALLOW_REPEATED_REQUESTS) {
                    userInstance.writeContent(new RequestParamWrapper(req,true),res);
                } else {
                    // generate and register a new tag
                    String newTag=Long.toHexString(randomGenerator.nextLong());
                    LogService.log(LogService.DEBUG,"PortalSessionManager::doGet() : generated new tag /""+newTag+"/" for the session "+req.getSession(false).getId());
                    // no need to check for duplicates :) we'd have to wait a lifetime of a universe for this time happen
                    if(!requestTags.add(newTag)) {
                        LogService.log(LogService.ERROR,"PortalSessionManager::doGet() : a duplicate tag has been generated ! Time's up !");
                    }

                    userInstance.writeContent(new RequestParamWrapper(req,request_verified), new ResponseSubstitutionWrapper(res,INTERNAL_TAG_VALUE,newTag));
                }
            } catch (Exception e) {
             ExceptionHelper.genericTopHandler(Errors.bug,e);
    ExceptionHelper.generateErrorPage(res,e);
             return;
           }

        } else {
            //throw new ServletException("Session object is null !");
        }

    }

  /**
   * Gets a URL associated with the named resource.
   * Call this to access files with paths relative to the
   * document root.  Paths should begin with a "/".
   * @param resource relative to the document root
   * @return a URL associated with the named resource or null if the URL isn't accessible
   * @throws java.net.MalformedURLException
   */
  public static URL getResourceAsURL(String resource) {
    //Make sure resource string starts with a "/"
    if (!resource.startsWith("/"))
      resource = "/" + resource;

    URL url = null;

    try {
      url = servletContext.getResource(resource);
    } catch (java.net.MalformedURLException murle) {
      // if the URL is bad, just return null
    }
    return url;
  }

  /**
   * Gets an input stream associated with the named resource.
   * Call this to access files with paths relative to the
   * document root. Paths should begin with a "/".
   * @param resource relative to the document root
   * @return an input stream assosiated with the named resource
   */
  public static java.io.InputStream getResourceAsStream(String resource) {
    //Make sure resource string starts with a "/"
    if (!resource.startsWith("/"))
      resource = "/" + resource;

    return servletContext.getResourceAsStream(resource);
  }

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值