Example usage for java.lang InterruptedException toString

List of usage examples for java.lang InterruptedException toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:com.ephesoft.dcma.imagemagick.MultiPageExecutor.java

/**
 * The <code>getCompressedImage</code> method is used to compress passed image according to compression type LZW, quality 100 and
 * convert image to monochrome i.e., black and white w.r.t isColoredImage passed.
 * //  w  w  w  .  ja  v  a  2s . c  om
 * @param isColoredImage true for colored image and false otherwise
 * @param imageUrl image to be converted
 * @return url of converted image from passed image
 */
private String getCompressedImage(boolean isColoredImage, String imageUrl) {
    String newImageUrl = imageUrl;
    if (null != imageUrl && imageUrl.length() > 0) {
        IMOperation imOperation = new IMOperation();

        // Applying default image quality
        imOperation.quality((double) IMAGE_QUALITY);
        imOperation.type(OPERATION_TYPE);
        if (!isColoredImage) {
            imOperation.monochrome();
        }

        // Apply compression
        imOperation.compress(COMPRESSION_TYPE);
        imOperation.addImage(); // place holder for input file
        imOperation.addImage(); // place holder for output file

        // Converting image
        ConvertCmd convert = new ConvertCmd();
        newImageUrl = imageUrl.substring(0, imageUrl.lastIndexOf(DOTS)) + NEW + TIF_EXTENSION;

        try {
            convert.run(imOperation, new Object[] { imageUrl, newImageUrl });
        } catch (org.im4java.core.CommandException commandException) {
            LOGGER.error("IM4JAVA_TOOLPATH is not set for converting images using image magic: "
                    + commandException.toString());
        } catch (IOException ioException) {
            LOGGER.error("Files not found for converting operation of image magic: " + ioException.toString());
        } catch (InterruptedException interruptedException) {
            LOGGER.error("Conversion operation of image magic interrupted in between: "
                    + interruptedException.toString());
        } catch (IM4JavaException im4JavaException) {
            LOGGER.error(
                    "Error occurred while converting images using image magic: " + im4JavaException.toString());
        }
    }
    return newImageUrl;
}

From source file:com.nubits.nubot.trading.wrappers.BitSparkWrapper.java

protected Long createNonce(String requester) {
    Long toReturn = 0L;/*from   w  w  w. ja  v  a2 s  .  co  m*/
    if (!apiBusy) {
        toReturn = getNonceInternal(requester);
    } else {
        try {

            if (Global.options.isVerbose()) {
                LOG.debug(System.currentTimeMillis() + " - Api is busy, I'll sleep and retry in a few ms ("
                        + requester + ")");
            }

            Thread.sleep(Math.round(2.2 * SPACING_BETWEEN_CALLS));
            createNonce(requester);
        } catch (InterruptedException e) {
            LOG.error(e.toString());
        }
    }
    return toReturn;
}

From source file:com.nubits.nubot.trading.wrappers.CcexWrapper.java

@Override
public ApiResponse clearOrders(CurrencyPair pair) {
    //Since there is no API entry point for that, this call will iterate over actie
    ApiResponse toReturn = new ApiResponse();
    boolean ok = true;

    ApiResponse activeOrdersResponse = getActiveOrders();
    if (activeOrdersResponse.isPositive()) {
        ArrayList<Order> orderList = (ArrayList<Order>) activeOrdersResponse.getResponseObject();
        for (int i = 0; i < orderList.size(); i++) {
            Order tempOrder = orderList.get(i);

            ApiResponse deleteOrderResponse = cancelOrder(tempOrder.getId(), pair);
            if (deleteOrderResponse.isPositive()) {
                boolean deleted = (boolean) deleteOrderResponse.getResponseObject();

                if (deleted) {
                    LOG.warn("Order " + tempOrder.getId() + " deleted succesfully");
                } else {
                    LOG.warn("Could not delete order " + tempOrder.getId() + "");
                    ok = false;//from w ww  .jav a 2  s.com
                }

            } else {
                LOG.error(deleteOrderResponse.getError().toString());
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                LOG.error(ex.toString());
            }

        }
        toReturn.setResponseObject(ok);
    } else {
        LOG.error(activeOrdersResponse.getError().toString());
        toReturn.setError(activeOrdersResponse.getError());
        return toReturn;
    }

    return toReturn;
}

From source file:uk.co.modularaudio.service.apprendering.util.AppRenderingStructure.java

public void useNewRenderingPlanWithWaitDestroyPrevious(final RenderingPlan newRenderingPlan)
        throws MadProcessingException {
    final RenderingPlan previousPlan = this.renderingPlan.get();
    if (previousPlan == null && newRenderingPlan == null) {
        // intentionally do nothing.
        log.warn("Attempted to use new rendering plan that is null - and we don't have one either");
        return;//from  w w w . j  ava2  s .  c  om
    }

    boolean needWaitForUse = false;
    int sleepWaitingForPlanMillis = 100;

    //      log.debug("Will attempt to hot-swap out rendering plan.");
    //      log.debug("New plan has " + newRenderingPlan.getTotalNumJobs() + " total rendering jobs");

    if (previousPlan == null && newRenderingPlan != null) {
        final HardwareIOChannelSettings planChannelSettings = newRenderingPlan.getPlanChannelSettings();
        final MadTimingParameters planTimingParameters = newRenderingPlan.getPlanTimingParameters();
        final MadFrameTimeFactory planFrameTimeFactory = newRenderingPlan.getPlanFrameTimeFactory();
        // Start em all
        final Set<MadInstance<?, ?>> auis = newRenderingPlan.getAllInstances();
        for (final MadInstance<?, ?> aui : auis) {
            aui.internalEngineStartup(planChannelSettings, planTimingParameters, planFrameTimeFactory);
        }
    } else if (previousPlan != null && newRenderingPlan == null) {
        needWaitForUse = graphService.graphHasListeners(internalRootGraph);
        final HardwareIOChannelSettings previousPlanChannelSettings = previousPlan.getPlanChannelSettings();
        final int sampleRate = previousPlanChannelSettings.getAudioChannelSetting().getDataRate().getValue();
        final long nanosPerPeriod = AudioTimingUtils.getNumNanosecondsForBufferLength(sampleRate,
                previousPlanChannelSettings.getAudioChannelSetting().getChannelBufferLength());
        sleepWaitingForPlanMillis = (int) ((nanosPerPeriod / 1000000) / 2);
    } else // Both non-null
    {
        // Got to work out which components are to be stopped
        final Set<MadInstance<?, ?>> previousAuis = previousPlan.getAllInstances();
        final Set<MadInstance<?, ?>> newAuis = newRenderingPlan.getAllInstances();

        final HardwareIOChannelSettings planChannelSettings = newRenderingPlan.getPlanChannelSettings();
        final MadTimingParameters planTimingParameters = newRenderingPlan.getPlanTimingParameters();
        final MadFrameTimeFactory planFrameTimeFactory = newRenderingPlan.getPlanFrameTimeFactory();
        for (final MadInstance<?, ?> newAui : newAuis) {
            if (!previousAuis.contains(newAui)) {
                newAui.internalEngineStartup(planChannelSettings, planTimingParameters, planFrameTimeFactory);
            }
        }
        needWaitForUse = graphService.graphHasListeners(internalRootGraph);
        final int sampleRate = planChannelSettings.getAudioChannelSetting().getDataRate().getValue();
        final long nanosPerPeriod = AudioTimingUtils.getNumNanosecondsForBufferLength(sampleRate,
                planChannelSettings.getAudioChannelSetting().getChannelBufferLength());
        sleepWaitingForPlanMillis = (int) ((nanosPerPeriod / 1000000) / 2);
    }

    this.renderingPlan.set(newRenderingPlan);

    if (needWaitForUse) {
        final long startTime = System.currentTimeMillis();
        long curTime = startTime;
        while (curTime < startTime + maxWaitForTransitionMillis && !newRenderingPlan.getPlanUsed()) {
            try {
                Thread.sleep(sleepWaitingForPlanMillis);
            } catch (final InterruptedException e) {
                if (log.isErrorEnabled()) {
                    log.error("InterruptedException during sleep waiting for plan usage: " + e.toString(), e);
                }
            }
            curTime = System.currentTimeMillis();
        }
    }

    // Need to start components that are in the new rendering plan, but not in the old
    if (previousPlan == null && newRenderingPlan != null) {
    } else if (previousPlan != null && newRenderingPlan == null) {
        // Stop em all
        final Set<MadInstance<?, ?>> auis = previousPlan.getAllInstances();
        for (final MadInstance<?, ?> aui : auis) {
            aui.internalEngineStop();
        }
    } else // Both non-null
    {
        // Got to work out which components are to be stopped
        final Set<MadInstance<?, ?>> previousAuis = previousPlan.getAllInstances();
        final Set<MadInstance<?, ?>> newAuis = newRenderingPlan.getAllInstances();

        for (final MadInstance<?, ?> previousAui : previousAuis) {
            if (!newAuis.contains(previousAui)) {
                previousAui.internalEngineStop();
            }
        }
    }

    if (previousPlan != null) {
        renderingPlanService.destroyRenderingPlan(previousPlan);
    }
}

From source file:org.ecocean.media.AssetStore.java

protected boolean _updateChildLocalWork(MediaAsset parentMA, String type, HashMap<String, Object> opts,
        File sourceFile, File targetFile) throws IOException {
    if (!this.writable)
        return false; //should we silently fail or throw exception??
    if (!sourceFile.exists())
        throw new IOException("updateChild() " + sourceFile.toString() + " does not exist");

    String action = "resize";
    int width = 0;
    int height = 0;
    float[] transformArray = new float[0];
    boolean needsTransform = false;
    String args = null; //i think the only real arg would be watermark text (which is largely unused)

    switch (type) {
    case "master":
        action = "maintainAspectRatio";
        width = 4096;/*from   w w  w  .  j av  a 2 s . c om*/
        height = 4096;
        break;
    case "thumb":
        width = 100;
        height = 75;
        break;
    case "mid":
        width = 1024;
        height = 768;
        break;
    case "watermark":
        action = "watermark";
        width = 250;
        height = 200;
        break;
    /*
    case "spot":  //really now comes from Annotation too, so kinda weirdly maybe should be "annot"ish....
        needsTransform = true;
        transformArray = (float[])opts.get("transformArray");
        break;
    */
    case "feature":
        needsTransform = true;
        Feature ft = (Feature) opts.get("feature");
        if (ft == null)
            throw new IOException("updateChild() has 'feature' type without a Feature passed in via opts");

        /*
            right now we only handle bbox (xywh) and transforms ... so we kinda get ugly here
            in the future, all this would be place with better FeatureType-specific magic.  :/  TODO !?
        */
        JSONObject params = ft.getParameters();
        System.out.println("updateChild() is trying feature! --> params = " + params);
        width = (int) Math.round(params.optDouble("width", -1));
        height = (int) Math.round(params.optDouble("height", -1));
        if ((width < 0) || (height < 0))
            throw new IOException(
                    "updateChild() could not get w/h for feature " + ft + " parameters " + params);

        transformArray = new float[] { 1, 0, 0, 1, 0, 0 };
        if (params.optJSONArray("transformMatrix") != null) {
            JSONArray tarr = params.optJSONArray("transformMatrix");
            for (int i = 0; i < tarr.length(); i++) {
                if (i > 5)
                    break; //fail!
                transformArray[i] = (float) tarr.optDouble(i, 0);
            }
        }

        if (Util.isIdentityMatrix(transformArray)) {
            //lets set offsets only (ImageMagick shell script will basically ignore most of matrix)
            transformArray[4] = (float) params.optDouble("x", 0);
            transformArray[5] = (float) params.optDouble("y", 0);
        }
        System.out.println("got transformArray -> " + transformArray);
        break;
    default:
        throw new IOException("updateChild() type " + type + " unknown");
    }
    System.out.println("AssetStore.updateChild(): " + sourceFile + " --> " + targetFile);

    /* a quandry - i *think* "we all" (?) have generally agreed that a *new* MediaAsset should be created for each change in the contents of the source file.
       as such, finding an existing child MediaAsset of the type desired probably means it should either be deleted or orphaned ... or maybe simply marked older?
       in short: "revisioning".  further, if the *parent has changed* should it also then not be a NEW MediaAsset itself anyway!? as such, we "should never" be
       altering an existing child type on an existing parent.  i think.  ???  sigh.... not sure what TODO  -jon */

    ImageProcessor iproc = null;
    if (needsTransform) {
        iproc = new ImageProcessor("context0", sourceFile.toString(), targetFile.toString(), width, height,
                transformArray, parentMA);
    } else {
        iproc = new ImageProcessor("context0", action, width, height, sourceFile.toString(),
                targetFile.toString(), args, parentMA);
    }

    Thread t = new Thread(iproc);
    t.start();
    try {
        t.join(); //we have to wait for it to finish, so we can do the copyIn() below
    } catch (InterruptedException ex) {
        throw new IOException("updateChild() ImageProcessor failed due to interruption: " + ex.toString());
    }

    if (!targetFile.exists())
        throw new IOException("updateChild() failed to create " + targetFile.toString());
    return true;
}

From source file:com.nubits.nubot.trading.wrappers.BitSparkWrapper.java

private long getNonceInternal(String requester) {
    apiBusy = true;//w  ww.  j a va 2 s .  c  o  m
    long currentTime = System.currentTimeMillis();

    if (Global.options.isVerbose()) {
        LOG.debug(currentTime + " Now apiBusy! req : " + requester);
    }

    long timeElapsedSinceLastCall = currentTime - lastSentTonce;
    if (timeElapsedSinceLastCall < SPACING_BETWEEN_CALLS) {
        try {
            long sleepTime = SPACING_BETWEEN_CALLS;
            Thread.sleep(sleepTime);
            currentTime = System.currentTimeMillis();
            if (Global.options != null) {
                if (Global.options.isVerbose()) {
                    LOG.debug("Just slept " + sleepTime + "; req : " + requester);
                }
            }
        } catch (InterruptedException e) {
            LOG.error(e.toString());
        }
    }

    lastSentTonce = currentTime;

    if (Global.options.isVerbose()) {
        LOG.debug("Final tonce to be sent: req : " + requester + " ; Tonce=" + lastSentTonce);
    }

    apiBusy = false;
    return lastSentTonce;
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.AbstractTableJdbcSource.java

/**
 * Checks whether any of the {@link TableJdbcRunnable} workers completed
 * and whether there is any error that needs to be handled from them.
 * @param completionService {@link ExecutorCompletionService} used to detect completion
 * @throws StageException if {@link StageException} is thrown by the workers (if the error handling is stop pipeline)
 *//*from  ww  w .  j a  v a  2s .  co m*/
private void checkWorkerStatus(ExecutorCompletionService<Future> completionService) throws StageException {
    Future future = completionService.poll();
    if (future != null) {
        try {
            future.get();
        } catch (InterruptedException e) {
            LOG.error("Thread interrupted", e);
        } catch (ExecutionException e) {
            Throwable cause = Throwables.getRootCause(e);
            if (cause != null && cause instanceof StageException) {
                throw (StageException) cause;
            } else {
                LOG.error("Internal Error", e);
                throw new StageException(JdbcErrors.JDBC_75, e.toString(), e);
            }
        }
    }
}

From source file:com.nubits.nubot.trading.wrappers.AllCoinWrapper.java

@Override
public ApiResponse clearOrders(CurrencyPair pair) {
    //Since there is no API entry point for that, this call will iterate over active orders
    ApiResponse toReturn = new ApiResponse();
    boolean ok = true;

    ApiResponse activeOrdersResponse = getActiveOrders();
    if (activeOrdersResponse.isPositive()) {
        ArrayList<Order> orderList = (ArrayList<Order>) activeOrdersResponse.getResponseObject();
        for (int i = 0; i < orderList.size(); i++) {
            Order tempOrder = orderList.get(i);
            if (tempOrder.getPair().equals(pair)) {
                ApiResponse deleteOrderResponse = cancelOrder(tempOrder.getId(), null);
                if (deleteOrderResponse.isPositive()) {
                    boolean deleted = (boolean) deleteOrderResponse.getResponseObject();

                    if (deleted) {
                        LOG.warn("Order " + tempOrder.getId() + " deleted succesfully");
                    } else {
                        LOG.warn("Could not delete order " + tempOrder.getId() + "");
                        ok = false;/*from   w  w  w  .jav  a  2  s  .c o m*/
                    }

                } else {
                    LOG.error(deleteOrderResponse.getError().toString());
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    LOG.error(ex.toString());
                }
            }

        }
        toReturn.setResponseObject(ok);
    } else {
        LOG.error(activeOrdersResponse.getError().toString());
        toReturn.setError(activeOrdersResponse.getError());
        return toReturn;
    }

    return toReturn;
}

From source file:com.buaa.cfs.utils.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;/*  ww w .ja  va  2 s  .c o  m*/
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(
            new InputStreamReader(process.getErrorStream(), Charset.defaultCharset()));
    BufferedReader inReader = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.defaultCharset()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    } catch (OutOfMemoryError oe) {
        LOG.error("Caught " + oe + ". One possible reason is that ulimit"
                + " setting of 'max user processes' is too low. If so, do"
                + " 'ulimit -u <largerNum>' and try again.");
        throw oe;
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        // make sure that the error thread exits
        joinThread(errThread);
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled.  the stream draining thread will attempt to
            // drain that fd!!  it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            //      issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
            joinThread(errThread);
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = Time.monotonicNow();
    }
}

From source file:com.gochinatv.datasync.util.Shell.java

/**
 * Run a command//from w  w  w  . ja v  a  2 s . c  om
 */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    process = builder.start();
    if (timeOutInterval > 0) {
        timeOutTimer = new Timer();
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ignored) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if ((timeOutTimer != null) && !timedOut.get()) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            inReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
        }
        try {
            errReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = System.currentTimeMillis();
    }
}