Example usage for java.lang InterruptedException printStackTrace

List of usage examples for java.lang InterruptedException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.betfair.application.performance.BaselinePerformanceTester.java

private static void makeRequest(HttpCallable call, String contentType, Random rnd) {
    HttpClient httpc = client.get();/*from  w w  w .j av  a 2  s . co  m*/
    if (httpc == null) {
        httpc = new DefaultHttpClient();
        client.set(httpc);
    }
    HttpCallLogEntry cle = new HttpCallLogEntry();
    int randomiser = rnd.nextInt(50);
    avgRandomiser.addAndGet(randomiser);
    HttpUriRequest method = call.getMethod(contentType, new Object[] { randomiser }, randomiser, cle);
    method.addHeader("Authority", "CoUGARUK");
    CallLogCount loggedCount = null;
    // Execute the method.
    synchronized (LOG) {
        loggedCount = LOG.get(cle);
        if (loggedCount == null) {
            loggedCount = new CallLogCount();
            LOG.put(cle, loggedCount);
        }
    }
    long nanoTime = System.nanoTime();

    InputStream is = null;

    try {

        if (TRACE_EVERY > 0 && callsMade.incrementAndGet() % TRACE_EVERY == 0) {
            method.addHeader("X-Trace-Me", "true");
        }
        loggedCount.numCalls.incrementAndGet();
        final HttpResponse httpResponse = httpc.execute(method);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        boolean failed = false;

        int expectedHTTPCode = call.expectedResult();
        if (contentType.equals(SOAP) && expectedHTTPCode != HttpStatus.SC_OK) {
            // All SOAP errors are 500.
            expectedHTTPCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        }
        if (statusCode != expectedHTTPCode) {
            System.err.println("Method failed: " + httpResponse.getStatusLine().getReasonPhrase());
            failed = true;
        }
        // Read the response body.
        is = httpResponse.getEntity().getContent();
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int b;
        while ((b = is.read()) != -1) {
            baos.write(b);
        }
        is.close();
        String result = new String(baos.toByteArray(), CHARSET);
        if (result.length() == 0) {
            System.err.println("FAILURE: Empty buffer returned");
            failed = true;
        }
        if (failed) {
            loggedCount.failures.incrementAndGet();
        }
        bytesReceived.addAndGet(baos.toByteArray().length);

        if (CHECK_LOG && NUM_THREADS == 1) {
            File logFile = new File(
                    "C:\\perforce\\se\\development\\HEAD\\cougar\\cougar-framework\\baseline\\baseline-launch\\logs\\request-Baseline.log");
            String lastLine = getLastLine(logFile);
            int tries = 0;
            while (!lastLine.contains(METHOD_NAMES.get(call.getName()))) {
                if (++tries > 5) {
                    System.err.println(
                            "LOG FAIL: Call: " + METHOD_NAMES.get(call.getName()) + ", Line: " + lastLine);
                } else {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                    }
                }
                lastLine = getLastLine(logFile);
            }
            totalLogRetries.addAndGet(tries);
        }

    } catch (Exception e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        loggedCount.failures.incrementAndGet();
    } finally {
        // Release the connection.
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                /* ignore */}
        }
        callsRemaining.decrementAndGet();

        nanoTime = System.nanoTime() - nanoTime;
        loggedCount.callTime.addAndGet(nanoTime);
    }
}

From source file:com.grarak.kerneladiutor.utils.kernel.cpu.CPUFreq.java

private static int getFreq(int cpu, String path, boolean forceRead) {
    boolean offline = forceRead && isOffline(cpu);
    if (offline) {
        onlineCpu(cpu, true, false, null);

        try {/*from www  .  j  a  v  a  2s . co m*/
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    int freq = 0;
    String value = Utils.readFile(Utils.strFormat(path, cpu));
    if (value != null)
        freq = Utils.strToInt(value);

    if (offline) {
        onlineCpu(cpu, false, false, null);
    }
    return freq;
}

From source file:org.geek.utils.ApplicationUtils.java

/**
 * Build the html result of weather//from w w  w  .ja  va2 s  . c  o  m
 * @param context The current context
 * @return The html result of weather
 */
private static String getWeatherHtml(Context context) {
    String result = "";

    //Thread getWeatherInfo = new Thread() {
    //@Override  
    //public void run() {  
    //Intent intent = new Intent(RECI_COAST);  
    try {
        //???  
        result = getRequest("http://www.weather.com.cn/data/sk/101010100.html");
        Message weather = new Message();
        weather.what = WEATHER;
        weather.obj = result;
        mHandler.sendMessage(weather);
        result = parseWeatherInfo(result);
        /*JSONObject jsonobject = new JSONObject(  
                intent.getStringExtra("weatherinfo"));  
        JSONObject jsoncity = new JSONObject(  
                jsonobject.getString("weatherinfo"));  
        show.setText(":" + jsoncity.getString("city") + "\t"  
                + ":" + jsoncity.getString("date_y") + "\n" + ":"  
                + jsoncity.getString("temp1") + "\t"  
                + jsoncity.getString("weather1")+"\t"+jsoncity.getString("wind1"));*/
        //intent.putExtra("weatherinfo", reslut);  
        //??  
        //sendBroadcast(intent);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    //}
    //};
    //getWeatherInfo.start();
    //try {
    //getWeatherInfo.join();
    //} catch (Exception e) {
    //e.printStackTrace();
    //}
    return result;
}

From source file:com.grarak.kerneladiutor.utils.kernel.cpu.CPUFreq.java

public static List<String> getGovernors() {
    if (sGovernors == null) {
        boolean offline = isOffline(0);
        if (offline) {
            onlineCpu(0, true, false, null);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }//w  w w  .j a  v  a 2 s.c  o m
        }

        if (Utils.existFile(Utils.strFormat(CPU_AVAILABLE_GOVERNORS, 0))) {
            sGovernors = Utils.readFile(Utils.strFormat(CPU_AVAILABLE_GOVERNORS, 0)).split(" ");
        }

        if (offline) {
            onlineCpu(0, false, false, null);
        }
    }
    if (sGovernors == null)
        return getGovernors();
    return Arrays.asList(sGovernors);
}

From source file:com.grarak.kerneladiutor.utils.kernel.cpu.CPUFreq.java

public static float[] getCpuUsage() {
    try {/* w  ww. jav a2s . c o  m*/
        Usage[] usage1 = getUsages();
        Thread.sleep(500);
        Usage[] usage2 = getUsages();

        if (usage1 != null && usage2 != null) {
            float[] pers = new float[usage1.length];
            for (int i = 0; i < usage1.length; i++) {
                long idle1 = usage1[i].getIdle();
                long up1 = usage1[i].getUptime();

                long idle2 = usage2[i].getIdle();
                long up2 = usage2[i].getUptime();

                float cpu = -1f;
                if (idle1 >= 0 && up1 >= 0 && idle2 >= 0 && up2 >= 0) {
                    if ((up2 + idle2) > (up1 + idle1) && up2 >= up1) {
                        cpu = (up2 - up1) / (float) ((up2 + idle2) - (up1 + idle1));
                        cpu *= 100.0f;
                    }
                }

                pers[i] = cpu < 0 ? 0 : cpu > 100 ? 100 : cpu;
            }
            return pers;
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:Browser.java

/**
 * Open the specified URL in the client web browser.
 * //  w  ww. j av  a 2 s  . c om
 * @param url  URL to open.
 * @throws     IOException If there is brwoser problem.   
 */
public static void openUrl(String url) throws IOException {
    if (!loadedWithoutErrors) {
        throw new IOException("Exception in finding browser: " + errorMessage);
    }
    Object browser = locateBrowser();
    if (browser == null) {
        throw new IOException("Unable to locate browser: " + errorMessage);
    }

    switch (jvm) {
    case MRJ_2_0:
        Object aeDesc = null;
        try {
            aeDesc = aeDescConstructor.newInstance(new Object[] { url });
            putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc });
            sendNoReply.invoke(browser, new Object[] {});
        } catch (InvocationTargetException ite) {
            throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage());
        } catch (IllegalAccessException iae) {
            throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage());
        } catch (InstantiationException ie) {
            throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage());
        } finally {
            aeDesc = null; // Encourage it to get disposed if it was created
            browser = null; // Ditto
        }
        break;

    case MRJ_2_1:
        Runtime.getRuntime().exec(new String[] { (String) browser, url });
        break;

    case MRJ_3_0:
        int[] instance = new int[1];
        int result = ICStart(instance, 0);
        if (result == 0) {
            int[] selectionStart = new int[] { 0 };
            byte[] urlBytes = url.getBytes();
            int[] selectionEnd = new int[] { urlBytes.length };
            result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes, urlBytes.length, selectionStart,
                    selectionEnd);
            if (result == 0) {
                // Ignore the return value; the URL was launched successfully
                // regardless of what happens here.
                ICStop(instance);
            } else {
                throw new IOException("Unable to launch URL: " + result);
            }
        } else {
            throw new IOException("Unable to create an Internet Config instance: " + result);
        }
        break;

    case MRJ_3_1:
        try {
            openURL.invoke(null, new Object[] { url });
        } catch (InvocationTargetException ite) {
            throw new IOException("InvocationTargetException while calling openURL: " + ite.getMessage());
        } catch (IllegalAccessException iae) {
            throw new IOException("IllegalAccessException while calling openURL: " + iae.getMessage());
        }
        break;

    case WINDOWS_NT:
    case WINDOWS_9x:
        // Add quotes around the URL to allow ampersands and other special
        // characters to work.
        Process process = Runtime.getRuntime().exec(new String[] { (String) browser, FIRST_WINDOWS_PARAMETER,
                SECOND_WINDOWS_PARAMETER, THIRD_WINDOWS_PARAMETER, '"' + url + '"' });

        // This avoids a memory leak on some versions of Java on Windows.
        // That's hinted at in <http://developer.java.sun.com/developer/qow/
        // archive/68/>.
        try {
            process.waitFor();
            process.exitValue();
        } catch (InterruptedException ie) {
            throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
        }
        break;

    case OTHER:
        // Assume that we're on Unix and that Netscape is installed
        // First, attempt to open the URL in a currently running session of 
        // Netscape
        String command = browser.toString() + " -raise " + NETSCAPE_REMOTE_PARAMETER + " "
                + NETSCAPE_OPEN_PARAMETER_START + url + NETSCAPE_OPEN_PARAMETER_END;

        process = Runtime.getRuntime().exec(command);

        try {
            int exitCode = process.waitFor();
            if (exitCode != 0) { // if Netscape was not open
                Runtime.getRuntime().exec(new String[] { (String) browser, url });
            }
        } catch (InterruptedException exception) {
            exception.printStackTrace();
            throw new IOException("InterruptedException while launching browser: " + exception.getMessage());
        }
        break;
    default:
        // This should never occur, but if it does, we'll try the simplest 
        // thing possible
        Runtime.getRuntime().exec(new String[] { (String) browser, url });
        break;
    }
}

From source file:msi.gama.application.workspace.WorkspaceModelsManager.java

public static void linkSampleModelsToWorkspace() {
    final Job job = new Job("Updating the Built-in Models Library") {

        @Override//  www  .  ja va  2  s  .c o  m
        protected IStatus run(final IProgressMonitor monitor) {
            // Nothing to do really. Maybe a later version will remove this
            // command. See Issue 669
            while (!GamaBundleLoader.LOADED) {
                try {
                    Thread.sleep(100);
                } catch (final InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            linkModelsToWorkspace("msi.gama.models", "models", true);
            linkPluginsModelsToWorkspace();
            return Status.OK_STATUS;
        }

    };
    job.setUser(true);
    job.schedule();

}

From source file:com.netflix.iep.http.RxHttpTest.java

@BeforeClass
public static void startServer() throws Exception {
    rxHttp.start();//from   www  .j  a  v  a2s  .c  o m

    server = HttpServer.create(new InetSocketAddress(0), 100);
    server.setExecutor(Executors.newFixedThreadPool(10, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "HttpServer");
        }
    }));
    port = server.getAddress().getPort();

    server.createContext("/empty", new HttpHandler() {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            ignore(exchange.getRequestBody());
            int port = exchange.getRemoteAddress().getPort();
            exchange.getResponseHeaders().add("X-Test-Port", "" + port);
            statusCounts.incrementAndGet(statusCode.get());
            exchange.sendResponseHeaders(statusCode.get(), -1L);
            exchange.close();
        }
    });

    server.createContext("/echo", new HttpHandler() {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            Headers headers = exchange.getRequestHeaders();
            int contentLength = Integer.parseInt(headers.getFirst("Content-Length"));
            String contentEnc = headers.getFirst("Content-Encoding");
            if (contentEnc != null) {
                exchange.getResponseHeaders().add("Content-Encoding", contentEnc);
            }

            int code = statusCode.get();
            if (contentLength > 512 && !"gzip".equals(contentEnc)) {
                code = 400;
            }

            statusCounts.incrementAndGet(code);
            exchange.sendResponseHeaders(code, contentLength);
            try (InputStream input = exchange.getRequestBody();
                    OutputStream output = exchange.getResponseBody()) {
                byte[] buf = new byte[1024];
                int length;
                while ((length = input.read(buf)) > 0) {
                    output.write(buf, 0, length);
                }
            }
            exchange.close();
        }
    });

    server.createContext("/relativeRedirect", new HttpHandler() {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            ignore(exchange.getRequestBody());
            if (redirects.get() <= 0) {
                statusCounts.incrementAndGet(statusCode.get());
                exchange.getResponseHeaders().add("Location", "/empty");
                exchange.sendResponseHeaders(statusCode.get(), -1L);
                exchange.close();
            } else {
                redirects.decrementAndGet();
                statusCounts.incrementAndGet(302);
                exchange.getResponseHeaders().add("Location", "/relativeRedirect");
                exchange.sendResponseHeaders(302, -1L);
                exchange.close();
            }
        }
    });

    server.createContext("/absoluteRedirect", new HttpHandler() {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String host = "http://" + exchange.getRequestHeaders().getFirst("Host");
            ignore(exchange.getRequestBody());
            if (redirects.get() <= 0) {
                statusCounts.incrementAndGet(302);
                exchange.getResponseHeaders().add("Location", host + "/empty");
                exchange.sendResponseHeaders(302, -1L);
                exchange.close();
            } else {
                redirects.decrementAndGet();
                statusCounts.incrementAndGet(302);
                exchange.getResponseHeaders().add("Location", host + "/absoluteRedirect");
                exchange.sendResponseHeaders(302, -1L);
                exchange.close();
            }
        }
    });

    server.createContext("/notModified", new HttpHandler() {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            ignore(exchange.getRequestBody());
            statusCounts.incrementAndGet(304);
            exchange.sendResponseHeaders(304, -1L);
            exchange.close();
        }
    });

    server.createContext("/redirectNoLocation", new HttpHandler() {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            ignore(exchange.getRequestBody());
            statusCounts.incrementAndGet(302);
            exchange.sendResponseHeaders(302, -1L);
            exchange.close();
        }
    });

    server.createContext("/readTimeout", new HttpHandler() {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            ignore(exchange.getRequestBody());
            statusCounts.incrementAndGet(statusCode.get()); // So we can track retries
            Object lock = new Object();
            try {
                synchronized (lock) {
                    lock.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

    server.start();

    set(client + ".niws.client.MaxAutoRetriesNextServer", "" + retries);
    set(client + ".niws.client.RetryDelay", "100");
    set(client + ".niws.client.ReadTimeout", "1000");
}

From source file:edu.polyu.screamalert.SoundProcessing.java

public static void stopRecording() {
    if (null != recorder) {
        if (vadThread != null) {
            try {
                vadThread.join();/*from  www  .  j  a  va2 s .  co m*/
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        isRecording = false;
        recorder.stop();
        recorder.release();
        recorder = null;
        if (recordingThread != null) { // recordingThread could be null if the user press the Stop button
            try { // before the startDetection Runnable is executed.
                recordingThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        recordingThread = null;
        vadShortData = null;
        vadBufferedShortData = null;
        vadBufEnergy = null;
        handler.removeCallbacks(processData);
        handler.removeCallbacks(detectEvent);
        if (bufferedShortData != null) {
            bufferedShortData.clear();
        }
        if (subframeList != null) {
            subframeList.clear();
        }
    }
}

From source file:edu.umass.cs.gigapaxos.testing.TESTPaxosClient.java

protected static void waitForResponses(TESTPaxosClient[] clients, long startTime, int numRequests) {
    for (int i = 0; i < Config.getGlobalInt(TC.NUM_CLIENTS); i++) {
        while ((numResponses < numRequests) || (clients[i].requests.size() > 0)) {
            synchronized (clients[i]) {
                if (clients[i].requests.size() > 0)
                    try {
                        clients[i].wait(4000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }//from  w ww.  j ava 2s .c  o m
            }
            if (System.currentTimeMillis() - startTime > 1000)
                System.out.println("[" + clients[i].myID + "] " + getWaiting(clients)
                        + (getRtxCount() > 0 ? "; #num_total_retransmissions = " + getRtxCount() : "")
                        + (getRtxCount() > 0 ? "; num_retransmitted_requests = " + getNumRtxReqs() : "")
                        + ("; aggregate response rate = " + Util.df(getTotalThroughput(clients, startTime))
                                + " reqs/sec")
                        + "; time = " + (System.currentTimeMillis() - startTime) + " ms");
            if (System.currentTimeMillis() - startTime > MAX_WAIT_TIME) {
                String err = ("Timing out after having received " + numResponses + " responses for "
                        + numRequests + " requests");
                System.out.println(err);
                log.warning(err);
                break;
            }
            // if (clients[i].requests.size() > 0)
            try {
                Thread.sleep(1000);
                // System.out.println(DelayProfiler.getStats());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    runDone = true;
    assert (numResponses >= numRequests && noOutstanding(clients)) : numResponses + " responses received for "
            + numRequests + " requests";
    synchronized (TESTPaxosClient.class) {
        TESTPaxosClient.class.notify();
    }
    assert (numResponses >= numRequests && noOutstanding(clients));
    clearOutstanding(clients);
}