Example usage for java.util.concurrent.locks ReentrantLock ReentrantLock

List of usage examples for java.util.concurrent.locks ReentrantLock ReentrantLock

Introduction

In this page you can find the example usage for java.util.concurrent.locks ReentrantLock ReentrantLock.

Prototype

public ReentrantLock() 

Source Link

Document

Creates an instance of ReentrantLock .

Usage

From source file:in.neoandroid.neoupdate.neoUpdate.java

/**
 * file:// implies local filesystem/*from  ww w.java 2 s .  co m*/
 * @param baseUrl
 * @param tmpDir
 * @param nSimultaneousConnections
 */
public neoUpdate(Context c, String baseUrl, String tmpDir, String appToken, String appSecret,
        int nSimultaneousConnections) {
    this.baseUrl = baseUrl;
    this.tmpDir = tmpDir;
    this.appToken = appToken;
    this.appSecret = appSecret;
    nConnections = nSimultaneousConnections;
    context = c;
    if (nConnections <= 0)
        nConnections = 1;
    // Check for local filesystem
    if (baseUrl.startsWith("file:///") || appToken == null || appSecret == null) {
        nConnections = 0;
        this.baseUrl = baseUrl.replace("file:///", "/");
        fromOfflineStorage = true;
        if (baseUrl.endsWith(".npk"))
            fromNPKStorage = true;
    } else {
        this.baseUrl = serverUrl + baseUrl;
        if (this.baseUrl.endsWith("/"))
            this.baseUrl = this.baseUrl.substring(0, this.baseUrl.length() - 1);
        lock = new ReentrantLock();
    }
    filesToDownload = new ArrayList<NewAsset>();
    deviceID = Settings.Secure.getString(c.getContentResolver(), Settings.Secure.ANDROID_ID);
    serialNo = neoUpdate.getSerialNo();
    macAddress = getWifiMac(c);
    if (deviceID == null)
        deviceID = "";
    if (serialNo == null)
        serialNo = "";
    if (macAddress == null)
        macAddress = "";
    try {
        packageInfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
    } catch (Exception e) {
    }
    db = new neoUpdateDB(c);
    stopped = false;
    totalFilesToDownload = 0;
    if (enableDebug) {
        Log.d(TAG, "DeviceID: " + deviceID);
        Log.d(TAG, "serialNo: " + serialNo);
        Log.d(TAG, "MAC Address: " + macAddress);
        Log.d(TAG, "SDCard: " + Environment.getExternalStorageDirectory().getAbsolutePath());
        Log.d(TAG, "Data: " + Environment.getDataDirectory().getAbsolutePath());
    }
}

From source file:com.haulmont.cuba.web.security.idp.BaseIdpSessionFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // send static files without authentication
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (StringUtils.startsWith(httpRequest.getRequestURI(), httpRequest.getContextPath() + "/VAADIN/")) {
        chain.doFilter(request, response);
        return;//from w  w  w.jav a 2  s .com
    }

    HttpServletResponse httpResponse = (HttpServletResponse) response;
    String idpBaseURL = webIdpConfig.getIdpBaseURL();
    if (Strings.isNullOrEmpty(idpBaseURL)) {
        log.error("Application property cuba.web.idp.url is not set");
        httpResponse.setStatus(500);
        return;
    }

    if (!idpBaseURL.endsWith("/")) {
        idpBaseURL += "/";
    }

    String requestUrl = httpRequest.getRequestURL().toString();
    if (StringUtils.startsWith(requestUrl, idpBaseURL)) {
        chain.doFilter(httpRequest, response);
        return;
    }

    HttpSession session = httpRequest.getSession(true);
    Lock sessionLock = (Lock) session.getAttribute(IDP_SESSION_LOCK_ATTRIBUTE);
    if (sessionLock == null) {
        sessionCheckLock.lock();
        try {
            sessionLock = (Lock) session.getAttribute(IDP_SESSION_LOCK_ATTRIBUTE);
            if (sessionLock == null) {
                sessionLock = new ReentrantLock();
                session.setAttribute(IDP_SESSION_LOCK_ATTRIBUTE, sessionLock);
            }
        } finally {
            sessionCheckLock.unlock();
        }
    }

    IdpSession boundIdpSession;
    sessionLock.lock();

    try {
        session.getAttribute(IDP_SESSION_LOCK_ATTRIBUTE);
    } catch (IllegalStateException e) {
        // Someone might have invalidated the session between fetching the lock and acquiring it.
        sessionLock.unlock();

        log.debug("Invalidated session {}", session.getId());
        httpResponse.sendRedirect(httpRequest.getRequestURL().toString());
        return;
    }

    try {
        if ("GET".equals(httpRequest.getMethod())
                && httpRequest.getParameter(IDP_TICKET_REQUEST_PARAM) != null) {
            String idpTicket = httpRequest.getParameter(IDP_TICKET_REQUEST_PARAM);

            IdpSession idpSession;
            try {
                idpSession = getIdpSession(idpTicket);
            } catch (IdpActivationException e) {
                log.error("Unable to obtain IDP session by ticket", e);
                httpResponse.setStatus(500);
                return;
            }

            if (idpSession == null) {
                log.warn("Used old IDP ticket {}, send redirect", idpTicket);
                // used old ticket, send redirect
                httpResponse.sendRedirect(getIdpRedirectUrl());
                return;
            }

            session.invalidate();

            session = httpRequest.getSession(true);
            session.setAttribute(IDP_SESSION_LOCK_ATTRIBUTE, sessionLock);
            session.setAttribute(IDP_SESSION_ATTRIBUTE, idpSession);

            log.debug("IDP session {} obtained, redirect to application", idpSession);

            // redirect to application without parameters
            httpResponse.sendRedirect(httpRequest.getRequestURL().toString());
            return;
        }

        if (session.getAttribute(IDP_SESSION_ATTRIBUTE) == null) {
            if ("GET".equals(httpRequest.getMethod()) && !StringUtils.startsWith(httpRequest.getRequestURI(),
                    httpRequest.getContextPath() + "/PUSH")) {
                httpResponse.sendRedirect(getIdpRedirectUrl());
            }
            return;
        }

        boundIdpSession = (IdpSession) session.getAttribute(IDP_SESSION_ATTRIBUTE);
    } finally {
        sessionLock.unlock();
    }

    HttpServletRequest authenticatedRequest = new IdpServletRequestWrapper(httpRequest,
            new IdpSessionPrincipalImpl(boundIdpSession));

    chain.doFilter(authenticatedRequest, response);
}

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>Tests asynchronous request execution with @{@link Async} and 
 * {@link AsyncHandler#onError(Exception)}.</p>
 *  //from w w  w . j a v a  2s .c o  m
 * @since 1.3.0
 */
@Test
public final void testAsyncError() throws InterruptedException {

    String subpath = "/asyncerror", body = "non-JSON-content";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200).withBody(body)));

    final Object[] content = new Object[1];

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    asyncEndpoint.asyncError(new AsyncHandler<User>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, User user) {
        }

        @Override
        public void onError(InvocationException error) {

            lock.lock();

            content[0] = error;
            condition.signal();

            lock.unlock();
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    assertTrue(content[0] != null);
    assertTrue(content[0] instanceof InvocationException);
}

From source file:org.eclipselabs.etrack.server.web.storage.AbstractStorageResource.java

@Override
protected Representation doConditionalHandle() throws ResourceException {
    ReentrantLock lock = null;//from w w  w.j av  a2  s  .com

    synchronized (locks) {
        lock = locks.get(getReference().toString());

        if (lock == null) {
            lock = new ReentrantLock();
            locks.put(getReference().toString(), lock);
        }
    }

    lock.lock();

    try {
        Representation result = super.doConditionalHandle();
        return result;
    } finally {
        lock.unlock();
    }
}

From source file:org.nuxeo.ecm.platform.wi.filter.WIRequestFilter.java

protected boolean simpleSyncOnSession(HttpServletRequest request) {
    if (log.isDebugEnabled()) {
        log.debug(doFormatLogMessage(request, "Trying to sync on session "));
    }// ww w.j  a  v  a  2 s . c  o  m

    if (request.getAttribute(SYNCED_REQUEST_FLAG) != null) {
        if (log.isWarnEnabled()) {
            log.warn(doFormatLogMessage(request,
                    "Request has already be synced, filter is reentrant, exiting without locking"));
        }
        return false;
    }

    WISession session = (WISession) request.getAttribute(SESSION_KEY);

    Lock lock = (Lock) session.getAttribute(SESSION_LOCK_KEY);
    if (lock == null) {
        lock = new ReentrantLock();
        session.setAttribute(SESSION_LOCK_KEY, lock);
    }

    boolean locked = false;
    try {
        locked = lock.tryLock(LOCK_TIMOUT_S, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        log.error(doFormatLogMessage(request, "Unable to acuire lock for Session sync"), e);
        return false;
    }

    if (locked) {
        request.setAttribute(SYNCED_REQUEST_FLAG, Boolean.TRUE);
        request.setAttribute(SESSION_LOCK_TIME, Long.valueOf(System.currentTimeMillis()));
        if (log.isDebugEnabled()) {
            log.debug(doFormatLogMessage(request, "Request synced on session"));
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug(doFormatLogMessage(request, "Sync timeout"));
        }
    }

    return locked;
}

From source file:org.apache.atlas.web.resources.AdminResource.java

@Inject
public AdminResource(ServiceState serviceState, MetricsService metricsService, AtlasTypeRegistry typeRegistry,
        AtlasTypeDefStore typeDefStore, AtlasEntityStore entityStore) {
    this.serviceState = serviceState;
    this.metricsService = metricsService;
    this.typeRegistry = typeRegistry;
    this.typesDefStore = typeDefStore;
    this.entityStore = entityStore;
    this.importExportOperationLock = new ReentrantLock();
}

From source file:com.runwaysdk.dataaccess.database.general.SQLServer.java

/**
 * Initializes datasource to point to SQL Server
 *//*w  w  w . ja v  a  2  s  . c o m*/
@Inject
public SQLServer() {
    super();

    this.nextSequenceNumberLock = new ReentrantLock();
    this.objectSequenceTableName = "object_seq_table";
    this.transactionSequenceTableName = "transaction_seq_table";

    // The container is not providing a pooled datasource
    if (this.dataSource == null) {
        JtdsDataSource serverDataSource = new JtdsDataSource();
        serverDataSource.setServerName(DatabaseProperties.getServerName());
        serverDataSource.setPortNumber(DatabaseProperties.getPort());
        serverDataSource.setDatabaseName(DatabaseProperties.getDatabaseName());
        serverDataSource.setUser(DatabaseProperties.getUser());
        serverDataSource.setPassword(DatabaseProperties.getPassword());

        int maxDbConnections = DatabaseProperties.getMaxConnections() - 1;

        if (maxDbConnections < 2) {
            maxDbConnections = 2;
        }

        boolean pooling = DatabaseProperties.getConnectionPooling();
        if (pooling) {
            SharedPoolDataSource sharedPoolDataSource = new SharedPoolDataSource();
            sharedPoolDataSource.setConnectionPoolDataSource(serverDataSource);
            sharedPoolDataSource.setMaxActive(maxDbConnections);
            sharedPoolDataSource.setTestOnBorrow(true);
            sharedPoolDataSource.setValidationQuery("SELECT 1");
            this.dataSource = sharedPoolDataSource;
        } else {
            this.dataSource = serverDataSource;
        }
    }
}

From source file:org.wso2.carbon.mediation.initializer.multitenancy.TenantServiceBusInitializer.java

public void createdConfigurationContext(ConfigurationContext configurationContext) {
    ServerContextInformation contextInfo;
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();

    log.info("Intializing the ESB Configuration for the tenant domain : " + tenantDomain);

    try {/*w  w  w .  j a  v a 2 s  .c om*/
        // first check which configuration should be active
        org.wso2.carbon.registry.core.Registry registry = (org.wso2.carbon.registry.core.Registry) PrivilegedCarbonContext
                .getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION);

        AxisConfiguration axisConfig = configurationContext.getAxisConfiguration();

        // initialize the lock
        Lock lock = new ReentrantLock();
        axisConfig.addParameter(ServiceBusConstants.SYNAPSE_CONFIG_LOCK, lock);

        // creates the synapse configuration directory hierarchy if not exists
        // useful at the initial tenant creation
        File tenantAxis2Repo = new File(configurationContext.getAxisConfiguration().getRepository().getFile());
        File synapseConfigsDir = new File(tenantAxis2Repo, ServiceBusConstants.SYNAPSE_CONFIGS);
        if (!synapseConfigsDir.exists()) {
            if (!synapseConfigsDir.mkdir()) {
                log.fatal("Couldn't create the synapse-config root on the file system "
                        + "for the tenant domain : " + tenantDomain);
                return;
            }
        }

        String synapseConfigsDirLocation = synapseConfigsDir.getAbsolutePath();

        // set the required configuration parameters to initialize the ESB
        axisConfig.addParameter(SynapseConstants.Axis2Param.SYNAPSE_CONFIG_LOCATION, synapseConfigsDirLocation);

        // init the multiple configuration tracker
        ConfigurationManager manger = new ConfigurationManager((UserRegistry) registry, configurationContext);
        manger.init();

        File synapseConfigDir = new File(synapseConfigsDir, manger.getTracker().getCurrentConfigurationName());
        if (!synapseConfigDir.exists()) {
            createTenantSynapseConfigHierarchy(synapseConfigDir, tenantDomain);
        }

        axisConfig.addParameter(SynapseConstants.Axis2Param.SYNAPSE_HOME, tenantAxis2Repo.getAbsolutePath());
        axisConfig.addParameter(SynapseConstants.Axis2Param.SYNAPSE_SERVER_NAME, "synapse." + tenantDomain);
        axisConfig.addParameter(SynapseConstants.Axis2Param.SYNAPSE_RESOLVE_ROOT,
                tenantAxis2Repo.getAbsolutePath());

        // Initialize Synapse
        contextInfo = initESB(manger.getTracker().getCurrentConfigurationName(), configurationContext,
                tenantDomain);

        if (contextInfo == null) {
            handleFatal("Failed to intilize the ESB for tenent:" + tenantDomain);
        }

        initPersistence(manger.getTracker().getCurrentConfigurationName(), configurationContext, contextInfo);

        configurationContext.setProperty(ConfigurationManager.CONFIGURATION_MANAGER, manger);

        int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
        // populate the SynapseEnv service and SynapseConfig OSGI Services so that other
        // components get to know about the availability of the new synapse configuration            
        //Properties props = new Properties();
        SynapseConfigurationService synCfgSvc = new SynapseConfigurationServiceImpl(
                contextInfo.getSynapseConfiguration(), tenantId, configurationContext);

        ServiceRegistration confRegistration = ConfigurationHolder.getInstance().getBundleContext()
                .registerService(SynapseConfigurationService.class.getName(), synCfgSvc, null);

        SynapseEnvironment synapseEnvironment = contextInfo.getSynapseEnvironment();
        //props = new Properties();
        SynapseEnvironmentService synEnvSvc = new SynapseEnvironmentServiceImpl(synapseEnvironment, tenantId,
                configurationContext);
        ServiceRegistration envRegistration = ConfigurationHolder.getInstance().getBundleContext()
                .registerService(SynapseEnvironmentService.class.getName(), synEnvSvc, null);
        synapseEnvironment.registerSynapseHandler(new SynapseExternalPropertyConfigurator());

        //props = new Properties();
        SynapseRegistrationsService synRegistrationsSvc = new SynapseRegistrationsServiceImpl(confRegistration,
                envRegistration, tenantId, configurationContext);
        ServiceRegistration synapseRegistration = ConfigurationHolder.getInstance().getBundleContext()
                .registerService(SynapseRegistrationsService.class.getName(), synRegistrationsSvc, null);

        //creating secure-vault specific location
        if (!isRepoExists(registry)) {
            org.wso2.carbon.registry.core.Collection secureVaultCollection = registry.newCollection();
            registry.put(ServiceBusConstants.CONNECTOR_SECURE_VAULT_CONFIG_REPOSITORY, secureVaultCollection);

        }

        ConfigurationTrackingService trackingService = ServiceBusInitializer.getConfigurationTrackingService();
        if (trackingService != null) {
            trackingService.setSynapseConfiguration(contextInfo.getSynapseConfiguration());
        }

        // set the event broker as a property for tenants
        EventBroker eventBroker = ServiceBusInitializer.getEventBroker();
        if (eventBroker != null) {
            configurationContext.setProperty("mediation.event.broker", eventBroker);
        }

        ConfigurationHolder.getInstance().addSynapseRegistration(tenantId, synapseRegistration);
        registerInboundDeployer(axisConfig, contextInfo.getSynapseEnvironment());
    } catch (Exception e) {
        handleFatal("Couldn't initialize the ESB for tenant:" + tenantDomain, e);
    } catch (Throwable t) {
        log.fatal("Failed to initialize ESB for tenant:" + tenantDomain + "due to a fatal error", t);
    }
}

From source file:com.offbynull.voip.ui.UiWebRegion.java

private UiWebRegion(Bus busFromGateway, Bus busToGateway) {
    Validate.notNull(busFromGateway);/*from w  w  w.  j a  v a2s.  c  om*/
    Validate.notNull(busToGateway);

    this.busFromGateway = busFromGateway;
    this.busToGateway = busToGateway;

    webView = new WebView();
    webEngine = webView.getEngine();

    webView.setContextMenuEnabled(false);
    webEngine.getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {
        @Override
        public void changed(ObservableValue<? extends Throwable> ov, Throwable t, Throwable t1) {
            System.out.println("Received exception: " + t1.getMessage());
        }
    });

    getChildren().add(webView);

    lock = new ReentrantLock();
}

From source file:com.runwaysdk.dataaccess.database.general.MySQL.java

/**
 * Initialize the datasource to point to a MySQL database.
 *///from  w w w. ja v a  2  s . co m
@Inject
public MySQL() {
    super();

    this.nextSequenceNumberLock = new ReentrantLock();
    this.objectSequenceTableName = "object_seq_table";
    this.transactionSequenceTableName = "transaction_seq_table";

    // The container is not providing a pooled datasource
    if (this.dataSource == null) {
        // We subtract 1 because we'll reserve a connection for sequence numbers
        int maxDbConnections = DatabaseProperties.getMaxConnections() - 1;

        if (maxDbConnections < 2) {
            maxDbConnections = 2;
        }

        boolean pooling = DatabaseProperties.getConnectionPooling();

        MysqlDataSource mysqlDataSource = null;
        if (pooling) {
            mysqlDataSource = new MysqlConnectionPoolDataSource();
        } else {
            mysqlDataSource = new MysqlDataSource();
        }

        // useServerPrepStmts=false
        // jdbc:mysql://[host][,failoverhost...][:port]/[database]
        // [?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...
        String url = "jdbc:mysql://" + DatabaseProperties.getServerName() + ":" + DatabaseProperties.getPort()
                + "/" + DatabaseProperties.getDatabaseName() + "?useServerPrepStmts=false";

        // is-connection-validation-required=true s
        // ?connectTimeout=1000"
        mysqlDataSource.setURL(url);
        mysqlDataSource.setUser(DatabaseProperties.getUser());
        mysqlDataSource.setPassword(DatabaseProperties.getPassword());

        /*
         * Alternate method for setting up the connection
         * mysqlDataSource.setServerName(vendorProps.getString(this.serverName));
         * mysqlDataSource.setPort(portNumber);
         * mysqlDataSource.setDatabaseName(vendorProps
         * .getString(this.databaseName));
         * mysqlDataSource.setUser(vendorProps.getString(this.user));
         * mysqlDataSource.setPassword(vendorProps.getString(this.password));
         */

        if (pooling) {
            SharedPoolDataSource sharedPoolDataSource = new SharedPoolDataSource();
            sharedPoolDataSource.setConnectionPoolDataSource((MysqlConnectionPoolDataSource) mysqlDataSource);
            sharedPoolDataSource.setMaxActive(maxDbConnections);
            sharedPoolDataSource.setTestOnBorrow(true);
            sharedPoolDataSource.setValidationQuery("SELECT 1");
            // sharedPoolDataSource.setMaxWait(50);
            this.dataSource = sharedPoolDataSource;
        }
        // If environment is not configured for connection pooling, do not pool
        // connections
        // This does not actually create connection pooling. It is used by the app
        // server.
        else {
            this.dataSource = mysqlDataSource;
        }
    }
}