Catching Java exceptions
Hi,
Could someone please assist with the following:
I have a class which calls a few internal/external methods which perform Oracle database lookups. These methods all throw SQLExceptions which I catch in the calling class.
I only have one 'catch' for the SQLException in my calling class. Is there a way to uniquely identify which method raised the SQLException within this 'catch' which will allow a meaningful error message to be written to a report.
Thank-you in advance
you may use some variables to log what is going on. Like a String in that you write the method you are calling next line. you can access that String in the catch block.
Similar Messages
-
Can Forte' IIOP Client catch Java exceptions?
Hi all,
we are using Forte' IIOP features in IDL Mode, to integrate a Forte' client
and a Java server.
Our configuration is:
- java jdk 1.1.5
- Visigenic VIsibroker 3.1 for Java ORB
- Forte' 3.0.G
Is it possible for the Forte' client to catch a Java exception?
We tried to define an IDL file based on our Java server:
module querye
interface QueryClass
exception MiaSQLException{};
string EseguiQuery(in string query_string) raises
(MiaSQLException);
Using forte' corbagen utility we generated the forte' .pex file:
begin TOOL querye;
forward QueryClass;
class QueryClass inherits from Framework.Object
class MiaSQLException inherits from FrameWork.GenericException
end class;
has public method EseguiQuery(
input query_string : string
) : string;
has property
distributed=(allow=on, override=on, default=on);
end class;
method QueryClass.EseguiQuery(
input query_string : string
) : string
begin
end method;
end querye;
We we tried to import the .pex file in the forte' repository, forte' raise
a Syntax Error.
Any idea?
TIA
Giuseppe Sorce
CSI Piemonte - C.so Unione Sovietica 216 - 10134 Torino - ITALY
tel. +39-011-3168736
fax +39-011-3168212
e-mail [email protected]
url http://www.csi.it
To unsubscribe, email '[email protected]' with
'unsubscribe forte-users' as the body of the message.
Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>I am trying to get Forte to communicate with Orbix (not the web
version) via IIOP. Right now I am trying to set up an Orbix C++
server with Forte being the client. Eventually I will need to
communicate the other way (Forte being the server -- I need to do
both). Right now I cannot get Forte to connect to the server. Any
suggestions would be appreciated.
Thanks in advance,
Dale Boan
Details
I am running Forte on an NT machine and the Orbix server under HP-UX.
Under NT, I am using Forte 3.0.F.2 with IIOP enabled (I think - it
shows up in the partition GUI).Which version of Orbix are you using? I believe 2.3c is required. At least I
know that Forte has successfully called Orbix services using 2.3c.
- Coty -
RE:Can Forte' IIOP Client catch Java exceptions?
you can't have nested classes !!!
Forté does not handle them yet...
try something like this :
module querye
exception MiaSQLException
string error;
interface QueryClass
string EseguiQuery(in string query_string) raises
(MiaSQLException);
Get Your Private, Free Email at http://www.hotmail.com
To unsubscribe, email '[email protected]' with
'unsubscribe forte-users' as the body of the message.
Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>I am trying to get Forte to communicate with Orbix (not the web
version) via IIOP. Right now I am trying to set up an Orbix C++
server with Forte being the client. Eventually I will need to
communicate the other way (Forte being the server -- I need to do
both). Right now I cannot get Forte to connect to the server. Any
suggestions would be appreciated.
Thanks in advance,
Dale Boan
Details
I am running Forte on an NT machine and the Orbix server under HP-UX.
Under NT, I am using Forte 3.0.F.2 with IIOP enabled (I think - it
shows up in the partition GUI).Which version of Orbix are you using? I believe 2.3c is required. At least I
know that Forte has successfully called Orbix services using 2.3c.
- Coty -
Catching the exception thrown in a java class on a JSP front end
I have a web service created in JAVA.. The modules throw certain exceptions and i am having auto generated JSP created from the WSDL's , which i can obviously edit. i want to catch these exceptions in this JSP page.. Any clue how to do this?
Thanks.Nee333 wrote:
I have a web service created in JAVA.. The modules throw certain exceptions and i am having auto generated JSP created from the WSDL's , which i can obviously edit. i want to catch these exceptions in this JSP page.. Any clue how to do this? It is not possible to catch the Exception in a JSP. You can however put any logging or even an if statement into your JSP to display the error or control the flow based on the error. -
Centralized way of catching unexpected Exceptions in Java?
Hi Guys,
Is there a centralized way to catch unexpected Exceptions in Java?
Here's an example:
public static void main(String[] args)
try
new Thread()
public void run()
String s = null;
//NullPointerException is thrown here
s.indexOf(12);
}.start();
catch (Exception ex)
System.err.println("This is not called");
ex.printStackTrace();
}Think about a program error, that the program is not prepared for, i.e. NullPointerException or an ArrayIndexOutOfBounds exception.
What I'm after is not like "put critical block in try-catch", but something like registering a global ExceptionListener in java.lang.Runtime, a monitoring MBean or something that I could use in my program to do a simple exception logging.
Any idea, help would be greatly appreciated!
peterNullPointerException , IOException ....all are subclasses of the base class Exception, so catch(Exception) will catch any exception in the current thread. So modify ur code a bit
public static void main(String[] args)
new Thread()
public void run()
try{
String s = null;
//NullPointerException is thrown here
s.indexOf(12);
catch (Exception ex)
System.err.println("This is not called");
ex.printStackTrace();
}.start();
..... -
Why do I need to catch this exception?
Hello all
This is a question about exception handling. I have to build a diary application that lets you save reminders on particular dates using xml. Just to make it a little tougher, I was not allowed to use the Calendar class. This is the code I wrote:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.text.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import static java.lang.Math.*;
public class CalendarAssignment extends JFrame implements ActionListener
int MonthLength [] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
public JButton [] days = new JButton[43];
private JLabel lbl, reminderlbl;
private JPanel top, grid, remindercenter, reminderbottom;
private JFrame reminderframe;
private JTextField year1, reminderinput, dayno;
private JComboBox months;
private Container container;
private JButton fetch, save, cancel;
private Document doc;
private File file;
private Node node;
private String year, month, day;
public static void main( String[] args ) {
CalendarAssignment c = new CalendarAssignment( );
c.setSize( 400, 300 );
c.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
c.show( );
public CalendarAssignment( ) {
int CurrentYear, CurrentMonth;
String YearString, MonthString, Now;
Date today;
container = getContentPane( );
container.setLayout( new BorderLayout( ) );
SimpleDateFormat DateFormatter;
DateFormatter = new SimpleDateFormat( "MM.yyyy" );
today = new Date( );
Now = DateFormatter.format( today );
MonthString = Now.substring( 0,2 );
YearString = Now.substring( 3,7 );
CurrentMonth = Integer.valueOf( MonthString );
CurrentYear = Integer.valueOf( YearString );
top = new JPanel( );
String [] items = { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November",
"December" };
months = new JComboBox( items );
months.setEditable( false );
months.setSelectedIndex( CurrentMonth - 1 );
year1 = new JTextField( );
year1.setText( YearString );
year1.setEditable( true );
year1.setHorizontalAlignment( year1.CENTER );
fetch = new JButton( "Fetch Month" );
fetch.addActionListener( this );
top.setLayout( new GridLayout( 1, 3, 20, 0 ) );
top.add( months );
top.add( year1 );
top.add( fetch );
grid = new JPanel( );
grid.setLayout( new GridLayout( 7, 7, 0, 0 ) );
String [] week = { "Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun" };
for ( int a = 0; a < 7; a ++ ) {
JLabel lbl = new JLabel( week[a], JLabel.CENTER );
grid.add( lbl );
for ( int i = 0; i < 42; i ++ ) {
days[i] = new JButton( );
grid.add( days[i] );
days.addActionListener( this );
DrawCalendar( CurrentMonth, CurrentYear );
container.add( top, BorderLayout.NORTH );
container.add( grid, BorderLayout.CENTER );
private void DrawCalendar( int SelectMonth, int SelectYear ) {
int DisplayMonthLength, Buttons;
String ButtonID = "";
int OffSet = MonthStart( SelectMonth, SelectYear );
DisplayMonthLength = MonthLength [SelectMonth - 1];
if ( SelectMonth == 2 )
DisplayMonthLength += LeapYear( SelectYear );
for ( Buttons = 1; Buttons < 43; Buttons ++ ) {
if ( ( Buttons <= OffSet ) || ( Buttons > ( DisplayMonthLength + OffSet ) ) ) {
ButtonID = "";
days[Buttons-1].setEnabled( false );
else {
ButtonID = Integer.toString( Buttons - OffSet );
days[Buttons-1].setEnabled( true );
days[Buttons-1].setLabel( ButtonID );
grid.add( days[Buttons-1] );
private int LeapYear( int year ) {
int FourHundred, OneHundred, Fourth;
FourHundred = year % 400;
OneHundred = year % 100;
Fourth = year % 4;
if( ( ( FourHundred == 0 ) ) || ( ( OneHundred != 0 ) && ( Fourth == 0 ) ) )
return ( 1 );
else
return ( 0 );
private int MonthStart( int Month, int Year ) {
int OffSet, LastMonths, BeforeOrAfter, Years;
int AllDays = 0;
int YearDays = 365;
int YearMonths = 12;
BeforeOrAfter = Year - 2006;
Years = abs( BeforeOrAfter );
if( BeforeOrAfter != 0 )
BeforeOrAfter = BeforeOrAfter / Years;
switch( BeforeOrAfter ) {
case 1:
for( int a = 2006; a < Year; a ++ ) {
AllDays += YearDays + LeapYear( a );
AllDays += LastMonthsCalc( Month, Year );
break;
case -1:
for( int a = 2005; a > Year; a -- ) {
AllDays += YearDays + LeapYear( a );
for( LastMonths = YearMonths; LastMonths >= Month; LastMonths -- ) {
AllDays += MonthLength[LastMonths - 1];
if( LastMonths == 2 )
AllDays += LeapYear( Year );
break;
default:
if( Month > 1 )
AllDays += ( LastMonthsCalc( Month, Year ) );
OffSet = AllDays % 7;
if( BeforeOrAfter ==( -1 ) )
return( 6 - OffSet );
else if( OffSet > 0 )
return( OffSet - 1 );
else
return( 6 );
private int LastMonthsCalc( int Month, int Year ) {
int Counter;
int days = 0;
for( Counter = 1; Counter < Month; Counter ++ ) {
days += MonthLength[Counter - 1];
if( Counter == 2 )
days += LeapYear( Year );
return( days );
public void CreateReminder( String buttonID, String yearID, String monthID ) {
reminderframe = new JFrame( );
reminderlbl = new JLabel( );
reminderframe.setLayout( new GridLayout( 2, 1, 0, 0 ) );
remindercenter = new JPanel( );
reminderlbl = new JLabel( "Please type in reminder to be saved for " + buttonID + " " + monthID + " " + yearID + ":", JLabel.CENTER );
reminderinput = new JTextField( 30 );
reminderinput.setHorizontalAlignment( reminderinput.CENTER );
reminderinput.setEditable( true );
remindercenter.setLayout( new GridLayout( 2, 1, 0, 0 ) );
remindercenter.add( reminderlbl );
remindercenter.add( reminderinput );
reminderbottom = new JPanel( );
save = new JButton( "Save" );
save.addActionListener( this );
cancel = new JButton( "Cancel" );
cancel.addActionListener( this );
dayno = new JTextField( buttonID );
dayno.setEditable( false );
dayno.setEnabled( false );
dayno.show( false );
reminderbottom.setLayout( new FlowLayout( ) );
reminderbottom.add( save );
reminderbottom.add( cancel );
reminderbottom.add( dayno );
reminderframe.setSize( 500, 75 );
reminderframe.add( remindercenter );
reminderframe.add( reminderbottom );
reminderframe.pack( );
reminderframe.show( );
public void SaveReminder( String dayID, String yearID, String monthID ) throws Exception {
file = new File( "Diary.xml" );
doc = DocumentBuilderFactory.newInstance( ).newDocumentBuilder( ).parse( file.toURL( ).toString( ) );
String year = yearID;
String month = monthID;
String day = dayID;
//System.out.println( year );
//System.out.println( month );
//System.out.println( day );
CreateEntry( doc.getDocumentElement( ) );
writeXmlFile( );
public boolean CreateEntry( Node node ) {
Node searchNode;
searchNode = getYear( node );
if( searchNode == null ) {
Element newNode = doc.createElement( "Year" );
searchNode = node.appendChild( newNode );
newNode.setAttribute( "Id", year );
node = searchNode;
searchNode = getMonth( node );
if( searchNode == null ) {
Element newNode = doc.createElement( "Month" );
searchNode = node.appendChild( newNode );
newNode.setAttribute( "Id", month );
node = searchNode;
searchNode = getDay( node );
if( searchNode == null ) {
Element newNode = doc.createElement( "Day" );
searchNode = node.appendChild( newNode );
newNode.setAttribute( "Id", day );
node = searchNode;
String entry = reminderinput.getText( );
Node textNode = doc.createTextNode( entry );
node.appendChild( textNode );
return true;
private Node getYear( Node node ) {
node = node.getFirstChild( );
while( node != null ) {
if(node.getNodeName( ).equals( "Year" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == year )
return node;
node = node.getNextSibling( );
return null;
private Node getMonth( Node node ) {
node = node.getFirstChild( );
while( node != null ) {
if( node.getNodeName( ).equals( "Month" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == month )
return node;
node = node.getNextSibling( );
return null;
private Node getDay( Node node ) {
node = node.getFirstChild( );
while( node != null ) {
if( node.getNodeName( ).equals( "Day" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == day )
return node;
node = node.getNextSibling( );
return null;
private void writeXmlFile( ) throws Exception {
Source source = new DOMSource( doc );
Result result = new StreamResult( file );
Transformer xformer = TransformerFactory.newInstance( ).newTransformer( );
xformer.setOutputProperty( OutputKeys.INDENT,"yes" );
xformer.setOutputProperty( OutputKeys.DOCTYPE_SYSTEM,"Diary.dtd" );
xformer.transform( source, result );
public void actionPerformed( ActionEvent e ) {
String IDButton = e.getActionCommand( );
String IDYear = year1.getText( );
Object IDMonthObj = months.getSelectedItem( );
if( e.getSource( ) == fetch ) {
String YearText = year1.getText( );
int YearNumber = Integer.valueOf( YearText );
int MonthsIndex = months.getSelectedIndex( ) + 1;
DrawCalendar( MonthsIndex, YearNumber );
else if( e.getSource( ) == cancel ) {
reminderframe.hide( );
else if( e.getSource( ) == save ) {
String IDDay = dayno.getText( );
String IDMonth = String.valueOf( IDMonthObj );
SaveReminder( IDDay, IDYear, IDMonth );
else {
String IDMonth = String.valueOf( IDMonthObj );
Toolkit.getDefaultToolkit( ).beep( );
int n = JOptionPane.showConfirmDialog( null, "Set reminder on this date?", "Question", JOptionPane.YES_NO_OPTION );
if( n == JOptionPane.YES_OPTION ) {
CreateReminder( IDButton, IDYear, IDMonth );
If you compile it, you will realise that I get an error about exception handling. My lecturer gave me an example code of how to do the same thing without using a GUI:
import javax.xml.parsers.*;
import org.xml.sax.*;
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
public class CallDOM
Document doc;
File file;
Scanner input;
int year, month, day;
String currentYear, currentMonth;
public static void main(String args[]) throws Exception
CallDOM cd=new CallDOM();
CallDOM() throws Exception
file=new File("Diary.xml");
//create DOM from file
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file.toURL().toString());
input=new Scanner(System.in);
System.out.println("1) Create entry");
System.out.println("2) Read entry");
System.out.println("3) Show Diary");
System.out.println("4) Quit");
int choice=input.nextInt();
while(choice!=4)
switch(choice)
case 1: GetDate();CreateEntry(doc.getDocumentElement());break;
case 2: GetDate();ReadEntry(doc.getDocumentElement());break;
case 3: ShowDiary(doc.getDocumentElement());
System.out.println("1) Create entry");
System.out.println("2) Read entry");
System.out.println("3) Show Diary");
System.out.println("4) Quit");
choice=input.nextInt();
writeXmlFile();
public void GetDate()
System.out.println("Enter date (dd mm yyyy)");
day=input.nextInt();
month=input.nextInt();
year=input.nextInt();
public boolean ReadEntry(Node node)
node = getYear(node);
if(node==null) return false;
node = getMonth(node);
if(node==null) return false;
node = getDay(node);
if(node==null) return false;
node = node.getFirstChild();
while(node!=null)
System.out.println(node.getNodeValue().trim());
node=node.getNextSibling();
return true;
public boolean CreateEntry(Node node)
Node searchNode;
searchNode = getYear(node);
if(searchNode==null)
Element newNode = doc.createElement("Year");
searchNode = node.appendChild(newNode);
newNode.setAttribute("Id",Integer.toString(year));
node = searchNode;
searchNode = getMonth(node);
if(searchNode==null)
Element newNode = doc.createElement("Month");
searchNode = node.appendChild(newNode);
newNode.setAttribute("Id",Integer.toString(month));
node = searchNode;
searchNode = getDay(node);
if(searchNode==null)
Element newNode = doc.createElement("Day");
searchNode = node.appendChild(newNode);
newNode.setAttribute("Id",Integer.toString(day));
node = searchNode;
System.out.println("Enter Text");
String entry=input.next();
entry+=input.nextLine();
Node textNode = doc.createTextNode(entry);
node.appendChild(textNode);
return true;
public void ShowDiary(Node node)
Stack<Node> stack=new Stack<Node>();
Node child;
stack.push(node);
while(!stack.empty())
node = stack.pop();
if(ProcessNode(node))
child = node.getLastChild();
while(child!=null)
stack.push(child);
child = child.getPreviousSibling();
private boolean ProcessNode(Node node)
if(node.getNodeName().equals("Year"))
currentYear=node.getAttributes().item(0).getNodeValue();
if(node.getNodeName().equals("Month"))
currentMonth=node.getAttributes().item(0).getNodeValue();
if(node.getNodeName().equals("Day"))
System.out.print(node.getAttributes().item(0).getNodeValue()+"/"+
currentMonth+"/"+currentYear+": ");
node=node.getFirstChild();
while(node!=null)
System.out.println(node.getNodeValue().trim());
node=node.getNextSibling();
return false;
return true;
private Node getYear(Node node)
node=node.getFirstChild();
while(node!=null)
if(node.getNodeName().equals("Year")
&& Integer.valueOf(node.getAttributes().item(0).getNodeValue())==year)
return node;
node = node.getNextSibling();
return null;
private Node getMonth(Node node)
node=node.getFirstChild();
while(node!=null)
if(node.getNodeName().equals("Month")
&& Integer.valueOf(node.getAttributes().item(0).getNodeValue())==month)
return node;
node = node.getNextSibling();
return null;
private Node getDay(Node node)
node=node.getFirstChild();
while(node!=null)
if(node.getNodeName().equals("Day")
&& Integer.valueOf(node.getAttributes().item(0).getNodeValue())==day)
return node;
node = node.getNextSibling();
return null;
private void writeXmlFile() throws Exception
Source source = new DOMSource(doc);
Result result = new StreamResult(file);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(OutputKeys.INDENT,"yes");
xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"Diary.dtd");
xformer.transform(source, result);
}My question is, why does the exceptions in the example code not need to be caught? And why do I have to catch the exceptions in my code? Several exceptions are thrown in the example code, but there is no catch statement.
Thanks for any advice!!Since your question didn't come with any relevant details, and since you have huge steaming piles of irrelevant code, all I can give is a general answer to "Why do I need to catch this exception?"
[url http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html]Exception tutorial at http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html
Here's a quick overview of exceptions:
The base class for all exceptions is Throwable. Java provides Exception and Error that extend Throwable. RuntimeException (and many others) extend Exception.
RuntimeException and its descendants, and Error and its descendants, are called unchecked exceptions. Everything else is a checked exception.
If your method, or any method it calls, can throw a checked exception, then your method must either catch that exception, or declare that your method throws that exception. This way, when I call your method, I know at compile time what can possibly go wrong and I can decide whether to handle it or just bubble it up to my caller. Catching a given exception also catches all that exception's descendants. Declaring that you throw a given exception means that you might throw that exception or any of its descendants.
Unchecked exceptions (RuntimeException, Error, and their descendants) are not subject to those restrictions. Any method can throw any unchecked exception at any time without declaring it. This is because unchecked exceptions are either the sign of a coding error (RuntimeException), which is totally preventable and should be fixed rather than handled by the code that encounters it, or a problem in the VM, which in general can not be predicted or handled. -
"ORA-29532: Java call terminated by uncaught Java exception
Dear Oracle:
I am trying to establish an HTTPS connection from a Java stored
procedure that is wrapped in a PL/SQL procedure and loaded into a
Package. We are running on Oracle 8.1.7.
My Java code compiles and runs fine when run stand-alone outside
Oracle; I can establish the connection to a secure server and talk to
the server. However when I load this Java class (using the loadjava
utility) this class can no longer run and I get a the following
exception:
"ORA-29532: Java call terminated by uncaught Java exception:
javax.net.ssl.SSLException: SSL handshake failed:
X509CertChainIncompleteErr"
I have tried loading the JSSE from Sun and I still get the same error.
Searching in the Discussing Forums I found the following link (which
describes a procedure that logs into the UPS secure server site and
grabs some XML) http://osi.oracle.com/~mbpierma/SSL_Java_DB.html .
This code works ok if we try to connect to UPS server. However this
code doesn't work if we try to log in to a different server (such as
???). If I modify this code slightly and try to log to any other
sever server I get the same error as the one above. Investigation
lead us to understand that the certificate at the UPS web site is a
self-signed certificate -- not one generated by a major 'recognized'
authority such as Verisign or Thawte.
Further research pointed me to the following URL
http://www.znow.com/sales/oracle/network.816/a76932/appf_ora.htm#619367
This URL has the documentation for JAVA SSL for 8.1.6 which I figure
I could read and try to make it work in 8.1.7.
I looked at your Secure Hello World example, however the code is
missing the most critical parts of the whole example, it does not
specify where the certificate or any of the security settings come
from (see the attached JavaCertExample.txt file).
So, my questions are the following:
1) What should I do to avoid the error mentioned above?
2) Do you have a sample piece of code that describes how to make a
HTTPS connection using a Java stored procedure?
3) Can I make the HTTPS connection using a URL class and not using
sockets directly?
4) Do I need to load the JSEE provided by Sun?
5) Will the solution be different for Oracle 9i?
// SecureHelloClient.java
import java.net.*;
import java.io.*;
import java.util.*;
import javax.net.ssl.*;
import javax.security.cert.X509Certificate;
import oracle.security.ssl.OracleSSLCredential;
import oracle.security.ssl.OracleSSLSocketFactory;
import oracle.security.ssl.OracleSSLProtocolVersion;
import oracle.security.ssl.OracleSSLSession;
public class SecureHelloClient
public static void main(String argv[])
String hostName = "localhost";
if(argv.length != 0)
String hostName = argv[0];
// Set the SSLSocketFactoryImpl class as follows:
java.util.Properties prop = System.getProperties();
prop.put("SSLSocketFactoryImplClass",
"oracle.security.ssl.OracleSSLSocketFactoryImpl");
try
// Get the default socket factory
OracleSSLSocketFactory sSocFactory
= (OracleSSLSocketFactory)SSLSocketFactory.getDefault();
sSocFactory.setSSLProtocolVersion(OracleSSLProtocolVersion.SSL_Version_3_0);
OracleSSLCredential sslCredObj = new OracleSSLCredential();
// Where did these values come from? caCert, userCert, trustedCert,
// Set the certificate chain and private key if the
// server requires client authentication
sslCredObj.addCertChain(caCert)
sslCredObj.addCertchain(userCert)
sslCredObj.setPrivateKey(userPvtKey, userPassword)
// Populate credential object
sslCredObj.addTrustedCert(trustedCert);
sSocFactory.setSSLCredentials(sslCredObj);
// Create the socket using factory
SSLSocket jsslSoc =
(SSLSocket)sSocFactory.createSocket(hostName, 8443);
String [] ciphers = jsslSoc.getSupportedCipherSuites() ;
// Select the ciphers you want and put them.
// Here we will put all availabel ciphers
jsslSoc.setEnabledCipherSuites(ciphers);
// We are creating socket in client mode
jsslSoc.setUseClientMode(true);
// Do SSL handshake
jsslSoc.startHandshake();
// Print negotiated cipher
System.out.println("Negotiated Cipher Suite: "
+jsslSoc.getSession().getCipherSuite());
System.out.println("");
X509Certificate[] peerCerts
= ((javax.net.ssl.SSLSocket)jsslSoc).getSession().getPeerCertificateChain();
if (peerCerts != null)
System.out.println("Printing server information:");
for(int i =0; i ? peerCerts.length; i++)
System.out.println("Peer Certificate ["+i+"] Information:");
System.out.println("- Subject: " + peerCerts.getSubjectDN().getName());
System.out.println("- Issuer: " + peerCerts[i].getIssuerDN().getName());
System.out.println("- Version: " + peerCerts[i].getVersion());
System.out.println("- Start Time: " + peerCerts[i].getNotBefore().toString());
System.out.println("- End Time: " + peerCerts[i].getNotAfter().toString());
System.out.println("- Signature Algorithm: " + peerCerts[i].getSigAlgName());
System.out.println("- Serial Number: " + peerCerts[i].getSerialNumber());
else
System.out.println("Failed to get peer certificates");
// Now do data exchange with client
OutputStream out = jsslSoc.getOutputStream();
InputStream in = jsslSoc.getInputStream();
String inputLine, outputLine;
byte [] msg = new byte[1024];
outputLine = "HELLO";
out.write(outputLine.getBytes());
int readLen = in.read(msg, 0, msg.length);
if(readLen > 0)
inputLine = new String(msg, 0, readLen);
System.out.println("");
System.out.println("Server Message:");
System.out.println(inputLine );
else
System.out.println("Can't read data from client");
// Close all sockets and streams
out.close();
in.close();
jsslSoc.close();
catch(SSLException e)
System.out.println("SSL exception caught:");
e.printStackTrace();
catch(IOException e)
System.out.println("IO exception caught:");
e.printStackTrace();
catch(Exception e)
System.out.println("Exception caught:");
e.printStackTrace();Hi,
I have the same problem.
Is some ORACLE guru that can help us ?
We need to communicate with some servlet
via POST method of https (SSL3)
and with using private certificate on the client site.
We need furthermore allow using of some proxy.
Client site is realized as set of stored procedures within ORACLE 8.1.7
In this time I am able to communicate with server without SSL and certificate
using package utl_tcp
(but with this solution without certificate is our customer not satisfied -:))
ORACLE help us please !
Pavel Pospisil
[email protected] -
Best Practice: JavaFX pattern for "Catching all Exceptions"
Hi,
what is on the current JavaFX Standard the best way to catch all Exceptions (centralized) within my JavaFX application...
I read thread outside this Oracle Forum who recommend following:
1. Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
--> catch all runtime exceptions
2. http://stackoverflow.com/questions/12318861/javafx-2-catching-all-runtime-exceptions
--> Implementing some source code who wrap the current GUI thread...
3. I read something like:
"JavaFX exception handling is almost identical to that in Java, apart from the fact that checked exceptions are handled in the same way as unchecked exceptions. This is good news for most Java programmers moving to JavaFX because you are no longer obliged to catch and handle exceptions."
Sounds very good! But where/how can I do this ???
Edited by: wschele on 19.02.2013 04:58
Edited by: wschele on 19.02.2013 05:16No recommendation whats the best way to do it?
Catching each Exception in different layers is boring ! :-( -
How to get details about Exception catched in Exception branch of the Block
Hello Experts,
Is it possible to get details about Exception catched in Exception branch of the Block in Integration Process (BPM)?
In the Exception branch System Error is catched, but from time to time different type of System Errors are happening during sync call to WebService - Connection Timeout, Connection Refused, UnknownHost, etc.
So the task is somehow to map the type of System Error to the response. I was trying to create a mapping using as source the message which is coming from the Adapter after the sync call, but the mapping is failing with "No Source Payload" error.
Maybe the description is somewhere in Header or Dynamic configuration?
Or it is possible to access it somehow with JAVA-maping?
Thanks for your help!Hey,
the message from the exception can be utilized by using alerts(in order to mail,sms r fax). but otherwise its not possible using mappings or container.
check this link for alert configuration.
/people/michal.krawczyk2/blog/2005/09/09/xi-alerts--step-by-step -
Catching an exception in an JSF page
Hi,
I have made the following example:
In my jsf page I have:
<a4j:commandButton id="save" action="#{settings.save}"
reRender="attributes" />
<h:outputLabel value="Save" for="save" />
<table width="100%" cellpadding="0" cellspacing="0">
<!--
<tr>
<td> If exception occurs add extra buttons here for more actions
</td>
</tr>
-->
<tr>
<td><ui:include src="/attributes.xhtml">
<ui:param name="parent" value="#{settings}" />
</ui:include></td>
</tr>
</table>
In SettingsBean.java
public void save() throws exception
try
doSomething();
catch(Exception e)
// catch the exception here and send it back to the jsf page????
I want to be able to catch the exception when it occurs in my jsf page. If the exception arrises I want to add some extra buttons.
Any ideas how to resolve this?
Thanks in advanceJSF does not work like JSP, even when using JSP with JSF, in that the execution is decoupled from the page being processed. So you cannot catch exceptions in JSF views.
Assuming I have sufficiently confused you now, let me give you some ideas as to how to handle your situation. The usual way this is handled is to register a message when an exception occurs which are then displayed by <h:messages> or <h:message> components.
However, this does not appear to be suitable for your purpose as you require specialized output when the exception occurs. So you could store a flag (or even the exception itself) in a backing bean and use the rendered property of all components to conditionally display your buttons. BUT you will need to take care that the dynamic value of the rendered property will be the same on the subsequent request or the actions for the buttons will not be queued. -
Catching an exception (help)!!!
Hi everyone, the problem i have is when the user enters a number that is out of bounds (higher or lower than the excepted values it should prompt the program to write to the screen "out of range, try again" or something along those lines.
However, it instead just prints "error - program terminated" which is the message that should be printed when there is a different problem within the program.
Can anyone help me get the program to print the correct messages, you can see what i mean from the code:
import java.io.*;
import java.util.ArrayList;
public class FlatCost {
ArrayList floors = new ArrayList();
public FlatCost(String filename) {
try {
readDataFromFile(filename);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int floor;
int rooms;
String another = "y";
while(another.equalsIgnoreCase("y")) {
System.out.print("\nEnter floor number (0 for ground): ");
floor = Integer.parseInt(in.readLine());
if(floor < 0 || floor > floors.size()) {
System.out.println("floor out of range, try again");
else {
System.out.print("\nEnter no. rooms: ");
rooms = Integer.parseInt(in.readLine());
if(rooms < 0 || rooms > ((String[])floors.get(floor)).length) {
System.out.println("rooms out of range, try again");
else {
System.out.println("\nThe cost of a "+rooms+"-room flat on floor "+floor+" is "+
((String[])floors.get(floor))[rooms+1]+" per month");
System.out.print("\nAnother? (y/n): ");
another = in.readLine();
catch(Exception e){
System.out.println("error - program terminated");
public void readDataFromFile(String filename)throws Exception {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line = "";
while((line = br.readLine()) != null)
floors.add(line.split(" "));
br.close();
public static void main(String args[])throws IOException{
new FlatCost(args[0]);
}any help is appreciated
thanks
Sarah xI barely know where to begin.
Start by printing out the stack trace when you catch an exception. That'll give you more information than the message you're printing out. You know the program is terminating - you need to know why.
You're writing in a VERY procedural style. There's little or nothing object-oriented about what you're doing.
You've got a bunch of stuff in that constructor that really doesn't belong there. You shouldn't have code to continuously ask a client for a floor and room number in a constructor. That really belongs in an application that drives the object, like the main method that you wrote.
Your FlatCost can read in a file that contains floor/room/price information, but if I were writing the application I'd read it in and store it in the ArrayList as you've done. Then I'd have a getCost() method that would take floor and room count as parameters and return the total cost.
Learning how to program is learning how to debug. I'd rewrite things a little bit and put System.out.println() statements into the code to narrow down exactly where the error was occurring and why. It won't take you long to figure it out. You don't even need a fancy debugger or IDE. -
Catching an exception thrown from another thread
I have a SocketServer that creates new threads to handle incoming clients. If one of the threads throw a SQLException is it possible to catch that exception in the SocketServer that created that thread.
I tried implementing this code and I cannot get the server to catch an exception thrown in the thread. Are my assumptions correct?
I was reading something about Thread Groups and implementing an uncoughtException() method, but this looked like overkill.
Thanks for your time!
Some Example code would be the following where the ClientThread will do a database query which could cause an SQLException. I'd like to catch that exception in my Socket Server
try
new ClientThread( socketServer.accept() , host, connection ).start();
catch( SQLException e )
System.out.println( "DataSource Connection Problem" );
e.printStackTrace();
}hehe, why?
The server's job is to listen for an incoming message from a client and pass it off to a thread to handle the client. Otherwise the server will have to block on that incoming port untill it has finished handling the client and usually there are many incoming clients continuously.
The reason I would want to catch an exception in the server based on the SQLException thrown in the thread is because the SQLException is usually going to be due to the fact the datasource connection has become unavalable, or needs to be refreshed. This datasource connection is a private variable stored in the socket server. The SocketServer now needs to know that it has to refresh that datasource connection. I would normally try to use somesort of flag to set the variable but to throw another wrench into my dilemma, the SocketServer is actually its own thread. So I can't make any of these variables static, which means I can't have the thread call a method on teh socket server to change the status flag. :)
I guess I need implement some sort of Listener that the thread can notify when a datasource connection goes down?
Thanks for the help so far, I figured java would not want one thread to catch another thread's exceptions, but I just wanted to make sure. -
Write and read txt files and catch the exceptions
hey everyone, im in a bit of a bind. im trying to set up this try catch statement. here is what i have for code so far.
import java.util.Scanner;
import java.io.*;
public class Warning
// Reads student data (name, semester hours, quality points) from a
// text file, computes the GPA, then writes data to another file
// if the student is placed on academic warning.
public static void main (String[] args)
int creditHrs; // number of semester hours earned
double qualityPts; // number of quality points earned
double gpa; // grade point (quality point) average
String line, name, inputName = "students.dat";
String outputName = "warning.dat";
try
Scanner FileScan1 = new Scanner (new File("students.dat"));
// Set up scanner to input file
// Set up the output file stream
// Print a header to the output file
outFile.println ();
outFile.println ("Students on Academic Warning");
outFile.println ();
// Process the input file, one token at a time
while (FileScan1.hasNext())//there is another line...
{ // Get the credit hours and quality points and
// determine if the student is on warning. If so,
// write the student data to the output file.
// Close output file
catch (FileNotFoundException exception)
System.out.println ("The file " + inputName + " was not found.");
catch (IOException exception)
System.out.println (exception);
catch (NumberFormatException e)
System.out.println ("Format error in input file: " + e);
}I am pretty sure the layout is good to go, but first and foremost that try statement is hanging me up. Could someone give me some suggestions about how i should set this up.
i want to read in this students.dat file, then output another file called warning.dat.
Thanks i really appreicate the help.no, i was really hoping to just see if the way it is
set up it will be doable, that way i wouldn't be
working on code that was impossiable to sort through
properlyFair enough.
One thing I'd suggest is that if you're really basically only going to be printing the exceptions, and since that is the top-level method (main) --
I'd instead just add some "throws" clauses to main, get rid of the try/catch stuff, and just let the VM handle the exceptions for you. It will print them, just like you're doing, except that it will also print the stack traces, which you are not doing.
If you're going to handle exceptions, it's better to actually do something about them rather than just print them - otherwise you might just as well let the runtime do that for you. -
FRM-92100 Java Exception (jacob)
I'm using Jacob to load specific parts of Office documents into an Oracle database. This works successfully in 99.9% of cases although some users experience intermittent problems which can't be pinned down to a particilar office document and appear to be totally random. The error message indicates that the exception occurs when trying to close the Word session down.
The error message is as follows:
FRM-92100: Your connection to the Server was interrupted.
Details:
Java Exception:
com.jacob.com.ComFailException: A COM exception has been encountered:
At invoke of: Quit
Description: Not enough storage is available to complete this operation.
I have seen several references to the 92100 catch all error code but none that tie in with this description.
Could anyone point me in the right direction as to what's causing this error? My first assumption would be the RAM available on the users PC at time of transfer but can't pin this down.
Many thanks.I think that fix for bug 5375851 has resolved the problem mentioned and hence this shall be of help.
Thanks,
Message was edited by:
user482823 -
Advantage of Java Exceptions over C error handling.
I understand the advantages of Java Exception handling(as against C) when it comes to the ability to define exclusive Exception types or reuse exceptions, documentation benefits of the throws clause, advantages due to OO etc. But some people say that using exceptions in Java it is possible to recover from an exceptional condition and that's an advantage over how errors are dealt in C.
Is that really an advantage? (I mean is that true?)AFAIK in C errors can be handled using perror or errno.h. For every error code generated there seems to be a description. And by checking the return values from functions we could see if there had been an exceptional condition and if there really had been one take appropriate action and recover from the error. So how is it that Java can recover from exceptions while in C it is not possible to recover from errors?
Thank you very much.I'm waiting in my cold cell when the bell begins to chime
Reflecting on my past life and it doesn't have much time
Cos at 5 o'clock they take me to the Gallows Pole
The sands of time for me are running low
When the priest comes to read me the last rites
I take a look through the bars at the last sights
Of a world that has gone very wrong for me
Can it be there's some sort of error
Hard to stop the surmounting terror
Is it really the end not some crazy dream
Somebody please tell me that I'm dreaming
It's not so easy to stop from screaming
But words escape me when I try to speak
Tears they flow but why am I crying
After all I am not afraid of dying
Don't believe that there is never an end
As the guards march me out to the courtyard
Someone calls from a cell "God be with you"
If there's a God then why has he let me die?
As I walk all my life drifts before me
And though the end is near I'm not sorry
Catch my soul cos it's willing to fly away
Mark my words please believe my soul lives on
Please don't worry now that I have gone
I've gone beyond to see the truth
When you know that your time is close at hand
maybe then you'll begin to understand
Life down there is just a strange illusion.
Yeah, yeah, yeah, Hallowed be thy name
Yeah, yeah, yeah, Hallowed be thy name
Maybe you are looking for
-
RMBP CUDA Playback Serious Issues/Glitches
Just purchased a new rMBP and am running Premiere 6.0.2 and with CUDA 5.0.45 installed. Here are the system specs: - 756gb SSD - 2.7 GHz Intel Core i7 - 16 GB Ram - NVIDIA GeForce GT 650M 1024 MB - OS X 10.8.3 I'm experiencing serious playback issue
-
Error in "Download a pdf" question
Sorry. In haste my question said "download". I can download pdfs OK. It is when I try to COPY to Desktop that the refusal occurs because of space. I have 200G space on C:\. Please advise.
-
How we create Schema group for every vendor?
If we have multiple vendors/transporters, how you configure pricing procedure for each vendor what is the process of creating Schema group for every vendor? Thanks in advance Suresh
-
It says the Add On Compatibility Reporter no longer works and I think this might be the problem. When I click to open my MAFF file, it asks would i like to open it with Firefox, I click open and then another tab opens asking me the same question. Wha
-
PC crash during update of iPod
I have an iPod touch 3G that I received for Christmas 2009 that I had connected to my PC (Windows XP Pro) for re-syncing files and was notified of an update to the iPod software. I started the download and during the update process my PC overheated a