Example usage for java.lang InterruptedException InterruptedException

List of usage examples for java.lang InterruptedException InterruptedException

Introduction

In this page you can find the example usage for java.lang InterruptedException InterruptedException.

Prototype

public InterruptedException(String s) 

Source Link

Document

Constructs an InterruptedException with the specified detail message.

Usage

From source file:org.kalypso.afgui.wizards.UnpackProjectTemplateOperation.java

@Override
public void execute(final IProgressMonitor monitor)
        throws CoreException, InvocationTargetException, InterruptedException {
    final IProject project = m_data.getProject();
    final ProjectTemplate template = m_data.getTemplate();
    final URL dataLocation = template.getData();

    final SubMonitor progress = SubMonitor.convert(monitor,
            Messages.getString("org.kalypso.afgui.wizards.NewProjectWizard.2"), 100); //$NON-NLS-1$
    try {//from   w w  w.ja  va2 s .  co  m
        // REMARK: we unpack into a closed project here (not using unzip(URL, IFolder)), as else
        // the project description will not be up-to-date in time, resulting in missing natures.
        project.close(progress.newChild(10));

        /* Unpack project from template */
        monitor.subTask(Messages.getString("UnpackProjectTemplateOperation.1")); //$NON-NLS-1$
        final File destinationDir = project.getLocation().toFile();
        unpackProjectData(dataLocation, destinationDir);
        ProgressUtilities.worked(progress, 30);

        /* Reset project to its own value, else we get the name from the zip, which leads to problems later. */
        ProjectUtilities.setProjectName(project, project.getName());

        project.open(progress.newChild(10));

        /* Necessary to remove all build specs from the data projects (we have at least the manifest builder now) */
        removeBuildspec(project);

        // IMPORTANT: As the project was already open once before, we need to refresh here, else
        // not all resources are up-to-date
        project.refreshLocal(IResource.DEPTH_INFINITE, progress.newChild(10));

        /* Let inherited wizards change the project */
        final INewProjectHandler handler = m_data.getHandler();
        if (handler == null)
            return;

        final IStatus postCreateStatus = handler.postCreateProject(project, template,
                progress.newChild(30, SubMonitor.SUPPRESS_NONE));
        if (!postCreateStatus.matches(IStatus.ERROR))
            handler.openProject(project);

        if (postCreateStatus != Status.OK_STATUS)
            throw new CoreException(postCreateStatus);

        /* Enforce and cleanup natures and description */
        final String moduleID = m_data.getModuleID();
        ModuleNature.enforceNature(project, moduleID);

        final String[] natureIds = cleanDescription(project, progress);
        configureNatures(project, natureIds, progress);
    } catch (final CoreException t) {
        final IStatus status = t.getStatus();
        if (status.matches(IStatus.ERROR | IStatus.CANCEL)) {
            // If anything went wrong, clean up the project
            // We use new monitor, else delete will not work if the monitor is already cancelled.
            project.delete(true, new NullProgressMonitor());
        }

        if (status.matches(IStatus.CANCEL))
            throw new InterruptedException(Messages.getString("UnpackProjectTemplateOperation.2")); //$NON-NLS-1$

        throw t;
    } catch (final Throwable t) {
        // If anything went wrong, clean up the project
        progress.setWorkRemaining(10);
        project.delete(true, progress);

        throw new InvocationTargetException(t);
    }
}

From source file:com.flipkart.poseidon.serviceclients.FutureTaskResultToDomainObjectPromiseWrapper.java

@Override
public DomainObject get(long timeout, TimeUnit timeUnit)
        throws PromiseBrokenException, TimeoutException, InterruptedException {
    try {/*w w w  .  ja  va 2s. c  o m*/
        ServiceResponse<DomainObject> serviceResponse = new ServiceResponse<>();
        for (Future<TaskResult> futureResult : futureList) {
            TaskResult result = futureResult.get(timeout, timeUnit);
            if (result == null) {
                throw new PromiseBrokenException("Task result is null");
            }
            ServiceResponse<DomainObject> response = (ServiceResponse<DomainObject>) result.getData();
            if (!response.getIsSuccess())
                throw response.getException();
            serviceResponse.addData(response.getDataList());
        }
        if (responseMerger != null) {
            return responseMerger.mergeResponse(serviceResponse.getDataList());
        } else {
            return serviceResponse.getDataList().get(0);
        }
    } catch (ExecutionException exception) {
        checkAndThrowServiceClientException(exception);
        promiseBrokenException = new PromiseBrokenException(exception);
        throw new InterruptedException(exception.getMessage());
    } catch (CancellationException exception) {
        promiseBrokenException = new PromiseBrokenException(exception);
        throw new PromiseBrokenException(promiseBrokenException);
    }
}

From source file:org.archive.io.RecordingInputStream.java

public void readToEndOfContent(long contentLength) throws IOException, InterruptedException {
    // Check we're open before proceeding.
    if (!isOpen()) {
        // TODO: should this be a noisier exception-raising error? 
        return;//from w  w w  .  ja  v  a  2s .  co m
    }

    long totalBytes = recordingOutputStream.position - recordingOutputStream.getMessageBodyBegin();
    long bytesRead = -1L;
    long maxToRead = -1;
    while (contentLength <= 0 || totalBytes < contentLength) {
        try {
            // read no more than soft max
            maxToRead = (contentLength <= 0) ? drainBuffer.length
                    : Math.min(drainBuffer.length, contentLength - totalBytes);
            // nor more than hard max
            maxToRead = Math.min(maxToRead, recordingOutputStream.getRemainingLength());
            // but always at least 1 (to trigger hard max exception) XXX wtf is this?
            maxToRead = Math.max(maxToRead, 1);

            bytesRead = read(drainBuffer, 0, (int) maxToRead);
            if (bytesRead == -1) {
                break;
            }
            totalBytes += bytesRead;

            if (Thread.interrupted()) {
                throw new InterruptedException("Interrupted during IO");
            }
        } catch (SocketTimeoutException e) {
            // A socket timeout is just a transient problem, meaning
            // nothing was available in the configured  timeout period,
            // but something else might become available later.
            // Take this opportunity to check the overall 
            // timeout (below).  One reason for this timeout is 
            // servers that keep up the connection, 'keep-alive', even
            // though we asked them to not keep the connection open.
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "socket timeout", e);
            }
            // check for interrupt
            if (Thread.interrupted()) {
                throw new InterruptedException("Interrupted during IO");
            }
            // check for overall timeout
            recordingOutputStream.checkLimits();
        } catch (SocketException se) {
            throw se;
        } catch (NullPointerException e) {
            // [ 896757 ] NPEs in Andy's Th-Fri Crawl.
            // A crawl was showing NPE's in this part of the code but can
            // not reproduce.  Adding this rethrowing catch block w/
            // diagnostics to help should we come across the problem in the
            // future.
            throw new NullPointerException(
                    "Stream " + this.in + ", " + e.getMessage() + " " + Thread.currentThread().getName());
        }
    }
}

From source file:com.amalto.workbench.providers.XtentisServerObjectsRetriever.java

public synchronized void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    try {//from w  ww  . j a  va  2  s .co  m
        if (password == null || password.length() == 0) {
            throw new Exception(Messages.XtentisServerObjectsRetriever_0);
        }
        monitor.beginTask(Messages.bind(Messages.XtentisServerObjectsRetriever_1, IConstants.TALEND),
                Messages.XtentisServerObjectsRetriever_3.equals(username) ? 12 : 9);
        // server
        serverRoot = new TreeParent(serverName, null, TreeObject._SERVER_, endpointaddress,
                username + ":" + (password == null ? "" : password));//$NON-NLS-1$//$NON-NLS-2$

        // init load category
        monitor.subTask(Messages.XtentisServerObjectsRetriever_4);
        LocalTreeObjectRepository.getInstance().startUp(endpointaddress, username, password);
        LocalTreeObjectRepository.getInstance().switchOnListening();
        LocalTreeObjectRepository.getInstance().setLazySaveStrategy(true, serverRoot);
        monitor.worked(1);
        // Access to server and get port
        TMDMService service = Util.getMDMService(new URL(endpointaddress), username, password);
        service.ping(new WSPing(Messages.XtentisServerObjectsRetriever_5));// viewer user can't use studio

        monitor.worked(1);

        // fetch version info
        try {
            WSVersion version = service
                    .getComponentVersion(new WSGetComponentVersion(WSComponent.DATA_MANAGER, null));
            String versionStr = version.getMajor() + "." + version.getMinor() + "." + version.getRevision() //$NON-NLS-1$//$NON-NLS-2$
                    + "_" //$NON-NLS-1$
                    + version.getBuild();
            log.info("Server version = " + versionStr); //$NON-NLS-1$
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        if (monitor.isCanceled()) {
            throw new InterruptedException(Messages.XtentisServerObjectsRetriever_6);
        }

        monitor.subTask(Messages.XtentisServerObjectsRetriever_7);
        UserInfo user = new UserInfo();
        user.setUsername(username);
        user.setPassword(password);
        user.setServerUrl(endpointaddress);

        serverRoot.setUser(user);

        // String uriPre=serverRoot.getEndpointIpAddress();

        // Data Models
        TreeParent models = new TreeParent(EXtentisObjects.DataMODEL.getDisplayName(), serverRoot,
                TreeObject.DATA_MODEL, null, null);
        List<WSDataModelPK> xdmPKs = null;
        try {
            xdmPKs = service.getDataModelPKs(new WSRegexDataModelPKs("")).getWsDataModelPKs(); //$NON-NLS-1$
        } catch (Exception e) {

            log.error(e.getMessage(), e);
        }
        if (xdmPKs != null) {
            monitor.subTask(Messages.XtentisServerObjectsRetriever_8);
            for (WSDataModelPK pk : xdmPKs) {
                String name = pk.getPk();
                if (!name.startsWith("XMLSCHEMA")) {//$NON-NLS-1$
                    WSDataModel wsobj = null;
                    if (retriveWSObject) {
                        wsobj = service.getDataModel(new WSGetDataModel(pk));
                    }
                    TreeObject obj = new TreeObject(name, serverRoot, TreeObject.DATA_MODEL, pk, wsobj);
                    models.addChild(obj);
                }
            }
        }
        monitor.worked(1);
        if (monitor.isCanceled()) {
            throw new InterruptedException(Messages.XtentisServerObjectsRetriever_9);
        }

        // DataClusters
        TreeParent dataClusters = new TreeParent(EXtentisObjects.DataCluster.getDisplayName(), serverRoot,
                TreeObject.DATA_CLUSTER, null, null);
        List<WSDataClusterPK> xdcPKs = null;
        try {
            xdcPKs = service.getDataClusterPKs(new WSRegexDataClusterPKs("*")).getWsDataClusterPKs();//$NON-NLS-1$
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        if (xdcPKs != null) {
            monitor.subTask(Messages.XtentisServerObjectsRetriever_10);
            for (WSDataClusterPK pk : xdcPKs) {
                String name = pk.getPk();
                if (!("CACHE".equals(name))) { // FIXME: Hardcoded CACHE//$NON-NLS-1$
                    WSDataCluster wsObject = null;
                    try {
                        if (retriveWSObject) {
                            wsObject = service.getDataCluster(new WSGetDataCluster(pk));
                        }
                        TreeObject obj = new TreeObject(name, serverRoot, TreeObject.DATA_CLUSTER, pk,
                                wsObject);
                        dataClusters.addChild(obj);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
        }
        monitor.worked(1);
        if (monitor.isCanceled()) {
            throw new InterruptedException(Messages.XtentisServerObjectsRetriever_11);
        }
        // event management
        TreeParent eventManagement = new TreeParent(EXtentisObjects.EventManagement.getDisplayName(),
                serverRoot, TreeObject.EVENT_MANAGEMENT, null, null);

        // subscript engine
        TreeObject engine = new TreeObject(EXtentisObjects.SubscriptionEngine.getDisplayName(), serverRoot,
                TreeObject.SUBSCRIPTION_ENGINE, null, null);
        eventManagement.addChild(engine);

        // transformer
        List<WSTransformerV2PK> transformerPKs = null;
        try {
            transformerPKs = service.getTransformerV2PKs(new WSGetTransformerV2PKs("")).getWsTransformerV2PK();//$NON-NLS-1$
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        TreeParent transformers = null;
        transformers = new TreeParent(EXtentisObjects.Transformer.getDisplayName(), serverRoot,
                TreeObject.TRANSFORMER, null, null);
        eventManagement.addChild(transformers);
        if (transformerPKs != null) {
            monitor.subTask(Messages.XtentisServerObjectsRetriever_12);
            for (WSTransformerV2PK pk : transformerPKs) {
                String id = pk.getPk();
                WSTransformerV2 wsobject = null;
                if (retriveWSObject) {
                    wsobject = service.getTransformerV2(new WSGetTransformerV2(pk));
                }
                TreeObject obj = new TreeObject(id, serverRoot, TreeObject.TRANSFORMER,
                        new WSTransformerV2PK(id), wsobject);
                transformers.addChild(obj);
            }
        }
        monitor.worked(1);

        // routing rule
        List<WSRoutingRulePK> routingRulePKs = null;
        try {
            routingRulePKs = service.getRoutingRulePKs(new WSGetRoutingRulePKs("")).getWsRoutingRulePKs();//$NON-NLS-1$
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        TreeParent rules = null;
        rules = new TreeParent(EXtentisObjects.RoutingRule.getDisplayName(), serverRoot,
                TreeObject.ROUTING_RULE, null, null);
        eventManagement.addChild(rules);
        if (routingRulePKs != null) {
            monitor.subTask(Messages.XtentisServerObjectsRetriever_13);
            for (WSRoutingRulePK pk : routingRulePKs) {
                String id = pk.getPk();
                WSRoutingRule wsobject = null;
                if (retriveWSObject) {
                    wsobject = service.getRoutingRule(new WSGetRoutingRule(pk));
                }
                TreeObject obj = new TreeObject(id, serverRoot, TreeObject.ROUTING_RULE,
                        new WSRoutingRulePK(id), wsobject);
                rules.addChild(obj);
            }
        }
        monitor.worked(1);

        // add event management to serverRoot
        serverRoot.addChild(eventManagement);

        // Views
        TreeParent views = new TreeParent(EXtentisObjects.View.getDisplayName(), serverRoot, TreeObject.VIEW,
                null, null);
        List<WSViewPK> viewPKs = null;
        try {
            viewPKs = service.getViewPKs((new WSGetViewPKs(""))).getWsViewPK();//$NON-NLS-1$
        } catch (Exception e) {
            log.error(e.getMessage(), e);

        }
        if (viewPKs != null) {
            monitor.subTask(Messages.XtentisServerObjectsRetriever_14);
            for (WSViewPK pk : viewPKs) {
                String name = pk.getPk();
                WSView wsobject = null;
                if (retriveWSObject) {
                    wsobject = service.getView(new WSGetView(pk));
                }
                TreeObject obj = new TreeObject(name, serverRoot, TreeObject.VIEW, new WSViewPK(name),
                        wsobject);
                views.addChild(obj);
            }
        }
        monitor.worked(1);
        if (monitor.isCanceled()) {
            throw new InterruptedException(Messages.XtentisServerObjectsRetriever_15);
        }

        // Stored Procedures
        TreeParent storedProcedures = new TreeParent(EXtentisObjects.StoredProcedure.getDisplayName(),
                serverRoot, TreeObject.STORED_PROCEDURE, null, null);
        List<WSStoredProcedurePK> spk = null;
        try {
            spk = service.getStoredProcedurePKs(new WSRegexStoredProcedure("")).getWsStoredProcedurePK();//$NON-NLS-1$
        } catch (Exception e) {

            log.error(e.getMessage(), e);
        }
        if (spk != null) {
            monitor.subTask(Messages.XtentisServerObjectsRetriever_16);
            for (WSStoredProcedurePK pk : spk) {
                String name = pk.getPk();
                WSStoredProcedure wsobject = null;
                if (retriveWSObject) {
                    wsobject = service.getStoredProcedure(new WSGetStoredProcedure(pk));
                }
                TreeObject obj = new TreeObject(name, serverRoot, TreeObject.STORED_PROCEDURE,
                        new WSStoredProcedurePK(name), wsobject);
                storedProcedures.addChild(obj);
            }
        }
        monitor.worked(1);
        if (monitor.isCanceled()) {
            throw new InterruptedException(Messages.XtentisServerObjectsRetriever_17);
        }

        // Service Configuration
        TreeObject serviceConfiguration = new TreeObject(EXtentisObjects.ServiceConfiguration.getDisplayName(),
                serverRoot, TreeObject.SERVICE_CONFIGURATION, null, null);
        // serviceConfiguration.setXObject(false);
        monitor.worked(1);
        if (monitor.isCanceled()) {
            throw new InterruptedException(Messages.XtentisServerObjectsRetriever_18);
        }

        // Menus
        List<WSMenuPK> menuPKs = null;
        boolean hasMenus = true;
        try {
            menuPKs = service.getMenuPKs(new WSGetMenuPKs("*")).getWsMenuPK();//$NON-NLS-1$
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            // This server IS old
            hasMenus = false;
        }
        TreeParent menus = null;
        if (hasMenus) {
            menus = new TreeParent(EXtentisObjects.Menu.getDisplayName(), serverRoot, TreeObject.MENU, null,
                    null);
            if (menuPKs != null) {
                monitor.subTask(Messages.XtentisServerObjectsRetriever_19);
                for (WSMenuPK pk : menuPKs) {
                    String id = pk.getPk();
                    WSMenu wsobject = null;
                    try {
                        if (retriveWSObject) {
                            wsobject = service.getMenu(new WSGetMenu(pk));
                        }
                        TreeObject obj = new TreeObject(id, serverRoot, TreeObject.MENU, new WSMenuPK(id),
                                wsobject);
                        menus.addChild(obj);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
            monitor.worked(1);

            if (monitor.isCanceled()) {
                throw new InterruptedException(Messages.XtentisServerObjectsRetriever_20);
            }
        }
        // move Job from EE to CE.

        monitor.worked(1);

        serverRoot.addChild(models);
        serverRoot.addChild(dataClusters);

        serverRoot.addChild(views);
        serverRoot.addChild(storedProcedures);

        serverRoot.addChild(serviceConfiguration);

        // serverRoot.addChild(workflow);
        // serverRoot.addChild(resources);

        if (hasMenus) {
            serverRoot.addChild(menus);
        }

        // available models
        List<IAvailableModel> availablemodels = AvailableModelUtil.getAvailableModels();
        for (IAvailableModel model : availablemodels) {
            model.addTreeObjects(service, monitor, serverRoot);
        }

        monitor.done();
    } catch (Exception e) {
        if (monitor.isCanceled()) {
            throw new InterruptedException(Messages.XtentisServerObjectsRetriever_21);
        }

        log.error(e.getMessage(), e);
        throw new InvocationTargetException(e);
    }
}

From source file:nya.miku.wishmaster.chans.lampach.LampachModule.java

@Override
public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception {
    String url = getUsingUrl() + model.boardName + "/imgboard.php";
    ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create().setDelegates(listener, task)
            .addString("parent", model.threadNumber != null ? model.threadNumber : "0")
            .addString("email", "noko").addString("subject", model.subject).addString("message", model.comment)
            .addString("password", model.password);
    if (model.sage)
        postEntityBuilder.addString("sage", "sage");
    if (RECAPTCHA_BOARD.equals(model.boardName)) {
        String response = Recaptcha2solved.pop(RECAPTCHA_KEY);
        if (response == null) {
            throw Recaptcha2.obtain(getUsingUrl(), RECAPTCHA_KEY, null, CHAN_NAME, false);
        }/*from   w w w.  j  a va2 s .c o m*/
        postEntityBuilder.addString("g-recaptcha-response", response);
    } else {
        postEntityBuilder.addString("captcha", model.captchaAnswer);
    }
    if (model.attachments != null && model.attachments.length > 0)
        postEntityBuilder.addFile("file", model.attachments[0], model.randomHash);

    if (task != null && task.isCancelled())
        throw new InterruptedException("interrupted");

    HttpRequestModel request = HttpRequestModel.builder().setPOST(postEntityBuilder.build()).setNoRedirect(true)
            .build();
    HttpResponseModel response = null;
    try {
        response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, null, task);
        if (response.statusCode == 200) {
            ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
            IOUtils.copyStream(response.stream, output);
            String htmlResponse = output.toString("UTF-8");
            if (htmlResponse.contains("Updat")) {
                Matcher redirectMatcher = REDIRECT_PATTERN.matcher(htmlResponse);
                if (redirectMatcher.find()) {
                    UrlPageModel redirModel = new UrlPageModel();
                    redirModel.chanName = CHAN_NAME;
                    redirModel.type = UrlPageModel.TYPE_THREADPAGE;
                    redirModel.boardName = model.boardName;
                    redirModel.threadNumber = redirectMatcher.group(1);
                    redirModel.postNumber = redirectMatcher.group(2);
                    return buildUrl(redirModel);
                }
                return null;
            }
            Matcher errorMatcher = ERROR_PATTERN.matcher(htmlResponse);
            if (errorMatcher.find()) {
                throw new Exception(errorMatcher.group(1));
            }
        } else
            throw new Exception(response.statusCode + " - " + response.statusReason);
    } finally {
        if (response != null)
            response.release();
    }
    return null;
}

From source file:com.netflix.genie.client.ExecutionServiceClient.java

/**
 * Wait for job to complete, until the given timeout.
 *
 * @param id           the Genie job ID to wait for completion
 * @param blockTimeout the time to block for (in ms), after which a
 *                     GenieException will be thrown
 * @param pollTime     the time to sleep between polling for job status
 * @return the jobInfo for the job after completion
 * @throws GenieException       For any other error.
 * @throws InterruptedException on timeout/thread errors
 *//*  w w w .  j  a  v  a2s  .co  m*/
public Job waitForCompletion(final String id, final long blockTimeout, final long pollTime)
        throws GenieException, InterruptedException {
    if (StringUtils.isEmpty(id)) {
        throw new GeniePreconditionException("Missing required parameter: id.");
    }

    final long startTime = System.currentTimeMillis();

    // wait for job to finish
    while (true) {
        final Job job = getJob(id);

        final JobStatus status = job.getStatus();
        if (status == JobStatus.FAILED || status == JobStatus.KILLED || status == JobStatus.SUCCEEDED) {
            return job;
        }

        // block until timeout
        if (System.currentTimeMillis() - startTime < blockTimeout) {
            Thread.sleep(pollTime);
        } else {
            throw new InterruptedException("Timed out waiting for job to finish");
        }
    }
}

From source file:com.ebay.pulsar.analytics.memcachedcache.MemcachedCacheTest.java

@Test
public void MemcachedCache() {
    // MemcachedCacheConfig test
    final MemcachedCacheConfig mc = new MemcachedCacheConfig();
    mc.setMaxObjectSize(mc.getMaxObjectSize());
    mc.setMaxOperationQueueSize(mc.getMaxOperationQueueSize());
    mc.setMemcachedPrefix(mc.getMemcachedPrefix());
    mc.setReadBufferSize(mc.getReadBufferSize());
    mc.setTimeout(mc.getMaxObjectSize());
    Assert.assertTrue(mc.getHosts() == null);
    //ArrayList<String> al2 = new ArrayList<String>();
    //al2.add("localhost:8080");
    mc.setHosts("localhost:8080");

    MemcachedCache INSTANCE = MemcachedCache.create(mc);

    Assert.assertTrue(INSTANCE != null);

    MemcachedClientIF client = Mockito.mock(MemcachedClientIF.class);
    try {/*from w w  w  .  ja va 2  s. co  m*/
        ReflectFieldUtil.setField(INSTANCE, "client", client);
    } catch (Exception e) {
        e.printStackTrace();
    }

    //regular test
    final NamedKey nk = new NamedKey("space", "key".getBytes());

    when(client.set(computeKeyHash(mc.getMemcachedPrefix(), nk), 1000, serializeValue(nk, "result".getBytes())))
            .thenAnswer(new Answer<Future<Boolean>>() {
                public Future<Boolean> answer(InvocationOnMock invocation) throws Throwable {
                    //Future<Boolean> future = Mockito.mock(FutureTask.class);
                    when(future1.get()).thenReturn(true);
                    return future1;
                }
            });

    try {
        INSTANCE.put(nk, "result".getBytes(), 1000);
    } catch (Exception e) {
        e.printStackTrace();
    }

    when(client.asyncGet(computeKeyHash(mc.getMemcachedPrefix(), nk))).thenAnswer(new Answer<Future<Object>>() {
        public Future<Object> answer(InvocationOnMock invocation) throws Throwable {
            //Future<Object> future = Mockito.mock(FutureTask.class);
            when(future2.get(mc.getTimeout(), TimeUnit.MILLISECONDS))
                    .thenReturn(serializeValue(nk, "result".getBytes()));
            return future2;
        }
    });

    String re = new String(INSTANCE.get(nk));
    Assert.assertTrue(re.equals("result"));

    /////client exception
    final NamedKey nkIllegalStateException = new NamedKey("space", "IllegalStateException".getBytes());

    when(client.asyncGet(computeKeyHash(mc.getMemcachedPrefix(), nkIllegalStateException)))
            .thenThrow(new IllegalStateException("nkIllegalStateException"));

    Assert.assertTrue(INSTANCE.get(nkIllegalStateException) == null);

    //future exception
    final NamedKey nkTimeoutException = new NamedKey("space", "TimeoutException".getBytes());
    when(client.asyncGet(computeKeyHash(mc.getMemcachedPrefix(), nkTimeoutException)))
            .thenAnswer(new Answer<Future<Object>>() {
                public Future<Object> answer(InvocationOnMock invocation) throws Throwable {
                    //Future<Object> future = Mockito.mock(FutureTask.class);
                    when(future3.get(mc.getTimeout(), TimeUnit.MILLISECONDS))
                            .thenThrow(new TimeoutException("TimeoutException"));
                    return future3;
                }
            });
    Assert.assertTrue(INSTANCE.get(nkTimeoutException) == null);

    final NamedKey nkInterruptedException = new NamedKey("space", "InterruptedException".getBytes());
    when(client.asyncGet(computeKeyHash(mc.getMemcachedPrefix(), nkInterruptedException)))
            .thenAnswer(new Answer<Future<Object>>() {
                public Future<Object> answer(InvocationOnMock invocation) throws Throwable {
                    //Future<Object> future = Mockito.mock(FutureTask.class);
                    when(future4.get(mc.getTimeout(), TimeUnit.MILLISECONDS))
                            .thenThrow(new InterruptedException("InterruptedException"));
                    return future4;
                }
            });
    try {
        Assert.assertTrue(INSTANCE.get(nkInterruptedException) == null);
    } catch (Exception e) {

    }

    final NamedKey nkExecutionException = new NamedKey("space", "ExecutionException".getBytes());
    when(client.asyncGet(computeKeyHash(mc.getMemcachedPrefix(), nkExecutionException)))
            .thenAnswer(new Answer<Future<Object>>() {
                public Future<Object> answer(InvocationOnMock invocation) throws Throwable {
                    //Future<Object> future = Mockito.mock(FutureTask.class);
                    when(future5.get(mc.getTimeout(), TimeUnit.MILLISECONDS)).thenThrow(
                            new ExecutionException("ExecutionException", new Exception("ExecutionException")));
                    return future5;
                }
            });
    Assert.assertTrue(INSTANCE.get(nkExecutionException) == null);

    ////////test bulk

    //get bulk fail
    final NamedKey nkIllegalStateExceptionBulk = new NamedKey("space", "IllegalStateException".getBytes());
    ArrayList<NamedKey> a1 = new ArrayList<NamedKey>();
    a1.add(nkIllegalStateExceptionBulk);
    Map<String, NamedKey> keyLookup = Maps.uniqueIndex(a1, new Function<NamedKey, String>() {
        @Override
        public String apply(NamedKey input) {
            return computeKeyHash(mc.getMemcachedPrefix(), input);
        }
    });

    when(client.asyncGetBulk(keyLookup.keySet()))
            .thenThrow(new IllegalStateException("nkIllegalStateException"));

    Assert.assertTrue(INSTANCE.getBulk(a1).size() == 0);

    //test future
    final NamedKey some = new NamedKey("space", "resultsome".getBytes());
    ArrayList<NamedKey> a2 = new ArrayList<NamedKey>();
    a2.add(some);
    Map<String, NamedKey> keyLookup2 = Maps.uniqueIndex(a2, new Function<NamedKey, String>() {
        @Override
        public String apply(NamedKey input) {
            return computeKeyHash(mc.getMemcachedPrefix(), input);
        }
    });

    when(client.asyncGetBulk(keyLookup2.keySet())).thenAnswer(new Answer<BulkFuture<Map<String, Object>>>() {
        public BulkFuture<Map<String, Object>> answer(InvocationOnMock invocation) throws Throwable {
            //BulkFuture<Map<String, Object>> future = Mockito.mock(BulkFuture.class);
            Map<String, Object> mp = new HashMap<String, Object>();
            mp.put(computeKeyHash(mc.getMemcachedPrefix(), some), serializeValue(some, "result".getBytes()));
            when(future8.getSome(mc.getTimeout(), TimeUnit.MILLISECONDS)).thenReturn(mp);
            return future8;
        }
    });

    String somere = new String(INSTANCE.getBulk(a2).get(some));
    Assert.assertTrue(somere.equals("result"));

    //test bulk exception
    final NamedKey someInterruptedException = new NamedKey("space", "someInterruptedException".getBytes());
    ArrayList<NamedKey> a3 = new ArrayList<NamedKey>();
    a3.add(someInterruptedException);
    Map<String, NamedKey> keyLookup3 = Maps.uniqueIndex(a3, new Function<NamedKey, String>() {
        @Override
        public String apply(NamedKey input) {
            return computeKeyHash(mc.getMemcachedPrefix(), input);
        }
    });

    when(client.asyncGetBulk(keyLookup3.keySet())).thenAnswer(new Answer<BulkFuture<Map<String, Object>>>() {
        public BulkFuture<Map<String, Object>> answer(InvocationOnMock invocation) throws Throwable {
            //BulkFuture<Map<String, Object>> future = Mockito.mock(BulkFuture.class);
            when(future6.getSome(mc.getTimeout(), TimeUnit.MILLISECONDS))
                    .thenThrow(new InterruptedException("someInterruptedException"));
            return future6;
        }
    });
    try {
        INSTANCE.getBulk(a3).get(someInterruptedException);
    } catch (Exception e) {
        System.out.println("Catch InterruptedException success!");
    }

    final NamedKey someExecutionException = new NamedKey("space", "someExecutionException".getBytes());
    ArrayList<NamedKey> a4 = new ArrayList<NamedKey>();
    a4.add(someExecutionException);
    Map<String, NamedKey> keyLookup4 = Maps.uniqueIndex(a4, new Function<NamedKey, String>() {
        @Override
        public String apply(NamedKey input) {
            return computeKeyHash(mc.getMemcachedPrefix(), input);
        }
    });

    when(client.asyncGetBulk(keyLookup4.keySet())).thenAnswer(new Answer<BulkFuture<Map<String, Object>>>() {
        public BulkFuture<Map<String, Object>> answer(InvocationOnMock invocation) throws Throwable {
            //BulkFuture<Map<String, Object>> future = Mockito.mock(BulkFuture.class);
            when(future7.getSome(mc.getTimeout(), TimeUnit.MILLISECONDS)).thenThrow(
                    new ExecutionException("someExecutionException", new Exception("someExecutionException")));
            return future7;
        }
    });

    Assert.assertTrue(INSTANCE.getBulk(a4).get(someExecutionException) == null);

    CacheStats st = INSTANCE.getStats();
    Assert.assertTrue(st.getNumErrors() == 4);
    Assert.assertTrue(st.getNumHits() == 2);
    Assert.assertTrue(st.getNumMisses() == 0);
}

From source file:com.hoccer.http.AsyncHttpRequest.java

@Override
public void doInBackground() {

    setUploadProgress(1);//from   w w w  .  j av  a2  s .c  o  m

    try {
        long uploadStart = System.currentTimeMillis();
        mResponse = mHttpClient.execute(mRequest);
        mUploadTime = System.currentTimeMillis() - uploadStart;
    } catch (ClientProtocolException e) {
        onClientError(e);
        return;
    } catch (SocketException e) {
        onClientError(e);
        return;
    } catch (SecurityException e) {
        onClientError(e);
        return;
    } catch (IOException e) {
        onIoError(e);
        return;
    }

    if (mResponse == null) {
        onClientError(new NullPointerException("expected http response object is null"));
        return;
    }

    onHttpHeaderAvailable(mResponse.getAllHeaders());

    try {
        InputStream is = mResponse.getEntity().getContent();
        OutputStream storageStream = mResponseContent.openNewOutputStream();
        long downloaded = 0;
        long size = mResponse.getEntity().getContentLength();
        byte[] buffer = new byte[0xFFFF];
        int len;
        long downloadStart = System.currentTimeMillis();
        while ((len = is.read(buffer)) != -1) {
            if (isInterrupted()) {
                onClientError(new InterruptedException("download is interruped"));
                return;
            }
            setDownloadProgress((int) ((downloaded / (double) size) * 100));
            storageStream.write(buffer, 0, len);
            downloaded += len;
        }
        setDownloadProgress(100);
        mDownloadTime = System.currentTimeMillis() - downloadStart;
    } catch (IOException e) {
        onIoError(e);
        return;
    } catch (Exception e) {
        onClientError(e);
        return;
    }
    mIsRequestCompleted = true;
}

From source file:com.haulmont.cuba.client.sys.FileLoaderClientImpl.java

protected void saveStreamWithServlet(FileDescriptor fd, Supplier<InputStream> inputStreamSupplier,
        @Nullable StreamingProgressListener streamingListener)
        throws FileStorageException, InterruptedException {

    Object context = serverSelector.initContext();
    String selectedUrl = serverSelector.getUrl(context);
    if (selectedUrl == null) {
        throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName());
    }/*from   ww  w .  j a  v  a 2s .  c  om*/

    ClientConfig clientConfig = configuration.getConfig(ClientConfig.class);
    String fileUploadContext = clientConfig.getFileUploadContext();

    while (true) {
        String url = selectedUrl + fileUploadContext + "?s=" + userSessionSource.getUserSession().getId()
                + "&f=" + fd.toUrlParam();

        try (InputStream inputStream = inputStreamSupplier.get()) {
            InputStreamProgressEntity.UploadProgressListener progressListener = null;
            if (streamingListener != null) {
                progressListener = streamingListener::onStreamingProgressChanged;
            }

            HttpPost method = new HttpPost(url);
            method.setEntity(new InputStreamProgressEntity(inputStream, ContentType.APPLICATION_OCTET_STREAM,
                    progressListener));

            HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
            HttpClient client = HttpClientBuilder.create().setConnectionManager(connectionManager).build();
            try {
                HttpResponse response = client.execute(method);

                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    break;
                } else {
                    log.debug("Unable to upload file to {}\n{}", url, response.getStatusLine());
                    selectedUrl = failAndGetNextUrl(context);
                    if (selectedUrl == null) {
                        throw new FileStorageException(FileStorageException.Type.fromHttpStatus(statusCode),
                                fd.getName());
                    }
                }
            } catch (InterruptedIOException e) {
                log.trace("Uploading has been interrupted");
                throw new InterruptedException("File uploading is interrupted");
            } catch (IOException e) {
                log.debug("Unable to upload file to {}\n{}", url, e);
                selectedUrl = failAndGetNextUrl(context);
                if (selectedUrl == null) {
                    throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName(), e);
                }
            } finally {
                connectionManager.shutdown();
            }
        } catch (IOException | RetryUnsupportedException e) {
            throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName(), e);
        }
    }
}

From source file:org.eclipse.osee.ote.core.test.shells.TelnetShell.java

public synchronized MatchResult waitForPattern(Pattern pattern, int millis) throws InterruptedException {
    MatchResult index = inputBuffer.waitFor(pattern, false, millis);
    if (index == null) {
        throw new InterruptedException(
                "Waiting for '" + pattern.pattern() + "' took longer then " + millis + " miliseconds.");
    }//from w  ww .  ja  v  a 2  s . c  o  m
    return index;
}