Writing Exception.printStackTrace to a string

Hi,
I need to write the exception strack trace to a String so that I can email it details of exceptions on a web site to a system administrator.
The printStackTrace() method prints exactly what I want to an OutputStream (such as system.out) but I don't know how I can get this into a string. Simply doing Exception.toString() does not produce enough detail about the exception to make it useful.
Can anyone help?
Below is some code that demonstrates what I'm trying to do but does not work because the printStackTrace() method on the exception object doesn't write to a string.
try {
// Some exception here, in this case / by 0
int i = 7 / 0;
catch (Exception e) {
// This is too short and does not give enough information
String exceptionInfoShort = e.toString()
// This is what I want to do but it is not supported
String exceptionInfoLong = e.printStackTrace();
Cheers,
Brent.

No point messing about with PrintWriters and StringWriters. When you call e.printStackTrace() the method will construct a StringBuffer from every item in the stack trace and then print out the String representation of the buffer.
You could do this yourself if only you could get the stack trace. Strangely, there is a method Exception.getStackTrace() that does exactly that (amasing what you can learn in two seconds from the API):
void eMailStackTrace(Exception e) {
   StackTraceElement[] trace = e.getStackTrace();
   StringBuffer stackTraceBuffer = new StringBuffer();
   for(int i = 0 ; i < trace.length ; i++)
      stackTraceBuffer.append(trace.toString());
String stackTrace = stackTraceBuffer.toString();
email(stackTrace);

Similar Messages

  • Exception stacktrace to a string?

    Hi
    My problem is that I want to get java exception stacktraces to a string using JNI calls in C.
    I know how to do it with Java using Throwable.printStackTrace and so on, but I'm just wondering if it's valid to do it that way due to the somewhat unclear descriptions of the exception functions in JNI. My program is invoking java from C so there is no java function I will return to that can handle the exceptions at a higher level so I want to handle things from C.
    I know I can get the exception using ExceptionDescribe, but then it says I can't use any other JNI calls until I use ExceptionClear (or ExceptionDescribe) to clear the exception. Thus my question is, can I use the jthrowable object the ExceptionDescribe returned after I call ExceptionClear, i.e. does the clear only clear the thrown status, but doesn't remove the actual throwable object? And if I can use it, I assume I have to release my reference to the throwable object useing DeleteLocalRef. Does it work this way or can't I use the throwable object at all in my code?
    Example:
    jthrowable err;
    >>>JNI call that throws an exception
    if ((err = (*env)->ExceptionOccurred(env)) != NULL)
    (*env)->ExceptionClear(env);
    >>>Function that use JNI to call java functions to print the exception stacktrace to a string
    (*env)->DeleteLocalRef(env, err);
    Hope someone can answer if this is possible or if I simply have to live without the stacktrace. The references and tutorials are a bit vague on this.

    My problem is that I want to get java exception
    stacktraces to a string using JNI calls in C.Throwable.printStackTrace(PrintStream s)
    Throwable.printStackTrace(PrintWriter s)
    You use a string stream for the output.
    You would of course have to convert all that to C code (and only use it after clearing the exception.)

  • Writed a dll for save string in teststand,get a error from teststand

    I'm writed a dll for save string in teststand, the dll can execute by itself well,but when loading by teststand, it always error heppen,I attached all resource here ,please kindly help me on this,thank you in advance.
    帖子被alexzheng在06-15-2006 03:19 AM时编辑过了
    Attachments:
    dll.zip ‏32 KB

    HI,
    I have resolved the problem, I have wrong define in the write function use : writetextfile(CString filename,CString text,int length)
    but the error happen when I transfer those string from teststand to dll,it generation a system level error and automatic close teststand software occur,
    after I change the define for :writetextfile(char *filename,char *text,int length) ,it is Ok now.
    帖子被alexzheng在06-15-2006 06:44 PM时编辑过了
    Attachments:
    err1.jpg ‏21 KB
    err1.jpg ‏21 KB

  • Reading & writing to file using ArrayList String incorrectly

    Hi Java Experts,
    I am running out of ideas on why my findSnomedCodes.java program is filling up the output file (Snomed-Codes.txt) with the
    same information ([M44110|T33010, , M92603|T10350, ]) continuously. This program goes through a dummy patient result file
    and pickup the 3rd line of each record and insert it into an ArrayList of String before writing it into a Snomed-Codes.txt
    file. A followed up method prints out everything from Snomed-Codes.txt.
    Below is the source code of findSnomedCodes.java program:
    import java.io.*;
    import java.io.IOException;
    import java.lang.String;
    import java.lang.Character;
    import java.util.regex.*;
    import java.util.ArrayList;
    import java.util.List;
    public class FindSnomedCode {
    static List<String> complete_records = new ArrayList<String>();
    static public void getContents(File existingFile) {
    StringBuffer contents = new StringBuffer();
    BufferedReader input = null;
    int line_number = 0;
    int number_of_records = 0;
    String snomedCodes = null;
    try {
    input = new BufferedReader( new FileReader(existingFile) );
    String current_line = null;
    while (( current_line = input.readLine()) != null) {
    // Create a pattern to match for the "\"
    Pattern p = Pattern.compile("\\\\");
    // Create a matcher with an input string
    Matcher m = p.matcher(current_line);
    boolean beginning_of_record = m.find();
    if (beginning_of_record) {
    line_number = 0;
    number_of_records++;
    } else {
    line_number++;
    if (line_number == 2) {
    snomedCodes = current_line;
    System.out.println(snomedCodes);
    complete_records.add(current_line);
    catch (FileNotFoundException ex) {
    ex.printStackTrace();
    catch (IOException ex){
    ex.printStackTrace();
    finally {
    try {
    if (input!= null) {
    input.close();
    catch (IOException ex) {
    ex.printStackTrace();
    static public void setContents(File reformatFile, List snomedCodes)
    throws FileNotFoundException, IOException {
    Writer output = null;
    try {
    output = new BufferedWriter( new FileWriter(reformatFile) );
    while (snomedCodes.iterator().hasNext())
    output.write( snomedCodes.toString() );
    finally {
    if (output != null) output.close();
    static public void printContents(File existingFile) {
    //...checks on existingFile are elided
    StringBuffer contents = new StringBuffer();
    BufferedReader input = null;
    int line_number = 0;
    int number_of_records = 0;
    long total_number_of_lines = 0;
    String snomedCodes = null;
    try {
    input = new BufferedReader( new FileReader(existingFile) );
    String current_line = null;
    while (( current_line = input.readLine()) != null)
    System.out.println(current_line);
    catch (FileNotFoundException ex) {
    ex.printStackTrace();
    catch (IOException ex){
    ex.printStackTrace();
    finally {
    try {
    if (input!= null) {
    input.close();
    catch (IOException ex) {
    ex.printStackTrace();
    public static void main (String args[]) throws IOException {
    File currentFile = new File("D:\\AP Data Conversion\\1988\\dummy_test_records.txt");
    getContents(currentFile);
    File snomedFile = new File( "D:\\AP Data Conversion\\1988\\Snomed-Codes.txt");
    setContents(snomedFile, complete_records);
    printContents(snomedFile);
    The output from Netbeans/Java is as follows:
    M44110|T33010
    M92603|T10350
    Exception in thread "main" java.io.IOException: There is not enough space on the disk
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:260)
    at sun.nio.cs.StreamEncoder$CharsetSE.writeBytes(StreamEncoder.java:336)
    at sun.nio.cs.StreamEncoder$CharsetSE.implClose(StreamEncoder.java:427)
    at sun.nio.cs.StreamEncoder.close(StreamEncoder.java:160)
    at java.io.OutputStreamWriter.close(OutputStreamWriter.java:222)
    at java.io.BufferedWriter.close(BufferedWriter.java:250)
    at FindSnomedCode.setContents(FindSnomedCode.java:90)
    at
    FindSnomedCode.main(FindSnomedCode.java:134)---------------------------------------------------------------------------------
    The content of Snomed-Codes.txt file is filled with continuous lines of [M44110|T33010, , M92603|T10350, ] as follows:
    [M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, ,
    M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350,
    ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, ,
    M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350,
    I must have done something wrong with the ArrayList.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    while (snomedCodes.iterator().hasNext())
      output.write( snomedCodes.toString() );
    }Here you have some kind of a list or something (I couldn't stand to read all that unformatted code but I suppose you can find out). It has an iterator which gives you the entries of the list one at a time. You keep asking if it has more entries -- which it does -- but you never get those entries by calling the next() method, so it always has all the entries still available.
    And your code inside the loop is independent of the iterator, so it's rather pointless to iterate over the entries and output exactly the same data for each entry. Even if you were iterating correctly.

  • Writing xml to more readable String

    Hi. I've written xml to string (without writing to a file) using the following method. Is there any way to make the xml string more readable? i.e have nice indentation, paragraphs etc like:
    <tag1>
        <tag2>
        </tag2>
    </tag1>
       public String getXMLData()
           String str = null;
           try
               ByteArrayOutputStream output= new ByteArrayOutputStream();
               TransformerFactory tfactory = TransformerFactory.newInstance();
               Transformer serializer = tfactory.newTransformer();
               serializer.setOutputProperty(
                   javax.xml.transform.OutputKeys.DOCTYPE_SYSTEM, dtdFile);
               serializer.transform(new DOMSource(document), new StreamResult(output));
               str = output.toString("UTF-8");
           catch(Exception e)
               e.printStackTrace();
           return str;
       }

    Hi,
    try
    serializer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT,"yes");
    regards

  • Reading & writing to file using ArrayList String incorrectly (2)

    I have been able to store two strings (M44110|T33010, M92603|T10350) using ArrayList<String>, which represent the result of some patient tests. Nevertheless, the order of these results have been stored correctly.
    E.g. currently stored in file Snomed-Codes as -
    [M44110|T33010, M92603|T10350][M44110|T33010, M92603|T10350]
    Should be stored and printed out as -
    M44110|T33010
    M92603|T10350
    Below is the detail of the source code of this program:
    import java.io.*;
    import java.io.IOException;
    import java.lang.String;
    import java.util.regex.*;
    import java.util.ArrayList;
    public class FindSnomedCode {
        static ArrayList<String> allRecords = new ArrayList<String>();
        static public ArrayList<String> getContents(File existingFile) {
            StringBuffer contents = new StringBuffer();
            BufferedReader input = null;
            int line_number = 0;
            int number_of_records = 0;
            String snomedCodes = null;
            ArrayList<String> complete_records = new ArrayList<String>();
            try {
                input = new BufferedReader( new FileReader(existingFile) );
                String current_line = null;
                while (( current_line = input.readLine()) != null) {
                    // Create a pattern to match for the "\"
                    Pattern p = Pattern.compile("\\\\");
                    // Create a matcher with an input string
                    Matcher m = p.matcher(current_line);
                    boolean beginning_of_record = m.find();
                    if (beginning_of_record) {
                        line_number = 0;
                        number_of_records++;
                    } else {
                        line_number++;
                    if ( (line_number == 2) && (current_line.length() != 0) ) {
                        snomedCodes = current_line;
                        System.out.println(snomedCodes);
                        complete_records.add(current_line);
            catch (FileNotFoundException ex) {
                ex.printStackTrace();
            catch (IOException ex){
                ex.printStackTrace();
            finally {
                try {
                    if (input!= null) {
                        input.close();
                catch (IOException ex) {
                    ex.printStackTrace();
            return complete_records;
        static public void setContents(File reformatFile, ArrayList<String> snomedCodes)
                                     throws FileNotFoundException, IOException {
           Writer output = null;
            try {
                output = new BufferedWriter( new FileWriter(reformatFile) );
                  for (String index : snomedCodes) {
                      output.write( snomedCodes.toString() );
            finally {
                if (output != null) output.close();
        static public void printContents(File existingFile) {
            StringBuffer contents = new StringBuffer();
            BufferedReader input = null;
            int line_number = 0;
            int number_of_records = 0;
            String snomedCodes = null;
            try {
                input = new BufferedReader( new FileReader(existingFile) );
                String current_line = null;
                while (( current_line = input.readLine()) != null)
                    System.out.println(current_line);
            catch (FileNotFoundException ex) {
                ex.printStackTrace();
            catch (IOException ex){
                ex.printStackTrace();
            finally {
                try {
                    if (input!= null) {
                        input.close();
                catch (IOException ex) {
                    ex.printStackTrace();
        public static void main (String args[]) throws IOException {
            File currentFile = new File("D:\\dummy_patient.txt");
            allRecords = getContents(currentFile);
            File snomedFile = new File( "D:\\Snomed-Codes.txt");
            setContents(snomedFile, allRecords);
            printContents(snomedFile);
    }There are 4 patient records in the dummy_patient.txt file but only the 1st (M44110|T33010) & 3rd (M92603|T10350) records have results in them. The 2nd & 4th records have blank results.
    Lastly, could someone explain to me the difference between java.util.List & java.util.ArrayList?
    I am running Netbeans 5.0, jdk1.5.0_09 on Windows XP, SP2.
    Many thanks,
    Netbeans Fan.

    while (snomedCodes.iterator().hasNext())
      output.write( snomedCodes.toString() );
    }Here you have some kind of a list or something (I couldn't stand to read all that unformatted code but I suppose you can find out). It has an iterator which gives you the entries of the list one at a time. You keep asking if it has more entries -- which it does -- but you never get those entries by calling the next() method, so it always has all the entries still available.
    And your code inside the loop is independent of the iterator, so it's rather pointless to iterate over the entries and output exactly the same data for each entry. Even if you were iterating correctly.

  • Exception: Call of execute(String) is not allowed for PreparedStatement

    Hi all,
    This query was run fine on SapDB 7.4 from Jave code using prepareStatement()  method:
    declare id11216053819634 cursor for select sc.name, measuredobjectid id from serviceconditions sc, measuredobjects mo where sc.collectionid = mo.collectionid and sc.name like 'DWindowsSLA/%,%,%,%' for reuse
    declare id21216053819634 cursor for select min(sampletime), max(sampletime), name, id11216053819634.id from id11216053819634, d_slastore ss where id11216053819634.id = ss.measuredobjectid and ss.sampletime between '2008-07-14 00:00:00' and '2008-07-14 12:43:35'  group by name, id11216053819634.id for reuse
    select ss.status, ss.statuschange, ss.sampletime, id21216053819634.name from d_slastore ss, id21216053819634 where ss.measuredobjectid = id21216053819634.id and ss.sampletime between '2008-07-14 00:00:00' and '2008-07-14 12:43:35'  and (statuschange != 0 or ss.sampletime = id21216053819634.expression1 or ss.sampletime = id21216053819634.expression2) order by name, sampletime
    We recently upgrade our old SapDb to the latest MaxDB. An now this query produces the error:
    com.sap.dbtech.jdbc.exceptions.JDBCDriverException: SAP DBTech JDBC: Call of execute(String) is not allowed for PreparedStatement.
    Does anyone know how to fix this?
    Thank you very much,
    Irina

    Hi Irina,
    First, welcome to SDN!
    Well, PreparedStatement represents a precompiled SQL statement, so you should be using the no-arg execute() method rather than execute(String).
    HTH!
    \-- Vladimir

  • Exception Stack Trace as String?

    Hello all!
    I need to convert the stack trace returned by the printStackTrace() method (return type void) into a String. Does anyone know of a good way of doing this?
    My interest in this stems from a desire to send any Java error messages to myself via email rather than having them displayed on the computer screen, which is remote to my workstation. Any help, hints, etc. are much appreciated.
    Thanks in advance.

    I don't know of a way to solve this via the Throwable API alone, but you could do one of the following things: a) send the stack trace to a known file via printStackTrace(PrintWriter s), then parse that file routinely and mail the information or b) extend PrintWriter with a class that sends the information to you when its write methods are called. Personally, I would write a log class that writes the stack trace to a file and then emails that file.

  • Exception.printStackTrace

    When I run code in the WTK emulator, I get a detailed stack trace. It actually says the name of the method when the exception occurred. Now I am running the code on the device, and the stack trace it gives me is useless. So, my question is, is there any way to find out what the offending method is?
    java.lang.NullPointerException
    Frame 120c77f8 contents:
    Previous frame....: 120c77d8
    Previous ip.......: 10313b03 (offset within invoking method: 123)
    Method............: 1025e428 'printStackTrace()V' (virtual)
    Class.............: 1023352c java/lang/Throwable
    Bytecode..........: 102399b7
    Exception handlers: 00000000
    Frame size........: 1 (1 arguments, 0 local variables)
    Argument[0].......: 120cb1f0
    Frame 120c77d8 contents:
    Previous frame....: 120c77d0
    Previous ip.......: 00000000
    Method............: 10313b6c 'run()V' (virtual)
    Class.............: 10315a8c a/a/b/a
    Bytecode..........: 10313a88
    Exception handlers: 10313a80
    Frame size........: 2 (1 arguments, 1 local variables)
    Argument[0].......: 120c64f0
    Local[1]..........: 120cb1f0

    Hi, sorry I don't think your going to get much info, without using emulators, I recomend using more than just the WTK, try it in the emulator of the target phone.
    I'd guess from "Method............: 10313b6c 'run()V' (virtual)" the error is thrown in 'void run()'.

  • Printing exceptions (printStackTrace()) in a file

    Dear everyone,
    I need to print the exceptions' stack traces in a file
    (e.printStackTrace()).
    How do I do that?
    I attempted by setting the out stream (System.setOut())
    to my file's print stream. But it didn't work.
    Thanks a bunch for your help!
    George

    Simple :
      try {
        //code
      } catch (Throwable t) {
        PrintWriter writer = new PrintWriter(new FileWriter("c:\\temp\\error.txt"));
        t.printStackTrace(writer);
        writer.flush();
        writer.close();
      }

  • How to reduce output line of  exception.printStackTrace()

    hi,
    i just want to print on console where exception eactly occured this is enough..but when i call e.printStackTrace()  it give a long list of stack trace...
    most probably just few 3 or 4 line is enough when i ask e.printStackTracehow to do this in java.. what are method i have to override in Throwable class.. plz

    The Exception class provides all this information, you don't necessarily have to invoke printStackTrace(). Read up on the API for Exception and you'll find several useful methods that you could call to retrieve just the information you like.
    On a side note, you'll be surprised how often some of that extraneous information will be helpful when trying to debug your code.

  • Writing Exception into ccBPM container trace from Graphical mapping

    Hi guys,
    I followed the Guarneri's blog /people/alessandro.guarneri/blog/2006/01/26/throwing-smart-exceptions-in-xi-graphical-mapping
    It works fine within message monitor, but at the trace of ccBPM nothing appears! I'm talking about the trace of the container at the message mapping in the ccBPM. (I increased the trace level, but didn't solve)
    Anyone knows if it is possible to use this approach for the ccBPM container trace as well, or I'm missing something here?
    Thanks in advance & regards,
    Ricardo.

    Hi Gonzalo,
    you wrote:
    >>Mark the tag 'Create new transaction' in your transformation step in your BPM. Then navigating in the sxmb_moni_bpe transaction wil bring you to your message. But it is hard to find the XML there.
    The low technology solution is simulating the data flow in your bpm throw a sequence of chained mapping tests. <<
    I already have the option "create new transaction". but maybe I'm searching in the wrong place. Could you point me where to find at ccBPM?
    Thanks &regards,
    Ricardo.

  • Writing Exception

    I am trying to figure out the best way to write exception classes for my program. I think i have 2 choices:
    1) For each type of user exception I create an Exception class. All of them are inherited from java.lang.Exception. So for example I have
    public class LocationNotFoundException extends Exception {
    2) Write Exception classes based on the level of code. So any basic exception will throw InfrastructureException:
    public class InfrastructureException extends Exception {
    Then if exception happens in DAO then DAOException:
    public class DAOException extends InfrastructureException {
    Is there any other choice? Which approach is better and why?
    Thanks

    I think the idea is to write different Exceptions for
    different means of failure that need to be handled
    differently. If two Exceptions are being used where
    they differ only in the information being conveyed,
    but neither warrants handling the situation much
    differently, they can be smushed into one.
    ~CheersThanks. So if I have LocationNotFoundException and DepartmentNotFoundException and both are same in functionality, its better to instead define ObjectNotFoundException and use it instead?
    How about using inheritance between these Exceptions? Is it a recommended approach?

  • .wav plays well but not .mp3

    In my swing code, I am playing .wav files (using getAudioClip() etc...)
    But I am unable to play .mp3
    can anybody help me out ?/ any kinda code ???
    thanx in advance

    * @(#)MiniPlayer.java          Tiger     2005 May 04
    * Copyright 2005 Ronillo Ang
    * All rights reserved
    package com.yahoo.ron.media;
    import java.awt.Component;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.Menu;
    import java.awt.MenuBar;
    import java.awt.MenuItem;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.File;
    import java.net.URL;
    import javax.media.ControllerEvent;
    import javax.media.ControllerListener;
    import javax.media.Manager;
    import javax.media.Player;
    import javax.media.RealizeCompleteEvent;
    import javax.swing.ImageIcon;
    import javax.swing.JFileChooser;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.UIManager;
    * @author          Ronillo Ang
    * @version          vm1.5.0-b64
    * A simple demo or usage of JMF.
    * NOTE: This program will not run without modification. Check the code and make some modification.
    final public class MiniPlayer extends WindowAdapter implements ActionListener, ControllerListener{
         final private String imageName = "com/yahoo/ron/images/t10.gif";
         private Frame frame;
         private MiniPlayerRecentFileMenu mprfm;
         private Player player;
         private MiniPlayer() throws Exception{
              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              frame = new Frame("Mini Player");
              frame.setMenuBar(createMenuBar(new MenuBar()));
              frame.setLayout(new BorderLayout());
              frame.add(BorderLayout.CENTER, new JLabel(new ImageIcon(imageName)));
              frame.pack();
              frame.addWindowListener(this);
              Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
              int x = (dimension.width - frame.getWidth()) / 2;
              int y = (dimension.height - frame.getHeight()) / 2;
              frame.setLocation(x, y);
              frame.setVisible(true);
         public void actionPerformed(ActionEvent ae){
              Object source = ae.getSource();
              try{
                   if(source instanceof MenuItem){
                        String command = ((MenuItem)source).getLabel().trim();
                        if(command.equalsIgnoreCase("open..."))
                             createPlayer(open());
                        else if(command.equalsIgnoreCase("exit"))
                             windowClosing(null);
                        else
                             createPlayer(open(command));
              } catch (Exception exception) {
                   showThrowableMessage(exception);
         public void controllerUpdate(ControllerEvent ce){
              if(ce instanceof RealizeCompleteEvent){
                   frame.removeAll();
                   Component component = player.getVisualComponent();
                   if(component != null){
                        frame.add(BorderLayout.CENTER, component);
                        component = null;
                   component = player.getControlPanelComponent();
                   if(component != null){
                        frame.add(BorderLayout.SOUTH, component);
                        component = null;
                   frame.pack();
         public void windowClosed(WindowEvent we){
              System.exit(0);
         public void windowClosing(WindowEvent we){
              try{
                   mprfm.close();
                   removePlayer();
              } catch (Exception exception) {
                   exception.printStackTrace();
              frame.dispose();
         private MenuBar createMenuBar(MenuBar bar) throws Exception{
              Menu file = bar.add(new Menu("File"));
              file.add(new MenuItem("Open...")).addActionListener(this);
              mprfm = (MiniPlayerRecentFileMenu) file.add(new MiniPlayerRecentFileMenu(this));
              file.addSeparator();
              file.add(new MenuItem("Exit")).addActionListener(this);
              return bar;
         private URL open() throws Exception{
              JFileChooser fileChooser = new JFileChooser();
              fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
              int option = fileChooser.showOpenDialog(frame);
              if(option == JFileChooser.APPROVE_OPTION)
                   return open(fileChooser.getSelectedFile().getCanonicalPath());
              return null;
         private URL open(String fileName) throws Exception{
              if(fileName == null)
                   return null;
              if(fileName.equals(""))
                   return null;
              File file = new File(fileName);
              if(!file.exists())
                   return null;
              if(file.isDirectory())
                   return null;
              mprfm.update(file.getCanonicalPath());
              return file.toURL();
         private void createPlayer(URL url) throws Exception{
              if(url == null)
                   return;
              removePlayer();
              player = Manager.createPlayer(url);
              player.addControllerListener(this);
              player.start();
         private void removePlayer(){
              if(player == null) return;
              frame.removeAll();
              frame.add(BorderLayout.CENTER, new JLabel(new ImageIcon(imageName)));
              frame.pack();
              player.close();
              player = null;
         private void showThrowableMessage(Throwable throwable){
              String title = (throwable instanceof Error? "Error" : "Exception");
              String message = throwable.toString();
              JOptionPane.showMessageDialog(frame, message, title, JOptionPane.ERROR_MESSAGE);
         static public void main(String[] args) throws Exception{
              new MiniPlayer();
    * @(#)MiniPlayerRecentFileMenu.java     Tiger     2005 May 04
    * Copyright 2005 Ronillo Ang
    * All rights reserved
    package com.yahoo.ron.media;
    import com.yahoo.ron.sql.QueryResult;
    import com.yahoo.ron.sql.OdbcConnector;
    import com.yahoo.ron.sql.OdbcConnection;
    import java.awt.Menu;
    import java.awt.MenuItem;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Stack;
    * @author          Ronillo Ang
    * @version          vm1.5.0-b64
    * A class that stores recently opened file to a database.
    final class MiniPlayerRecentFileMenu extends Menu implements ActionListener{
         private ActionListener actionListener;
         private OdbcConnection odbcConnection;
         MiniPlayerRecentFileMenu(){
              this(null);
         MiniPlayerRecentFileMenu(ActionListener actionListener){
              super("Recent Files");
              try{
                   if(actionListener == null)
                        this.actionListener = this;
                   else
                        this.actionListener = actionListener;
                   odbcConnection = OdbcConnector.getOdbcConnection("RecentMenu");
                   add(new MenuItem("empty"));
                   update();
              } catch (Exception exception) {
                   exception.printStackTrace();
         void update(String fileName){
              String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
              try{
                   String sql = "SELECT [filename] FROM tblfiles WHERE [filename]='" + fileName + "'";
                   QueryResult queryResult = odbcConnection.executeQuery(sql);
                   if(!queryResult.isEmpty()){
                        sql = "DELETE * FROM tblfiles WHERE [filename]='" + fileName + "'";
                        odbcConnection.executeUpdate(sql);
                   sql = "INSERT INTO tblfiles VALUES ('" + extension + "', '" + fileName + "')";
                   int updateCount = odbcConnection.executeUpdate(sql);
                   if(updateCount == 1)
                        update();
              } catch (Exception exception) {
                   exception.printStackTrace();
         private void update(){
              try{
                   int[] counter = {0, 0};
                   QueryResult[] queryResult = {null, null};
                   String sql = "SELECT [filetype] FROM tblfiles";
                   queryResult[0] = odbcConnection.executeQuery(sql);
                   removeAll();
                   Stack stack = new Stack();
                   if(queryResult[0].next())
                        do{
                             String filetype = queryResult[0].getStringAt(0);
                             if(!stack.contains(filetype)){
                                  stack.push(filetype);
                                  sql = "SELECT [filename] FROM tblfiles WHERE [filetype]='" + filetype + "'";
                                  queryResult[1] = odbcConnection.executeQuery(sql);
                                  Menu menu = (Menu) add(new Menu(filetype));
                                  if(queryResult[1].last()){
                                       counter[1] = 0;
                                       do{
                                            String filename = queryResult[1].getStringAt(0);
                                            menu.add(new MenuItem(filename)).addActionListener(actionListener);
                                       while(++counter[1] < 15 && queryResult[1].previous());
                                  else
                                       menu.add(new MenuItem("empty"));
                        while(++counter[0] < 15 && queryResult[0].next());
                   else
                        add(new MenuItem("empty"));
              } catch (Exception exception) {
                   exception.printStackTrace();
         void close() throws Exception{
              odbcConnection.close();
         public void actionPerformed(ActionEvent ae){
    }Make some modification for this program to run.
    Okie! I'll log out na I have to study pa eh, God bless you all and take care!

  • How to catch exception into a String variable ?

    I have a code
    catch(Exception e)
                e.printStackTrace();
                logger.error("\n Exception in method Process"+e.getMessage());
            }when i open log i find
    Exception in method Process null.
    But i get a long error message in the server console !! I think thats coming from e.printStackTrace().
    can i get the error message from e.printStackTrace() into a String variable ?
    I want the first line of that big stacktrace in a String variable.
    How ?

    A trick is to issue e.printStackTrace() against a memory-based output object.
    void      printStackTrace(PrintStream s)
             // Prints this throwable and its backtrace to the specified print stream.
    void      printStackTrace(PrintWriter s)
    //          Prints this throwable and its backtrace to the specified print writer.Edited by: BIJ001 on Oct 5, 2007 8:54 AM

Maybe you are looking for

  • Long running query--- included steps given by Randolf

    Hi, I have done my best to follow Randolf instruction word-by-word and hope to get solution for my problem soon. Sometime back I have posted a thread on this problem then got busy with other stuff and was not able to follow it. Here I am again with s

  • PO Creation after CRM Sales Order Creation

    I am creating a CRM Sales Order and the moment I save the CRM Sales Order, it creates a PO in ECC. I need to find out how PO is getting triggered? When I open the CRM Sales Order it shows a PO already created for this Sales Order. Has anyone face thi

  • Language Chosen but can't get any further

    I am running on a G5 Dual 2GHZ but I am unable to install leopard. I have restart the disk like it tells me too, but then after I choose the language for install process, it says it can't install 10.5 Leopard on this computer. Any suggestions on how

  • Error connecting to database after upgrade P6 R7.0 to P6 R8.2

    Dear friends, could you help me, i have problem with primavera P6, currently we using P6 R7.0 with server client. i have succesfully to installed it at sever and client and database connected too. but after we purchased the new version R8.2, and i ha

  • Please help with these indesign Questions:))

    1. What happens if you hold down the shift key while creating an object using a frame tool? 2. List 3 ways to add new pages to a document. 3. List three ways to navigate a document 4. How do you apply a master page to a document page? 5. How do you s