Example usage for javax.servlet ServletConfig getInitParameter

List of usage examples for javax.servlet ServletConfig getInitParameter

Introduction

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

Prototype

public String getInitParameter(String name);

Source Link

Document

Gets the value of the initialization parameter with the given name.

Usage

From source file:axiom.servlet.AbstractServletClient.java

/**
 * Init this servlet./*  ww w . ja va  2  s .co m*/
 *
 * @param init the servlet configuration
 *
 * @throws ServletException ...
 */
public void init(ServletConfig init) throws ServletException {
    super.init(init);

    // get max size for file uploads
    String upstr = init.getInitParameter("uploadLimit");
    try {
        uploadLimit = (upstr == null) ? 1024 : Integer.parseInt(upstr);
    } catch (NumberFormatException x) {
        System.err.println("Bad number format for uploadLimit: " + upstr);
        uploadLimit = 1024;
    }

    // get max total upload size
    upstr = init.getInitParameter("totalUploadLimit");
    try {
        totalUploadLimit = (upstr == null) ? uploadLimit : Integer.parseInt(upstr);
    } catch (NumberFormatException x) {
        log("Bad number format for totalUploadLimit: " + upstr);
        totalUploadLimit = uploadLimit;
    }

    // soft fail mode for upload errors
    uploadSoftfail = ("true".equalsIgnoreCase(init.getInitParameter("uploadSoftfail")));

    // get cookie domain
    cookieDomain = init.getInitParameter("cookieDomain");
    if (cookieDomain != null) {
        cookieDomain = cookieDomain.toLowerCase();
    }

    // get session cookie name
    sessionCookieName = init.getInitParameter("sessionCookieName");
    if (sessionCookieName == null) {
        sessionCookieName = "AxiomSession";
    }

    // disable binding session cookie to ip address?
    protectedSessionCookie = !("false".equalsIgnoreCase(init.getInitParameter("protectedSessionCookie")));

    // debug mode for printing out detailed error messages
    debug = ("true".equalsIgnoreCase(init.getInitParameter("debug")));

    // generally disable response caching for clients?
    caching = !("false".equalsIgnoreCase(init.getInitParameter("caching")));
}

From source file:net.wastl.webmail.server.WebMailServlet.java

public void init(ServletConfig config) throws ServletException {
    final ServletContext sc = config.getServletContext();
    log.debug("Init");
    final String depName = (String) sc.getAttribute("deployment.name");
    final Properties rtProps = (Properties) sc.getAttribute("meta.properties");
    log.debug("RT configs retrieved for application '" + depName + "'");
    srvlt_config = config;/*www .j a  va2 s. c o m*/
    this.config = new Properties();
    final Enumeration enumVar = config.getInitParameterNames();
    while (enumVar.hasMoreElements()) {
        final String s = (String) enumVar.nextElement();
        this.config.put(s, config.getInitParameter(s));
        log.debug(s + ": " + config.getInitParameter(s));
    }

    /*
     * Issue a warning if webmail.basepath and/or webmail.imagebase are not
     * set.
     */
    if (config.getInitParameter("webmail.basepath") == null) {
        log.warn("webmail.basepath initArg should be set to the WebMail " + "Servlet's base path");
        basepath = "";
    } else {
        basepath = config.getInitParameter("webmail.basepath");
    }
    if (config.getInitParameter("webmail.imagebase") == null) {
        log.error("webmail.basepath initArg should be set to the WebMail " + "Servlet's base path");
        imgbase = "";
    } else {
        imgbase = config.getInitParameter("webmail.imagebase");
    }

    /*
     * Try to get the pathnames from the URL's if no path was given in the
     * initargs.
     */
    if (config.getInitParameter("webmail.data.path") == null) {
        this.config.put("webmail.data.path", sc.getRealPath("/data"));
    }
    if (config.getInitParameter("webmail.lib.path") == null) {
        this.config.put("webmail.lib.path", sc.getRealPath("/lib"));
    }
    if (config.getInitParameter("webmail.template.path") == null) {
        this.config.put("webmail.template.path", sc.getRealPath("/lib/templates"));
    }
    if (config.getInitParameter("webmail.xml.path") == null) {
        this.config.put("webmail.xml.path", sc.getRealPath("/lib/xml"));
    }
    if (config.getInitParameter("webmail.log.facility") == null) {
        this.config.put("webmail.log.facility", "net.wastl.webmail.logger.ServletLogger");
    }

    // Override settings with webmail.* meta.properties
    final Enumeration rte = rtProps.propertyNames();
    int overrides = 0;
    String k;
    while (rte.hasMoreElements()) {
        k = (String) rte.nextElement();
        if (!k.startsWith("webmail.")) {
            continue;
        }
        overrides++;
        this.config.put(k, rtProps.getProperty(k));
    }
    log.debug(Integer.toString(overrides) + " settings passed to WebMailServer, out of " + rtProps.size()
            + " RT properties");

    /*
     * Call the WebMailServer's initialization method and forward all
     * Exceptions to the ServletServer
     */
    try {
        doInit();
    } catch (final Exception e) {
        log.error("Could not intialize", e);
        throw new ServletException("Could not intialize: " + e.getMessage(), e);
    }
    Helper.logThreads("Bottom of WebMailServlet.init()");
}

From source file:org.openlaszlo.servlets.responders.ResponderCompile.java

@Override
synchronized public void init(String reqName, ServletConfig config, Properties prop)
        throws ServletException, IOException {
    super.init(reqName, config, prop);

    // All compilation classes share cache directory and compilation manager.
    if (!mIsInitialized) {

        mAllowRequestSOURCE = prop.getProperty("allowRequestSOURCE", "true").intern() == "true";
        mCheckModifiedSince = prop.getProperty("checkModifiedSince", "true").intern() == "true";
        mAllowRecompile = prop.getProperty("allowRecompile", "true").intern() == "true";

        mAdminPassword = prop.getProperty("adminPassword", null);

        // Initialize the Compilation Cache
        String cacheDir = config.getInitParameter("lps.cache.directory");
        if (cacheDir == null) {
            cacheDir = prop.getProperty("cache.directory");
        }//w  w  w  .  j  av a2  s. c  o m
        if (cacheDir == null) {
            cacheDir = LPS.getWorkDirectory() + File.separator + "cache";
        }

        File cache = checkDirectory(cacheDir);
        mLogger.info(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="application cache is at " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(ResponderCompile.class.getName(), "051018-95",
                        new Object[] { cacheDir }));

        if (mCompMgr == null) {
            mCompMgr = new CompilationManager(null, cache, prop);
            boolean clear = "true".equals(LPS.getProperty("compile.cache.clearonstartup"));
            if (clear) {
                mCompMgr.clearCacheDirectory();
            }
        }

        if (mScriptCache == null) {
            String scacheDir = config.getInitParameter("lps.scache.directory");
            if (scacheDir == null) {
                scacheDir = prop.getProperty("scache.directory");
            }
            if (scacheDir == null) {
                scacheDir = LPS.getWorkDirectory() + File.separator + "scache";
            }
            File scache = checkDirectory(scacheDir);
            boolean enableScriptCache = "true".equals(LPS.getProperty("compiler.scache.enabled"));
            if (enableScriptCache) {
                mScriptCache = ScriptCompiler.initScriptCompilerCache(scache, prop);
            }
        }

        String cmOption = prop.getProperty("compMgrDependencyOption");
        if (cmOption != null) {
            mLogger.debug(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="Setting cm option to \"" + p[0] + "\""
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(ResponderCompile.class.getName(),
                            "051018-122", new Object[] { cmOption }));
            mCompMgr.setProperty("recompile", cmOption);
        }
    }
}

From source file:org.kawanfw.file.servlet.ServerFileManager.java

/**
 * Init.//from   ww w.  ja  v  a 2 s.c o  m
 */

public void init(ServletConfig config) throws ServletException {
    super.init(config);

    // Clean the olders folders of uploader classes, can't be done when closing
    String classpathUsernames = ClassPathUtil.getUserHomeDotKawansoftDotClasspath() + File.separator
            + ".usernames";
    try {
        FileUtils.deleteDirectory(new File(classpathUsernames));
        new File(classpathUsernames).delete();
    } catch (IOException ignore) {
        ignore.printStackTrace(System.out);
    }

    // Variable use to store the current name when loading, used to
    // detail
    // the exception in the catch clauses
    String classNameToLoad = null;

    String commonsConfiguratorClassName = config.getInitParameter(COMMONS_CONFIGURATOR_CLASS_NAME);
    String fileConfiguratorClassName = config.getInitParameter(FILE_CONFIGURATOR_CLASS_NAME);

    try {

        // Check spelling with first letter capitalized
        if (commonsConfiguratorClassName == null || commonsConfiguratorClassName.isEmpty()) {
            String capitalized = StringUtils.capitalize(COMMONS_CONFIGURATOR_CLASS_NAME);
            commonsConfiguratorClassName = config.getInitParameter(capitalized);
        }

        if (fileConfiguratorClassName == null || fileConfiguratorClassName.isEmpty()) {
            String capitalized = StringUtils.capitalize(FILE_CONFIGURATOR_CLASS_NAME);
            fileConfiguratorClassName = config.getInitParameter(capitalized);
        }

        // Call the specific FILE Configurator class to use

        classNameToLoad = commonsConfiguratorClassName;
        if (commonsConfiguratorClassName != null && !commonsConfiguratorClassName.isEmpty()) {
            Class<?> c = Class.forName(commonsConfiguratorClassName);
            commonsConfigurator = (CommonsConfigurator) c.newInstance();
        } else {
            commonsConfigurator = new DefaultCommonsConfigurator();
        }

        // Immediately create the Logger
        Logger logger = null;
        try {
            logger = commonsConfigurator.getLogger();
            ServerLogger.createLogger(logger);
            ServerLogger.getLogger().log(Level.WARNING, "Starting " + FileVersion.PRODUCT.NAME + "...");
            serverLoggerOk = true;
        } catch (Exception e) {
            initErrrorMesage = Tag.PRODUCT_USER_CONFIG_FAIL + " Impossible to create the Logger: " + logger;
            exception = e;

        }

        classNameToLoad = fileConfiguratorClassName;
        if (fileConfiguratorClassName != null && !fileConfiguratorClassName.isEmpty()) {
            Class<?> c = Class.forName(fileConfiguratorClassName);
            fileConfigurator = (FileConfigurator) c.newInstance();
        } else {
            fileConfigurator = new DefaultFileConfigurator();
        }

    } catch (ClassNotFoundException e) {
        initErrrorMesage = Tag.PRODUCT_USER_CONFIG_FAIL
                + " Impossible to load (ClassNotFoundException) Configurator class: " + classNameToLoad;
        exception = e;
    } catch (InstantiationException e) {
        initErrrorMesage = Tag.PRODUCT_USER_CONFIG_FAIL
                + " Impossible to load (InstantiationException) Configurator class: " + classNameToLoad;
        exception = e;
    } catch (IllegalAccessException e) {
        initErrrorMesage = Tag.PRODUCT_USER_CONFIG_FAIL
                + " Impossible to load (IllegalAccessException) Configurator class: " + classNameToLoad;
        exception = e;
    } catch (Exception e) {
        initErrrorMesage = Tag.PRODUCT_PRODUCT_FAIL + " Please contact support support@kawansoft.com";
        exception = e;
    }

    if (commonsConfigurator == null) {
        commonsConfiguratorClassName = COMMONS_CONFIGURATOR_CLASS_NAME;
    } else {
        commonsConfiguratorClassName = commonsConfigurator.getClass().getName();
    }

    if (fileConfigurator == null) {
        fileConfiguratorClassName = FILE_CONFIGURATOR_CLASS_NAME;
    } else {
        fileConfiguratorClassName = fileConfigurator.getClass().getName();
    }

    System.out.println();
    System.out.println(Tag.PRODUCT_START + " " + org.kawanfw.file.version.FileVersion.getVersion());
    System.out.println(Tag.PRODUCT_START + " " + this.getServletName() + " Servlet:");
    System.out.println(Tag.PRODUCT_START + " - Init Parameter commonsConfiguratorClassName: " + CR_LF
            + Tag.PRODUCT_START + SPACES_3 + commonsConfiguratorClassName);
    System.out.println(Tag.PRODUCT_START + " - Init Parameter fileConfiguratorClassName: " + CR_LF
            + Tag.PRODUCT_START + SPACES_3 + fileConfiguratorClassName);

    if (exception == null) {
        System.out.println(Tag.PRODUCT_START + " " + FileVersion.PRODUCT.NAME + " Configurator Status: OK.");
        System.out.println();
    } else {
        System.out.println(Tag.PRODUCT_START + " " + FileVersion.PRODUCT.NAME + " Configurator Status: KO.");
        System.out.println(initErrrorMesage);
        System.out.println(ExceptionUtils.getStackTrace(exception));
    }

    if (serverLoggerOk) {
        if (KawanNotifier.existsNoNotifyTxt()) {
            ServerLogger.getLogger().log(Level.WARNING,
                    Tag.PRODUCT_START + " Notification to Kawan Servers: OFF");
        }
    } else {
        if (KawanNotifier.existsNoNotifyTxt()) {
            System.out.println(Tag.PRODUCT_START + " Notification to Kawan Servers: OFF");
        }
    }

}

From source file:com.funambol.transport.http.server.Sync4jServlet.java

/**
 * Initializes the servlet/*from ww w.  j a  v a 2  s.  co  m*/
 * @throws javax.servlet.ServletException if an error occurs
 */
@Override
public void init() throws ServletException {
    initialized = false;
    String value;

    if (log.isInfoEnabled()) {
        System.getProperties().list(System.out);
        System.out.println("================================================================================");
    }

    ServletConfig config = getServletConfig();

    value = config.getInitParameter(PARAM_SYNCHOLDER_CLASS);

    if (StringUtils.isEmpty(value)) {
        String msg = "The servlet configuration parameter " + PARAM_SYNCHOLDER_CLASS + " cannot be empty ("
                + value + ")";
        log(msg);
        throw new ServletException(msg);
    }
    syncHolderClass = value;

    value = config.getInitParameter(PARAM_SESSION_TIMEOUT);
    if (!StringUtils.isEmpty(value)) {
        try {
            sessionTimeout = Integer.parseInt(value);
        } catch (NumberFormatException e) {
            String msg = "The servlet configuration parameter " + PARAM_SESSION_TIMEOUT
                    + " is not an integer number (" + value + ")";
            log.fatal(msg);
            throw new ServletException(msg);
        }
    }

    value = config.getInitParameter(PARAM_LOG_MESSAGES);
    if ("true".equalsIgnoreCase(value)) {
        logMessages = true;
        dirlogMessages = config.getInitParameter(PARAM_DIRLOG_MESSAGES);
    }

    value = config.getInitParameter(PARAM_PREFERRED_ENCODING);
    if (value != null) {
        preferredEncoding = value;
    } else {
        preferredEncoding = DEFAULT_PREFERRED_ENCODING;
    }

    value = config.getInitParameter(PARAM_SUPPORTED_ENCODING);
    if (value != null) {
        supportedEncoding = value;
    } else {
        supportedEncoding = DEFAULT_SUPPORTED_ENCODING;
    }

    value = config.getInitParameter(PARAM_COMPRESSION_LEVEL);
    if (value != null) {
        try {
            compressionLevel = Integer.parseInt(value);
        } catch (NumberFormatException e) {
            String msg = "The servlet configuration parameter " + PARAM_COMPRESSION_LEVEL
                    + " is not an integer (" + value + ")";
            log.fatal(msg);
            throw new ServletException(msg);
        }
    } else {
        //
        // The default compression level of the Deflater class
        //
        compressionLevel = DEFAULT_COMPRESSION_LEVEL;
    }

    value = config.getInitParameter(PARAM_ENABLE_COMPRESSION);
    if (value != null) {
        if ("true".equalsIgnoreCase(value)) {
            enableCompression = true;
        } else {
            enableCompression = false;
        }
    } else {
        //
        // If not specified, the default value is true
        //
        enableCompression = DEFAULT_ENABLE_COMPRESSION;
    }

    //
    // Now we are ready to bootstrap the Funambol components
    //
    bootstrap();

    //
    // Engine initialized!
    //
    initialized = true;
}

From source file:lucee.runtime.engine.CFMLEngineImpl.java

/**
 * loads Configuration File from System, from init Parameter from web.xml
 * @param sg/*from  w w  w  .j a  va 2 s .c  om*/
 * @param configServer 
 * @param countExistingContextes 
 * @return return path to directory
 */
private Resource getConfigDirectory(ServletConfig sg, ConfigServerImpl configServer, int countExistingContextes,
        RefBoolean isCustomSetting) throws PageServletException {
    isCustomSetting.setValue(true);
    ServletContext sc = sg.getServletContext();
    String strConfig = sg.getInitParameter("configuration");
    if (StringUtil.isEmpty(strConfig))
        strConfig = sg.getInitParameter("lucee-web-directory");
    if (StringUtil.isEmpty(strConfig))
        strConfig = System.getProperty("lucee.web.dir");

    if (StringUtil.isEmpty(strConfig)) {
        isCustomSetting.setValue(false);
        strConfig = "{web-root-directory}/WEB-INF/lucee/";
    }
    // only for backward compatibility
    else if (strConfig.startsWith("/WEB-INF/lucee/"))
        strConfig = "{web-root-directory}" + strConfig;

    strConfig = StringUtil.removeQuotes(strConfig, true);

    // static path is not allowed
    if (countExistingContextes > 1 && strConfig != null && strConfig.indexOf('{') == -1) {
        String text = "static path [" + strConfig
                + "] for servlet init param [lucee-web-directory] is not allowed, path must use a web-context specific placeholder.";
        System.err.println(text);
        throw new PageServletException(new ApplicationException(text));
    }
    strConfig = SystemUtil.parsePlaceHolder(strConfig, sc, configServer.getLabels());

    ResourceProvider frp = ResourcesImpl.getFileResourceProvider();
    Resource root = frp.getResource(ReqRspUtil.getRootPath(sc));
    Resource configDir = ResourceUtil.createResource(root.getRealResource(strConfig),
            FileUtil.LEVEL_PARENT_FILE, FileUtil.TYPE_DIR);

    if (configDir == null) {
        configDir = ResourceUtil.createResource(frp.getResource(strConfig), FileUtil.LEVEL_GRAND_PARENT_FILE,
                FileUtil.TYPE_DIR);
    }
    if (configDir == null)
        throw new PageServletException(new ApplicationException("path [" + strConfig + "] is invalid"));

    if (!configDir.exists() || ResourceUtil.isEmptyDirectory(configDir, null)) {
        Resource railoRoot;
        // there is a railo directory
        if (configDir.getName().equals("lucee")
                && (railoRoot = configDir.getParentResource().getRealResource("railo")).isDirectory()) {
            try {
                copyRecursiveAndRename(railoRoot, configDir);
            } catch (IOException e) {
                try {
                    configDir.createDirectory(true);
                } catch (IOException ioe) {
                }
                return configDir;
            }
            // zip the railo-server di and delete it (optional)
            try {
                Resource p = railoRoot.getParentResource();
                CompressUtil.compress(CompressUtil.FORMAT_ZIP, railoRoot,
                        p.getRealResource("railo-web-context-old.zip"), false, -1);
                ResourceUtil.removeEL(railoRoot, true);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        } else {
            try {
                configDir.createDirectory(true);
            } catch (IOException e) {
            }
        }
    }
    return configDir;
}

From source file:com.netscape.cms.servlet.cert.DoRevoke.java

/**
 * initialize the servlet. This servlet uses the template
 * file "revocationResult.template" to render the result
 *
 * @param sc servlet configuration, read from the web.xml file
 *///from   ww w .ja  va 2s .com
public void init(ServletConfig sc) throws ServletException {
    super.init(sc);
    mFormPath = "/" + mAuthority.getId() + "/" + TPL_FILE;

    if (mAuthority instanceof ICertificateAuthority) {
        mCertDB = ((ICertificateAuthority) mAuthority).getCertificateRepository();
    }
    if (mAuthority instanceof ICertAuthority) {
        mPublisherProcessor = ((ICertAuthority) mAuthority).getPublisherProcessor();
    }

    mTemplates.remove(ICMSRequest.SUCCESS);
    if (mOutputTemplatePath != null)
        mFormPath = mOutputTemplatePath;

    /* Server-Side time limit */
    try {
        mTimeLimits = Integer.parseInt(sc.getInitParameter("timeLimits"));
    } catch (Exception e) {
        /* do nothing, just use the default if integer parsing failed */
    }
}

From source file:test.unit.be.fedict.eid.applet.service.AuthenticationDataMessageHandlerTest.java

public void testHandleMessage() throws Exception {
    // setup/*from  ww  w  .  j a v  a 2 s.  co  m*/
    KeyPair keyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    String userId = "1234";
    X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(),
            "CN=Test, SERIALNUMBER=" + userId, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null,
            null);

    byte[] salt = "salt".getBytes();
    byte[] sessionId = "session-id".getBytes();

    AuthenticationDataMessage message = new AuthenticationDataMessage();
    message.authnCert = certificate;
    message.saltValue = salt;
    message.sessionId = sessionId;

    Map<String, String> httpHeaders = new HashMap<String, String>();
    HttpSession testHttpSession = new HttpTestSession();
    HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class);
    ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class);

    byte[] challenge = AuthenticationChallenge.generateChallenge(testHttpSession);

    AuthenticationContract authenticationContract = new AuthenticationContract(salt, null, null, sessionId,
            null, challenge);
    byte[] toBeSigned = authenticationContract.calculateToBeSigned();
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(keyPair.getPrivate());
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();
    message.signatureValue = signatureValue;

    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.CHALLENGE_MAX_MATURITY_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(AuthenticationTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.HOSTNAME_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INET_ADDRESS_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(AuditTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVER_CERTIFICATE))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(HelloMessageHandler.SESSION_ID_CHANNEL_BINDING_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_SECRET_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_IDENTITY_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_CERTS_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_ADDRESS_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_PHOTO_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME + "Class"))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE + "Class"))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_ORG_ID_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_APP_ID_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(
            AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES))
            .andReturn(null);

    EasyMock.expect(mockServletRequest.getAttribute("javax.servlet.request.ssl_session"))
            .andStubReturn(new String(Hex.encodeHex(sessionId)));
    EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("1.2.3.4");

    // prepare
    EasyMock.replay(mockServletRequest, mockServletConfig);

    // operate
    AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance);
    this.testedInstance.init(mockServletConfig);
    this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, testHttpSession);

    // verify
    EasyMock.verify(mockServletRequest, mockServletConfig);
    assertTrue(AuthenticationTestService.isCalled());
    assertEquals(userId, AuditTestService.getAuditUserId());
    assertEquals(userId, testHttpSession.getAttribute("eid.identifier"));
}

From source file:test.unit.be.fedict.eid.applet.service.AuthenticationDataMessageHandlerTest.java

public void testHandleMessageWithoutAuditService() throws Exception {
    // setup//from   www.  j  a v a2 s  .  c  o m
    KeyPair keyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    String userId = "1234";
    X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(),
            "CN=Test, SERIALNUMBER=" + userId, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null,
            null);

    byte[] salt = "salt".getBytes();
    byte[] sessionId = "session-id".getBytes();

    AuthenticationDataMessage message = new AuthenticationDataMessage();
    message.authnCert = certificate;
    message.saltValue = salt;
    message.sessionId = sessionId;

    Map<String, String> httpHeaders = new HashMap<String, String>();
    HttpSession testHttpSession = new HttpTestSession();
    HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class);
    ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class);

    byte[] challenge = AuthenticationChallenge.generateChallenge(testHttpSession);

    AuthenticationContract authenticationContract = new AuthenticationContract(salt, null, null, sessionId,
            null, challenge);
    byte[] toBeSigned = authenticationContract.calculateToBeSigned();
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(keyPair.getPrivate());
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();
    message.signatureValue = signatureValue;

    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.CHALLENGE_MAX_MATURITY_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(AuthenticationTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.HOSTNAME_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INET_ADDRESS_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVER_CERTIFICATE))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(HelloMessageHandler.SESSION_ID_CHANNEL_BINDING_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_SECRET_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_IDENTITY_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_CERTS_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_ADDRESS_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_PHOTO_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME + "Class"))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE + "Class"))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_ORG_ID_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_APP_ID_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(
            AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(null);

    EasyMock.expect(mockServletRequest.getAttribute("javax.servlet.request.ssl_session"))
            .andStubReturn(new String(Hex.encodeHex(sessionId)));
    EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES))
            .andReturn(null);
    EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("1.2.3.4");

    // prepare
    EasyMock.replay(mockServletRequest, mockServletConfig);

    // operate
    AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance);
    this.testedInstance.init(mockServletConfig);
    this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, testHttpSession);

    // verify
    EasyMock.verify(mockServletRequest, mockServletConfig);
    assertTrue(AuthenticationTestService.isCalled());
    assertNull(AuditTestService.getAuditUserId());
    assertEquals(userId, testHttpSession.getAttribute("eid.identifier"));
}

From source file:org.kawanfw.sql.servlet.ServerSqlManager.java

/**
 * Init/*from   w  ww  . j a v a 2  s  . c o  m*/
 */

public void init(ServletConfig config) throws ServletException {
    super.init(config);

    // Variable use to store the current name when loading, used to
    // detail
    // the exception in the catch clauses
    String classNameToLoad = null;

    String commonsConfiguratorClassName;
    String fileConfiguratorClassName;
    String sqlConfiguratorClassName;

    String servletName = this.getServletName();

    String index = null;

    if (!TomcatModeStore.isTomcatEmbedded()) {
        System.out.println(SqlTag.SQL_PRODUCT_START + " " + Version.getServerVersion());
    }

    // We are in SQL Framework
    TomcatModeStore.setFrameworkSql(true);

    try {

        if (!TomcatModeStore.isTomcatEmbedded()) {
            String propertiesFileStr = config.getInitParameter("properties");

            if (propertiesFileStr == null || propertiesFileStr.isEmpty()) {

                String aceqlHome = System.getenv("ACEQL_HOME");

                if (aceqlHome != null) {

                    // Remove surrounding " if present
                    aceqlHome = aceqlHome.replaceAll("\"", "");

                    if (aceqlHome.endsWith(File.separator)) {
                        aceqlHome = StringUtils.substringBeforeLast(aceqlHome, File.separator);
                    }
                    propertiesFileStr = aceqlHome + File.separator + "conf" + File.separator
                            + "aceql-server.properties";
                } else {
                    throw new SqlConfigurationException(Tag.PRODUCT_USER_CONFIG_FAIL
                            + " ACEQL_HOME property not set. Impossible to use the default ACEQL_HOME"
                            + File.separator + "conf" + File.separator + "aceql-server.properties file");
                }

                //          throw new SqlConfigurationException(
                //             Tag.PRODUCT_USER_CONFIG_FAIL
                //                + " <param-name> \"properties\" not found for servlet "
                //                + servletName);
            }

            File propertiesFile = new File(propertiesFileStr);

            if (!propertiesFile.exists()) {
                throw new SqlConfigurationException(
                        Tag.PRODUCT_USER_CONFIG_FAIL + " properties file not found: " + propertiesFile);
            }

            System.out.println(SqlTag.SQL_PRODUCT_START + " " + "Using properties file: " + propertiesFile);

            properties = TomcatStarterUtil.getProperties(propertiesFile);

            index = TomcatStarterUtil.getIndexFromServletName(properties, servletName);

            TomcatStarterUtil.setInitParametersInStore(properties, index);

            // Create the default DataSource if necessary
            TomcatStarterUtil.createAndStoreDataSource(properties, index);
        }

        commonsConfiguratorClassName = ServletParametersStore.getInitParameter(servletName,
                COMMONS_CONFIGURATOR_CLASS_NAME);
        fileConfiguratorClassName = ServletParametersStore.getInitParameter(servletName,
                FILE_CONFIGURATOR_CLASS_NAME);
        sqlConfiguratorClassName = ServletParametersStore.getInitParameter(servletName,
                SQL_CONFIGURATOR_CLASS_NAME);

        debug("commonsConfiguratorClassName: " + commonsConfiguratorClassName);
        debug("fileConfiguratorClassName   : " + fileConfiguratorClassName);
        debug("sqlConfiguratorClassName    : " + sqlConfiguratorClassName);

        // Check spelling with first letter capitalized

        if (commonsConfiguratorClassName == null || commonsConfiguratorClassName.isEmpty()) {
            String capitalized = StringUtils.capitalize(ServerFileManager.COMMONS_CONFIGURATOR_CLASS_NAME);
            commonsConfiguratorClassName = ServletParametersStore.getInitParameter(servletName, capitalized);
        }

        if (fileConfiguratorClassName == null || fileConfiguratorClassName.isEmpty()) {
            String capitalized = StringUtils.capitalize(ServerFileManager.FILE_CONFIGURATOR_CLASS_NAME);
            fileConfiguratorClassName = ServletParametersStore.getInitParameter(servletName, capitalized);
        }

        if (sqlConfiguratorClassName == null || sqlConfiguratorClassName.isEmpty()) {
            String capitalized = StringUtils.capitalize(SQL_CONFIGURATOR_CLASS_NAME);
            sqlConfiguratorClassName = ServletParametersStore.getInitParameter(servletName, capitalized);
        }

        // Call the specific Configurator class to use

        classNameToLoad = commonsConfiguratorClassName;
        if (commonsConfiguratorClassName != null && !commonsConfiguratorClassName.isEmpty()) {
            Class<?> c = Class.forName(commonsConfiguratorClassName);
            commonsConfigurator = (CommonsConfigurator) c.newInstance();
        } else {

            commonsConfigurator = new DefaultCommonsConfigurator();

        }

        // Immediately create the ServerLogger
        Logger logger = null;
        try {
            logger = commonsConfigurator.getLogger();
            ServerLogger.createLogger(logger);
            serverLoggerOk = true;
        } catch (Exception e) {
            exception = e;
            initErrrorMesage = Tag.PRODUCT_USER_CONFIG_FAIL + " Impossible to create the Logger: " + logger
                    + ". Reason: " + e.getMessage();
        }

        classNameToLoad = fileConfiguratorClassName;
        if (fileConfiguratorClassName != null && !fileConfiguratorClassName.isEmpty()) {
            Class<?> c = Class.forName(fileConfiguratorClassName);
            fileConfigurator = (FileConfigurator) c.newInstance();
        } else {
            fileConfigurator = new DefaultFileConfigurator();
        }

        classNameToLoad = sqlConfiguratorClassName;
        if (sqlConfiguratorClassName != null && !sqlConfiguratorClassName.isEmpty()) {
            Class<?> c = Class.forName(sqlConfiguratorClassName);
            sqlConfigurator = (SqlConfigurator) c.newInstance();
        } else {
            sqlConfigurator = new DefaultSqlConfigurator();
        }

    } catch (ClassNotFoundException e) {
        initErrrorMesage = Tag.PRODUCT_USER_CONFIG_FAIL
                + " Impossible to load (ClassNotFoundException) Configurator class: " + classNameToLoad;
        exception = e;
    } catch (InstantiationException e) {
        initErrrorMesage = Tag.PRODUCT_USER_CONFIG_FAIL
                + " Impossible to load (InstantiationException) Configurator class: " + classNameToLoad;
        exception = e;
    } catch (IllegalAccessException e) {
        initErrrorMesage = Tag.PRODUCT_USER_CONFIG_FAIL
                + " Impossible to load (IllegalAccessException) Configurator class: " + classNameToLoad;
        exception = e;
    } catch (SqlConfigurationException e) {
        initErrrorMesage = e.getMessage();
        exception = e;
    } catch (Exception e) {
        initErrrorMesage = Tag.PRODUCT_PRODUCT_FAIL + " Please contact support at: support@kawansoft.com";
        exception = e;
    }

    if (commonsConfigurator == null) {
        commonsConfiguratorClassName = COMMONS_CONFIGURATOR_CLASS_NAME;
    } else {
        commonsConfiguratorClassName = commonsConfigurator.getClass().getName();
    }

    if (fileConfigurator == null) {
        fileConfiguratorClassName = FILE_CONFIGURATOR_CLASS_NAME;
    } else {
        fileConfiguratorClassName = fileConfigurator.getClass().getName();
    }

    if (sqlConfigurator == null) {
        sqlConfiguratorClassName = SQL_CONFIGURATOR_CLASS_NAME;
    } else {
        sqlConfiguratorClassName = sqlConfigurator.getClass().getName();
    }

    System.out.println(SqlTag.SQL_PRODUCT_START + " " + servletName + " Servlet Configurators:");
    System.out.println(
            SqlTag.SQL_PRODUCT_START + "  -> commonsConfiguratorClassName: " + commonsConfiguratorClassName);
    System.out.println(
            SqlTag.SQL_PRODUCT_START + "  -> sqlConfiguratorClassName    : " + sqlConfiguratorClassName);
    System.out.println(
            SqlTag.SQL_PRODUCT_START + "  -> fileConfiguratorClassName   : " + fileConfiguratorClassName);

    if (exception == null) {
        System.out.println(SqlTag.SQL_PRODUCT_START + "  -> Configurators Status: OK.");
    } else {

        if (!TomcatModeStore.isTomcatEmbedded()) {
            String errorMessage1 = SqlTag.SQL_PRODUCT_START + "  -> Configurators Status: KO.";
            String errorMessage2 = initErrrorMesage;
            String errorMessage3 = ExceptionUtils.getStackTrace(exception);

            System.out.println(errorMessage1);
            System.out.println(errorMessage2);
            System.out.println(errorMessage3);

            if (serverLoggerOk) {
                ServerLogger.getLogger().log(Level.WARNING, errorMessage1);
                ServerLogger.getLogger().log(Level.WARNING, errorMessage2);
                ServerLogger.getLogger().log(Level.WARNING, errorMessage3);
            }

            System.out.println();
        }

    }
}