Search in sources :

Example 66 with TimeUnit

use of java.util.concurrent.TimeUnit in project OpenAM by OpenRock.

the class LDAPUtils method newConnectionFactory.

/**
     * Creates a new connection factory based on the provided parameters.
     *
     * @param ldapurl The address of the LDAP server.
     * @param username The directory user's DN. May be null if this is an anonymous connection.
     * @param password The directory user's password.
     * @param heartBeatInterval The interval for sending out heartbeat requests.
     * @param heartBeatTimeUnit The timeunit for the heartbeat interval.
     * @param ldapOptions Additional LDAP settings used to create the connection factory.
     * @return An authenticated/anonymous connection factory, which may also send heartbeat requests.
     */
private static ConnectionFactory newConnectionFactory(LDAPURL ldapurl, String username, char[] password, int heartBeatInterval, String heartBeatTimeUnit, Options ldapOptions) {
    Boolean ssl = ldapurl.isSSL();
    int heartBeatTimeout = SystemPropertiesManager.getAsInt(Constants.LDAP_HEARTBEAT_TIMEOUT, DEFAULT_HEARTBEAT_TIMEOUT);
    if (ssl != null && ssl.booleanValue()) {
        try {
            //Creating a defensive copy of ldapOptions to handle the case when a mixture of SSL/non-SSL connections
            //needs to be established.
            ldapOptions = Options.copyOf(ldapOptions).set(LDAPConnectionFactory.SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
        } catch (GeneralSecurityException gse) {
            DEBUG.error("An error occurred while creating SSLContext", gse);
        }
    }
    // Enable heartbeat
    if (heartBeatInterval > 0 && heartBeatTimeUnit != null) {
        TimeUnit unit = TimeUnit.valueOf(heartBeatTimeUnit.toUpperCase());
        ldapOptions = ldapOptions.set(HEARTBEAT_ENABLED, true).set(HEARTBEAT_INTERVAL, new Duration(unit.toSeconds(heartBeatInterval), TimeUnit.SECONDS)).set(HEARTBEAT_TIMEOUT, new Duration(unit.toSeconds(heartBeatTimeout), TimeUnit.SECONDS));
    }
    // Enable Authenticated connection
    if (username != null) {
        ldapOptions = ldapOptions.set(AUTHN_BIND_REQUEST, LDAPRequests.newSimpleBindRequest(username, password));
    }
    return new LDAPConnectionFactory(ldapurl.getHost(), ldapurl.getPort(), ldapOptions);
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) TimeUnit(java.util.concurrent.TimeUnit) Duration(org.forgerock.util.time.Duration) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder)

Example 67 with TimeUnit

use of java.util.concurrent.TimeUnit in project voltdb by VoltDB.

the class JDBCSQLXML method getExecutorService.

/**
     * @return that may be used to perform processesing asynchronously.
     */
protected static ExecutorService getExecutorService() {
    if (JDBCSQLXML.executorService == null) {
        int corePoolSize = 1;
        int maximumPoolSize = 10;
        long keepAliveTime = 1;
        TimeUnit unit = TimeUnit.SECONDS;
        JDBCSQLXML.workQueue = new ArrayBlockingQueue<Runnable>(10);
        JDBCSQLXML.executorService = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }
    return executorService;
}
Also used : TimeUnit(java.util.concurrent.TimeUnit) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Example 68 with TimeUnit

use of java.util.concurrent.TimeUnit in project ACS by ACS-Community.

the class PubSubExecutor method execute.

/**
	 * Run the specified pub/sub container and components.
	 * Since no timeout is passed to this method, one of the following must be true:
	 * <ul>
	 *   <li>The XML spec contains the (optional) <code>Termination</code> element
	 *       that defines a timeout, or
	 *   <li>No pub/sub component has an unbounded number of events, which means 
	 *       that all component definitions must contain the <code>numberOfEvents</code> attribute.
	 * </ul>
	 * @param scenario
	 * @throws Throwable
	 */
public void execute(PubSubScenario scenario) throws Throwable {
    PubSubInfrastructureSpec pubSubSpec = scenario.getSpec();
    TerminationSpecT teminationSpec = pubSubSpec.getTermination();
    if (teminationSpec == null) {
        for (PublisherSpecT pubSpec : pubSubSpec.getPublisher()) {
            if (!pubSpec.hasNumberOfEvents() || pubSpec.getNumberOfEvents() <= 0) {
                throw new IllegalArgumentException("Publisher " + pubSpec.getComponentName() + " needs numberOfEvents >= 0, or call 'execute' with a timeout.");
            }
        }
        for (SubscriberSpecT subSpec : pubSubSpec.getSubscriber()) {
            if (!subSpec.hasNumberOfEvents() || subSpec.getNumberOfEvents() <= 0) {
                throw new IllegalArgumentException("Subscriber " + subSpec.getComponentName() + " needs numberOfEvents >= 0, or call 'execute' with a timeout.");
            }
        }
        // timeout is implied by the finite number of events
        execute(scenario, -1, null);
    } else {
        // use timeout from XML, complementary to any finite number of events if those are specified.
        long timeout = teminationSpec.getTimeout();
        TimeUnit timeUnit = TimeUnit.valueOf(teminationSpec.getTimeUnit().toString());
        m_logger.fine("Will use timeout from the XML spec: timeout=" + timeout + ", timeUnit=" + timeUnit);
        execute(scenario, timeout, timeUnit);
    }
}
Also used : PublisherSpecT(alma.acs.pubsubtest.config.PublisherSpecT) SubscriberSpecT(alma.acs.pubsubtest.config.SubscriberSpecT) TerminationSpecT(alma.acs.pubsubtest.config.TerminationSpecT) TimeUnit(java.util.concurrent.TimeUnit) PubSubInfrastructureSpec(alma.acs.pubsubtest.config.PubSubInfrastructureSpec)

Example 69 with TimeUnit

use of java.util.concurrent.TimeUnit in project ACS by ACS-Community.

the class Executor method remoteDaemonForServices.

/**
	 * Starts or stops ACS via the ACS services daemon. 
	 * This call returns only when the action has completed.
	 * Exceptions will be returned instead of thrown.
	 * @return any exception that occurs underways
	 */
/* msc 2009-12: this method has never thrown exceptions, instead they can be detected through
	 * Flow listening, and as of today also by looking at the return value. Starting to throw exceptions
	 * would be too big a change that I don't want to risk. I have no time to verify it doesn't harm. */
public static Exception remoteDaemonForServices(String host, int instance, boolean startStop, String cmdFlags, NativeCommand.Listener listener) {
    if (listener != null) {
        listener.stdoutWritten(null, "\nIn daemon mode, output cannot be displayed.\n" + "See logs in <daemon-owner>/.acs/commandcenter on host " + host + "\n");
    }
    String info = ((startStop) ? "Starting" : "Stopping") + " Acs Suite on host '" + host + "' (instance " + instance + ")";
    remoteServicesDaemonFlow.reset(info);
    ServicesDaemon daemon = null;
    // msc 2014-11 ICT-3753: finer-grained logging
    String step = "";
    try {
        org.omg.CORBA.ORB orb;
        AcsCorba acsCorba = null;
        remoteServicesDaemonFlow.trying(RemoteServicesDaemonFlow.INIT_CORBA);
        step = "access acs-corba object";
        // throws OrbInitException
        acsCorba = firestarter.giveAcsCorba();
        step = "access orb";
        orb = acsCorba.getORB();
        remoteServicesDaemonFlow.success(RemoteServicesDaemonFlow.INIT_CORBA);
        remoteServicesDaemonFlow.trying(RemoteServicesDaemonFlow.CONNECT_DAEMON);
        step = "convert host name to daemon address";
        String daemonLoc = AcsLocations.convertToServicesDaemonLocation(host);
        step = "convert daemon address to corba reference";
        org.omg.CORBA.Object object = orb.string_to_object(daemonLoc);
        step = "narrow corba reference to daemon object";
        daemon = ServicesDaemonHelper.narrow(object);
        step = "sanity check daemon object";
        if (daemon == null)
            throw new NullPointerException("received null trying to retrieve acsdaemon " + daemonLoc);
        try {
            if (// this may be superfluous with daemons but shouldn't hurt either
            daemon._non_existent())
                log.log(Level.INFO, "acsdaemon '" + daemonLoc + "' reported as non_existent, trying to use it nonetheless.");
        } catch (Exception exc) {
            log.log(Level.INFO, "problem verifying acsdaemon " + daemonLoc + " exists, trying to use it anyhow.", exc);
        }
        remoteServicesDaemonFlow.success(RemoteServicesDaemonFlow.CONNECT_DAEMON);
        remoteServicesDaemonFlow.trying(RemoteServicesDaemonFlow.SEND_COMMAND);
        final BlockingQueue<Completion> sync = new ArrayBlockingQueue<Completion>(1);
        DaemonSequenceCallbackPOA daemonCallbackImpl = new DaemonSequenceCallbackPOA() {

            public void done(Completion comp) {
                sync.add(comp);
            }

            public void working(String service, String host, short instance_number, Completion comp) {
            }
        };
        step = "create daemon callback";
        DaemonSequenceCallback daemonCallback = DaemonSequenceCallbackHelper.narrow(acsCorba.activateOffShoot(daemonCallbackImpl, acsCorba.getRootPOA()));
        step = "send request to daemon";
        if (startStop == true)
            daemon.start_acs(daemonCallback, (short) instance, cmdFlags);
        else
            daemon.stop_acs(daemonCallback, (short) instance, cmdFlags);
        remoteServicesDaemonFlow.success(RemoteServicesDaemonFlow.SEND_COMMAND);
        remoteServicesDaemonFlow.trying(RemoteServicesDaemonFlow.AWAIT_RESPONSE);
        // The services daemon's start/stop methods are implemented asynchronously,
        // which means we need to wait for the callback notification.
        // @TODO: Perhaps a 10 minute timeout is too much though?
        step = "poll on reply queue";
        long timeout = 10;
        TimeUnit timeoutUnit = TimeUnit.MINUTES;
        Completion daemonReplyRaw = sync.poll(timeout, timeoutUnit);
        if (daemonReplyRaw == null)
            throw new RuntimeException("Timeout: Acs daemon did not " + (startStop ? "start" : "stop") + " Acs within " + timeout + " " + timeoutUnit);
        step = "deserialize daemon response";
        AcsJCompletion daemonReply = AcsJCompletion.fromCorbaCompletion(daemonReplyRaw);
        if (daemonReply.isError()) {
            AcsJException exc = daemonReply.getAcsJException();
            throw new Exception("daemon responded with error " + exc.getMessage(), exc);
        }
        remoteServicesDaemonFlow.success(RemoteServicesDaemonFlow.AWAIT_RESPONSE);
        return null;
    } catch (Exception exc) {
        remoteServicesDaemonFlow.failure(exc);
        return new Exception(remoteServicesDaemonFlow.current() + ":" + step + ": " + exc.getMessage(), exc);
    } finally {
        // msc 2014-11 ICT-3753: omc-to-daemon connection can get stale. this apparently helps.
        if (daemon != null) {
            try {
                daemon._release();
            } catch (Exception exc) {
                log.log(Level.INFO, "failure releasing internal resources for daemon, ignoring: " + exc.getMessage(), exc);
            }
        }
    }
}
Also used : AcsJCompletion(alma.acs.exceptions.AcsJCompletion) AcsCorba(alma.acs.container.corba.AcsCorba) AcsJException(alma.acs.exceptions.AcsJException) PreparedString(alma.acs.commandcenter.util.PreparedString) ServicesDaemon(alma.acsdaemon.ServicesDaemon) DaemonSequenceCallbackPOA(alma.acsdaemon.DaemonSequenceCallbackPOA) IOException(java.io.IOException) OrbInitException(alma.acs.commandcenter.meta.Firestarter.OrbInitException) AcsJException(alma.acs.exceptions.AcsJException) DaemonSequenceCallback(alma.acsdaemon.DaemonSequenceCallback) Completion(alma.ACSErr.Completion) AcsJCompletion(alma.acs.exceptions.AcsJCompletion) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) TimeUnit(java.util.concurrent.TimeUnit)

Example 70 with TimeUnit

use of java.util.concurrent.TimeUnit in project geode by apache.

the class GemFireDeadlockDetector method find.

/**
   * Find any deadlocks the exist in this distributed system.
   * 
   * The deadlocks are returned as a list of dependencies. See {@link DeadlockDetector}
   */
public DependencyGraph find() {
    final DeadlockDetector detector = new DeadlockDetector();
    ResultCollector<HashSet<Dependency>, Serializable> collector = new ResultCollector<HashSet<Dependency>, Serializable>() {

        public synchronized Serializable getResult() throws FunctionException {
            return null;
        }

        public synchronized Serializable getResult(long timeout, TimeUnit unit) throws FunctionException, InterruptedException {
            return null;
        }

        public synchronized void addResult(DistributedMember memberID, HashSet<Dependency> resultOfSingleExecution) {
            detector.addDependencies(resultOfSingleExecution);
        }

        public void endResults() {
        }

        public void clearResults() {
        }
    };
    Execution execution;
    if (targetMembers != null) {
        execution = FunctionService.onMembers(targetMembers).withCollector(collector);
    } else {
        execution = FunctionService.onMembers().withCollector(collector);
    }
    ((AbstractExecution) execution).setIgnoreDepartedMembers(true);
    collector = execution.execute(new CollectDependencyFunction());
    // Wait for results
    collector.getResult();
    return detector.getDependencyGraph();
}
Also used : Serializable(java.io.Serializable) AbstractExecution(org.apache.geode.internal.cache.execute.AbstractExecution) Execution(org.apache.geode.cache.execute.Execution) AbstractExecution(org.apache.geode.internal.cache.execute.AbstractExecution) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) DistributedMember(org.apache.geode.distributed.DistributedMember) TimeUnit(java.util.concurrent.TimeUnit) ResultCollector(org.apache.geode.cache.execute.ResultCollector) HashSet(java.util.HashSet)

Aggregations

TimeUnit (java.util.concurrent.TimeUnit)190 Test (org.junit.Test)28 ExecutionException (java.util.concurrent.ExecutionException)16 IOException (java.io.IOException)11 TimeoutException (java.util.concurrent.TimeoutException)11 Future (java.util.concurrent.Future)10 HashMap (java.util.HashMap)7 TimeSpec (com.linkedin.thirdeye.api.TimeSpec)6 ArrayList (java.util.ArrayList)6 TimeValue (org.elasticsearch.common.unit.TimeValue)6 DataType (com.linkedin.pinot.common.data.FieldSpec.DataType)5 File (java.io.File)5 HashSet (java.util.HashSet)5 Matcher (java.util.regex.Matcher)5 WaitUntilGatewaySenderFlushedCoordinatorJUnitTest (org.apache.geode.internal.cache.wan.WaitUntilGatewaySenderFlushedCoordinatorJUnitTest)5 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)5 TimeGranularity (com.linkedin.thirdeye.api.TimeGranularity)4 GwtIncompatible (com.google.common.annotations.GwtIncompatible)3 RestException (com.linkedin.r2.message.rest.RestException)3 Map (java.util.Map)3