Example usage for java.lang Exception getStackTrace

List of usage examples for java.lang Exception getStackTrace

Introduction

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

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

Provides programmatic access to the stack trace information printed by #printStackTrace() .

Usage

From source file:com.wifi.brainbreaker.mydemo.spydroid.api.RequestHandler.java

/** 
 * The implementation of all the possible requests is here
 * -> "sounds": returns a list of available sounds on the phone
 * -> "screen": returns the screen state (whether the app. is on the foreground or not)
 * -> "play": plays a sound on the phone
 * -> "set": update Spydroid's configuration
 * -> "get": returns Spydroid's configuration (framerate, bitrate...)
 * -> "state": returns a JSON containing information about the state of the application
 * -> "battery": returns an approximation of the battery level on the phone
 * -> "buzz": makes the phone buuz //from  w ww  . j av a 2 s.  c  om
 * -> "volume": sets or gets the volume 
 * @throws JSONException
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 **/
static private void exec(JSONObject object, StringBuilder response)
        throws JSONException, IllegalArgumentException, IllegalAccessException {

    SpydroidApplication application = SpydroidApplication.getInstance();
    Context context = application.getApplicationContext();

    String action = object.getString("action");

    // Returns a list of available sounds on the phone
    if (action.equals("sounds")) {
        Field[] raws = R.raw.class.getFields();
        response.append("[");
        for (int i = 0; i < raws.length - 1; i++) {
            response.append("\"" + raws[i].getName() + "\",");
        }
        response.append("\"" + raws[raws.length - 1].getName() + "\"]");
    }

    // Returns the screen state (whether the app. is on the foreground or not)
    else if (action.equals("screen")) {
        response.append(application.applicationForeground ? "\"1\"" : "\"0\"");
    }

    // Plays a sound on the phone
    else if (action.equals("play")) {
        Field[] raws = R.raw.class.getFields();
        for (int i = 0; i < raws.length; i++) {
            if (raws[i].getName().equals(object.getString("name"))) {
                mSoundPool.load(application, raws[i].getInt(null), 0);
            }
        }
        response.append("[]");
    }

    // Returns Spydroid's configuration (framerate, bitrate...)
    else if (action.equals("get")) {
        final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

        response.append("{\"streamAudio\":" + settings.getBoolean("stream_audio", false) + ",");
        response.append("\"audioEncoder\":\""
                + (application.audioEncoder == SessionBuilder.AUDIO_AMRNB ? "AMR-NB" : "AAC") + "\",");
        response.append("\"streamVideo\":" + settings.getBoolean("stream_video", true) + ",");
        response.append("\"videoEncoder\":\""
                + (application.videoEncoder == SessionBuilder.VIDEO_H263 ? "H.263" : "H.264") + "\",");
        response.append("\"videoResolution\":\"" + application.videoQuality.resX + "x"
                + application.videoQuality.resY + "\",");
        response.append("\"videoFramerate\":\"" + application.videoQuality.framerate + " fps\",");
        response.append("\"videoBitrate\":\"" + application.videoQuality.bitrate / 1000 + " kbps\"}");

    }

    // Update Spydroid's configuration
    else if (action.equals("set")) {
        final JSONObject settings = object.getJSONObject("settings");
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        final Editor editor = prefs.edit();

        editor.putBoolean("stream_video", settings.getBoolean("stream_video"));
        application.videoQuality = VideoQuality.parseQuality(settings.getString("video_quality"));
        editor.putInt("video_resX", application.videoQuality.resX);
        editor.putInt("video_resY", application.videoQuality.resY);
        editor.putString("video_framerate", String.valueOf(application.videoQuality.framerate));
        editor.putString("video_bitrate", String.valueOf(application.videoQuality.bitrate / 1000));
        editor.putString("video_encoder", settings.getString("video_encoder").equals("H.263") ? "2" : "1");
        editor.putBoolean("stream_audio", settings.getBoolean("stream_audio"));
        editor.putString("audio_encoder", settings.getString("audio_encoder").equals("AMR-NB") ? "3" : "5");
        editor.commit();
        response.append("[]");

    }

    // Returns a JSON containing information about the state of the application
    else if (action.equals("state")) {

        Exception exception = application.lastCaughtException;

        response.append("{");

        if (exception != null) {

            // Used to display the message on the user interface
            String lastError = exception.getMessage();

            // Useful to display additional information to the user depending on the error
            StackTraceElement[] stack = exception.getStackTrace();
            StringBuilder builder = new StringBuilder(
                    exception.getClass().getName() + " : " + lastError + "||");
            for (int i = 0; i < stack.length; i++)
                builder.append("at " + stack[i].getClassName() + "." + stack[i].getMethodName() + " ("
                        + stack[i].getFileName() + ":" + stack[i].getLineNumber() + ")||");

            response.append("\"lastError\":\"" + (lastError != null ? lastError : "unknown error") + "\",");
            response.append("\"lastStackTrace\":\"" + builder.toString() + "\",");

        }

        response.append("\"activityPaused\":\"" + (application.applicationForeground ? "1" : "0") + "\"");
        response.append("}");

    }

    else if (action.equals("clear")) {
        application.lastCaughtException = null;
        response.append("[]");
    }

    // Returns an approximation of the battery level
    else if (action.equals("battery")) {
        response.append("\"" + application.batteryLevel + "\"");
    }

    // Makes the phone vibrates for 300ms
    else if (action.equals("buzz")) {
        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(300);
        response.append("[]");
    }

    // Sets or gets the system's volume
    else if (action.equals("volume")) {
        AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (object.has("set")) {
            audio.setStreamVolume(AudioManager.STREAM_MUSIC, object.getInt("set"),
                    AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
            response.append("[]");
        } else {
            int max = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            int current = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
            response.append("{\"max\":" + max + ",\"current\":" + current + "}");
        }
    }

}

From source file:net.authorize.api.controller.test.ApiCoreTestBase.java

public static void showProperties(Object bean) {
    if (null == bean) {
        return;/*w  ww. ja v a  2  s.  c  o m*/
    }
    try {
        BeanInfo info = Introspector.getBeanInfo(bean.getClass(), Object.class);
        PropertyDescriptor[] props = info.getPropertyDescriptors();
        for (PropertyDescriptor pd : props) {
            String name = pd.getName();
            Method getter = pd.getReadMethod();
            Class<?> type = pd.getPropertyType();

            if (null != getter && !"class".equals(name)) {
                Object value = getter.invoke(bean);
                logger.info(String.format("Type: '%s', Name:'%s', Value:'%s'", type, name, value));
                processCollections(type, name, value);
                //process compositions of custom classes
                if (null != value && 0 <= type.toString().indexOf("net.authorize.")) {
                    showProperties(value);
                }
            }
        }
    } catch (Exception e) {
        logger.error(String.format("Exception during navigating properties: Message: %s, StackTrace: %s",
                e.getMessage(), e.getStackTrace()));
    }
}

From source file:loci.apps.SlideScannerImport.VentanaScannerInterpreter.java

public static ArrayList<ArrayList<Float>> interpretROISfromXML(String xmlPath) {

    ArrayList<ArrayList<Float>> retVal = null;
    ArrayList<Float> x = null, y = null;
    BufferedReader reader = null;
    try {//from   w w  w.j  a v  a  2 s  .  c o  m
        reader = new BufferedReader(new FileReader(xmlPath));
        String line;
        retVal = new ArrayList<ArrayList<Float>>();
        x = new ArrayList<Float>();
        y = new ArrayList<Float>();

        int indexTracker = 0, nextIndexTracker = 0;
        while ((line = removeNullFromString(reader.readLine())) != null) {

            while (indexTracker >= 0) {
                indexTracker = line.indexOf("X=\"", indexTracker);
                nextIndexTracker = line.indexOf("\"", indexTracker + 3);
                if (indexTracker < 0 || nextIndexTracker < 0) {
                    indexTracker = nextIndexTracker = 0;
                    break;
                }

                x.add(Float.parseFloat(line.substring(indexTracker + 3, nextIndexTracker)));

                indexTracker = line.indexOf("Y=\"", indexTracker);
                nextIndexTracker = line.indexOf("\"", indexTracker + 3);

                y.add(Float.parseFloat(line.substring(indexTracker + 3, nextIndexTracker)));

            } //end while(indexTracker)

        } //end while(line)

    } catch (Exception e) {
        e.printStackTrace();
        IJ.log("Error encountered while parsing XML file.");
        IJ.log(e.getStackTrace().toString());
        retVal = null;
        x = null;
        y = null;

    } //end try/catch XML parser

    try {
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
        IJ.log("Error encountered while parsing XML file.");
        IJ.log(e.getStackTrace().toString());
    }

    if (retVal != null && x != null && y != null && x.size() > 0 && y.size() > 0) {
        retVal.add(x);
        retVal.add(y);
    }

    return retVal;
}

From source file:com.visva.voicerecorder.utils.Utils.java

public static boolean deleteContact(Context ctx, Uri contactUri) {
    try {/*from ww w .  j av a 2  s .com*/
        ctx.getContentResolver().delete(contactUri, null, null);
        return true;
    } catch (Exception e) {
        System.out.println(e.getStackTrace());
    }
    return false;
}

From source file:com.sds.acube.ndisc.mts.xserver.util.XNDiscUtils.java

/**
 * ?  ?/*from w ww .ja v  a  2  s  .  com*/
 * 
 * @param e
 *            Exception ?
 * @return ?? ? ?
 */
public static String printStackTrace(Exception e) {
    StringBuilder str = new StringBuilder();
    str.append(e + "\r\n");
    str.append("-----------------------------------------\r\n");
    StackTraceElement[] trace = e.getStackTrace();
    for (int i = 0; i < trace.length; i++) {
        if (trace[i].getLineNumber() == -1)
            continue;
        str.append(trace[i] + "\r\n");
    }
    return str.toString();
}

From source file:gov.nih.nci.nbia.StandaloneDMDispatcher.java

static void printStackTraceToDialog(String note, Exception e) {
    StringBuilder sb = new StringBuilder(note);
    sb.append(e.getMessage());/*w  w  w .ja v  a2  s  .co  m*/
    sb.append("\n");
    for (StackTraceElement ste : e.getStackTrace()) {
        sb.append(ste.toString());
        sb.append("\n");
    }
    JTextArea jta = new JTextArea(sb.toString());
    JScrollPane jsp = new JScrollPane(jta) {
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(480, 320);
        }
    };
    JOptionPane.showMessageDialog(null, jsp, "Error", JOptionPane.ERROR_MESSAGE);
}

From source file:Main.java

public static void openFeedback(Activity activity) {
    try {/*from   ww  w . j a v  a 2 s.  c  o  m*/
        throw new Exception();
    } catch (Exception e) {
        ApplicationErrorReport report = new ApplicationErrorReport();
        report.packageName = report.processName = activity.getApplication().getPackageName();
        report.time = System.currentTimeMillis();
        report.type = ApplicationErrorReport.TYPE_CRASH;
        report.systemApp = false;
        ApplicationErrorReport.CrashInfo crash = new ApplicationErrorReport.CrashInfo();
        crash.exceptionClassName = e.getClass().getSimpleName();
        crash.exceptionMessage = e.getMessage();
        StringWriter writer = new StringWriter();
        PrintWriter printer = new PrintWriter(writer);
        e.printStackTrace(printer);
        crash.stackTrace = writer.toString();
        StackTraceElement stack = e.getStackTrace()[0];
        crash.throwClassName = stack.getClassName();
        crash.throwFileName = stack.getFileName();
        crash.throwLineNumber = stack.getLineNumber();
        crash.throwMethodName = stack.getMethodName();
        report.crashInfo = crash;
        Intent intent = new Intent(Intent.ACTION_APP_ERROR);
        intent.putExtra(Intent.EXTRA_BUG_REPORT, report);
        activity.startActivity(intent);
    }
}

From source file:eu.learnpad.simulator.mon.manager.ResponseDispatcher.java

public static void NotifyMeException(String ruleMatched, String enablerName, Exception exception) {
    ConsumerProfile enablerMatched = (ConsumerProfile) requestMap.get(ruleMatched);

    ComplexEventException exceptionRaised = ComplexEventException.Factory.newInstance();
    if (exception.getCause() == null) {
        exceptionRaised.setCauseClassName("null");
    } else {//from  w w w.j a v a  2  s. c  o m
        exceptionRaised.setCauseClassName(exception.getCause().getClass().getName());
    }
    exceptionRaised.setClassName(exception.getClass().getName());
    exceptionRaised.setLocalizedMessage(exception.getLocalizedMessage());
    exceptionRaised.setMessage(exception.getMessage());
    exceptionRaised.setStackTrace(exception.getStackTrace().toString());

    ResponseDispatcher.sendResponse(exceptionRaised, enablerName, enablerMatched.getAnswerTopic());

    DebugMessages.print(TimeStamp.getCurrentTime(), ResponseDispatcher.class.getSimpleName(),
            "ruleMatched: " + ruleMatched + " - enablerName: " + enablerName + " - evaluationResult: "
                    + exceptionRaised.getClassName());
}

From source file:de.da_sense.moses.client.AvailableFragment.java

/**
 * Concatenate the stack trace of an exception to one String.
 * /*ww  w  .j ava2  s  .co  m*/
 * @param e
 *            the exception to concatenate
 * @return the concatenated String of the exception
 */
public static String concatStacktrace(Exception e) {
    String stackTrace = "";
    for (int i = 0; i < e.getStackTrace().length; i++) {
        stackTrace += e.getStackTrace()[i];
    }
    return stackTrace;
}

From source file:com.seer.datacruncher.utils.generic.CommonUtils.java

public static String getExceptionMessage(Exception ex) {
    String msg = ex.getMessage();
    if (msg != null) {
        return msg;
    } else {//from w  w  w  .j  a  v  a  2 s.  com
        try {
            msg = "";
            StackTraceElement[] trace = ex.getStackTrace();
            Throwable e1 = ex.getCause();
            if (e1 != null) {
                for (int i = 0; i < trace.length; i++) {
                    if (e1 != null) {
                        msg = e1.getMessage();
                        if (msg != null) {
                            System.out.println(msg);
                            break;
                        } else {
                            e1 = e1.getCause();
                        }
                    }
                }
            }
            return msg;
        } catch (Exception e) {
            return msg;
        }
    }
}