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:org.openmrs.contrib.metadatarepository.webapp.listener.StartupListener.java

/**
 * {@inheritDoc}/* w  w  w .  j a  v a 2 s .  com*/
 */
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent event) {
    log.debug("Initializing context...");

    ServletContext context = event.getServletContext();

    // Orion starts Servlets before Listeners, so check if the config
    // object already exists
    Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG);

    if (config == null) {
        config = new HashMap<String, Object>();
    }

    if (context.getInitParameter(Constants.CSS_THEME) != null) {
        config.put(Constants.CSS_THEME, context.getInitParameter(Constants.CSS_THEME));
    }

    ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    /*String[] beans = ctx.getBeanDefinitionNames();
    for (String bean : beans) {
    log.debug(bean);
    }*/

    PasswordEncoder passwordEncoder = null;
    try {
        ProviderManager provider = (ProviderManager) ctx
                .getBean("org.springframework.security.authentication.ProviderManager#0");
        for (Object o : provider.getProviders()) {
            AuthenticationProvider p = (AuthenticationProvider) o;
            if (p instanceof RememberMeAuthenticationProvider) {
                config.put("rememberMeEnabled", Boolean.TRUE);
            } else if (ctx.getBean("passwordEncoder") != null) {
                passwordEncoder = (PasswordEncoder) ctx.getBean("passwordEncoder");
            }
        }
    } catch (NoSuchBeanDefinitionException n) {
        log.debug("authenticationManager bean not found, assuming test and ignoring...");
        // ignore, should only happen when testing
    }

    context.setAttribute(Constants.CONFIG, config);

    // output the retrieved values for the Init and Context Parameters
    if (log.isDebugEnabled()) {
        log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
        if (passwordEncoder != null) {
            log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName());
        }
        log.debug("Populating drop-downs...");
    }

    setupContext(context);
}

From source file:org.impalaframework.web.integration.ModuleProxyServlet.java

protected void processMapping(ServletContext context, HttpServletRequest request, HttpServletResponse response,
        RequestModuleMapping moduleMapping, String applicationId) throws ServletException, IOException {

    String attributeName = ModuleHttpServiceInvoker.class.getName() + "." + moduleMapping.getModuleName();
    Object attribute = context.getAttribute(attributeName);

    HttpServiceInvoker invoker = ObjectUtils.cast(attribute, HttpServiceInvoker.class);

    if (logger.isInfoEnabled()) {
        if (invoker != null) {
            logger.info("Invoker for attribute '" + attributeName + "': " + invoker);
        } else {/*from  w  w  w. java  2 s.  co  m*/
            if (logger.isDebugEnabled())
                logger.debug("No invoker found for attribute '" + attributeName);
        }
    }

    if (invoker != null) {
        HttpServletRequest wrappedRequest = wrappedRequest(request, context, moduleMapping, applicationId);
        invoker.invoke(wrappedRequest, response, null);
    }
}

From source file:org.intermine.bio.webservice.GFFQueryService.java

@Override
protected void execute() throws Exception {
    HttpSession session = request.getSession();
    ServletContext servletContext = session.getServletContext();
    // get the project title to be written in GFF3 records
    Properties props = (Properties) servletContext.getAttribute(Constants.WEB_PROPERTIES);
    String sourceName = props.getProperty("project.title");

    Set<Integer> organisms = null;

    PathQuery pathQuery = getQuery();/*from w w w  .j a v  a2 s  .c  om*/

    Exporter exporter;
    try {
        List<Integer> indexes = new ArrayList<Integer>();
        List<String> viewColumns = new ArrayList<String>(pathQuery.getView());
        for (int i = 0; i < viewColumns.size(); i++) {
            indexes.add(Integer.valueOf(i));
        }

        removeFirstItemInPaths(viewColumns);
        exporter = new GFF3Exporter(pw, indexes, getSoClassNames(servletContext), viewColumns, sourceName,
                organisms, false);
        ExportResultsIterator iter = null;
        try {
            Profile profile = SessionMethods.getProfile(session);
            PathQueryExecutor executor = this.im.getPathQueryExecutor(profile);
            iter = executor.execute(pathQuery, 0, WebServiceRequestParser.DEFAULT_MAX_COUNT);
            iter.goFaster();
            exporter.export(iter);
        } finally {
            if (iter != null) {
                iter.releaseGoFaster();
            }
        }
    } catch (Exception e) {
        throw new InternalErrorException("Service failed:" + e, e);
    }

}

From source file:eu.celarcloud.jcatascopia.api.subscriptions.SubscriptionsServer.java

/**
 * Returns a list of all the agents invoked in this subscription.
 * /*w  ww  . j  av  a2  s .  co m*/
 * @param req
 * @param response
 * @param context
 * @param subID The subscription's id
 * @return a list of all the agents in this subscription
 */
@GET
@Path("/{subid}/agents")
@Produces(MediaType.APPLICATION_JSON)
public Response getSubscriptionAgents(@Context HttpServletRequest req, @Context HttpServletResponse response,
        @Context ServletContext context, @PathParam("subid") String subID) {
    IDBInterface dbInterface = (IDBInterface) context.getAttribute("dbInterface");
    ArrayList<AgentObj> subAgents = dbInterface.getAgentsForSub(subID);

    StringBuilder sb = new StringBuilder();
    sb.append("{\"agents\":[");
    if (subAgents != null) {
        boolean first = true;
        for (AgentObj a : subAgents) {
            if (!first)
                sb.append(",");
            sb.append(a.toJSON());
            first = false;
        }
    }
    sb.append("]}");

    if (context.getAttribute("debug_mode") != null
            && context.getAttribute("debug_mode").toString().equals("true")) {
        System.out.println("Request to retrieve sub: " + subID + " agents");
        System.out.println(sb.toString());
    }

    return Response.status(Response.Status.OK).entity(sb.toString()).build();
}

From source file:org.intermine.web.struts.BuildBagAction.java

/**
 * Action for creating a bag of InterMineObjects or Strings from identifiers in text field.
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 * @return an ActionForward object defining where control goes next
 * @exception Exception if the application business logic throws
 *  an exception//from w ww .j a va 2 s. c o m
 */
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    final InterMineAPI im = SessionMethods.getInterMineAPI(session);
    ServletContext servletContext = request.getSession().getServletContext();
    Properties webProperties = (Properties) servletContext.getAttribute(Constants.WEB_PROPERTIES);
    BuildBagForm buildBagForm = (BuildBagForm) form;

    String type = buildBagForm.getType();

    if (StringUtils.isEmpty(type)) {
        recordError(new ActionMessage("bagBuild.typeNotSet"), request);
        return mapping.findForward("bags");
    }

    BagQueryRunner bagRunner = im.getBagQueryRunner();

    int maxBagSize = WebUtil.getIntSessionProperty(session, "max.bag.size", 100000);
    Profile profile = SessionMethods.getProfile(session);
    if (profile == null || profile.getUsername() == null) {
        int defaultMaxNotLoggedSize = 3;
        maxBagSize = WebUtil.getIntSessionProperty(session, "max.bag.size.notloggedin",
                defaultMaxNotLoggedSize);
    }
    BufferedReader reader = null;
    FormFile formFile = buildBagForm.getFormFile();

    /*
     * FormFile used from Struts works a bit strangely.
     * 1. Although the file does't exist formFile.getInputStream() doesn't
     * throw FileNotFoundException.
     * 2. When user specified empty file path or very invalid file path,
     * like file path not starting at '/' then formFile.getFileName() returns empty string.
     */
    if (formFile != null && formFile.getFileName() != null && formFile.getFileName().length() > 0) {
        // attach file name as the name of the bag
        String fileName = formFile.getFileName();
        // strip suffix
        Integer lastPos = new Integer(fileName.lastIndexOf('.'));
        if (lastPos.intValue() > 0) {
            fileName = fileName.substring(0, lastPos.intValue());
        }
        // replace underscores
        fileName = fileName.replaceAll("_", " ");
        // attach
        request.setAttribute("bagName", fileName);

        String mimetype = formFile.getContentType();
        if (!"application/octet-stream".equals(mimetype) && !mimetype.startsWith("text")) {
            recordError(new ActionMessage("bagBuild.notText", mimetype), request);
            return mapping.findForward("bags");
        }
        if (formFile.getFileSize() == 0) {
            recordError(new ActionMessage("bagBuild.noBagFileOrEmpty"), request);
            return mapping.findForward("bags");
        }
        reader = new BufferedReader(new InputStreamReader(formFile.getInputStream()));
    } else if (buildBagForm.getText() != null && buildBagForm.getText().length() != 0) {
        String trimmedText = buildBagForm.getText().trim();
        if (trimmedText.length() == 0) {
            recordError(new ActionMessage("bagBuild.noBagPaste"), request);
            return mapping.findForward("bags");
        }
        reader = new BufferedReader(new StringReader(trimmedText));
    } else {
        recordError(new ActionMessage("bagBuild.noBagFile"), request);
        return mapping.findForward("bags");
    }

    reader.mark(READ_AHEAD_CHARS);

    char[] buf = new char[READ_AHEAD_CHARS];

    int read = reader.read(buf, 0, READ_AHEAD_CHARS);

    for (int i = 0; i < read; i++) {
        if (buf[i] == 0) {
            recordError(new ActionMessage("bagBuild.notText", "binary"), request);
            return mapping.findForward("bags");
        }
    }

    reader.reset();

    String thisLine;
    List<String> list = new ArrayList<String>();
    int elementCount = 0;
    while ((thisLine = reader.readLine()) != null) {
        // append whitespace to valid delimiters
        String bagUploadDelims = (String) webProperties.get("list.upload.delimiters") + " ";
        StrMatcher matcher = StrMatcher.charSetMatcher(bagUploadDelims);
        StrTokenizer st = new StrTokenizer(thisLine, matcher, StrMatcher.doubleQuoteMatcher());
        while (st.hasNext()) {
            String token = st.nextToken();
            list.add(token);
            elementCount++;
            if (elementCount > maxBagSize) {
                ActionMessage actionMessage = null;
                if (profile == null || profile.getUsername() == null) {
                    actionMessage = new ActionMessage("bag.bigNotLoggedIn", new Integer(maxBagSize));
                } else {
                    actionMessage = new ActionMessage("bag.tooBig", new Integer(maxBagSize));
                }
                recordError(actionMessage, request);
                return mapping.findForward("bags");
            }
        }
    }
    BagQueryResult bagQueryResult = bagRunner.search(type, list, buildBagForm.getExtraFieldValue(), false,
            buildBagForm.getCaseSensitive());
    session.setAttribute("bagQueryResult", bagQueryResult);
    request.setAttribute("bagType", type);
    request.setAttribute("bagExtraFilter", buildBagForm.getExtraFieldValue());
    //buildNewBag used by jsp to set editable the bag name field
    request.setAttribute("buildNewBag", "true");
    return mapping.findForward("bagUploadConfirm");
}

From source file:com.gisgraphy.webapp.listener.StartupListener.java

@SuppressWarnings({ "unchecked" })
public void contextInitialized(ServletContextEvent event) {
    log.debug("initializing context...");

    ServletContext context = event.getServletContext();

    // Orion starts Servlets before Listeners, so check if the config
    // object already exists
    Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG);

    if (config == null) {
        config = new HashMap<String, Object>();
    }//  ww w  . ja  v  a 2s  . c om

    if (context.getInitParameter(Constants.CSS_THEME) != null) {
        config.put(Constants.CSS_THEME, context.getInitParameter(Constants.CSS_THEME));
    }

    ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    boolean encryptPassword = true;

    try {
        ProviderManager provider = (ProviderManager) ctx
                .getBean(ctx.getBeanNamesForType(ProviderManager.class)[0]);
        for (Object o : provider.getProviders()) {
            AuthenticationProvider p = (AuthenticationProvider) o;
            if (p instanceof RememberMeAuthenticationProvider) {
                config.put("rememberMeEnabled", Boolean.TRUE);
            }
            config.put(Constants.ENCRYPT_PASSWORD, Boolean.TRUE);
            config.put(Constants.ENC_ALGORITHM, "SHA");
        }
    } catch (NoSuchBeanDefinitionException n) {
        log.debug("authenticationManager bean not found, assuming test and ignoring...");
        // ignore, should only happen when testing
    }

    context.setAttribute(Constants.CONFIG, config);

    // output the retrieved values for the Init and Context Parameters
    if (log.isDebugEnabled()) {
        log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
        log.debug("Encrypt Passwords? " + encryptPassword);
        if (encryptPassword) {
            log.debug("Encryption Algorithm: " + config.get(Constants.ENC_ALGORITHM));
        }
        log.debug("Populating drop-downs...");
    }

    setupContext(context);
}

From source file:edu.uniminuto.servlets.GuardarDisco.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w w w.j  a v a  2  s .c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String nombre = "";
    long precio = 0;
    int anhio = 0;
    short genero = 1;
    int interprete = 1;

    //        String nombre = getParameter(request, "nombre");
    //        long precio = Long.valueOf(getParameter(request, "precio"));
    //        int anhio = Integer.valueOf(getParameter(request, "anhio"));
    //
    //        int genero = Integer.valueOf(getParameter(request, "genero"));
    //        int interprete = Integer.valueOf(getParameter(request, "interprete"));

    String url = "";
    try {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        String imagen = "images/";

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 4, new File("c;//tmp"));

        // Configure a repository (to ensure a secure temp location is used)
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
                if (item.getFieldName().equals("nombre")) {
                    nombre = item.getString();
                } else if (item.getFieldName().equals("anhio")) {
                    anhio = Integer.valueOf(item.getString());
                } else if (item.getFieldName().equals("genero")) {
                    genero = Short.valueOf(item.getString());
                } else if (item.getFieldName().equals("interprete")) {
                    interprete = Integer.valueOf(item.getString());
                } else if (item.getFieldName().equals("precio")) {
                    precio = Long.valueOf(item.getString());
                }

            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();

                //                    InputStream uploadedStream = item.getInputStream();
                //                    uploadedStream.close();
                //                    InputStream uploadedStream = item.getInputStream();
                //                    uploadedStream.close();
                imagen = imagen + fileName;
                File uploadedFile = new File(RUTA + fileName);

                item.write(uploadedFile);
                //                    } else {
                //                        
                //                    }
            }
        }

        java.util.Calendar cl = java.util.Calendar.getInstance();
        cl.set(anhio, 0, 0, 0, 0, 0);

        Disco disco = new Disco();
        disco.setGenero(generoFacade.find(genero));
        disco.setInterprete(interpreteFacade.find(interprete));
        disco.setNombre(nombre);
        disco.setImagen(imagen);
        disco.setAnhio(cl.getTime());

        discoFacade.create(disco);

        if (disco.getId() != null) {

            Discopropietario dp = new Discopropietario();
            dp.setDisco(disco);
            dp.setPropietario((Persona) request.getSession().getAttribute("usuario"));
            dp.setPrecio(precio);
            dp.setVendido(false);

            dpFacade.create(dp);

            url = "disco?id=" + disco.getId();

        } else {
            url = "fdisco?nombre=" + nombre + "&precio=" + precio + "&anhio=" + anhio + "&genero=" + genero
                    + "&interprete=" + interprete;
        }

    } catch (FileUploadException ex) {
        Logger.getLogger(GuardarDisco.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(GuardarDisco.class.getName()).log(Level.SEVERE, null, ex);
    }

    response.sendRedirect(url);

}

From source file:org.apache.stratos.redirector.servlet.ui.clients.RedirectorServletServiceClient.java

public RedirectorServletServiceClient(ServletContext context, HttpSession session) throws RegistryException {

    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
    String backendServerURL = CarbonUIUtil.getServerURL(context, session);
    ConfigurationContext configContext = (ConfigurationContext) context
            .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
    epr = backendServerURL + "RedirectorServletService";

    try {/*ww  w .j  a v a 2  s.c  om*/
        stub = new RedirectorServletServiceStub(configContext, epr);

        ServiceClient client = stub._getServiceClient();
        Options option = client.getOptions();
        option.setManageSession(true);
        option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);

    } catch (AxisFault axisFault) {
        String msg = "Failed to initiate Add Services service client. " + axisFault.getMessage();
        log.error(msg, axisFault);
        throw new RegistryException(msg, axisFault);
    }
}

From source file:org.apache.struts2.JSPLoader.java

private ClassLoaderInterface getClassLoaderInterface() {
    ClassLoaderInterface classLoaderInterface = null;
    ServletContext ctx = ServletActionContext.getServletContext();
    if (ctx != null)
        classLoaderInterface = (ClassLoaderInterface) ctx
                .getAttribute(ClassLoaderInterface.CLASS_LOADER_INTERFACE);

    return (ClassLoaderInterface) ObjectUtils.defaultIfNull(classLoaderInterface,
            new ClassLoaderInterfaceDelegate(JSPLoader.class.getClassLoader()));
}

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

@Override
public String intercept(ActionInvocation invocation) throws Exception {

    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    String result = null;/*  www  .  j a v  a 2  s  . c  o  m*/
    ServletContext sc = ServletActionContext.getServletContext();
    String userName = request.getParameter("userName");

    Map currentUserSessionMap = (Map) sc.getAttribute("LOGGED_IN_USERS");
    if (currentUserSessionMap == null) {
        response.getOutputStream()
                .write(("ErrorMsg:" + EmbeddedErrors.SESSION_EXPIRED + "ErrorCode:01|").getBytes());
        return result;
    }

    HttpSession session = (HttpSession) currentUserSessionMap.get(userName);

    if (!isAllowed(session, invocation.getAction())) {
        if (saleStatus != null) {
            String message = null;
            if ("ANDROID".equals(interfaceType)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("responseCode", AndroidErrors.SALE_TIME_EXPIRED_ERROR_CODE);
                jsonObject.put("responseMsg", AndroidErrors.SALE_TIME_EXPIRED_ERROR_MESSAGE);
                message = jsonObject.toString();
            } else
                message = "ErrorMsg:Sale Time Expired|";

            response.getOutputStream().write(message.getBytes());
        } else {
            result = handleRejection(invocation, response);
        }
    } else {
        result = invocation.invoke();
    }

    return result;
}