Example usage for java.lang Throwable getMessage

List of usage examples for java.lang Throwable getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:de.micromata.genome.gwiki.utils.ClassUtils.java

public static Class<?> classForName(String className) {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    try {/*w ww  .jav a 2 s.co m*/
        return Class.forName(className, true, cl);
    } catch (Throwable ex) {
        try {
            Class.forName(className, true, cl);
        } catch (Exception ex2) {

        }
        throw new RuntimeException("Failed to load class: " + className + "; " + ex.getMessage(), ex);
    }
}

From source file:org.openjira.jira.utils.LoadImageAsync.java

public static void saveImageToFile(String url, Bitmap bm) {
    try {//w  w w.  j a v a  2  s . c om
        File root = Environment.getExternalStorageDirectory();
        if (root.canWrite()) {
            File dir = new File(root, "openjiracache");
            dir.mkdir();
            File file = new File(dir,
                    url.replace("/", "_").replace(":", "-").replace("?", "_").replace("=", "-"));

            FileOutputStream os = new FileOutputStream(file);
            bm.compress(CompressFormat.PNG, 5, os);
            // Log.v(LOGTAG, "Saved bitmap in " + file.getAbsolutePath());
        }
    } catch (Throwable e) {
        Log.e(LOGTAG, "Could not write file " + e.getMessage());
    }
}

From source file:com.shareplaylearn.OauthPasswordFlow.java

public static LoginInfo googleLogin(String username, String password, String clientId, String callbackUri)
        throws URISyntaxException, IOException, AuthorizationException, UnauthorizedException {

    CloseableHttpClient httpClient = HttpClients.custom().build();
    String oAuthQuery = "client_id=" + clientId + "&";
    oAuthQuery += "response_type=code&";
    oAuthQuery += "scope=openid email&";
    oAuthQuery += "redirect_uri=" + callbackUri;
    URI oAuthUrl = new URI("https", null, "accounts.google.com", 443, "/o/oauth2/auth", oAuthQuery, null);
    Connection oauthGetCoonnection = Jsoup.connect(oAuthUrl.toString());
    Connection.Response oauthResponse = oauthGetCoonnection.method(Connection.Method.GET).execute();
    if (oauthResponse.statusCode() != 200) {
        String errorMessage = "Error contacting Google's oauth endpoint: " + oauthResponse.statusCode() + " / "
                + oauthResponse.statusMessage();
        if (oauthResponse.body() != null) {
            errorMessage += oauthResponse.body();
        }/*from  w  w  w . jav a  2  s. c o m*/
        throw new AuthorizationException(errorMessage);
    }
    Map<String, String> oauthCookies = oauthResponse.cookies();
    Document oauthPage = oauthResponse.parse();
    Element oauthForm = oauthPage.getElementById("gaia_loginform");
    System.out.println(oauthForm.toString());
    Connection oauthPostConnection = Jsoup.connect("https://accounts.google.com/ServiceLoginAuth");
    HashMap<String, String> formParams = new HashMap<>();

    for (Element child : oauthForm.children()) {
        System.out.println("Tag name: " + child.tagName());
        System.out.println("attrs: " + Arrays.toString(child.attributes().asList().toArray()));
        if (child.tagName().equals("input") && child.hasAttr("name")) {

            String keyName = child.attr("name");
            String keyValue = null;

            if (child.hasAttr("value")) {
                keyValue = child.attr("value");
            }

            if (keyName != null && keyName.trim().length() != 0 && keyValue != null
                    && keyValue.trim().length() != 0) {
                oauthPostConnection.data(keyName, keyValue);
                formParams.put(keyName, keyValue);
            }
        }
    }
    oauthPostConnection.cookies(oauthCookies);
    formParams.put("Email", username);
    formParams.put("Passwd-hidden", password);
    //oauthPostConnection.followRedirects(false);
    System.out.println("form post params were: ");
    for (Map.Entry<String, String> kvp : formParams.entrySet()) {
        //DO NOT let passwords end up in the logs ;)
        if (kvp.getKey().equals("Passwd")) {
            continue;
        }
        System.out.println(kvp.getKey() + "," + kvp.getValue());
    }
    System.out.println("form cookies were: ");
    for (Map.Entry<String, String> cookie : oauthCookies.entrySet()) {
        System.out.println(cookie.getKey() + "," + cookie.getValue());
    }
    //System.exit(0);
    Connection.Response postResponse = null;
    try {
        postResponse = oauthPostConnection.method(Connection.Method.POST).timeout(5000).execute();
    } catch (Throwable t) {
        System.out.println("Failed to post login information to googles endpoint :/ " + t.getMessage());
        System.out.println("This usually means the connection is bad, shareplaylearn.com is down, or "
                + " google is being a punk - login manually and check.");
        assertTrue(false);
    }
    if (postResponse.statusCode() != 200) {
        String errorMessage = "Failed to validate credentials: " + oauthResponse.statusCode() + " / "
                + oauthResponse.statusMessage();
        if (oauthResponse.body() != null) {
            errorMessage += oauthResponse.body();
        }
        throw new UnauthorizedException(errorMessage);
    }
    System.out.println("Response headers (after post to google form & following redirect):");
    for (Map.Entry<String, String> header : postResponse.headers().entrySet()) {
        System.out.println(header.getKey() + "," + header.getValue());
    }
    System.out.println("Final response url was: " + postResponse.url().toString());
    String[] args = postResponse.url().toString().split("&");
    LoginInfo loginInfo = new LoginInfo();
    for (String arg : args) {
        if (arg.startsWith("access_token")) {
            loginInfo.accessToken = arg.split("=")[1].trim();
        } else if (arg.startsWith("id_token")) {
            loginInfo.idToken = arg.split("=")[1].trim();
        } else if (arg.startsWith("expires_in")) {
            loginInfo.expiry = arg.split("=")[1].trim();
        }
    }

    //Google doesn't actually throw a 401 or anything - it just doesn't redirect
    //and sends you back to it's login page to try again.
    //So this is what happens with an invalid password.
    if (loginInfo.accessToken == null || loginInfo.idToken == null) {
        //Document oauthPostResponse = postResponse.parse();
        //System.out.println("*** Oauth response from google *** ");
        //System.out.println(oauthPostResponse.toString());
        throw new UnauthorizedException(
                "Error retrieving authorization: did you use the correct username/password?");
    }
    String[] idTokenFields = loginInfo.idToken.split("\\.");
    if (idTokenFields.length < 3) {
        throw new AuthorizationException("Error parsing id token " + loginInfo.idToken + "\n" + "it only had "
                + idTokenFields.length + " field!");
    }
    String jwtBody = new String(Base64.decodeBase64(idTokenFields[1]), StandardCharsets.UTF_8);
    loginInfo.idTokenBody = new Gson().fromJson(jwtBody, OauthJwt.class);
    loginInfo.id = loginInfo.idTokenBody.sub;
    return loginInfo;
}

From source file:com.dattack.dbtools.drules.engine.DrulesEngine.java

private static ThreadFactory createThreadFactory() {
    return new ThreadFactoryBuilder() //
            .withThreadNamePrefix("source") //
            .withUncaughtExceptionHandler(new UncaughtExceptionHandler() {

                @Override//from   www  .j a v a 2  s. co m
                public void uncaughtException(final Thread thread, final Throwable throwable) {
                    LOGGER.error("Uncaught exception throwed by thread '{}': {}", thread.getName(),
                            throwable.getMessage());
                }
            }).build();
}

From source file:org.openjira.jira.utils.LoadImageAsync.java

public static Bitmap getImageFromFile(String url) {
    try {/*w  w  w.  j a  va  2 s  .  c o m*/
        File root = Environment.getExternalStorageDirectory();
        if (root.canWrite()) {
            File dir = new File(root, "openjiracache");
            dir.mkdir();
            File file = new File(dir,
                    url.replace("/", "_").replace(":", "-").replace("?", "_").replace("=", "-"));
            if (file.exists() && file.length() > 0) {
                FileInputStream is = new FileInputStream(file);
                Bitmap bm = BitmapFactory.decodeStream(is);
                // Log.v(LOGTAG, "Loaded file from " +
                // file.getAbsolutePath());
                WeakReference<Bitmap> ref = new WeakReference<Bitmap>(bm);
                cachedBitmaps.put(url, ref);
                return bm;
            }
        }
    } catch (Throwable e) {
        Log.e(LOGTAG, "Could not read file " + e.getMessage());
    }
    return null;
}

From source file:com.taobao.android.builder.tools.cache.FileCacheCenter.java

public static void fetchFile(String type, String key, boolean folder, boolean remote, File dest)
        throws FileCacheException {

    if (!BUILD_CACHE_ENABLED) {
        return;//from  w  w  w  . j  a v  a  2s.co  m
    }

    File cacheFile = queryFile(type, key, folder, remote);

    if (null != cacheFile && cacheFile.exists()) {

        try {
            if (cacheFile.isFile()) {
                FileUtils.copyFile(cacheFile, dest);
            } else {
                FileUtils.copyDirectory(cacheFile, dest);
            }
            logger.log(type + "." + key + " fech  file success  " + dest.getAbsolutePath());
        } catch (Throwable e) {
            throw new FileCacheException(e.getMessage(), e);
        }

    }

}

From source file:eu.openanalytics.rsb.message.AbstractJob.java

/**
 * Builds an {@link ErrorResult} for a job whose processing has failed.
 * /*from  w  w w .j av  a  2 s . co  m*/
 * @param job
 * @param error
 * @return
 */
public static ErrorResult buildJobProcessingErrorResult(final AbstractJob job, final Throwable error) {
    final ErrorResult errorResult = Util.REST_OBJECT_FACTORY.createErrorResult();
    errorResult.setApplicationName(job.getApplicationName());
    errorResult.setJobId(job.getJobId().toString());
    errorResult.setSubmissionTime(Util.convertToXmlDate(job.getSubmissionTime()));
    errorResult.setErrorMessage(error.getMessage());
    return errorResult;
}

From source file:org.dkpro.lab.Util.java

private static void getComprehensiveMessage(StringBuilder aSb, Throwable aThrowable, int aLevel) {
    aSb.append(aThrowable.getMessage());
    Throwable cause = ExceptionUtils.getCause(aThrowable);
    if (cause != null && cause != aThrowable) {
        aSb.append('\n');
        for (int i = 0; i < aLevel; i++) {
            aSb.append("  ");
        }//from  w w  w  . j ava2  s .c  om
        getComprehensiveMessage(aSb, cause, aLevel + 1);
    }
}

From source file:com.atlassian.jira.rest.client.TestUtil.java

@SuppressWarnings("unused")
public static <T extends Throwable> void assertThrows(Class<T> clazz, String regexp, Runnable runnable) {
    try {// ww w .j  a v a  2  s. c o m
        runnable.run();
        Assert.fail(clazz.getName() + " exception expected");
    } catch (Throwable e) {
        Assert.assertTrue(
                "Expected exception of class " + clazz.getName() + " but was caught " + e.getClass().getName(),
                clazz.isInstance(e));
        if (e.getMessage() == null && regexp != null) {
            Assert.fail("Exception with no message caught, while expected regexp [" + regexp + "]");
        }
        if (regexp != null && e.getMessage() != null) {
            Assert.assertTrue("Message [" + e.getMessage() + "] does not match regexp [" + regexp + "]",
                    e.getMessage().matches(regexp));
        }
    }

}

From source file:at.wada811.dayscounter.CrashExceptionHandler.java

/**
 * ?//  ww w.  ja  v  a 2s . c  o m
 *
 * @param throwable
 *
 * @return
 *
 * @throws JSONException
 */
public static JSONObject getExceptionInfo(Throwable throwable) throws JSONException {
    JSONObject json = new JSONObject();
    json.put("name", throwable.getClass().getName());
    json.put("message", throwable.getMessage());
    if (throwable.getStackTrace() != null) {
        // ExceptionStacktrace
        JSONArray exceptionStacktrace = new JSONArray();
        for (StackTraceElement element : throwable.getStackTrace()) {
            exceptionStacktrace.put("at " + LogUtils.getMetaInfo(element));
        }
        json.put("ExceptionStacktrace", exceptionStacktrace);
    }
    if (throwable.getCause() != null) {
        json.put("cause", throwable.getCause());
        // CausedStacktrace
        if (throwable.getCause().getStackTrace() != null) {
            JSONArray causedStacktrace = new JSONArray();
            for (StackTraceElement element : throwable.getCause().getStackTrace()) {
                causedStacktrace.put("at " + LogUtils.getMetaInfo(element));
            }
            json.put("CausedStacktrace", causedStacktrace);
        }
    }
    return json;
}