Example usage for java.util.concurrent TimeoutException TimeoutException

List of usage examples for java.util.concurrent TimeoutException TimeoutException

Introduction

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

Prototype

public TimeoutException(String message) 

Source Link

Document

Constructs a TimeoutException with the specified detail message.

Usage

From source file:com.streamsets.datacollector.cluster.ShellClusterProvider.java

@Override
public ClusterPipelineStatus getStatus(File tempDir, ApplicationState applicationState,
        PipelineConfiguration pipelineConfiguration, PipelineConfigBean pipelineConfigBean)
        throws TimeoutException, IOException {
    String appId = applicationState.getAppId();
    Map<String, String> environment = new HashMap<>();
    environment.put(CLUSTER_TYPE, CLUSTER_TYPE_YARN);
    addKerberosConfiguration(environment);
    ImmutableList.Builder<String> args = ImmutableList.builder();
    args.add(clusterManagerScript.getAbsolutePath());
    args.add("status");
    args.add(applicationState.getAppId());
    ExecutionMode executionMode = PipelineBeanCreator.get().getExecutionMode(pipelineConfiguration,
            new ArrayList<Issue>());
    if (executionMode == ExecutionMode.CLUSTER_MESOS_STREAMING) {
        addMesosArgs(pipelineConfiguration, environment, args);
    }/*w  w  w.j av a  2 s.  c  o  m*/
    SystemProcess process = getSystemProcessFactory().create(BaseClusterProvider.class.getSimpleName(), tempDir,
            args.build());
    try {
        process.start(environment);
        if (!process.waitFor(30, TimeUnit.SECONDS)) {
            throw new TimeoutException(
                    errorString("YARN status command for {} timed out.", applicationState.getAppId()));
        }
        if (process.exitValue() != 0) {
            throw new IllegalStateException(errorString("Status command for {} failed with exit code {}.",
                    applicationState.getAppId(), process.exitValue()));
        }
        String status;
        if (executionMode == ExecutionMode.CLUSTER_MESOS_STREAMING) {
            status = mesosStatusParser.parseStatus(process.getAllOutput());
        } else {
            status = yarnStatusParser.parseStatus(process.getAllOutput());
        }
        return ClusterPipelineStatus.valueOf(status);
    } finally {
        process.cleanup();
    }
}

From source file:org.openspaces.grid.gsm.machines.plugins.NonBlockingElasticMachineProvisioningAdapter.java

@Override
public FutureGridServiceAgent[] startMachinesAsync(final CapacityRequirements capacityRequirements,
        final ExactZonesConfig zones, final FailedGridServiceAgent[] failedAgents, final long duration,
        final TimeUnit unit) {

    if (!isStartMachineSupported()) {
        throw new UnsupportedOperationException();
    }//w w  w .  j  av a2s.c om

    final GSAReservationId reservationId = GSAReservationId.randomGSAReservationId();
    final CapacityRequirements singleMachineCapacity = machineProvisioning.getCapacityOfSingleMachine();
    int numberOfMachines = calcNumberOfMachines(capacityRequirements, machineProvisioning);
    if (numberOfMachines < failedAgents.length) {
        throw new IllegalArgumentException("capacity requirements should be at least " + failedAgents.length
                + " machines for failure recovery. " + "Instead found " + numberOfMachines
                + " machines, capacity = " + capacityRequirements);
    }
    FutureGridServiceAgent[] futureAgents = new FutureGridServiceAgent[numberOfMachines];

    for (int i = 0; i < futureAgents.length; i++) {
        final AtomicReference<Object> ref = new AtomicReference<Object>(null);

        final int throttlingDelay = i * THROTTLING_DELAY_SECONDS;
        final long start = System.currentTimeMillis();
        final long end = start + throttlingDelay * 1000 + unit.toMillis(duration);
        final FailedGridServiceAgent failedAgent = failedAgents.length > i ? failedAgents[i] : null;
        submit(new Runnable() {
            public void run() {
                try {
                    logger.info("Starting a new machine");
                    StartedGridServiceAgent agent = machineProvisioning.startMachine(zones, reservationId,
                            failedAgent, duration, unit);
                    ref.set(agent);
                    logger.info("New machine started");
                } catch (ElasticMachineProvisioningException e) {
                    ref.set(e);
                } catch (ElasticGridServiceAgentProvisioningException e) {
                    ref.set(e);
                } catch (InterruptedException e) {
                    ref.set(e);
                } catch (TimeoutException e) {
                    ref.set(e);
                } catch (NoClassDefFoundError e) {
                    ref.set((new NoClassDefFoundElasticMachineProvisioningException(e)));
                } catch (Throwable e) {
                    logger.error("Unexpected exception:" + e.getMessage(), e);
                    ref.set(e);
                }
            }

        }, throttlingDelay, TimeUnit.SECONDS);

        futureAgents[i] = new FutureGridServiceAgent() {

            public boolean isDone() {
                return System.currentTimeMillis() > end || ref.get() != null;
            }

            public ExecutionException getException() {
                Object result = ref.get();
                if (result != null && result instanceof Throwable) {
                    Throwable throwable = (Throwable) result;
                    return new ExecutionException(throwable.getMessage(), throwable);
                }
                return null;
            }

            public boolean isTimedOut() {
                Object result = ref.get();
                return System.currentTimeMillis() > end
                        || (result != null && result instanceof TimeoutException);
            }

            public Date getTimestamp() {
                return new Date(start);
            }

            public StartedGridServiceAgent get()
                    throws ExecutionException, IllegalStateException, TimeoutException {

                Object result = ref.get();

                if (result == null) {
                    if (System.currentTimeMillis() > end) {
                        throw new TimeoutException("Starting a new machine took more than "
                                + unit.toSeconds(duration) + " seconds to complete.");
                    }

                    throw new IllegalStateException("Async operation is not done yet.");
                }

                if (getException() != null) {
                    throw getException();
                }

                return (StartedGridServiceAgent) result;
            }

            public NonBlockingElasticMachineProvisioning getMachineProvisioning() {
                return NonBlockingElasticMachineProvisioningAdapter.this;
            }

            public CapacityRequirements getFutureCapacity() {
                return singleMachineCapacity;
            }

            public GSAReservationId getReservationId() {
                return reservationId;
            }

            public FailedGridServiceAgent getFailedGridServiceAgent() {
                return failedAgent;
            }
        };
    }
    return futureAgents;
}

From source file:com.streamsets.datacollector.cluster.ClusterProviderImpl.java

@Override
public void killPipeline(SystemProcessFactory systemProcessFactory, File sparkManager, File tempDir,
        String appId, PipelineConfiguration pipelineConfiguration) throws TimeoutException, IOException {
    Map<String, String> environment = new HashMap<>();
    environment.put(CLUSTER_TYPE, CLUSTER_TYPE_YARN);
    addKerberosConfiguration(environment);
    ImmutableList.Builder<String> args = ImmutableList.builder();
    args.add(sparkManager.getAbsolutePath());
    args.add("kill");
    args.add(appId);/*from  w w w  .ja v a2  s. c o  m*/
    ExecutionMode executionMode = PipelineBeanCreator.get().getExecutionMode(pipelineConfiguration,
            new ArrayList<Issue>());
    if (executionMode == ExecutionMode.CLUSTER_MESOS_STREAMING) {
        addMesosArgs(pipelineConfiguration, environment, args);
    }
    SystemProcess process = systemProcessFactory.create(ClusterProviderImpl.class.getSimpleName(), tempDir,
            args.build());
    try {
        process.start(environment);
        if (!process.waitFor(30, TimeUnit.SECONDS)) {
            logOutput(appId, process);
            throw new TimeoutException(errorString("Kill command for {} timed out.", appId));
        }
    } finally {
        process.cleanup();
    }
}

From source file:org.spring.springxdcloudInstaller.MainApp.java

static RunningInstance blockAdminInstanceRunning(EC2Client client, RunningInstance instance)
        throws TimeoutException {
    // create utilities that wait for the instance to finish
    RetryablePredicate<RunningInstance> runningTester = new RetryablePredicate<RunningInstance>(
            new InstanceStateRunning(client), 180, 5, TimeUnit.SECONDS);

    System.out.printf("%d: %s awaiting instance to run %n", System.currentTimeMillis(), instance.getId());
    if (!runningTester.apply(instance))
        throw new TimeoutException("timeout waiting for instance to run: " + instance.getId());

    instance = findInstanceById(client, instance.getId());

    RetryablePredicate<HostAndPort> socketTester = new RetryablePredicate<HostAndPort>(
            new InetSocketAddressConnect(), 300, 1, TimeUnit.SECONDS);
    System.out.printf("%d: %s awaiting ssh service to start%n", System.currentTimeMillis(),
            instance.getIpAddress());/*from   w  w  w .  java 2 s  .c o  m*/
    if (!socketTester.apply(HostAndPort.fromParts(instance.getIpAddress(), 22)))
        throw new TimeoutException("timeout waiting for ssh to start: " + instance.getIpAddress());

    System.out.printf("%d: %s ssh service started%n", System.currentTimeMillis(), instance.getIpAddress());

    System.out.printf("%d: %s awaiting Redis service to start%n", System.currentTimeMillis(),
            instance.getIpAddress());
    if (!socketTester.apply(HostAndPort.fromParts(instance.getIpAddress(), 6379)))
        throw new TimeoutException("timeout waiting for http to start: " + instance.getIpAddress());

    System.out.printf("%d: %s http service started%n", System.currentTimeMillis(), instance.getIpAddress());
    System.out.printf("instance %s ready%n", instance.getId());
    System.out.printf("ip address: %s%n", instance.getIpAddress());
    System.out.printf("dns name: %s%n", instance.getDnsName());
    return instance;
}

From source file:org.daisy.pipeline.execution.rmi.PoolableRMIPipelineInstanceFactory.java

/**
 * Launch a new RMI Pipeline instance from the launcher script, and wait for
 * this instance to be registered in the RMI Registry to return it.
 * //  w  w  w .ja va2 s . c  om
 * @throws TimeoutException
 *             if the RMI Pipeline instance was not registered before a
 *             fixed 5000ms timeout.
 */
public Object makeObject() throws Exception {
    String uuid = UUID.randomUUID().toString();
    Process process = launchNewPipelineInstance(uuid);
    long starttime = System.currentTimeMillis();
    long endtime = starttime + timeout;
    RMIPipelineInstance pipeline = null;
    while (pipeline == null && System.currentTimeMillis() <= endtime) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
        try {
            pipeline = (RMIPipelineInstance) rmiRegistry.lookup(uuid);
        } catch (NotBoundException e) {
        }
    }
    if (pipeline == null) {
        throw new TimeoutException("Couldn't load the Pipeline instance");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Launched instance {}", uuid);
    }
    return new RMIPipelineInstanceWrapper(pipeline, process);
}

From source file:no.ntnu.osnap.com.Protocol.java

/**
 * Sends a ping to the remote device and returns when it is finished. This
 * method is blocking.//from   www  .j  av  a  2s  .co m
 * @throws TimeoutException if the remote device used too long time to respond 
 *                      (defined in TIMEOUT)
 */
public final void ping() throws TimeoutException {
    lock();

    ProtocolInstruction newInstruction = new ProtocolInstruction(OpCode.PING, (byte) 0, new byte[1]);

    try {
        sendBytes(newInstruction.getInstructionBytes());
    } catch (IOException ex) {
        throw new TimeoutException("Could not send data: " + ex);
    }

    waitingForAck = OpCode.PING;

    release();

    //Wait up to TIMEOUT milliseconds before giving up
    long time = System.currentTimeMillis() + TIMEOUT;
    while (waitingForAck != null) {
        if (System.currentTimeMillis() > time) {
            waitingForAck = null;
            throw new TimeoutException("Timeout (remote device used too long time to respond)");
        }
        try {
            Thread.sleep(10);
        } catch (InterruptedException ex) {
            /*nothing*/
        }
    }

    ackProcessingComplete();
}

From source file:com.reactivetechnologies.analytics.core.handlers.ModelCombinerComponent.java

/**
 * Request a dump of classifier models from all cluster members
 * @param duration/*from  w  w w.j  a  v  a  2s.co m*/
 * @param unit
 * @return
 * @throws InterruptedException
 * @throws TimeoutException 
 */
boolean tryMemberSnapshot(long duration, TimeUnit unit) throws InterruptedException, TimeoutException {
    boolean snapshotDone = false;
    boolean locked = hzService.acquireLock(TimeUnit.SECONDS, 10);
    try {
        if (locked) {
            snapshotDone = signalAndAwait(duration, unit);
            if (!snapshotDone)
                throw new TimeoutException("Operation timed out in [" + duration + " " + unit
                        + "] before getting response from all members");
        }
    } finally {
        hzService.releaseLock(true);
    }

    return snapshotDone;
}

From source file:com.vmware.photon.controller.common.xenon.ServiceHostUtils.java

/**
 * Function used to wait for a service to be available.
 *
 * @param host//from w w  w.  j  a  va2s .c o  m
 * @param timeout
 * @param serviceLinks
 * @throws Throwable
 */
public static void waitForServiceAvailability(ServiceHost host, long timeout, String... serviceLinks)
        throws Throwable {
    final CountDownLatch latch = new CountDownLatch(serviceLinks.length);
    final Throwable error = new Throwable("Error: registerForAvailability returned errors");

    Operation.CompletionHandler handler = new Operation.CompletionHandler() {
        @Override
        public void handle(Operation operation, Throwable throwable) {
            if (null != throwable) {
                error.addSuppressed(throwable);
            }

            latch.countDown();
        }
    };
    host.registerForServiceAvailability(handler, serviceLinks);

    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw new TimeoutException(String.format("One or several of service(s) %s not available",
                Utils.toJson(false, false, serviceLinks)));
    }

    if (error.getSuppressed().length > 0) {
        throw error;
    }
}

From source file:io.bitsquare.btc.WalletService.java

public void initialize(@Nullable DeterministicSeed seed, ResultHandler resultHandler,
        ExceptionHandler exceptionHandler) {
    Log.traceCall();/* w  w w .j  a  v  a2  s  .  c om*/
    // Tell bitcoinj to execute event handlers on the JavaFX UI thread. This keeps things simple and means
    // we cannot forget to switch threads when adding event handlers. Unfortunately, the DownloadListener
    // we give to the app kit is currently an exception and runs on a library thread. It'll get fixed in
    // a future version.

    Threading.USER_THREAD = UserThread.getExecutor();

    Timer timeoutTimer = UserThread.runAfter(
            () -> exceptionHandler.handleException(
                    new TimeoutException("Wallet did not initialize in " + STARTUP_TIMEOUT_SEC + " seconds.")),
            STARTUP_TIMEOUT_SEC);

    backupWallet();

    final Socks5Proxy socks5Proxy = preferences.getUseTorForBitcoinJ() ? socks5ProxyProvider.getSocks5Proxy()
            : null;
    log.debug("Use socks5Proxy for bitcoinj: " + socks5Proxy);

    // If seed is non-null it means we are restoring from backup.
    walletAppKit = new WalletAppKitBitSquare(params, socks5Proxy, walletDir, "Bitsquare") {
        @Override
        protected void onSetupCompleted() {
            // Don't make the user wait for confirmations for now, as the intention is they're sending it
            // their own money!
            walletAppKit.wallet().allowSpendingUnconfirmedTransactions();
            final PeerGroup peerGroup = walletAppKit.peerGroup();

            if (params != RegTestParams.get())
                peerGroup.setMaxConnections(11);

            // We don't want to get our node white list polluted with nodes from AddressMessage calls.
            if (preferences.getBitcoinNodes() != null && !preferences.getBitcoinNodes().isEmpty())
                peerGroup.setAddPeersFromAddressMessage(false);

            wallet = walletAppKit.wallet();
            wallet.addEventListener(walletEventListener);

            addressEntryList.onWalletReady(wallet);

            peerGroup.addEventListener(new PeerEventListener() {
                @Override
                public void onPeersDiscovered(Set<PeerAddress> peerAddresses) {
                }

                @Override
                public void onBlocksDownloaded(Peer peer, Block block, FilteredBlock filteredBlock,
                        int blocksLeft) {
                }

                @Override
                public void onChainDownloadStarted(Peer peer, int blocksLeft) {
                }

                @Override
                public void onPeerConnected(Peer peer, int peerCount) {
                    numPeers.set(peerCount);
                    connectedPeers.set(peerGroup.getConnectedPeers());
                }

                @Override
                public void onPeerDisconnected(Peer peer, int peerCount) {
                    numPeers.set(peerCount);
                    connectedPeers.set(peerGroup.getConnectedPeers());
                }

                @Override
                public Message onPreMessageReceived(Peer peer, Message m) {
                    return null;
                }

                @Override
                public void onTransaction(Peer peer, Transaction t) {
                }

                @Nullable
                @Override
                public List<Message> getData(Peer peer, GetDataMessage m) {
                    return null;
                }
            });

            // set after wallet is ready
            tradeWalletService.setWalletAppKit(walletAppKit);
            tradeWalletService.setAddressEntryList(addressEntryList);
            timeoutTimer.stop();

            // onSetupCompleted in walletAppKit is not the called on the last invocations, so we add a bit of delay
            UserThread.runAfter(resultHandler::handleResult, 100, TimeUnit.MILLISECONDS);
        }
    };

    // Bloom filters in BitcoinJ are completely broken
    // See: https://jonasnick.github.io/blog/2015/02/12/privacy-in-bitcoinj/
    // Here are a few improvements to fix a few vulnerabilities.

    // Bitsquare's BitcoinJ fork has added a bloomFilterTweak (nonce) setter to reuse the same seed avoiding the trivial vulnerability
    // by getting the real pub keys by intersections of several filters sent at each startup.
    walletAppKit.setBloomFilterTweak(bloomFilterTweak);

    // Avoid the simple attack (see: https://jonasnick.github.io/blog/2015/02/12/privacy-in-bitcoinj/) due to the 
    // default implementation using both pubkey and hash of pubkey. We have set a insertPubKey flag in BasicKeyChain to default false.

    // Default only 266 keys are generated (2 * 100+33). That would trigger new bloom filters when we are reaching 
    // the threshold. To avoid reaching the threshold we create much more keys which are unlikely to cause update of the
    // filter for most users. With lookaheadSize of 500 we get 1333 keys which should be enough for most users to 
    // never need to update a bloom filter, which would weaken privacy.
    walletAppKit.setLookaheadSize(500);

    // Calculation is derived from: https://www.reddit.com/r/Bitcoin/comments/2vrx6n/privacy_in_bitcoinj_android_wallet_multibit_hive/coknjuz
    // No. of false positives (56M keys in the blockchain): 
    // First attempt for FP rate:
    // FP rate = 0,0001;  No. of false positives: 0,0001 * 56 000 000  = 5600
    // We have 1333keys: 1333 / (5600 + 1333) = 0.19 -> 19 % probability that a pub key is in our wallet
    // After tests I found out that the bandwidth consumption varies widely related to the generated filter.
    // About 20- 40 MB for upload and 30-130 MB for download at first start up (spv chain).
    // Afterwards its about 1 MB for upload and 20-80 MB for download.
    // Probably better then a high FP rate would be to include foreign pubKeyHashes which are tested to not be used 
    // in many transactions. If we had a pool of 100 000 such keys (2 MB data dump) to random select 4000 we could mix it with our
    // 1000 own keys and get a similar probability rate as with the current setup but less variation in bandwidth 
    // consumption.

    // For now to reduce risks with high bandwidth consumption we reduce the FP rate by half.
    // FP rate = 0,00005;  No. of false positives: 0,00005 * 56 000 000  = 2800
    // 1333 / (2800 + 1333) = 0.32 -> 32 % probability that a pub key is in our wallet
    walletAppKit.setBloomFilterFalsePositiveRate(0.00005);

    String btcNodes = preferences.getBitcoinNodes();
    log.debug("btcNodes: " + btcNodes);
    boolean usePeerNodes = false;

    // Pass custom seed nodes if set in options
    if (!btcNodes.isEmpty()) {
        String[] nodes = StringUtils.deleteWhitespace(btcNodes).split(",");
        List<PeerAddress> peerAddressList = new ArrayList<>();
        for (String node : nodes) {
            String[] parts = node.split(":");
            if (parts.length == 1) {
                // port not specified.  Use default port for network.
                parts = new String[] { parts[0], Integer.toString(params.getPort()) };
            }
            if (parts.length == 2) {
                // note: this will cause a DNS request if hostname used.
                // note: DNS requests are routed over socks5 proxy, if used.
                // note: .onion hostnames will be unresolved.
                InetSocketAddress addr;
                if (socks5Proxy != null) {
                    try {
                        // proxy remote DNS request happens here.  blocking.
                        addr = new InetSocketAddress(DnsLookupTor.lookup(socks5Proxy, parts[0]),
                                Integer.parseInt(parts[1]));
                    } catch (Exception e) {
                        log.warn("Dns lookup failed for host: {}", parts[0]);
                        addr = null;
                    }
                } else {
                    // DNS request happens here. if it fails, addr.isUnresolved() == true.
                    addr = new InetSocketAddress(parts[0], Integer.parseInt(parts[1]));
                }
                if (addr != null && !addr.isUnresolved()) {
                    peerAddressList.add(new PeerAddress(addr.getAddress(), addr.getPort()));
                }
            }
        }
        if (peerAddressList.size() > 0) {
            PeerAddress peerAddressListFixed[] = new PeerAddress[peerAddressList.size()];
            log.debug("btcNodes parsed: " + Arrays.toString(peerAddressListFixed));

            walletAppKit.setPeerNodes(peerAddressList.toArray(peerAddressListFixed));
            usePeerNodes = true;
        }
    }

    // Now configure and start the appkit. This will take a second or two - we could show a temporary splash screen
    // or progress widget to keep the user engaged whilst we initialise, but we don't.
    if (params == RegTestParams.get()) {
        if (regTestHost == RegTestHost.REG_TEST_SERVER) {
            try {
                walletAppKit.setPeerNodes(
                        new PeerAddress(InetAddress.getByName(RegTestHost.SERVER_IP), params.getPort()));
                usePeerNodes = true;
            } catch (UnknownHostException e) {
                throw new RuntimeException(e);
            }
        } else if (regTestHost == RegTestHost.LOCALHOST) {
            walletAppKit.connectToLocalHost(); // You should run a regtest mode bitcoind locally.}
        }
    } else if (params == MainNetParams.get()) {
        // Checkpoints are block headers that ship inside our app: for a new user, we pick the last header
        // in the checkpoints file and then download the rest from the network. It makes things much faster.
        // Checkpoint files are made using the BuildCheckpoints tool and usually we have to download the
        // last months worth or more (takes a few seconds).
        try {
            walletAppKit.setCheckpoints(getClass().getResourceAsStream("/wallet/checkpoints"));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
        }
    } else if (params == TestNet3Params.get()) {
        walletAppKit.setCheckpoints(getClass().getResourceAsStream("/wallet/checkpoints.testnet"));
    }

    // If operating over a proxy and we haven't set any peer nodes, then
    // we want to use SeedPeers for discovery instead of the default DnsDiscovery.
    // This is only because we do not yet have a Dns discovery class that works
    // reliably over proxy/tor.
    //
    // todo: There should be a user pref called "Use Local DNS for Proxy/Tor"
    // that disables this.  In that case, the default DnsDiscovery class will
    // be used which should work, but is less private.  The aim here is to
    // be private by default when using proxy/tor.  However, the seedpeers
    // could become outdated, so it is important that the user be able to
    // disable it, but should be made aware of the reduced privacy.
    if (socks5Proxy != null && !usePeerNodes) {
        // SeedPeers uses hard coded stable addresses (from MainNetParams). It should be updated from time to time.
        walletAppKit.setDiscovery(new Socks5MultiDiscovery(socks5Proxy, params, socks5DiscoverMode));
    }

    walletAppKit.setDownloadListener(downloadListener).setBlockingStartup(false)
            .setUserAgent(userAgent.getName(), userAgent.getVersion()).restoreWalletFromSeed(seed);

    walletAppKit.addListener(new Service.Listener() {
        @Override
        public void failed(@NotNull Service.State from, @NotNull Throwable failure) {
            walletAppKit = null;
            log.error("walletAppKit failed");
            timeoutTimer.stop();
            UserThread.execute(() -> exceptionHandler.handleException(failure));
        }
    }, Threading.USER_THREAD);
    walletAppKit.startAsync();
}

From source file:org.cloudifysource.utilitydomain.context.blockstorage.VolumeUtils.java

private static void executeCommandLine(final String commandLine, final long timeout)
        throws LocalStorageOperationException, TimeoutException {

    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);/*from  ww w  .j av  a2 s  .  c  om*/
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);
    ProcessOutputStream outAndErr = new ProcessOutputStream();
    try {
        PumpStreamHandler streamHandler = new PumpStreamHandler(outAndErr);
        executor.setStreamHandler(streamHandler);
        logger.info("Executing commandLine : '" + commandLine + "'");
        executor.execute(CommandLine.parse(commandLine));
        logger.info("Execution completed successfully. Process output was : " + outAndErr.getOutput());
    } catch (final Exception e) {
        if (watchdog.killedProcess()) {
            throw new TimeoutException("Timed out while executing commandLine : '" + commandLine + "'");
        }

        throw new LocalStorageOperationException("Failed executing commandLine : '" + commandLine
                + ". Process output was : " + outAndErr.getOutput(), e);
    }
}