Example usage for javax.servlet ServletConfig getServletContext

List of usage examples for javax.servlet ServletConfig getServletContext

Introduction

In this page you can find the example usage for javax.servlet ServletConfig getServletContext.

Prototype

public ServletContext getServletContext();

Source Link

Document

Returns a reference to the ServletContext in which the caller is executing.

Usage

From source file:org.efs.openreports.dispatcher.FileDispatcher.java

public void init(ServletConfig servletConfig) throws ServletException {
    ORComponentManager.initializeObject(this);

    //If not using WebWork IOC try Spring...
    if (directoryProvider == null) {
        ApplicationContext appContext = WebApplicationContextUtils
                .getRequiredWebApplicationContext(servletConfig.getServletContext());

        directoryProvider = (DirectoryProvider) appContext.getBean("directoryProvider", ReportService.class);
    }//from w  w  w . j  a va2s  .  c o m

    imageDirectory = directoryProvider.getReportImageDirectory();
    imageTempDirectory = directoryProvider.getReportImageTempDirectory();
    reportGenerationDirectory = directoryProvider.getReportGenerationDirectory();

    super.init(servletConfig);

    log.info("Started...");
}

From source file:user.controller.ProcessData.java

public void processAdd(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {//from  w  w  w. ja v a 2s . c o  m
        List<String> tenBangCaps = new ArrayList<>();
        List<String> noiCaps = new ArrayList<>();
        List<String> ngayCaps = new ArrayList<>();

        request.setCharacterEncoding("UTF-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        File filedir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
        factory.setRepository(filedir);
        List items = new ServletFileUpload(factory).parseRequest(request);
        StringBuilder builder = new StringBuilder();
        builder.append("{");
        for (FileItem item : (List<FileItem>) items) {
            if (item.isFormField()) {
                if (item.getFieldName().equals("gioiTinh")) {
                    builder.append("\"").append(item.getFieldName()).append("\"" + ":").append("\"")
                            .append(item.getString().equals("on") ? 1 : 0).append("\",");
                } else if (item.getFieldName().contains("[]")) {
                    InputStreamReader inputStreamReader;
                    BufferedReader bufferedReader;
                    String line;
                    switch (item.getFieldName()) {
                    case "tenBangCap[]":
                        inputStreamReader = new InputStreamReader((InputStream) item.getInputStream(), "UTF-8");
                        bufferedReader = new BufferedReader(inputStreamReader);
                        while ((line = bufferedReader.readLine()) != null) {
                            tenBangCaps.add(item.getString());

                        }
                        break;
                    case "ngayCap[]":
                        inputStreamReader = new InputStreamReader((InputStream) item.getInputStream(), "UTF-8");
                        bufferedReader = new BufferedReader(inputStreamReader);
                        while ((line = bufferedReader.readLine()) != null) {
                            ngayCaps.add(item.getString());
                        }
                        break;
                    case "noiCap[]":
                        inputStreamReader = new InputStreamReader((InputStream) item.getInputStream(), "UTF-8");
                        bufferedReader = new BufferedReader(inputStreamReader);
                        while ((line = bufferedReader.readLine()) != null) {
                            noiCaps.add(item.getString());
                        }
                        break;
                    }
                } else {
                    InputStreamReader inputStreamReader = new InputStreamReader(
                            (InputStream) item.getInputStream(), "UTF-8");
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        builder.append("\"").append(item.getFieldName()).append("\"" + ":").append("\"")
                                .append(line).append("\",");
                    }
                }
            } else if (!"".equals(item.getName())) {
                builder.append("\"").append(item.getFieldName()).append("\"" + ":").append("\"")
                        .append(item.getName()).append("\",");
                // get file path
                ServletConfig config = getServletConfig();
                ServletContext context = config.getServletContext();
                String webInfPath = context.getRealPath("static");

                InputStream inputStream = item.getInputStream();
                File file = new File(webInfPath + "/images/" + item.getName());
                //                    file.createNewFile();
                OutputStream os = new FileOutputStream(file);
                byte[] buffer = new byte[10 * 1024];
                for (int length; (length = inputStream.read(buffer)) != -1;) {
                    os.write(buffer, 0, length);
                }
            }
        }
        builder.deleteCharAt(builder.length() - 1);
        //           
        builder.append("}");
        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson g = gsonBuilder.create();
        Systemuser systemuser = g.fromJson(builder.toString(), Systemuser.class);
        Systemuserhelper s = new Systemuserhelper();
        String id = s.create(systemuser);
        if (id == null) {
            sendResultSignal(request, response, FAIL);
        } else {
            StringBuilder stringBuilderDiploma;

            for (int i = 0; i < tenBangCaps.size(); i++) {
                stringBuilderDiploma = new StringBuilder();
                stringBuilderDiploma.append("{").append("\"tenBangCap\":\"").append(tenBangCaps.get(i))
                        .append("\",").append("\"ngayCap\":\"").append(ngayCaps.get(i)).append("\",")
                        .append("\"noiCap\":\"").append(noiCaps.get(i)).append("\"}");
                Userdiploma userdiploma = g.fromJson(stringBuilderDiploma.toString(), Userdiploma.class);
                userdiploma.setSystemuser(systemuserhelper.findOne(Integer.parseInt(id)));
                Diplomahelper d = new Diplomahelper();
                if (null == d.create(userdiploma)) {
                    sendResultSignal(request, response, FAIL);
                }
            }

        }
    } catch (FileUploadException | IOException e) {
        sendResultSignal(request, response, FAIL);

    }
}

From source file:fi.eis.applications.osgi.support.OsgiBundleXmlWebApplicationContext.java

/**
 * {@inheritDoc}//from w w  w .  java  2  s  .com
 * 
 * Additionally, it also sets the context namespace if it's not initialized
 * (null).
 */
public void setServletConfig(ServletConfig servletConfig) {
    this.servletConfig = servletConfig;
    if (servletConfig != null) {

        if (this.servletContext == null) {
            setServletContext(servletConfig.getServletContext());
        }

        if (getNamespace() == null) {
            setNamespace(this.servletConfig.getServletName() + DEFAULT_NAMESPACE_SUFFIX);
        }
    }
}

From source file:org.jasig.portal.portlet.container.services.LocalPortletContextManager.java

/**
 * Retrieves the PortletContext associated with the given ServletContext.
 * If one does not exist, it is created.
 *
 * @param config the servlet config./* w  ww.  j  av a 2s .c  o m*/
 * @return the InternalPortletContext associated with the ServletContext.
 * @throws PortletContainerException
 */
@Override
public synchronized String register(ServletConfig config) throws PortletContainerException {
    ServletContext servletContext = config.getServletContext();
    String contextPath = servletContext.getContextPath();
    if (!portletContexts.containsKey(contextPath)) {

        PortletApplicationDefinition portletApp = this.getPortletAppDD(servletContext, contextPath,
                contextPath);

        DriverPortletContext portletContext = new DriverPortletContextImpl(servletContext, portletApp,
                requestDispatcherService);

        portletContexts.put(contextPath, portletContext);

        fireRegistered(portletContext);

        if (logger.isInfoEnabled()) {
            logger.info("Registered portlet application for context '" + contextPath + "'");

            logger.info("Registering " + portletApp.getPortlets().size() + " portlets for context "
                    + portletContext.getApplicationName());
        }

        //TODO have the portlet servlet provide the portlet's classloader as parameter to this method
        //This approach is needed as all pluto callbacks in uPortal have an aspect that switches the thread classloader back
        //to uPortal's classloader.
        ClassLoader classLoader = ThreadContextClassLoaderAspect.getPreviousClassLoader();
        if (classLoader == null) {
            classLoader = Thread.currentThread().getContextClassLoader();
        }
        classLoaders.put(portletApp.getName(), classLoader);
        for (PortletDefinition portlet : portletApp.getPortlets()) {
            String appName = portletContext.getApplicationName();
            if (appName == null) {
                throw new PortletContainerException("Portlet application name should not be null.");
            }
            portletConfigs.put(portletContext.getApplicationName() + "/" + portlet.getPortletName(),
                    new DriverPortletConfigImpl(portletContext, portlet));
        }
    } else {
        if (logger.isInfoEnabled()) {
            logger.info("Portlet application for context '" + contextPath + "' already registered.");
        }
    }
    return contextPath;
}

From source file:org.apache.cocoon.portal.wsrp.adapter.WSRPPortletWindowAspect.java

/**
 * @see org.apache.avalon.framework.context.Contextualizable#contextualize(org.apache.avalon.framework.context.Context)
 *//*from w w  w  .j a v  a  2  s.  c  om*/
public void contextualize(Context context) throws ContextException {
    try {
        // now get the wsrp adapter
        ServletConfig servletConfig = (ServletConfig) context.get(CocoonServlet.CONTEXT_SERVLET_CONFIG);
        this.adapter = (WSRPAdapter) servletConfig.getServletContext()
                .getAttribute(WSRPAdapter.class.getName());
        if (this.adapter != null) {
            this.environment = this.adapter.getConsumerEnvironment();
        }
    } catch (ContextException ignore) {
        // we ignore the context exception
        // this avoids startup errors if the portal is configured for the CLI
        // environment
        this.getLogger().warn("The wsrp support is disabled as the servlet context is not available.", ignore);
    }
}

From source file:shapeways.api.robocreator.RoboCreatorWeb.java

/**
 * Initialize the servlet. Sets up the base directory properties for finding
 * stuff later on./*from w ww  .  j  ava2s  . c o m*/
 */
public void init() throws ServletException {

    if (DEBUG) {
        System.out.println("Starting RoboCreatorWeb");
    }

    ServletConfig config = getServletConfig();
    ServletContext ctx = config.getServletContext();

    kernels = getInitParameter("Kernels");
    if (kernels == null) {
        System.out.println("ServiceQueue is null, add entry to web.xml");
    }

    System.out.println("Handling Kernels: " + kernels);
    instanceType = getInstanceMetadata("instance-type", "localhost");

    // 0 = number of processors.  > 0 specific number.  Default is 1
    String num_threads_st = getInitParameter("NumThreads");
    Gson gson = new Gson();
    Map<String, Number> threadsMap = new HashMap<String, Number>();
    try {
        threadsMap = gson.fromJson(num_threads_st, Map.class);
    } catch (Exception e) {
        System.out.println(
                "Cannot parse threads in RoboCreatorWeb.  Should be map of instanceType to numThreads");
        System.out.println("numThreads: " + num_threads_st);
        e.printStackTrace();
    }

    int threads = threadsMap.get(instanceType).intValue();

    if (threads == 0) {
        int cores = Runtime.getRuntime().availableProcessors();
        threads = cores;
    }

    threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(threads);

    System.out.println("ThreadPool: " + threadPool);
    awsAccessKey = getInitParameter("AWSAccessKey");
    awsAccessSecret = getInitParameter("AWSAccessSecret");
    awsRegion = getInitParameter("AWSRegion");
    String st = getInitParameter("AWSSQSVisibilityTimeout");
    if (st != null) {
        visibilityTimeout = Integer.parseInt(st);
    }

    // TODO: Not certain we want to do these here as it delays deploy and might stop all deploys if AWS is down.
    // Switch to a threaded runnable or maybe just add the job to the threadPool we have.
    sqs = new AmazonSQSClient(new BasicAWSCredentials(awsAccessKey, awsAccessSecret));

    Region region = RegionUtils.getRegion(awsRegion);
    sqs.setRegion(region);

    queUrlMap = new HashMap<String, String>();

    System.out.println("Creating Queues");
    String[] queues = kernels.split(" ");
    for (int i = 0; i < queues.length; i++) {
        threadPool.submit(new SQSCreateQueueTask(sqs, QUEUE_PREPEND + queues[i], visibilityTimeout, this));
    }
}

From source file:org.accelerators.activiti.servlet.SpringApplicationServlet.java

@SuppressWarnings("unchecked")
@Override/* w ww. j ava  2s .  c om*/
public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
    applicationBean = servletConfig.getInitParameter("applicationBean");
    if (applicationBean == null) {
        throw new ServletException("ApplicationBean not specified in servlet parameters");
    }

    applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());

    applicationClass = (Class<? extends Application>) applicationContext.getType(applicationBean);
}

From source file:org.wso2.spring.ws.axis2.SpringBeanSystemConfigurator.java

public SpringBeanSystemConfigurator(SpringAxisConfiguration springConfig, ServletConfig config)
        throws DeploymentException {

    this.springConfig = springConfig;
    this.axisConfig = new AxisConfiguration();
    this.config = config;

    Parameter param = new Parameter();
    param.setName(Constants.Configuration.ARTIFACTS_TEMP_DIR);
    param.setValue(config.getServletContext().getAttribute("javax.servlet.context.tempdir"));
    try {//from ww w  . java2 s.c o m
        axisConfig.addParameter(param);
    } catch (AxisFault axisFault) {
        axisFault.printStackTrace(System.out);
    }
}

From source file:org.fao.unredd.servlet.AdminGUIAbstractServlet.java

/**
 * The call to the {@link SpringBeanAutowiringSupport#processInjectionBasedOnServletContext(Object, javax.servlet.ServletContext)} method is mandatory for each servlet
 * since we want to use the Spring Autowiring system into the Servlets that, of course, aren't declared in the Spring ApplicationContext  
 * //w w  w.j av a 2s. com
 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
 */
@Override
public void init(ServletConfig config) {
    try {
        super.init(config);
    } catch (ServletException e) {
        throw new IllegalStateException(
                "An exception occurred while executing servlet init method... this should never happen...");
    }
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
    LOGGER.info("Loading Servlet '" + this.getServletName() + "'");
}

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