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.musicrecital.webapp.listener.StartupListener.java

/**
 * {@inheritDoc}/*from   w ww  .  j av a2s . c o  m*/
 */
@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>();
    }

    ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    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);

    // Determine version number for CSS and JS Assets
    String appVersion = null;
    try {
        InputStream is = context.getResourceAsStream("/META-INF/MANIFEST.MF");
        if (is == null) {
            log.warn("META-INF/MANIFEST.MF not found.");
        } else {
            Manifest mf = new Manifest();
            mf.read(is);
            Attributes atts = mf.getMainAttributes();
            appVersion = atts.getValue("Implementation-Version");
        }
    } catch (IOException e) {
        log.error("I/O Exception reading manifest: " + e.getMessage());
    }

    // If there was a build number defined in the war, then use it for
    // the cache buster. Otherwise, assume we are in development mode
    // and use a random cache buster so developers don't have to clear
    // their browser cache.
    if (appVersion == null || appVersion.contains("SNAPSHOT")) {
        appVersion = "" + new Random().nextInt(100000);
    }

    log.info("Application version set to: " + appVersion);
    context.setAttribute(Constants.ASSETS_VERSION, appVersion);
}

From source file:org.debux.webmotion.server.render.RenderException.java

protected Map<String, Object> getServletContextAttributes(ServletContext servletContext) {
    Map<String, Object> result = new HashMap<String, Object>();
    for (Enumeration<String> names = servletContext.getAttributeNames(); names.hasMoreElements();) {
        String name = names.nextElement();
        Object value = servletContext.getAttribute(name);
        result.put(name, value);//  w w w.java  2s  .  c om
    }
    return result;
}

From source file:org.red5.logging.LoggerContextFilter.java

public void init(FilterConfig config) throws ServletException {
    ServletContext servletContext = config.getServletContext();
    contextName = servletContext.getContextPath().replaceAll("/", "");
    if ("".equals(contextName)) {
        contextName = "root";
    }//from w  w w  .j  a  v  a2  s . c om
    System.out.printf("Filter init: %s%n", contextName);
    ConfigurableWebApplicationContext appctx = (ConfigurableWebApplicationContext) servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (appctx != null) {
        System.out.printf(
                "ConfigurableWebApplicationContext is not null in LoggerContextFilter for: %s, this indicates a misconfiguration or load order problem%n",
                contextName);
    }
}

From source file:org.apache.hadoop.mapred.TaskLogServlet.java

/**
 * Get the logs via http.//from  w w w .j a  va2  s  . c  o m
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    long start = 0;
    long end = -1;
    boolean plainText = false;
    TaskLog.LogName filter = null;
    boolean isCleanup = false;

    String attemptIdStr = request.getParameter("attemptid");
    if (attemptIdStr == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Argument attemptid is required");
        return;
    }

    String logFilter = request.getParameter("filter");
    if (logFilter != null) {
        try {
            filter = TaskLog.LogName.valueOf(TaskLog.LogName.class, logFilter.toUpperCase());
        } catch (IllegalArgumentException iae) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Illegal value for filter: " + logFilter);
            return;
        }
    }

    String sLogOff = request.getParameter("start");
    if (sLogOff != null) {
        start = Long.valueOf(sLogOff).longValue();
    }

    String sLogEnd = request.getParameter("end");
    if (sLogEnd != null) {
        end = Long.valueOf(sLogEnd).longValue();
    }

    String sPlainText = request.getParameter("plaintext");
    if (sPlainText != null) {
        plainText = Boolean.valueOf(sPlainText);
    }

    String sCleanup = request.getParameter("cleanup");
    if (sCleanup != null) {
        isCleanup = Boolean.valueOf(sCleanup);
    }

    TaskAttemptID attemptId = TaskAttemptID.forName(attemptIdStr);
    if (!TaskLog.getAttemptDir(attemptId, isCleanup).exists()) {
        response.sendError(HttpServletResponse.SC_GONE, "Task log directory for task " + attemptId
                + " does not exist. May be cleaned up by Task Tracker, if older logs.");
        return;
    }

    // get user name who is accessing
    String user = request.getRemoteUser();
    if (user != null) {
        ServletContext context = getServletContext();
        TaskTracker taskTracker = (TaskTracker) context.getAttribute("task.tracker");
        JobID jobId = attemptId.getJobID();

        // get jobACLConf from ACLs file
        JobConf jobACLConf = getConfFromJobACLsFile(jobId);
        // Ignore authorization if job-acls.xml is not found
        if (jobACLConf != null) {
            try {
                checkAccessForTaskLogs(jobACLConf, user, jobId.toString(), taskTracker);
            } catch (AccessControlException e) {
                String errMsg = "User " + user + " failed to view tasklogs of job " + jobId + "!\n\n"
                        + e.getMessage();
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, errMsg);
                return;
            }
        }
    }

    OutputStream out = response.getOutputStream();
    if (!plainText) {
        out.write(("<html>\n" + "<title>Task Logs: '" + attemptId + "'</title>\n" + "<body>\n"
                + "<h1>Task Logs: '" + attemptId + "'</h1><br>\n").getBytes());

        if (filter == null) {
            printTaskLog(response, out, attemptId, start, end, plainText, TaskLog.LogName.STDOUT, isCleanup);
            printTaskLog(response, out, attemptId, start, end, plainText, TaskLog.LogName.STDERR, isCleanup);
            if (haveTaskLog(attemptId, isCleanup, TaskLog.LogName.SYSLOG)) {
                printTaskLog(response, out, attemptId, start, end, plainText, TaskLog.LogName.SYSLOG,
                        isCleanup);
            }
            if (haveTaskLog(attemptId, isCleanup, TaskLog.LogName.DEBUGOUT)) {
                printTaskLog(response, out, attemptId, start, end, plainText, TaskLog.LogName.DEBUGOUT,
                        isCleanup);
            }
            if (haveTaskLog(attemptId, isCleanup, TaskLog.LogName.PROFILE)) {
                printTaskLog(response, out, attemptId, start, end, plainText, TaskLog.LogName.PROFILE,
                        isCleanup);
            }
        } else {
            printTaskLog(response, out, attemptId, start, end, plainText, filter, isCleanup);
        }

        out.write("</body></html>\n".getBytes());
        out.close();
    } else if (filter == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "You must supply a value for `filter' (STDOUT, STDERR, or SYSLOG) if you set plainText = true");
    } else {
        printTaskLog(response, out, attemptId, start, end, plainText, filter, isCleanup);
    }
}

From source file:communicator.doMove.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w ww .  ja va2 s  .c o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = null;
    JSONObject outputObject = new JSONObject();
    try {

        HashMap<String, String> bigItemIds = new HashMap<>();
        Iterator mIterator = bigItemIds.keySet().iterator();
        out = response.getWriter();
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // 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);

        final String moveId = UUID.randomUUID().toString();
        final MovesDb movesDb = new MovesDb();
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {

                System.out.println("Form field" + item.getString());

                bigItemIds = processFormField(new JSONObject(item.getString()), out, moveId, movesDb);
                mIterator = bigItemIds.keySet().iterator();
                System.out.println("ITEM ID SIZE " + bigItemIds.size());

            } else {
                //processUploadedFile(item);
                System.out.print("Photo Field");
                String key = (String) mIterator.next();
                File mFile = new File(bigItemIds.get(key));
                item.write(mFile);

            }
        }
        new Thread() {

            public void run() {
                pushMovetoMailQueue moveToMailQueue = new pushMovetoMailQueue();
                moveToMailQueue.pushMoveToMailQueue(movesDb);
            }
        }.start();
        outputObject = new JSONObject();
        try {
            outputObject.put(Constants.JSON_STATUS, Constants.JSON_SUCCESS);
            outputObject.put(Constants.JSON_MSG, Constants.JSON_GET_QUOTE);
        } catch (JSONException ex1) {
            Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1);
        }

        out.println(outputObject.toString());

    } catch (Exception ex) {

        outputObject = new JSONObject();
        try {
            outputObject.put(Constants.JSON_STATUS, Constants.JSON_FAILURE);
            outputObject.put(Constants.JSON_MSG, Constants.JSON_EXCEPTION);
        } catch (JSONException ex1) {
            Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1);
        }

        out.println(outputObject.toString());
        Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

From source file:edu.fullerton.ldvservlet.Upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request//w  ww .ja  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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    long startTime = System.currentTimeMillis();

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("This action requires a multipart form with a file attached.");
    }
    ServletSupport servletSupport;

    servletSupport = new ServletSupport();
    servletSupport.init(request, viewerConfig, false);

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // 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);

    ImageTable imageTable;
    String viewServletPath = request.getContextPath() + "/view";

    try {
        imageTable = new ImageTable(servletSupport.getDb());
    } catch (SQLException ex) {
        String ermsg = "Image upload: can't access the Image table: " + ex.getClass().getSimpleName() + " "
                + ex.getLocalizedMessage();
        throw new ServletException(ermsg);
    }
    try {
        HashMap<String, String> params = new HashMap<>();
        ArrayList<Integer> uploadedIds = new ArrayList<>();

        Page vpage = servletSupport.getVpage();
        vpage.setTitle("Image upload");
        try {
            servletSupport.addStandardHeader(version);
            servletSupport.addNavBar();
        } catch (WebUtilException ex) {
            throw new ServerException("Adding nav bar after upload", ex);
        }

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        int cnt = items.size();
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                if (!value.isEmpty()) {
                    params.put(name, value);
                }
            }
        }
        for (FileItem item : items) {
            if (!item.isFormField()) {
                int imgId = addFile(item, params, vpage, servletSupport.getVuser().getCn(), imageTable);
                if (imgId != 0) {
                    uploadedIds.add(imgId);
                }
            }
        }
        if (!uploadedIds.isEmpty()) {
            showImages(vpage, uploadedIds, imageTable, viewServletPath);
        }
        servletSupport.showPage(response);
    } catch (FileUploadException ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.apache.qpid.server.management.plugin.servlet.rest.AbstractServlet.java

@Override
public void init() throws ServletException {
    ServletConfig servletConfig = getServletConfig();
    ServletContext servletContext = servletConfig.getServletContext();
    _broker = (Broker) servletContext.getAttribute(ATTR_BROKER);
    _rootLogger = _broker.getRootMessageLogger();
    _httpManagement = (HttpManagement) servletContext.getAttribute(ATTR_MANAGEMENT);
    super.init();
}

From source file:jp.terasoluna.fw.service.thin.BLogicMapper.java

/**
 * T?[ubgReLXgwv?peBL?[l?B//from www . j  ava2s.  c  om
 *
 * @param propName v?peB
 * @param request HTTPNGXg
 * @param response HTTPX|X
 * @return v?peBl
 */
@Override
public Object getValueFromApplication(String propName, HttpServletRequest request,
        HttpServletResponse response) {

    if (propName == null || "".equals(propName)) {
        log.error("illegal argument:propName = [" + propName + "]");
        throw new IllegalArgumentException();
    }

    // T?[ubgReLXg
    HttpSession session = request.getSession(true);
    ServletContext context = session.getServletContext();
    // ZbVl
    Object value = context.getAttribute(propName);

    if (log.isDebugEnabled()) {
        if (value == null) {
            log.debug("ServletContext's attribute is null:key =[" + propName + "]");
        }
    }
    return value;
}

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

/**
 * Determines if the request should be allowed for the action
 * /*  w w  w. j  a va2 s .  c o  m*/
 * @param request
 *            The request
 * @param action
 *            The action object
 * @return True if allowed, false otherwise
 * @throws SQLException
 */
protected boolean isAllowed(HttpSession session, Object action) throws SQLException {

    //logger.info("i am inside priv interceptor");
    setActionName(ActionContext.getContext().getName());
    //logger.info("allowed privs are " + getActionName());

    boolean result = false;
    /*ArrayList<String> userActionList = new ArrayList<String>();
    userActionList = (ArrayList<String>) session
    .getAttribute("ACTION_LIST");*/
    //logger.info("ACTION LIST " + userActionList);

    UserInfoBean userBean = (UserInfoBean) session.getAttribute("USER_INFO");
    ServletContext sc = ServletActionContext.getServletContext();
    if (userBean.getUserType().equals("RETAILER") && !isSaleDuration(userBean)) {
        List<String> disableTabs;
        disableTabs = Arrays.asList(((String) sc.getAttribute("RET_SALE_BOUND")).split(","));
        for (int i = 0; i < disableTabs.size(); i++) {
            if (getActionName().contains(disableTabs.get(i))) {
                saleStatus = "SALE_STOP";
                return false;
            }
        }
    }
    result = true;
    return result;
}

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

/**
 * Adds/removes an agent to/from a subscription.
 * //from w ww .  ja va  2  s .c o m
 * @param req
 * @param response
 * @param context
 * @param subID The subscription's id
 * @param agentID The agent's id
 * @param action The action to perform (addAgent/removeAgent)
 * @return
 */
@GET
@Path("{subid}/agent/{agentid}")
@QueryParam("action")
@Produces(MediaType.APPLICATION_JSON)
public Response actionForAgent(@Context HttpServletRequest req, @Context HttpServletResponse response,
        @Context ServletContext context, @PathParam("subid") String subID, @PathParam("agentid") String agentID,
        @QueryParam("action") String action) {
    String serverIP = (String) context.getAttribute("serverIP");
    String serverPort = (String) context.getAttribute("serverPort");
    IDBInterface dbInterface = (IDBInterface) context.getAttribute("dbInterface");

    boolean success = false;
    StringBuilder sb = new StringBuilder();
    sb.append("{\"subID\":\"" + subID + "\",");
    sb.append("\"agentID\":\"" + agentID + "\"}");

    if (action.equals("addAgent")) {
        success = dbInterface.addAgent(serverIP, serverPort, sb.toString());
    } else if (action.equals("removeAgent")) {
        success = dbInterface.removeAgent(serverIP, serverPort, sb.toString());
    } else {
        System.out.println("Action " + action + " is not valid");
        return Response.status(Response.Status.NOT_FOUND).entity("{\"status\":\"NOT_FOUND\"}").build();
    }
    System.out.println(action + " with id " + agentID + " to subscription " + subID);
    return Response.status(success ? Response.Status.OK : Response.Status.INTERNAL_SERVER_ERROR)
            .entity("{\"status\":\"DONE\"}").build();
}