Example usage for java.util Collections synchronizedMap

List of usage examples for java.util Collections synchronizedMap

Introduction

In this page you can find the example usage for java.util Collections synchronizedMap.

Prototype

public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m) 

Source Link

Document

Returns a synchronized (thread-safe) map backed by the specified map.

Usage

From source file:cn.com.loopj.android.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//from  w w  w  . j  ava 2s  . c o m
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ClientConnectionManager cm = createConnectionManager(schemeRegistry, httpParams);
    Utils.asserts(cm != null,
            "Custom implementation of #createConnectionManager(SchemeRegistry, BasicHttpParams) returned null");

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    //remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:com.lfrj.diancan.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*  ww w. j  a v  a2s .com*/
 * 
 * @param schemeRegistry
 *            SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    // remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:org.apache.cocoon.components.modules.input.XMLFileModule.java

/**
 * Static (cocoon.xconf) configuration.//from w  w w  .ja  v  a  2  s.c  o m
 * Configuration is expected to be of the form:
 * &lt;...&gt;
 *   &lt;reloadable&gt;true|<b>false</b>&lt;/reloadable&gt;
 *   &lt;cacheable&gt;<b>true</b>|false&lt;/cacheable&gt;
 *   &lt;file src="<i>src1</i>" reloadable="true|<b>false</b>" cacheable="<b>true</b>|false"/&gt;
 *   &lt;file src="<i>src2</i>" reloadable="true|<b>false</b>" cacheable="<b>true</b>|false"/&gt;
 *   ...
 * &lt;/...&gt;
 *
 * Each &lt;file/&gt; element pre-loads an XML DOM for querying. Typically only one
 * &lt;file&gt; is specified, and its <i>src</i> is used as a default if not
 * overridden in the {@link #getContextObject(Configuration, Map)}
 *
 * @param config a <code>Configuration</code> value, as described above.
 * @exception ConfigurationException if an error occurs
 */
public void configure(Configuration config) throws ConfigurationException {
    super.configure(config);
    this.staticConfLocation = config.getLocation();
    this.reloadAll = config.getChild("reloadable").getValueAsBoolean(false);

    if (config.getChild("cachable", false) != null) {
        throw new ConfigurationException("Bzzt! Wrong spelling at " + config.getChild("cachable").getLocation()
                + ": please use 'cacheable', not 'cachable'");
    }
    this.cacheAll = config.getChild("cacheable").getValueAsBoolean(true);

    this.documents = Collections.synchronizedMap(new HashMap());
    Configuration[] files = config.getChildren("file");
    for (int i = 0; i < files.length; i++) {
        boolean reload = files[i].getAttributeAsBoolean("reloadable", this.reloadAll);
        boolean cache = files[i].getAttributeAsBoolean("cacheable", this.cacheAll);
        this.src = files[i].getAttribute("src");
        // by assigning the source uri to this.src the last one will be the default
        // OTOH caching / reload parameters can be specified in one central place
        // if multiple file tags are used.
        this.documents.put(files[i], new DocumentHelper(reload, cache, this.src, this));
    }

    // init caches
    this.cacheExpressions = config.getChild("cache-expressions").getValueAsBoolean(true);
    if (this.cacheExpressions) {
        this.expressionCache = new ReferenceMap(AbstractReferenceMap.SOFT, AbstractReferenceMap.SOFT);
        this.expressionValuesCache = new ReferenceMap(AbstractReferenceMap.SOFT, AbstractReferenceMap.SOFT);
    }
}

From source file:com.xinlan.otma.net.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from w  w w .  j a v  a2 s.  com*/
 * 
 * @param schemeRegistry
 *            SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    // remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            } // end for
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                } // end for
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:org.pentaho.platform.engine.core.system.PentahoSystem.java

public static boolean init(final IApplicationContext pApplicationContext, final Map listenerMap) {
    if (debug) {//  www.j  av  a2  s . c om
        Logger.debug(PentahoSystem.class, "PentahoSystem init called"); //$NON-NLS-1$
    }

    if (PentahoSystem.initializedStatus == PentahoSystem.SYSTEM_INITIALIZED_OK) {
        // TODO: Removing the catching of this IllegalStateException. It's being trapped here now as too many existing
        // tests call init more than once without an intervening shutdown().
        try {
            throw new IllegalStateException("'Init' method was run twice without 'shutdown'");
        } catch (IllegalStateException e) {
            Logger.error(PentahoSystem.class,
                    "PentahoSystem was already initialized when init() called again without a preceding shutdown(). "
                            + "This is likely in error",
                    e);
        }
    }

    PentahoSystem.initializedStatus = PentahoSystem.SYSTEM_INITIALIZED_OK;

    // PDI-3438 Scheduled job fails to open a transformation
    // Kettle jobs spawn threads which may require authentication to load transformations from
    // the kettle repository, by using the INHERITABLETHREADLOCAL strategy, spawned threads will
    // enjoy the same SecurityContext as their parent!
    SecurityContextHolder.setStrategyName(securityContextHolderStrategy);

    PentahoSystem.globalAttributes = Collections.synchronizedMap(new HashMap());
    PentahoSystem.globalParameters = new SimpleParameterProvider(PentahoSystem.globalAttributes);

    PentahoSystem.applicationContext = pApplicationContext;

    if (debug) {
        Logger.debug(PentahoSystem.class, "Setting property path"); //$NON-NLS-1$
    }
    System.setProperty("pentaho.solutionpath", "solution:"); //$NON-NLS-1$
    if (LocaleHelper.getLocale() == null) {
        LocaleHelper.setLocale(Locale.getDefault());
    }

    if (PentahoSystem.systemSettingsService != null) {
        if (debug) {
            Logger.debug(PentahoSystem.class, "Reading ACL list from pentaho.xml"); //$NON-NLS-1$
        }
        // Set Up ACL File Extensions by reading pentaho.xml for acl-files
        //
        // Read the files that are permitted to have ACLs on them from
        // the pentaho.xml.
        //
        String aclFiles = PentahoSystem.getSystemSetting("acl-files", "xaction,url"); //$NON-NLS-1$ //$NON-NLS-2$
        StringTokenizer st = new StringTokenizer(aclFiles, ","); //$NON-NLS-1$
        String extn;
        while (st.hasMoreElements()) {
            extn = st.nextToken();
            if (!extn.startsWith(".")) { //$NON-NLS-1$
                extn = "." + extn; //$NON-NLS-1$
            }
            PentahoSystem.ACLFileExtensionList.add(extn);
        }
    }

    if (debug) {
        Logger.debug(PentahoSystem.class, "Initialize XML Factories"); //$NON-NLS-1$
    }
    PentahoSystem.initXMLFactories();

    if (debug) {
        Logger.debug(PentahoSystem.class, "Set Logging Level from pentaho.xml setting"); //$NON-NLS-1$
    }
    PentahoSystem.loggingLevel = ILogger.ERROR;
    if (PentahoSystem.systemSettingsService != null) {
        PentahoSystem.loggingLevel = Logger
                .getLogLevel(PentahoSystem.systemSettingsService.getSystemSetting("log-level", "ERROR")); //$NON-NLS-1$//$NON-NLS-2$
    }

    Logger.setLogLevel(PentahoSystem.loggingLevel);

    // to guarantee hostnames in SSL mode are not being spoofed
    if (debug) {
        Logger.debug(PentahoSystem.class, "Register host name verifier"); //$NON-NLS-1$
    }
    PentahoSystem.registerHostnameVerifier();

    assert null != aggObjectFactory : "aggObjectFactory must be non-null"; //$NON-NLS-1$
    try {
        if (debug) {
            Logger.debug(PentahoSystem.class, "Validating object factory"); //$NON-NLS-1$
        }
        PentahoSystem.validateObjectFactory();
    } catch (PentahoSystemException e1) {
        throw new RuntimeException(e1); // this is fatal
    }

    // store a list of the system listeners
    try {
        if (debug) {
            Logger.debug(PentahoSystem.class, "Start System Listeners"); //$NON-NLS-1$
        }
        PentahoSystem.notifySystemListenersOfStartup();
    } catch (PentahoSystemException e) {
        String msg = e.getLocalizedMessage();
        Logger.error(PentahoSystem.class.getName(), msg, e);
        PentahoSystem.initializedStatus |= PentahoSystem.SYSTEM_LISTENERS_FAILED;
        PentahoSystem.addInitializationFailureMessage(PentahoSystem.SYSTEM_LISTENERS_FAILED, msg);
        return false;
    }

    // once everything else is initialized, start global actions
    if (debug) {
        Logger.debug(PentahoSystem.class, "Global startup"); //$NON-NLS-1$
    }
    PentahoSystem.globalStartup();

    if (debug) {
        Logger.debug(PentahoSystem.class, "PentahoSystem Init Complete"); //$NON-NLS-1$
    }
    return true;
}

From source file:com.all.messengine.impl.ResponseManager.java

public void initialize() {
    listeners = Collections.synchronizedMap(new HashMap<String, ResponseLock>());
    executor = Executors.newCachedThreadPool();
}

From source file:com.codefollower.lealone.omid.client.TSOClient.java

public TSOClient(Configuration conf) throws IOException {
    state = State.DISCONNECTED;/*from w ww. j  a va  2s.  c  o m*/
    queuedOps = new ArrayBlockingQueue<Op>(200);
    retryTimer = new Timer(true);

    commitCallbacks = Collections.synchronizedMap(new HashMap<Long, CommitCallback>());
    isCommittedCallbacks = Collections.synchronizedMap(new HashMap<Long, List<CommitQueryCallback>>());
    createCallbacks = new ConcurrentLinkedQueue<CreateCallback>();
    channel = null;

    LOG.info("Starting TSOClient");

    // Start client with Nb of active threads = 3 as maximum.
    factory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool(), 3);
    // Create the bootstrap
    bootstrap = new ClientBootstrap(factory);

    int executorThreads = conf.getInt("tso.executor.threads", 3);

    bootstrap.getPipeline().addLast("executor", new ExecutionHandler(
            new OrderedMemoryAwareThreadPoolExecutor(executorThreads, 1024 * 1024, 4 * 1024 * 1024)));
    bootstrap.getPipeline().addLast("handler", this);
    bootstrap.setOption("tcpNoDelay", false);
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("reuseAddress", true);
    bootstrap.setOption("connectTimeoutMillis", 100);

    String host = conf.get("tso.host");
    int port = conf.getInt("tso.port", 1234);
    maxRetries = conf.getInt("tso.max_retries", 100);
    retryDelayMs = conf.getInt("tso.retry_delay_ms", 1000);

    if (host == null) {
        throw new IOException("tso.host missing from configuration");
    }

    addr = new InetSocketAddress(host, port);
    connectIfNeeded();
}

From source file:org.isatools.isacreator.spreadsheet.model.TableReferenceObject.java

public Map<String, FieldObject> getMissingFields() {
    if (missingFields != null) {
        getMultipleInstanceFields();//from   w ww.j  a v  a  2  s .  c  o m
        return Collections.synchronizedMap(missingFields);
    } else {
        return null;
    }
}

From source file:org.josso.jaspi.agent.JASPISSOAuthModule.java

@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
        throws AuthException {

    HttpServletRequest hreq = (HttpServletRequest) messageInfo.getRequestMessage();
    HttpServletResponse hres = (HttpServletResponse) messageInfo.getResponseMessage();

    if (log.isDebugEnabled()) {
        log.debug("Processing : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "]");
    }//from  w  w  w  . j a v a 2  s . c o  m

    try {
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();
        String vhost = hreq.getServerName();

        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath)) {
            contextPath = "/";
        }

        if (!_agent.isPartnerApp(vhost, contextPath)) {
            if (log.isDebugEnabled()) {
                log.debug("Context is not a josso partner app : " + hreq.getContextPath());
            }
            AuthStatus status = AuthStatus.SUCCESS;
            return status;
        }

        // ------------------------------------------------------------------
        // Check some basic HTTP handling
        // ------------------------------------------------------------------
        // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME
        SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath);
        if (cfg.isSendP3PHeader() && !hres.isCommitted()) {
            hres.setHeader("P3P", cfg.getP3PHeaderValue());
        }

        // Get our session ...
        HttpSession session = hreq.getSession(true);

        // ------------------------------------------------------------------
        // Check if the partner application required the login form
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'");
        }

        if (hreq.getRequestURI().endsWith(_agent.getJossoLoginUri())
                || hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {

            if (log.isDebugEnabled()) {
                log.debug("josso_login_request received for uri '" + hreq.getRequestURI() + "'");
            }

            //save referer url in case the user clicked on Login from some public resource (page)
            //so agent can redirect the user back to that page after successful login
            if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {
                saveLoginBackToURL(hreq, hres, session, true);
            } else {
                saveLoginBackToURL(hreq, hres, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

            if (log.isDebugEnabled()) {
                log.debug("Redirecting to login url '" + loginUrl + "'");
            }

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(loginUrl));

            // Request is authorized for this URI
            return AuthStatus.SEND_CONTINUE;
        }

        // ------------------------------------------------------------------
        // Check if the partner application required a logout
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'");
        }

        if (hreq.getRequestURI().endsWith(_agent.getJossoLogoutUri())) {

            if (log.isDebugEnabled()) {
                log.debug("josso_logout request received for uri '" + hreq.getRequestURI() + "'");
            }

            String logoutUrl = _agent.buildLogoutUrl(hreq, cfg);

            if (log.isDebugEnabled()) {
                log.debug("Redirecting to logout url '" + logoutUrl + "'");
            }

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
            hres.addCookie(ssoCookie);

            // invalidate session (unbind josso security context)
            session.invalidate();

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(logoutUrl));

            // Request is authorized for this URI
            return AuthStatus.SEND_CONTINUE;
        }

        // ------------------------------------------------------------------
        // Check for the single sign on cookie
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Checking for SSO cookie");
        }
        Cookie cookie = null;
        Cookie cookies[] = hreq.getCookies();
        if (cookies == null) {
            cookies = new Cookie[0];
        }
        for (int i = 0; i < cookies.length; i++) {
            if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
                cookie = cookies[i];
                break;
            }
        }

        String jossoSessionId = (cookie == null) ? null : cookie.getValue();
        if (log.isDebugEnabled()) {
            log.debug("Session is: " + session);
        }

        // Get session map for this servlet context.
        Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
        if (sessionMap == null) {
            synchronized (this) {
                sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
                if (sessionMap == null) {
                    sessionMap = Collections.synchronizedMap(new HashMap());
                    hreq.getSession().getServletContext().setAttribute(KEY_SESSION_MAP, sessionMap);
                }
            }
        }

        LocalSession localSession = (LocalSession) sessionMap.get(session.getId());
        if (localSession == null) {
            localSession = new JASPILocalSession(session);
            // the local session is new so, make the valve listen for its events so that it can
            // map them to local session events.
            // Not Supported : session.addSessionListener(this);
            sessionMap.put(session.getId(), localSession);

        }

        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------

        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) {

            if (log.isDebugEnabled()) {
                log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'");
            }

            JASPISSOAgentRequest customAuthRequest = (JASPISSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(),
                    SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, hreq,
                    hres);

            _agent.processRequest(customAuthRequest);

            // Request is authorized
            return AuthStatus.SEND_CONTINUE;
        }

        if (cookie == null || cookie.getValue().equals("-")) {

            // ------------------------------------------------------------------
            // Trigger LOGIN OPTIONAL if required
            // ------------------------------------------------------------------

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, verifying optional login process ");

            // We have no cookie, remember me is enabled and a security check without assertion was received ...
            // This means that the user could not be identified ... go back to the original resource
            if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") == null) {

                if (log.isDebugEnabled())
                    log.debug(_agent.getJossoSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

                String requestURI = this.getSavedRequestURL(hreq);
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
                AuthStatus status = AuthStatus.SEND_CONTINUE;
                return status;
            }

            // This is a standard anonymous request!
            if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) {

                // If saved request is NOT null, we're in the middle of another process ...
                if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) {

                    if (log.isDebugEnabled()) {
                        log.debug("SSO cookie is not present, attempting automatic login");
                    }

                    // Save current request, so we can co back to it later ...
                    saveRequestURL(hreq, hres);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (log.isDebugEnabled()) {
                        log.debug("Redirecting to login url '" + loginUrl + "'");
                    }

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    //hreq.getRequestDispatcher(loginUrl).forward(hreq, hres);
                    AuthStatus status = AuthStatus.SEND_CONTINUE;
                    return status;
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("SSO cookie is not present, but login optional process is not required");
                    }
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("SSO cookie is not present, checking for outbound relaying");
            }

            if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") != null)) {
                log.debug("SSO cookie not present and relaying was not requested, skipping");
                AuthStatus status = AuthStatus.SUCCESS;
                return status;
            }

        }

        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        if (_agent.isResourceIgnored(cfg, hreq)) {
            // Ignored resources are authorized
            return AuthStatus.SUCCESS;
        }

        // This URI should be protected by SSO, go on ...
        if (log.isDebugEnabled()) {
            log.debug("Session is: " + session);
        }

        // ------------------------------------------------------------------
        // Invoke the SSO Agent
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Executing agent...");
        }

        // ------------------------------------------------------------------
        // Check if a user has been authenticated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");
        }

        if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                && hreq.getParameter("josso_assertion_id") != null) {

            if (log.isDebugEnabled()) {
                log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '"
                        + hreq.getParameter("josso_assertion_id"));
            }

            String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            JASPISSOAgentRequest relayRequest;

            if (log.isDebugEnabled()) {
                log.debug("Outbound relaying requested for assertion id [" + assertionId + "]");
            }

            relayRequest = (JASPISSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(),
                    SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId, hreq, hres);

            SingleSignOnEntry entry = _agent.processRequest(relayRequest);
            if (entry == null) {
                // This is wrong! We should have an entry here!
                if (log.isDebugEnabled()) {
                    log.debug("Outbound relaying failed for assertion id [" + assertionId
                            + "], no Principal found.");
                }
                // Throw an exception, we will handle it below !
                throw new RuntimeException(
                        "Outbound relaying failed. No Principal found. Verify your SSO Agent Configuration!");
            } else {
                // Add the SSOUser as a Principal
                if (!clientSubject.getPrincipals().contains(entry.principal)) {
                    clientSubject.getPrincipals().add(entry.principal);
                }
                SSORole[] ssoRolePrincipals = _agent.getRoleSets(cfg.getId(), entry.ssoId,
                        relayRequest.getNodeId());
                List<String> rolesList = new ArrayList<String>();

                for (int i = 0; i < ssoRolePrincipals.length; i++) {
                    if (clientSubject.getPrincipals().contains(ssoRolePrincipals[i])) {
                        continue;
                    }
                    rolesList.add(ssoRolePrincipals[i].getName());

                    clientSubject.getPrincipals().add(ssoRolePrincipals[i]);
                    log.debug("Added SSORole Principal to the Subject : " + ssoRolePrincipals[i]);
                }

                registerWithCallbackHandler(entry.principal, entry.principal.getName(), entry.ssoId,
                        rolesList.toArray(new String[rolesList.size()]));
            }

            if (log.isDebugEnabled()) {
                log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]");
            }

            if (log.isDebugEnabled()) {
                log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]");
            }

            // The cookie is valid to for the partner application only ... in the future each partner app may
            // store a different auth. token (SSO SESSION) value
            cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure());
            hres.addCookie(cookie);

            //Redirect user to the saved splash resource (in case of auth request) or to request URI otherwise
            String requestURI = getSavedSplashResource(hreq);
            if (requestURI == null) {
                requestURI = getSavedRequestURL(hreq);
                if (requestURI == null) {

                    if (cfg.getDefaultResource() != null) {
                        requestURI = cfg.getDefaultResource();
                    } else {
                        // If no saved request is found, redirect to the partner app root :
                        requestURI = hreq.getRequestURI().substring(0,
                                (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length()));
                    }

                    // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?!
                    String singlePointOfAccess = _agent.getSinglePointOfAccess();
                    if (singlePointOfAccess != null) {
                        requestURI = singlePointOfAccess + requestURI;
                    } else {
                        String reverseProxyHost = hreq
                                .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER);
                        if (reverseProxyHost != null) {
                            requestURI = reverseProxyHost + requestURI;
                        }
                    }

                    if (log.isDebugEnabled())
                        log.debug("No saved request found, using : '" + requestURI + "'");
                }
            }

            _agent.clearAutomaticLoginReferer(hreq, hres);
            _agent.prepareNonCacheResponse(hres);

            // Check if we have a post login resource :
            String postAuthURI = cfg.getPostAuthenticationResource();
            if (postAuthURI != null) {
                String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI);
                if (log.isDebugEnabled()) {
                    log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'");
                }
                hres.sendRedirect(postAuthURL);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Redirecting to original '" + requestURI + "'");
                }
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            }

            AuthStatus status = AuthStatus.SEND_SUCCESS;
            return status;
        }

        if (log.isDebugEnabled()) {
            log.debug("Creating Security Context for Session [" + session + "]");
        }
        SSOAgentRequest r = doMakeSSOAgentRequest(cfg.getId(),
                SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, hreq,
                hres);
        SingleSignOnEntry entry = _agent.processRequest(r);

        if (log.isDebugEnabled()) {
            log.debug("Executed agent.");
        }

        // ------------------------------------------------------------------
        // Has a valid user already been authenticated?
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Process request for '" + hreq.getRequestURI() + "'");
        }

        if (entry != null) {
            if (log.isDebugEnabled()) {
                log.debug("Principal '" + entry.principal + "' has already been authenticated");
            }
            // Add the SSOUser as a Principal
            if (!clientSubject.getPrincipals().contains(entry.principal)) {
                clientSubject.getPrincipals().add(entry.principal);
            }
            SSORole[] ssoRolePrincipals = _agent.getRoleSets(cfg.getId(), entry.ssoId, r.getNodeId());
            List<String> rolesList = new ArrayList<String>();
            for (int i = 0; i < ssoRolePrincipals.length; i++) {
                if (clientSubject.getPrincipals().contains(ssoRolePrincipals[i])) {
                    continue;
                }
                rolesList.add(ssoRolePrincipals[i].getName());
                clientSubject.getPrincipals().add(ssoRolePrincipals[i]);
                log.debug("Added SSORole Principal to the Subject : " + ssoRolePrincipals[i]);
            }
            registerWithCallbackHandler(entry.principal, entry.principal.getName(), entry.ssoId,
                    rolesList.toArray(new String[rolesList.size()]));
        } else {
            log.debug("No Valid SSO Session, attempt an optional login?");
            // This is a standard anonymous request!

            if (cookie != null) {
                // cookie is not valid
                cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
                hres.addCookie(cookie);
            }

            if (cookie != null
                    || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) {
                if (log.isDebugEnabled()) {
                    log.debug("SSO Session is not valid, attempting automatic login");
                }

                // Save current request, so we can co back to it later ...
                saveRequestURL(hreq, hres);
                String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                if (log.isDebugEnabled()) {
                    log.debug("Redirecting to login url '" + loginUrl + "'");
                }

                //set non cache headers
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(loginUrl));

                // Request is authorized for this URI
                return AuthStatus.SEND_CONTINUE;
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("SSO cookie is not present, but login optional process is not required");
                }
            }

        }

        // propagate the login and logout URLs to
        // partner applications.
        hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl());
        hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl());
        hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId);

        clearSavedRequestURLs(hreq, hres);

        AuthStatus status = AuthStatus.SUCCESS;
        return status;
    } catch (Throwable t) {
        log.warn(t.getMessage(), t);
        throw new AuthException(t.getMessage());
        //return AuthStatus.FAILURE;
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("Processed : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "]");
        }
    }
}

From source file:com.amytech.android.library.utils.asynchttp.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//from   w  w  w  . jav a2  s. c om
 *
 * @param schemeRegistry
 *            SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ClientConnectionManager cm = createConnectionManager(schemeRegistry, httpParams);
    Utils.asserts(cm != null,
            "Custom implementation of #createConnectionManager(SchemeRegistry, BasicHttpParams) returned null");

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    // remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}