Example usage for javax.servlet ServletContext getAttribute

List of usage examples for javax.servlet ServletContext getAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletContext getAttribute.

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the servlet container attribute with the given name, or null if there is no attribute by that name.

Usage

From source file:com.concursive.connect.web.modules.login.auth.session.SessionValidatorFactory.java

public ISessionValidator getSessionValidator(ServletContext context, HttpServletRequest request) {
    // Retrieve prefs to use global connection info
    ApplicationPrefs prefs = (ApplicationPrefs) context.getAttribute("applicationPrefs");
    // Connection info
    ConnectionElement ce = new ConnectionElement();
    ce.setDriver(prefs.get("SITE.DRIVER"));
    ce.setUrl(prefs.get("SITE.URL"));
    ce.setUsername(prefs.get("SITE.USER"));
    ce.setPassword(prefs.get("SITE.PASSWORD"));
    ConnectionPool sqlDriver = (ConnectionPool) context.getAttribute("ConnectionPool");
    // Determine session validator class to use, or default
    Connection db = null;//from  ww w . j a  v a  2s  . c om
    String className = null;
    try {
        String loginMode = ((ApplicationPrefs) context.getAttribute("applicationPrefs"))
                .get(ApplicationPrefs.LOGIN_MODE);
        LOG.debug("Seeking Session Authenticator for Mode: " + loginMode);
        // Get connection
        db = sqlDriver.getConnection(ce);
        // Get specified authentication class
        AuthenticationClassesLookupList aclList = new AuthenticationClassesLookupList();
        aclList.setLoginMode(loginMode);
        aclList.buildList(db);
        if (aclList.size() == 0) {
            className = DEFAULT_SESSION_VALIDATOR;
        } else {
            AuthenticationClassesLookup acl = aclList.get(0);
            className = acl.getLoginAuthenticator();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (db != null) {
            sqlDriver.free(db);
        }
    }
    // Instantiate the authenticator class
    try {
        if (className == null) {
            className = DEFAULT_SESSION_VALIDATOR;
        }
        Class clazz = Class.forName(className);
        return (ISessionValidator) clazz.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.happyuno.controller.StartGame.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*  w  w w . j  a  v a  2s  . c o m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html;charset=utf-8");
    request.setCharacterEncoding("utf-8");

    //?tableId
    String tableId = (String) request.getParameter("tableId");

    System.out.println(tableId);
    //?userId
    String userId = (String) request.getSession().getAttribute("userId");

    //
    ServletContext application = request.getSession().getServletContext();
    HashMap<Integer, GameTable> gameTableMap = (HashMap<Integer, GameTable>) application
            .getAttribute("gameTableMap");

    String resultMessage = "??";

    //User??Player
    ArrayList<Player> players = new ArrayList<Player>();

    int tindex = Integer.parseInt(tableId);
    GameTable gt = gameTableMap.get(tindex);
    ArrayList<User> userList = gt.getUserList();

    resultMessage = "??";
    //????
    gt.setStateStart(true);
    System.out.println(userList.size() + "changdu");
    for (int i = 0; i < userList.size(); i++) {
        //Playerid,nameUser?
        System.out.println(i + "position");
        String curUserId = ((User) userList.get(i)).getId();
        System.out.println("UserId" + curUserId);
        int cUserId = Integer.parseInt(curUserId);
        String curUserName = ((User) userList.get(i)).getName();
        Player curPlayer = new Player(cUserId, curUserName);
        players.add(curPlayer);
    }
    gt.getCurrentGame().initGame(players);

    HttpSession session = request.getSession();
    session.setAttribute("tableId", tindex);
    session.setAttribute("players", players);
    session.setAttribute("curPlayerId", Integer.parseInt(userId));

    //
    application.setAttribute("gameTableMap", gameTableMap);

    //tableMap?
    application.setAttribute("tatoNum", gameTableMap.size());

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/table.jsp");
    dispatcher.forward(request, response);

}

From source file:com.happyuno.controller.JoinGameTable.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=utf-8");
    request.setCharacterEncoding("utf-8");

    //?//w w  w.  java2s  .c  o  m
    String tableId = (String) request.getParameter("tableId");
    //      int tableId =Integer.parseInt(request.getSession().getAttribute("tableId").toString());

    //      String setNum = request.getParameter("setNum").trim();

    //      
    ServletContext application = request.getSession().getServletContext();
    HashMap<Integer, GameTable> gameTableMap = (HashMap<Integer, GameTable>) application
            .getAttribute("gameTableMap");

    //?ID user
    String userId = (String) request.getSession().getAttribute("userId");
    maindeal md = new maindeal();
    List dbUserList = md.query("from User as u where u.id='" + userId + "'");
    User curUser = (User) dbUserList.get(0);

    //
    String resultMessage = "?";
    int index = Integer.parseInt(tableId);
    System.out.println(index);
    //
    GameTable gametable = gameTableMap.get(index);
    if (gametable == null) {
        System.out.println("true");
    }

    int defiNum = gametable.getDefiNum();

    //
    if (gametable.isStateStart() == false) { //?
        if (gametable.getUserList().size() < defiNum) { //??
            if (!gametable.getUserList().contains(curUser)) {
                gametable.getUserList().add(curUser);
            }
            resultMessage = "??";
        } else {
            resultMessage = "???";
        }
    } else {
        resultMessage = "????";
    }

    //
    application.setAttribute("gameTableMap", gameTableMap);

    //??
    HttpSession session = request.getSession();
    session.setAttribute("tableId", index);
    session.setAttribute("userList", gameTableMap.get(index).getUserList());

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/waiting.jsp");
    dispatcher.forward(request, response);

    //      PrintWriter out = response.getWriter();
    //      out.print("ID");
    //      out.println(userId);
    //      out.print("?:");
    //      out.println(resultMessage);
    //      out.print("?");
    //      out.println(gametable.getUserList().size());

}

From source file:com.ocpsoft.pretty.faces.el.resolver.SpringBeanNameResolver.java

public boolean init(ServletContext servletContext, ClassLoader classLoader) {

    // try to get WebApplicationContext from ServletContext
    webAppContext = servletContext.getAttribute("org.springframework.web.context.WebApplicationContext.ROOT");

    // Not found? Disable resolver!
    if (webAppContext == null) {
        if (log.isDebugEnabled()) {
            log.debug("WebApplicationContext not found in ServletContext. Resolver has been disabled.");
        }//from ww w  . j a v a 2s .  com
        return false;
    }

    // catch reflection failures
    try {
        // get findBeanNamesByType method
        Class<?> webAppContextClass = classLoader.loadClass(WEB_APP_CONTEXT_CLASS);
        getBeanNamesMethod = webAppContextClass.getMethod(GET_BEAN_NAMES_METHOD, Class.class);

        // init successful
        if (log.isDebugEnabled()) {
            log.debug("Spring detected. Enabling Spring bean name resolving.");
        }
        return true;

    } catch (ClassNotFoundException e) {
        // will happen when Spring is not on the classpath
        if (log.isDebugEnabled()) {
            log.debug("WebApplicationContext class could not be found. Resolver has been disabled.");
        }
    } catch (NoSuchMethodException e) {
        // Spring is expected to offer this methods
        log.warn("Cannot find getBeanNamesByType() method.", e);
    } catch (SecurityException e) {
        // security issues
        log.warn("Unable to init resolver due to security restrictions", e);
    }

    // resolver will be disabled
    return false;

}

From source file:org.apache.pluto.driver.tags.PortletModeAnchorTag.java

/**
 * Method invoked when the start tag is encountered.
 * @throws JspException  if an error occurs.
 *//*ww w.j  ava2 s . co  m*/
public int doStartTag() throws JspException {

    // Ensure that the modeAnchor tag resides within a portlet tag.
    PortletTag parentTag = (PortletTag) TagSupport.findAncestorWithClass(this, PortletTag.class);
    if (parentTag == null) {
        throw new JspException("Portlet window controls may only reside " + "within a pluto:portlet tag.");
    }

    portletId = parentTag.getPortletId();
    // Evaluate portlet ID attribute.
    evaluatePortletId();

    // Retrieve the portlet window config for the evaluated portlet ID.
    ServletContext servletContext = pageContext.getServletContext();
    DriverConfiguration driverConfig = (DriverConfiguration) servletContext
            .getAttribute(AttributeKeys.DRIVER_CONFIG);

    if (isPortletModeAllowed(driverConfig, portletMode)) {
        // Retrieve the portal environment.
        PortalRequestContext portalEnv = PortalRequestContext
                .getContext((HttpServletRequest) pageContext.getRequest());

        PortalURL portalUrl = portalEnv.createPortalURL();
        portalUrl.setPortletMode(evaluatedPortletId, new PortletMode(portletMode));

        // Build a string buffer containing the anchor tag
        StringBuffer tag = new StringBuffer();
        //            tag.append("<a class=\"" + ToolTips.CSS_CLASS_NAME + "\" href=\"" + portalUrl.toString() + "\">");
        //            tag.append("<span class=\"" + portletMode + "\"></span>");
        //            tag.append("<span class=\"" + ToolTips.CSS_CLASS_NAME + "\">");
        //            tag.append(ToolTips.forMode(new PortletMode(portletMode)));
        //            tag.append("</span></a>");
        tag.append("<a title=\"");
        tag.append(ToolTips.forMode(new PortletMode(portletMode)));
        tag.append("\" ");
        tag.append("href=\"" + portalUrl.toString() + "\">");
        tag.append("<span class=\"" + portletMode + "\"></span>");
        tag.append("</a>");
        // Print the mode anchor tag.
        try {
            JspWriter out = pageContext.getOut();
            out.print(tag.toString());
        } catch (IOException ex) {
            throw new JspException(ex);
        }
    }

    // Continue to evaluate the tag body.
    return EVAL_BODY_INCLUDE;
}

From source file:com.skilrock.lms.embedded.roleMgmt.common.PrivsInterceptor.java

public boolean isSaleDuration(UserInfoBean userInfoBean) {
    Date d = new Date();
    ServletContext sc = ServletActionContext.getServletContext();
    if (d.toString().split(" ")[3].compareTo((String) sc.getAttribute("SALE_START_TIME")) >= 0
            && d.toString().split(" ")[3].compareTo((String) sc.getAttribute("SALE_END_TIME")) <= 0) {
        return true;
    }//w  w  w . j  a  va2  s  . co m
    return false;
}

From source file:io.neba.core.logviewer.LogfileViewerConsolePlugin.java

/**
 * The {@link #DECORATED_OBJECT_FACTORY} is a dependency for using websockets and may not be registered,
 * depending on the jetty runtime setup. If it is not registered, this method loads and registers it.
 *//*from  w  w  w.jav a2  s.com*/
private void injectDecoratorObjectFactoryIntoServletContext()
        throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    ServletContext servletContext = getServletContext();
    if (servletContext.getAttribute(DECORATED_OBJECT_FACTORY) != null || !isDecoratedObjectFactoryAvailable()) {
        return;
    }

    servletContext.setAttribute(DECORATED_OBJECT_FACTORY, forName(DECORATED_OBJECT_FACTORY).newInstance());
    this.isManagingDecoratedObjectFactory = true;
}

From source file:com.betfair.tornjak.monitor.overlay.AuthUtilsTest.java

@Test
public void testCreateRolePerms() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletContext context = mock(ServletContext.class);
    ApplicationContext appContext = mock(ApplicationContext.class);

    Principal p = mock(Principal.class);

    when(context.getAttribute("com.betfair.tornjak.monitor.overlay.RolePerms")).thenReturn(null);
    when(context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE))
            .thenReturn(appContext);/*from ww  w  .ja v  a 2  s.  c o  m*/
    when(context.getInitParameter("contextAuthConfigLocation")).thenReturn("somewhere");
    when(appContext.getResource("somewhere")).thenReturn(
            new DefaultResourceLoader().getResource("com/betfair/tornjak/monitor/overlay/auth.properties"));

    when(request.getUserPrincipal()).thenReturn(p);
    when(request.isUserInRole("jmxadmin")).thenReturn(true);

    Auth auth = AuthUtils.checkAuthorised(request, response, context);

    assertThat(auth, notNullValue());
    assertThat("User should be authorised", auth.check(), equalTo(AUTHORISED));
}

From source file:de.appsolve.padelcampus.utils.HtmlResourceUtil.java

public String getAllMinCss(ServletContext context, String customerName) throws IOException {
    return (String) context.getAttribute(customerName);
}

From source file:com.medlog.webservice.rest.ApplicationBean.java

public ApplicationBean(ServletContext context) {
    try {/*  ww w .j  a v  a 2s.  com*/
        try {
            if (context.getAttribute(APPLICATION_STATE_BEAN) != null) {
                this.statesMap = (Map<Integer, StateVO>) context.getAttribute(APPLICATION_STATE_BEAN);
                stateSet = !statesMap.isEmpty();
            }
        } catch (Exception ea) {

        }
        try {
            if (context.getAttribute(APPLICATION_SIG_BEAN) != null) {
                this.sigMap = (Map<String, SigVO>) context.getAttribute(APPLICATION_SIG_BEAN);
                sigSet = !sigMap.isEmpty();
            }
        } catch (Exception eb) {

        }
        try {
            if (context.getAttribute(APPLICATION_RX_BEAN) != null) {
                this.rxMap = (Map<Integer, PharmaRxOtcVO>) context.getAttribute(APPLICATION_RX_BEAN);
                rxSet = !rxMap.isEmpty();
            }
        } catch (Exception ec) {

        }
    } catch (Exception e) {

    }
    this.context = context;
}