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.theospi.portfolio.portal.web.XsltPortal.java

private Templates createTemplate(ServletConfig config, String transformPath)
        throws MalformedURLException, TransformerConfigurationException {
    InputStream stream = config.getServletContext().getResourceAsStream(transformPath);
    URL url = config.getServletContext().getResource(transformPath);
    String urlPath = url.toString();
    String systemId = urlPath.substring(0, urlPath.lastIndexOf('/') + 1);
    Templates templates = TransformerFactory.newInstance().newTemplates(new StreamSource(stream, systemId));
    return templates;
}

From source file:org.kurento.repository.internal.http.RepositoryHttpServlet.java

private String configureWebappPublicUrl(ServletConfig servletConfig) {
    String webappUrl = config.getWebappPublicUrl();
    if (webappUrl == null || webappUrl.trim().isEmpty()) {
        webappUrl = servletConfig.getServletContext().getContextPath();
    } else {/*from  w  w  w.  j  a  v a  2  s .  co m*/
        if (webappUrl.endsWith("/")) {
            webappUrl = webappUrl.substring(0, webappUrl.length() - 1);
        }
    }

    repoHttpManager.setWebappPublicUrl(webappUrl);
    return webappUrl;
}

From source file:com.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java

private String configureWebappPublicURL(ServletConfig servletConfig) {
    String webappURL = config.getWebappPublicURL();
    if (webappURL == null || webappURL.trim().isEmpty()) {
        webappURL = servletConfig.getServletContext().getContextPath();
    } else {//from   w  ww.j av  a  2  s  .  c  o  m
        if (webappURL.endsWith("/")) {
            webappURL = webappURL.substring(0, webappURL.length() - 1);
        }
    }

    repoHttpManager.setWebappPublicURL(webappURL);
    return webappURL;
}

From source file:zj.bean.doAddEmp.java

public static boolean doInsert(ServletConfig config, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    boolean flag = false;

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setFileSizeMax(3145728);/*from w  w w  . j a v  a 2  s  .co  m*/

    List<FileItem> items = upload.parseRequest(request);

    Iterator<FileItem> iter = items.iterator();

    Emp emp = new Emp();

    while (iter.hasNext()) {
        FileItem item = iter.next();
        if (item.getFieldName().equals("ename")) {

            emp.setEname(item.getString());
        } else if (item.getFieldName().equals("job")) {
            emp.setJob(item.getString());
        } else if (item.getFieldName().equals("hiredate")) {
            emp.setHiredate(item.getString());
        } else if (item.getFieldName().equals("sal")) {
            emp.setSal(Double.parseDouble(item.getString()));
        } else if (item.getFieldName().equals("comm")) {
            if (item.getString().equals("")) {
                emp.setComm(0);

            } else {
                emp.setComm(Double.parseDouble(item.getString()));
            }
        } else if (item.getFieldName().equals("mgr")) {
            if (item.getString().equals("")) {
                emp.setMgr(0);
            } else {
                emp.setMgr(Integer.parseInt(item.getString()));
            }
        } else if (item.getFieldName().equals("depno")) {
            if (item.getString().equals("")) {
                emp.setDeptno(0);
            }
            emp.setDeptno(Integer.parseInt(item.getString()));
        } else if (item.getFieldName().equals("note")) {
            emp.setNote(item.getString());
        } else if (item.getFieldName().equals("photo")) {

            System.out.println("item_name:" + item.getName());

            if (item.getName() == "") {
                emp.setPhoto("nophoto.jpg");

            } else {

                InputStream input = null;
                OutputStream output = null;
                File saveDirectory = null;

                saveDirectory = new File(config.getServletContext().getRealPath("/") + "images");
                if (!saveDirectory.exists()) {
                    saveDirectory.mkdir();
                }

                String filename = saveDirectory.toString() + item.getName();
                File saveFile = null;
                String fname = item.getName();
                String fname2 = fname.substring(0, fname.lastIndexOf("."));
                String fname3 = fname.substring(fname.lastIndexOf(".") + 1, fname.length());

                int i = 0;
                while (true) {
                    saveFile = new File(filename);
                    if (saveFile.exists()) {
                        i++;
                        filename = saveDirectory.toString() + fname2 + "(" + i + ")" + fname3;
                        emp.setPhoto(saveDirectory.getName() + fname2 + "(" + i + ")" + "." + fname3);
                        System.out.println(
                                "photopath:" + saveDirectory.getName() + fname2 + "(" + i + ")" + fname3);
                    } else {
                        break;
                    }
                }

                input = item.getInputStream();
                output = new FileOutputStream(saveFile);

                byte[] data = new byte[512];

                while (input.read(data) != -1) {
                    output.write(data);
                }

                input.close();
                output.close();

            }

        }

    }

    flag = IEmpDAOFactory.getConnection().doInsert(emp);
    return flag;
}

From source file:se.natusoft.osgi.aps.rpchttpextender.servlet.RPCServlet.java

/**
 * First time setup./*from  w ww .  j av a  2s.co  m*/
 *
 * @param servletConfig The configuration for the servlet.
 * @throws ServletException on failure.
 */
public void init(javax.servlet.ServletConfig servletConfig) throws javax.servlet.ServletException {
    servletConfig.getServletContext().getServerInfo();
    if (this.bundleContext == null) {
        this.bundleContext = (BundleContext) servletConfig.getServletContext()
                .getAttribute("osgi-bundlecontext");

        if (this.bundleContext == null) {
            throw new ServletException(
                    "BundleContext not found! This war must be deployed in an OSGi compatible web container!");
        }

        this.loginHandler = new APSAdminWebLoginHandler(this.bundleContext);

        try {
            this.logger = new APSLogger(System.out);
            this.logger.setLoggingFor("aps-rpc-http-transport-provider");
            this.logger.start(this.bundleContext);

            this.externalProtocolServiceTracker = new APSServiceTracker<>(this.bundleContext,
                    APSExternalProtocolService.class, APSServiceTracker.SHORT_TIMEOUT);
            this.externalProtocolServiceTracker.start();
            this.externalProtocolService = this.externalProtocolServiceTracker.getWrappedService();
            this.externalProtocolService.addExternalProtocolListener(this);

            this.jsonServiceTracker = new APSServiceTracker<>(this.bundleContext, APSJSONExtendedService.class,
                    APSServiceTracker.SHORT_TIMEOUT);
            this.jsonServiceTracker.start();
            this.jsonService = this.jsonServiceTracker.getWrappedService();

            this.discoveryServiceTracker = new APSServiceTracker<>(this.bundleContext,
                    APSSimpleDiscoveryService.class, APSServiceTracker.SHORT_TIMEOUT);
            this.discoveryServiceTracker.start();
            this.discoveryServiceTracker.onServiceAvailable(this);
        } catch (APSNoServiceAvailableException nsae) {
            throw new ServletException(nsae.getMessage(), nsae);
        }
    }
}

From source file:com.naryx.tagfusion.cfm.engine.cfEngine.java

/**
 * ------------------------------------------------------
 * Initialisation method/*  w w  w. ja va 2 s  .  c  o  m*/
 *
 * Run once and initialises all the sub-components of the main engine
 */
private cfEngine(ServletConfig config) throws ServletException {
    thisInstance = this;
    thisServletContext = config.getServletContext();

    // Setup the main marker class for the platform flag
    String bluedragonXmlParm = config.getInitParameter("BLUEDRAGON_XML");

    try {

        thisPlatform = (Platform) Class.forName("com.bluedragon.platform.java.JavaPlatform").newInstance();

        if ((bluedragonXmlParm != null) && (bluedragonXmlParm.length() > 0))
            xmlFileLocation = getOpenBDXmlFile(bluedragonXmlParm);

    } catch (Exception e) {
        throw new ServletException(PRODUCT_NAME + ": " + e);
    }

    // Load in the main XML configuration file
    try {
        setSystemParameters(xmlConfigManagerFactory.createXmlConfigManager(xmlFileLocation).getXMLCFML());
        engineListeners = new Vector<engineListener>();
    } catch (Exception E) {
        thisInstance = null;
        System.out.println(PRODUCT_NAME + ": Error " + E + " loading: BLUEDRAGON_XML=" + bluedragonXmlParm);
        throw new ServletException(
                PRODUCT_NAME + ": Error occurred loading: BLUEDRAGON_XML=" + bluedragonXmlParm + ", " + E);
    }

    // Load in the image
    try {
        InputStream in = this.getClass().getResourceAsStream("openbdlogo.txt");
        if (in != null)
            OpenBDLogoDataUri = StreamUtils.readToString(in);
    } catch (NullPointerException e1) {
        OpenBDLogoDataUri = null;
    } catch (IOException e1) {
        OpenBDLogoDataUri = null;
    }

    // Initialise the Platform
    thisPlatform.init(config);

    // Get a handle to the underlying FileSystem manager
    vfsManager = thisPlatform.getFileIO().vfsManager();

    // Initialize the Datasource
    dataSourcePoolFactory = new DataSourcePoolFactory();

    try {
        // Load up the runtimeErrorMessages
        runtimeMessages = ResourceBundle.getBundle("com.naryx.tagfusion.cfm.engine.exceptionMessage");

        log(runtimeMessages.getString("cfEngine.welcomeMessage"));
        log("Product Version: " + PRODUCT_VERSION);
        log("Build date: " + BUILD_ISSUE);

        // TagChecker
        TagChecker = new tagChecker();

        // Core Expression
        expressionEngine.init();

        // fileCache initialisation
        cfmlFileCache.init(thisServletContext, getSystemParameters());

        // CFX initalization
        com.naryx.tagfusion.cfx.cfCFX.init(getSystemParameters());

        // CFCs
        ComponentFactory.init(getSystemParameters());

        startTime = System.currentTimeMillis();

    } catch (Exception E) {
        log(PRODUCT_NAME + " Engine Failed to load:" + E.getMessage());
        E.printStackTrace();
        thisInstance = null;
        throw new ServletException("Failed to initialise the cfEngine: " + E.getMessage());
    }

    // Create the plugin Manager and load up any extensions
    pluginManager = new PluginManager(getSystemParameters());

    // Set the Default Character set
    setDefaultCharset();

    // Set the Web Resource path
    setWebResourcePath();

    // Set the native library path; must be done before tags are initialised
    setNativeLibDirectory();

    // Initialise any of the tags
    try {
        TagChecker.initialiseTags(getSystemParameters());
    } catch (Throwable t) {
        t.printStackTrace();
        thisInstance = null;
        log(PRODUCT_NAME + " Engine Failed to initialise tags:" + t.getMessage());
        com.nary.Debug.printStackTrace(t);
        throw new ServletException(PRODUCT_NAME + " Engine Failed to initialise tags: " + t.getMessage());
    }

    // Set the startup engine flags
    String ipList = getSystemParameters().getString("server.debugoutput.ipaddresses");
    if ((ipList == null) || (ipList.length() == 0))
        debugIPsAsInts = new int[0];
    else
        debugIPsAsInts = cfSession.DecodeIPs(ipList);

    setDebugOutputFlag();
    setScriptProtectFlag();
    setStrictFlags();
    setAssertionsFlag();
    setCombinedFormUrlFlag();
    setLegacyFormValidation();
    setSuppressWhiteSpace();
    setDefaultBufferSize();
    setDefaultJSONFlags();
    setFormUrlCaseMaintainedFlag();
    setCFOutpuShorthand();

    // Only update the bluedragon.xml file if flagged to do so
    if (getSystemParameters().getBoolean("server.system.rewritebluedragonxml", true)
            && !bluedragonXmlParm.startsWith("http")) {
        try {
            writeXmlFile(getSystemParameters(), false);
        } catch (cfmRunTimeException e) {
            log(PRODUCT_NAME + "  " + e.getMessage());
        }
    }

    // Auto-configure ODBC datasources (notifyListeners=false, autoConfig=true)
    autoConfigOdbcDataSources(false, true);

    // Setup/clean the dynamic web service cache (and any other resources)
    try {
        cfWebServices.initialize(config);
    } catch (Exception e) {
        throw new ServletException(
                PRODUCT_NAME + " Engine Failed to initialise Web Services: " + e.getMessage());
    }

    startRequestStats();

    // Setup the Journal Manager
    journalManager = new JournalManager();

    log(runtimeMessages.getString("cfEngine.serverStarted"));

    // The Engine is ready for requests, so lets call the ServerCFC handling
    new ServerCFC().onServerStart(getSystemParameters());
}

From source file:com.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java

private void configureKurentoAppContext(ServletConfig servletConfig) {

    if (KurentoApplicationContextUtils.getKurentoApplicationContext() == null) {
        KurentoApplicationContextUtils.createKurentoApplicationContext(servletConfig.getServletContext());
    }/*from   w ww  .  j ava2  s  . c o  m*/

    KurentoApplicationContextUtils.processInjectionBasedOnKurentoApplicationContext(this);
}

From source file:zj.bean.doModEmp.java

public static boolean doModify(ServletConfig config, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    boolean flag = false;

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setFileSizeMax(3145728);// w  w  w  . j  a  v a  2  s. c o  m

    List<FileItem> items = upload.parseRequest(request);

    Iterator<FileItem> iter = items.iterator();

    Emp emp = new Emp();

    while (iter.hasNext()) {
        FileItem item = iter.next();
        if (item.getFieldName().equals("ename")) {

            emp.setEname(item.getString());
        } else if (item.getFieldName().equals("job")) {
            emp.setJob(item.getString());
        } else if (item.getFieldName().equals("hiredate")) {
            emp.setHiredate(item.getString());
        } else if (item.getFieldName().equals("sal")) {
            emp.setSal(Double.parseDouble(item.getString()));
        } else if (item.getFieldName().equals("comm")) {
            if (item.getString().equals("")) {
                emp.setComm(0);

            } else {
                emp.setComm(Double.parseDouble(item.getString()));
            }
        } else if (item.getFieldName().equals("mgr")) {
            if (item.getString().equals("")) {
                emp.setMgr(0);
            } else {
                emp.setMgr(Integer.parseInt(item.getString()));
            }
        } else if (item.getFieldName().equals("depno")) {
            if (item.getString().equals("")) {
                emp.setDeptno(0);
            }
            emp.setDeptno(Integer.parseInt(item.getString()));
        } else if (item.getFieldName().equals("note")) {
            emp.setNote(item.getString());
        } else if (item.getFieldName().equals("photo")) {

            System.out.println("item_name:" + item.getName());

            if (item.getName() == "") {
                emp.setPhoto("nophoto.jpg");

            } else {

                InputStream input = null;
                OutputStream output = null;
                File saveDirectory = null;

                saveDirectory = new File(config.getServletContext().getRealPath("/") + "images");
                if (!saveDirectory.exists()) {
                    saveDirectory.mkdir();
                }

                String filename = saveDirectory.toString() + File.separator + item.getName();
                File saveFile = null;
                String fname = item.getName();
                String fname2 = fname.substring(0, fname.lastIndexOf("."));
                String fname3 = fname.substring(fname.lastIndexOf(".") + 1, fname.length());

                int i = 0;
                while (true) {
                    saveFile = new File(filename);
                    emp.setPhoto(
                            saveDirectory.getName() + File.separator + fname2 + "(" + i + ")" + "." + fname3);
                    System.out.println("photopath:" + saveDirectory.getName() + File.separator + fname2 + "("
                            + i + ")" + "." + fname3);

                    if (saveFile.exists()) {
                        i++;
                        filename = saveDirectory.toString() + File.separator + fname2 + "(" + i + ")" + "."
                                + fname3;
                        emp.setPhoto(saveDirectory.getName() + File.separator + fname2 + "(" + i + ")" + "."
                                + fname3);
                        System.out.println("photopath:" + saveDirectory.getName() + File.separator + fname2
                                + "(" + i + ")" + "." + fname3);
                    } else {
                        break;
                    }
                }

                input = item.getInputStream();
                output = new FileOutputStream(saveFile);

                byte[] data = new byte[512];

                while (input.read(data) != -1) {
                    output.write(data);
                }

                input.close();
                output.close();

            }

        }

    }

    Emp tmp = (Emp) request.getSession().getAttribute("emp");

    emp.setEmpno(tmp.getEmpno());

    flag = IEmpDAOFactory.getConnection().doUpdate(emp);
    return flag;
}

From source file:de.itsvs.cwtrpc.controller.RemoteServiceControllerServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    final WebApplicationContext applicationContext;
    final RemoteServiceControllerConfig controllerConfig;
    String configBeanName;//from   w  ww  . jav a2 s  .c om
    String initParam;

    super.init(config);

    initParam = config.getInitParameter(SPRING_REQUEST_CONTEXT_ENABLED_INIT_PARAM);
    if (initParam != null) {
        setSpringRequestContextEnabled(Boolean.valueOf(initParam));
    } else {
        setSpringRequestContextEnabled(DEFAULT_SPRING_REQUEST_CONTEXT_ENABLED);
    }
    if (log.isInfoEnabled()) {
        log.info("Spring request context initialization on every request: " + isSpringRequestContextEnabled());
    }

    configBeanName = config.getInitParameter(CONFIG_BEAN_NAME_INIT_PARAM);
    if (configBeanName == null) {
        configBeanName = RemoteServiceControllerConfig.DEFAULT_BEAN_ID;
    }

    applicationContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
    if (log.isDebugEnabled()) {
        log.debug(
                "Resolving controller config with bean name '" + configBeanName + "' from application context");
    }
    controllerConfig = applicationContext.getBean(configBeanName, RemoteServiceControllerConfig.class);

    setApplicationContext(applicationContext);
    setSerializationPolicyProvider(controllerConfig.getSerializationPolicyProvider());
    setServiceConfigsByUri(
            Collections.unmodifiableMap(createPreparedRemoteServiceConfigBuilder().build(controllerConfig)));

    setUncaughtExceptions(getUncaughtExceptions(controllerConfig));
}

From source file:com.jaspersoft.jasperserver.war.OlapPrint.java

/** Initializes the servlet.
 *///from   w  w  w  .j  a va2 s . com
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    /*
     * TODO Add init parameters for:
     *      ChartServlet path,
     *      Excel XSL and content type,
     *      PDF XSL and content type
     */
    try {
        /*
        // set base FOP FONT directory.  The font config  stuff will be looked for here
        Configuration.put("fontBaseDir", config.getServletContext().getRealPath("/WEB-INF/jpivot/print/"));
        logger.debug("fontBaseDir=" + Configuration.getStringValue("fontBaseDir"));
        // get the physical path for the config file
        String fopConfigPath = config.getServletContext().getRealPath("/WEB-INF/jpivot/print/userconfig.xml");
        // load the user proerties, contining the CustomFont font.
        logger.debug("fopConfigPath=" + fopConfigPath);
        new Options(new File(fopConfigPath));
        logger.debug("Construct driver");
        driver = new Driver();
        driver.setLogger(new NullLogger());
        */

        fopFactory = FopFactory.newInstance();
        String fopConfigPath = config.getServletContext()
                .getRealPath("/WEB-INF/jpivot/print/userconfig-0.95.xml");
        fopFactory.setUserConfig(new File(fopConfigPath));

        String fontBaseDir = config.getServletContext().getRealPath("/WEB-INF/jpivot/print/");

        fopFactory.setFontBaseURL("file:///" + fontBaseDir);

        fopFactory.setStrictValidation(false);

        /*
        logger.debug("Setup Renderer (output format)");
        driver.setRenderer(Driver.RENDER_PDF);
        logger.debug("FOP renderer set to PDF");
        */
    } catch (Exception e) {
        e.printStackTrace();
        logger.info("FOP user config file not loaded");
    }
}