Validate Password
This may sound trivial but here is what I want to do:
1. when I create a user in htmldb, I assign a password = first name,
2. I have a page where user can change his password using
htmldb_util.change_current_user_pw procedure.
Now, I would like to force the user to change the password after first login.
How do I validate the password? Is creating a conditional branching the right
way to forward the user to the password change page if it eqals first name?
Thanks in advance,
Denes Kubicek
Sorry for the misleading terminology from my side. It was late in the evening yesterday.
I followed your proposal on creating a page process instead of
branching and making it conditional. Here is what I came up with:
1. created an item that will hold the conditional value for the application process
2. created a process
BEGIN
IF htmldb_util.is_login_password_valid
(:app_user,
LOWER (htmldb_util.get_first_name (:app_user)
THEN
:p1_password_check := 2;
owa_util.redirect_url('f?p=&APP_ID.:102:&SESSION.:::::');
ELSE
:p1_password_check := 1;
END IF;
END;
3. Created a condition to fire the process only:
IF :p1_password_check IS NULL
AND NVL (v ('APP_USER'), 'nobody') NOT IN
('HTMLDB_PUBLIC_USER', 'nobody')
THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
This solution works as expected. Thanks again for your hints.
Denes Kubicek
Similar Messages
-
Re-Validate password every day?
Not too long after replacing an old Sbs2003/Exchange2003 server with a new Sbs2008/Exchange2007 server all of my blackberry users started getting the validate password message below. Please note that with the current account settings all blackberries worked fine on the old server with Exchange 2003 and for at time seemed to on the new server with Exchange 2007.
“Validate the password for [email protected] in the BlackBerry Internet Service! Email messages from [email protected] are not being delivered to your BlackBerry device. To resume receiving email messages from this email address, validate the password for [email protected] in the BlackBerry Internet Service:”
When they try to revalidate their password they get the “your password is invalid” error. Now if I manually restart all internet services on my Sbs2008/Exchange2007 server they can then go back to BIS and revalidate their password and everything works fine for a few hours then this process starts all over again. I have read on the forms that Exchange 2007 and 2010 have changed the way users authenticate through OWA. Is this the reason? Is there a fix forthcoming from BB or do we dump the blackberries?
Any help or advice is appreciated but keep in mind I’m just an Engineer who was dump enough to fix a computer once so keep it simple.welcome to the BT community forum where customers help customers and only BT employees are the forum mods
I moved your post to avoid the replies getting confused with other post originator
the hh3 normally works ok so better to have a look to see if you can improve that before trying a new router
in order for the forum members to help please can you post the adsl stats from your router you may need to 'show detail' to get all stats (if hub enter 192.168.1.254 in your browser and navigate to adsl or if HH4/5 then go to troubleshooting then logs and you are looking for 2 line together when hub last connected to internet and they will show your connection speed and noise margin or if netgear enter 192.168.0.1). Then run btspeedtester (MAC users may have problems). when first test completes then run diagnostic test and post the results ( do not reset the router).
are you connected directly via a filter to the NTE5 master or test socket or to somewhere else? Is the master the only phone socket in your home?
Have you tried the quiet line test? - dial 17070 option 2 - should hear nothing - best done with a corded phone. if cordless phone you may hear a 'dull hum' which is normal
Someone may then be able to offer help/assistance/suggestions to your problem
If you like a post, or want to say thanks for a helpful answer, please click on the Ratings star on the left-hand side of the post.
If someone answers your question correctly please let other members know by clicking on ’Mark as Accepted Solution’. -
How to validate password using LDAP using client script JSOM
Hi All,
I have a requirement in my sharepoint 2013 project. I need to force user to signature digitally by reentering his password so that the system will validate his user name and password. If its validated user can access that document.
For this, can we use any JSOM funnctions to access LDAP and validate the password ? Can anyone help with possible approaches I can take for achieving this functionality ?
Thanks in advance.
Regards
NimishaHi Nimisha,
Thanks. Got your requirement, if you validate user credentials using client side script, it can be security breach. Because the password can be accessible by other user.
I would suggest you to go with server side.
Still you would like to go with client side script please refer the below link
http://sharepoint.stackexchange.com/questions/79803/how-to-authenticate-user-in-sharepoint-online-using-javascript
Sekar - Our life is short, so help others to grow
Whenever you see a reply and if you think is helpful, click "Vote As Helpful"! And whenever you
see a reply being an answer to the question of the thread, click "Mark As Answer -
Hi there,
I am trying to build a custom user login (LabVIEW 6.1) for TestStand2.0. I am trying to validate the user password. I am using a reference from the TS.IEngine and about every other time I run it I get the following error:
Microsoft Visual C++ Runtime Library
Runtime Error!
Program:...ogram Files\National Instruments\LabVIEW 6.1\LabVIEW.exe
R6025
-pure virtual function call
I have attached the vi to see if you get the same error. Also, I have not been able to get the function to successfully return a true for validated password.
Thanks,
Kevin
Attachments:
TestStand_-_Check_User_Name_and_Password_Error.vi 22 KBNemo,
Thanks for the reply. This is not exactly what I needed but your comments really helped a lot!! (especially regarding obtain the Engine Reference from the sequence context---missed that one I thought I could just open a new reference to the TestStand Engine but as it turns out (not quite sure yet why...ActiveX rules I sure but I do not know them all yet one can simply open the reference and use it. I actually thought I was doing something similar to what the LV TestStand Operator Interface does, which is open a reference and then start using it...bad assumption! So, long story short, When I place this vi in a TS sequence (remove the garbage) and run it, it works how I want it to. So thanks again for the advice.
Kevin -
HELP- my blackbery wont receive emails and wont let me validate password or email address
Hi
Not sure if in the right forum,but having major problems with my blackberry.I had a message to say i needed to validate email address and password which i did and keep doing and it just keeps coming up with invalid email address and password and i dont know why because i havent changed anything.I then thought if i deleted email address etc off phone and try and re add it again it would work but it still doesnt an still says invalidated. i just dont know what to do because that was the main reason to get a blackberry so i could get my emails.im really annoyed this has happened. So if anyone could help or have any ideas id so appreciate it.Try setting a new password on your email account and then try to re-add it to BIS on your BlackBerry. If that doesn't work, you can add the email via your PC. If you tell us what email service you're using (i.e. Yahoo!, GMail, etc.) and who your wireless service provider is we can give you more information.
1. Please thank those who help you by clicking the "Like" button at the bottom of the post that helped you.
2. If your issue has been solved, please resolve it by marking the post "Solution?" which solved it for you! -
Af:validateRegExp fails to validate password
I use a af:validateRegExp in a change password page to validate new password is strong enough.
I have the regular expression pattern like this: ^.*(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$
But it fails almost valid inputs, for example:
123qweASD
1qA
abC123
I've validate the pattern in http://www.regular-expressions.info/javascriptexample.html
the values above should be valid.
Is it a bug of the af:validateRegExp?
I am using JDeveloper 11.1.1.2 with ADF BC
Thanks,
Samson FuHi John,
Thanks for your suggestion,
I want the regular expression enforces the following rule:
- Must contain at least one lower case letter, one upper case letter and one digit
Regards,
Samson Fu -
How to validate password of the AD that was recorded in database?
Hello,
It forgives for my English who was translated by google...
It would like to know two information on the AD.
First,it has as to record the password of the AD in database.
Second, as I make to validate through my application for this password. I have that to use some function of criptografy?
Thanks.
CiprianoRefer to the answer in a previous post (several posts below yours !).
http://forum.java.sun.com/thread.jspa?threadID=704364&tstart=0 -
Authentication with hashed password
Hi,
the user passwords in my iPlanet 5.1 are stored by using SHA. I authenticate a user from a JBoss AppServer by using an LDAPLoginModule which works fine.
Now I want to secure this access by no longer sending the clear text password over the network. Instead I configured my JBoss-LoginModule to hash the password by using "SHA-1" before accessing the LDAP server. But now the authentication fails.
ERROR [LdapLoginModule] Failed to validate password
javax.naming.AuthenticationException: [LDAP: error code 49 - Invalid Credentials
Do I have to configure something in the iPlanet before I can access it with a password that is already hashed?
Does iPlanet recognize that the sent password is already hashed? Maybe it tries to hash the password again before checking?
Andreas
As far as my experience with this has gone, the simple answer is no. You'll have to enter it in cleartext.
The most used methodology is to create some kind of standard password to send for each new account, and make it mandatory to change it as soon as the user logs on for the first time. I don't know any other way to do this.
- Mark -
Hi Friends,
I have five passwords in my ztable.
Now my requirement is to validate password, if i enter a password ,then it should not accept the previous five passwords which are in my ztable.
i tried with concatenation, but it is not working properly.
whether I need to compare each password independently or is there any other way.
Could any one plase help me with piece of code.
Thanks in advance.
Regads,
kumar.Hi,
U can use
SELECT *
FORM ztable
WHERE PASS = <NEW_PASS>.
IF sy-subrc = 0.
MESSAGE 'Password already Present.' type 'E'.
ENDIF -
Changing password logic - old password, new password, retype password
I have a MainFrame class which has a Change Password button. The action for the button is:
// Change password
aListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
ChangeMyPassword cmp = new ChangeMyPassword(
MainFrame.this);
cmp.dispose();
changePasswordButton.addActionListener(aListener);When the user press the Change Password button, it pass control to the ChangeMyPassword class which as a submit button and a cancel button. When the user press the submit button, it should validate the old password (i.e. compare it to the password in the text file), validate the new password match the retype password:
// submit button
ActionListener aListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Retrieve the password.
char[] pw = oldPasswordField.getPassword();
oldPassword = new String(pw).trim();
pw = newPasswordField.getPassword();
newPassword = new String(pw).trim();
pw = retypePasswordField.getPassword();
retypePassword = new String(pw).trim();
// Hide, but don't dispose of, this window ...
// we need to give the client code a chance to
// retrieve the user's typed response via
// the getPassword() method first.
ChangeMyPassword.this.setVisible(false);
submitButton.addActionListener(aListener);I have a Student class which compare the old password with the password in the text file. The student class constructor takes the student id to identify which student text file it should call.
The problem is that the ChangeMyPassword does not know about student id (because I am getting these from the text field in MainFrame class). So how can I call the validatePassword method in Student class?
public boolean validatePassword(String pw) {
if (pw == null) return false;
if (pw.equals(password)) return true;
else return false;
}I don�t understand why it does not update the text file with the new password.
The submit button has the action in ChangeMyPassword class:
// submit button
ActionListener aListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Retrieve the password.
char[] pw = oldPasswordField.getPassword();
oldPassword = new String(pw).trim();
pw = newPasswordField.getPassword();
newPassword = new String(pw).trim();
pw = retypePasswordField.getPassword();
retypePassword = new String(pw).trim();
Student theStudent = new Student(id);
if(theStudent.validatePassword(oldPassword)){
if(validateChangePassword()){
// write the new password to file
theStudent.setPassword(getNewPassword());
// Let the user know that the
// password succeeded.
JOptionPane.showMessageDialog(null,
"Password change successfully.",
"Password Changed",
JOptionPane.INFORMATION_MESSAGE);
}else{
JOptionPane.showMessageDialog(null,
"You have used an invalid user name or password; please try again.",
"Authentication failed",
JOptionPane.WARNING_MESSAGE);
}else{
JOptionPane.showMessageDialog(null,
"You have used an invalid user name or password; please try again.",
"Authentication failed",
JOptionPane.WARNING_MESSAGE);
// Hide, but don't dispose of, this window ...
// we need to give the client code a chance to
// retrieve the user's typed response via
// the getPassword() method first.
ChangeMyPassword.this.setVisible(false);
submitButton.addActionListener(aListener);Validate password method in Student class:
public boolean validatePassword(String pw) {
if (pw == null) return false;
if (pw.equals(password)) return true;
else return false;
}Validate change password method in ChangeMyPassword class:
public boolean validateChangePassword(){
if(newPassword.equals(retypePassword))return true;
else return false;
}When the user press the Change Password button the action performed in the MainFrame class is:
// Change password
aListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String id = ssnField.getText();
ChangeMyPassword cmp = new ChangeMyPassword(MainFrame.this, id);
boolean success = currentUser.persist();
cmp.dispose();
changePasswordButton.addActionListener(aListener);Now remember that I set the password that should be written in ChangeMyPassword class as you can see above. Now that I called the persist method, it should write all the details back to the text. For some reason it not doing that and I don�t understand why.
The persist method:
public boolean persist() {
FileOutputStream fos = null;
PrintWriter pw = null;
try {
// Attempt to create the ssn.dat file. Note that
// it will overwrite one if it already exists.
fos = new FileOutputStream("C://Files//" + getSsn() + ".dat");
pw = new PrintWriter(fos);
// First, we output the header record as a tab-delimited
// record.
pw.println(getSsn() + "\t" + getName() + "\t" +
getMajor() + "\t" + getDegree() + "\t" + getPassword());
// Then, we output one record for every Section that
// the Student is enrolled in.
for (int i = 0; i < attends.size(); i++) {
Section s = (Section) attends.elementAt(i);
pw.println(s.getFullSectionNo());
pw.close();
fos.close(); //? needed?
catch (IOException e) {
// Signal that an error has occurred.
return false;
// All is well!
return true;
} -
I had my Yahoo email account linked to my BlackBerry. I had to change my password to my Yahoo account. Once I did this the email was no longer linked. How do I update the BlackBerry to receie the Yahoo emails?
go to Email setup and select yahoo mail id.
press menu button and choose validate password. -
Password Policy and user account lockout in OAM
Hi folks,
I'm new to OAM and have rather silly question: I created Password Policy where I've defined the Number of login tries allowed, Custom Account Lockout Redirect URL, etc. Now, how do I tie it to the authentication / authorization rules inside my Policy Domain which I'm using to protect a certain resource?
Thank you
RomanHi Colin,
I do have the validate_password plugins defined in the Authent scheme, here they are:
credential_mapping obMappingBase="xxxxxx"
validate_password obCredentialPassword="password"
validate_password obReadPasswdMode="LDAP"
validate_password obWritePasswdMode="LDAP"
Yet, after the third unsuccessful login, nothing happens. I still don't get it how the password policy I've created kicks into the action? Should it be evaluated each time a user attempts an access? Is it getting engaged due to the validate password plugin names?
I've also noticed that the only default step I have in the Authent scheme doesn't list the last two validate password plugins in it. Does it have to?
Thanks Roman
Edited by: roman_zilist on Dec 17, 2009 9:12 AM -
Hello all you fellow Flexers out there
I want to use the StringValidator, or some bit of action
script I suppose, to ensure that my end users has a password of 6
chars with at least one special character and at least one number.
I already have two password boxes and have the checks to
ensure that the password is the same in both boxes. Now all I need
to do is to validate the length and check for the required special
character and number. Any ideas???
Thanks in advance!!!
Have an Ordinary Day...
KomputerMan ~|:-)The following code is not at all an elegant solution, but it
uses regular expressions, and may get you started:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="
http://www.adobe.com/2006/mxml"
layout="vertical">
<mx:Script>
<![CDATA[
public var digit:RegExp = /.*\d.*/;
public var special:RegExp = /.*\W|_.*/;
public function validatePassword():Boolean {
var result:Boolean = false;
if( (txtInput.length != 6) ||
(!digit.test(txtInput.text)) ||
(!special.test(txtInput.text)) ){
return false;
} else {
return true;
]]>
</mx:Script>
<mx:TextInput id="txtInput"/>
<mx:Button label="Validate Password"
click="mx.controls.Alert.show(String(validatePassword()))"/>
</mx:Application> -
How to use interface and abstract class in the real time sennario ?
how to validate password and reenter password fields in the struts through the xml files?
Here is a modified dealForm.jsp that merges the 2 steps - both symbol submission and Yahoo convert is done by it. Play with it and add your DB code to it:
<html>
<head><title>IPIB Database Selection</title></head>
<body bgcolor="#DFDFFF">
<H1><CENTER>IPIB Database Selection</CENTER></H1>
<font size=4>
<%@ page language="java" %>
<%@ page import="java.net.*,java.io.*,java.util.*" %>
<%
String symbol = request.getParameter("symbol");
if (symbol != null) {
String urlString = "http://finance.yahoo.com/download/javasoft.beans?SYMBOLS=" + symbol + "&format=ab";
try {
URL url = new URL(urlString);
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
StringTokenizer tokenizer = new StringTokenizer(line,",");
String name = tokenizer.nextToken();
name = name.substring(1, name.length()-2);
String price = tokenizer.nextToken();
price = price.substring(1, price.length()-2);
%>
<p>
Original line from yahoo <%= line %>
</p> <p>
Name: <%= name %>
</p> <p>
Price: <%= price %>
</p> <p>
Pub DB processing code from dealLoad.jsp here
</p>
<%
} catch (IOException exception) {
System.err.println("IOException: " + exception);
} else { %>
<form action="dealForm.jsp"method="GET">
<p>Enter Symbol: <input size="20" name="symbol">
<inputtype="submit" value="Submit">
</p></form>
<% } %>
</font>
</body>
</html> -
Database Access in Java (Count field incorrect)
Was given a stock tracking application to be edited for use as a Student/Admin login application which accesses a database and adds/deletes/edits student information. When I try to login, I get the following error: [Microsoft][OBDC Microsoft Access Driver]Count Field Incorrect
The driver was set up in the Admin tools in Windows XP.
The columns exist in the database.
//makeDB.java
import java.sql.*;
import java.io.*;
public class MakeDB
public static void main(String[] args) throws Exception
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:saad";
Connection con = DriverManager.getConnection(url);
Statement stmt = con.createStatement();
// The following code deletes each index and table, if they exist.
// If they do not exist, a message is displayed and execution continues.
System.out.println("Dropping indexes & tables ...");
try
stmt.executeUpdate("DROP INDEX PK_StudentUserBridge ON StudentUserBridge");
catch (Exception e)
System.out.println("Could not drop primary key on saad table: "
+ e.getMessage());
try
stmt.executeUpdate("DROP TABLE Student");
catch (Exception e)
System.out.println("Could not drop Student table: "
+ e.getMessage());
try
stmt.executeUpdate("DROP TABLE Users");
catch (Exception e)
System.out.println("Could not drop Users table: "
+ e.getMessage());
try
stmt.executeUpdate("DROP TABLE StudentUserBridge");
catch (Exception e)
System.out.println("Could not drop StudentUserBridge table: "
+ e.getMessage());
///////// Create the database tables /////////////
System.out.println("\nCreating tables ............");
// Create Stocks table with primary key index
try
System.out.println("Creating Student table with primary key index...");
stmt.executeUpdate("CREATE TABLE Student ("
+"IDNumber TEXT(8) NOT NULL "
+"CONSTRAINT PK_Student PRIMARY KEY, "
+"FirstName TEXT(50), "
+"LastName TEXT(50)"
+")");
catch (Exception e)
System.out.println("Exception creating Student table: "
+ e.getMessage());
// Create Users table with primary key index
try
System.out.println("Creating Users table with primary key index...");
stmt.executeUpdate("CREATE TABLE Users ("
+"userID TEXT(20) NOT NULL "
+"CONSTRAINT PK_Users PRIMARY KEY, "
+"FirstName TEXT(30) NOT NULL, "
+"LastName TEXT(30) NOT NULL, "
+"pswd LONGBINARY, "
+"email TEXT(30) NOT NULL, "
+"admin BIT"
+")");
catch (Exception e)
System.out.println("Exception creating Users table: "
+ e.getMessage());
// Create UserStocks table with foreign keys to Users and Stocks tables
try
System.out.println("Creating StudentUserBridge table ...");
stmt.executeUpdate("CREATE TABLE StudentUserBridge ("
+"userID TEXT(20) "
+"CONSTRAINT FK1_StudentUserBridge REFERENCES Users (userID), "
+"IDNumber TEXT(8), "
+"CONSTRAINT FK2_StudentUserBridge FOREIGN KEY (IDNumber) "
+"REFERENCES Student (IDNumber)"
+")");
catch (Exception e)
System.out.println("Exception creating StudentUserBridge table: "
+ e.getMessage());
// Create UserStocks table primary key index
try
System.out.println("Creating StudentUserBridge table primary key index...");
stmt.executeUpdate("CREATE UNIQUE INDEX PK_StudentUserBridge "
+"ON StudentUserBridge (userID, IDNumber) "
+"WITH PRIMARY DISALLOW NULL");
catch (Exception e)
System.out.println("Exception creating StudentUserBridge index: "
+ e.getMessage());
// Create one administrative user with password as initial data
String userID = "admin01";
String FirstName = "Default";
String LastName = "Admin";
String initialPswd = "admin01";
String email = "[email protected]";
Password pswd = new Password(initialPswd);
boolean admin = true;
PreparedStatement pStmt =
con.prepareStatement("INSERT INTO Users VALUES (?,?,?,?,?,?)");
try
pStmt.setString(1, userID);
pStmt.setString(2, FirstName);
pStmt.setString(3, LastName);
pStmt.setBytes(4, serializeObj(pswd));
pStmt.setString(5, email);
pStmt.setBoolean(6, admin);
pStmt.executeUpdate();
catch (Exception e)
System.out.println("Exception inserting user: "
+ e.getMessage());
pStmt.close();
// Read and display all User data in the database.
ResultSet rs = stmt.executeQuery("SELECT * FROM Users");
System.out.println("Database created.\n");
System.out.println("Displaying data from database...\n");
System.out.println("Users table contains:");
Password pswdFromDB;
byte[] buf = null;
while(rs.next())
System.out.println("Logon ID = "
+ rs.getString("userID"));
System.out.println("Last name = "
+ rs.getString("FirstName"));
System.out.println("First name = "+rs.getString("LastName"));
System.out.println("E-mail = "+rs.getString("email"));
System.out.println("Administrative = "+rs.getBoolean("admin"));
System.out.println("Initial password = "+initialPswd);
// Do NOT use with JDK 1.2.2 using JDBC-ODBC bridge as
// SQL NULL data value is not handled correctly.
buf = rs.getBytes("pswd");
if (buf != null)
System.out.println("Password Object = "
+ (pswdFromDB=(Password)deserializeObj(buf)));
System.out.println(" AutoExpires = "+ pswdFromDB.getAutoExpires());
System.out.println(" Expiring now = "+ pswdFromDB.isExpiring());
System.out.println(" Remaining uses = "
+ pswdFromDB.getRemainingUses()+"\n");
else
System.out.println("Password Object = NULL!");
rs = stmt.executeQuery("SELECT * FROM Student");
if(!rs.next())
System.out.println("Student table contains no records.");
else
System.out.println("Student table still contains records!");
rs = stmt.executeQuery("SELECT * FROM StudentUserBridge");
if(!rs.next())
System.out.println("StudentUserBridge table contains no records.");
else
System.out.println("StudentUserBridge table still contains records!");
stmt.close(); // closing Statement also closes ResultSet
} // end of main()
// Method to write object to byte array and then insert into prepared statement
public static byte[] serializeObj(Object obj)
throws IOException
ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);
objOStream.writeObject(obj); // object must be Serializable
objOStream.flush();
objOStream.close();
return baOStream.toByteArray(); // returns stream as byte array
// Method to read bytes from result set into a byte array and then
// create an input stream and read the data into an object
public static Object deserializeObj(byte[] buf)
throws IOException, ClassNotFoundException
Object obj = null;
if (buf != null)
ObjectInputStream objIStream =
new ObjectInputStream(new ByteArrayInputStream(buf));
obj = objIStream.readObject(); // throws IOException, ClassNotFoundException
return obj;
} // end of class
//STLogon.java
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.sql.*;
public class STLogon extends JFrame implements ActionListener, Activator
StudentDB db;
User user = null;
String userID;
String password;
JTextField userIDField;
JPasswordField passwordField;
JButton jbtLogon;
public STLogon()
super("Stock Tracker"); // call super (JFrame) constructor
int width = 300;
int height = 100;
try{
db = new StudentDB();
catch(ClassNotFoundException ex){
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"Class not found exception creating database object",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
catch(SQLException ex){
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"SQL exception creating database object",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
// define GUI components
JLabel label1 = new JLabel("User ID: ");
userIDField = new JTextField(20);
JLabel label2 = new JLabel("Password: ");
passwordField = new JPasswordField(20);
passwordField.setEchoChar('*');
jbtLogon = new JButton("Log on");
// set up GUI
JPanel userPanel= new JPanel(new BorderLayout());
userPanel.add(label1,BorderLayout.CENTER);
userPanel.add(userIDField,BorderLayout.EAST);
JPanel pswdPanel= new JPanel(new BorderLayout());
pswdPanel.add(label2,BorderLayout.CENTER);
pswdPanel.add(passwordField,BorderLayout.EAST);
JPanel buttonPanel= new JPanel(new FlowLayout());
buttonPanel.add(jbtLogon);
JPanel contentPanel= new JPanel(new BorderLayout());
contentPanel.add(userPanel, BorderLayout.NORTH);
contentPanel.add(pswdPanel, BorderLayout.CENTER);
contentPanel.add(buttonPanel, BorderLayout.SOUTH);
contentPanel.setBorder(new TitledBorder("Log on"));
setContentPane(contentPanel);
// add listeners
jbtLogon.addActionListener(this);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
try {db.close();
catch(Exception ex)
System.exit(0);
// Enable Enter key for each JButton
InputMap map;
map = jbtLogon.getInputMap();
if (map != null){
map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,false), "pressed");
map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,true), "released");
pack();
if( width < getWidth()) // prevent setting width too small
width = getWidth();
if(height < getHeight()) // prevent setting height too small
height = getHeight();
centerOnScreen(width, height);
public void centerOnScreen(int width, int height)
int top, left, x, y;
// Get the screen dimension
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
// Determine the location for the top left corner of the frame
x = (screenSize.width - width)/2;
y = (screenSize.height - height)/2;
left = (x < 0) ? 0 : x;
top = (y < 0) ? 0 : y;
// Set the frame to the specified location & size
this.setBounds(left, top, width, height);
private boolean validUser(String userID,String password)
throws PasswordException,SQLException,IOException,ClassNotFoundException
boolean userOK = false;
user = db.getUser(userID); // get user object from DB for this ID
if(user != null)
user.validate(password); // throws PasswordException
userOK = true;
if(user.pswdAutoExpires()) // if tracking uses
db.updUser(user); // update DB for this use
return userOK;
private void doStockActivity()throws PasswordException,SQLException,
IOException,ClassNotFoundException
StockTracker f = new StockTracker(user,this,db);
f.pack();
this.setVisible(false);
f.setVisible(true);
public void activate()
this.setVisible(true);
userIDField.setText("");
userIDField.requestFocus();
user = null;
public void actionPerformed(ActionEvent e)
try
userID = userIDField.getText();
if(userID.equals(""))
JOptionPane.showMessageDialog(this,
"Please enter a valid user ID.",
"Missing User ID.",
JOptionPane.ERROR_MESSAGE);
userIDField.requestFocus();
else
password = new String(passwordField.getPassword());
if(password.equals(""))
JOptionPane.showMessageDialog(this,
"Please enter a valid password.",
"Missing Password.",
JOptionPane.ERROR_MESSAGE);
passwordField.requestFocus();
else
try
// See if userID exists and validate password
if(validUser(userID,password))
if(user.pswdIsExpiring())
JOptionPane.showMessageDialog(this,
user.getUserID()+" logon successful; "
+user.getPswdUses()+" use(s) remaining.");
if(e.getSource() == jbtLogon)
doStockActivity();
else
JOptionPane.showMessageDialog(this, "Invalid user.");
catch (PasswordExpiredException ex)
JPasswordField pf1 = new JPasswordField();
JPasswordField pf2 = new JPasswordField();
Object[] message1 = new Object[]
{"Password has expired. Please enter a new password.", pf1};
Object[] options = new String[] {"OK", "Cancel"};
JOptionPane op1 = new JOptionPane(message1,
JOptionPane.WARNING_MESSAGE,
JOptionPane.OK_CANCEL_OPTION, null, options);
JDialog dialog1 = op1.createDialog(null, "Change Password");
dialog1.show();
if(op1.getValue() != null && options[0].equals(op1.getValue()))
String pswd1 = new String(pf1.getPassword());
if(pswd1 != null)
Object[] message2 = new Object[]
{"Please verify new password.", pf2};
JOptionPane op2 = new JOptionPane(message2,
JOptionPane.WARNING_MESSAGE,
JOptionPane.OK_CANCEL_OPTION,
null, options);
JDialog dialog2 = op2.createDialog(null, "Verify Password");
dialog2.show();
if(op2.getValue() != null && options[0].equals(op2.getValue()))
String pswd2 = new String(pf2.getPassword());
if(pswd2 != null)
if(pswd1.equals(pswd2))
user.changePassword(password, pswd1);
db.updUser(user);
doStockActivity();
else
JOptionPane.showMessageDialog(this,
"Both passwords are not identical.",
"Password not changed",
JOptionPane.ERROR_MESSAGE);
userIDField.setText("");
passwordField.setText("");
userIDField.requestFocus();
}// end of try
catch (PasswordUsedException ex)
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"Password Previously Used. Try again.",
JOptionPane.ERROR_MESSAGE);
catch (PasswordSizeException ex)
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"Invalid password size. Try again.",
JOptionPane.ERROR_MESSAGE);
catch (PasswordInvalidFormatException ex)
if(ex.getCount() > 2) // allows only 3 tries, then exits program
System.exit(0);
else
JOptionPane.showMessageDialog(this,ex.getMessage()+", count:"+ex.getCount(),
"Invalid password format. Try again.",
JOptionPane.ERROR_MESSAGE);
catch (PasswordInvalidException ex)
if(ex.getCount() > 2) // allows only 3 tries, then exits program
System.exit(0);
else
JOptionPane.showMessageDialog(this,ex.getMessage()+", count:"+ex.getCount(),
"Invalid password. Try again.",
JOptionPane.ERROR_MESSAGE);
catch (PasswordException ex)
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"PasswordException.",
JOptionPane.ERROR_MESSAGE);
catch (IOException ex)
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"IOException.",
JOptionPane.ERROR_MESSAGE);
catch (SQLException ex)
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"SQLException.",
JOptionPane.ERROR_MESSAGE);
catch (ClassNotFoundException ex)
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"ClassNotFoundException.",
JOptionPane.ERROR_MESSAGE);
public static void main(String[] argv)
final STLogon f = new STLogon();
f.setVisible(true);
//StudentDB.java
import java.io.*;
import java.sql.*;
import java.util.*;
public class StudentDB
private Connection con = null;
// Constructor; makes database connection
public StudentDB() throws ClassNotFoundException,SQLException
if(con == null)
String url = "jdbc:odbc:saad";
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch(ClassNotFoundException ex)
throw new ClassNotFoundException(ex.getMessage() +
"\nCannot locate sun.jdbc.odbc.JdbcOdbcDriver");
try
con = DriverManager.getConnection(url);
catch(SQLException ex)
throw new SQLException(ex.getMessage()+
"\nCannot open database connection for "+url);
// Close makes database connection; null reference to connection
public void close() throws SQLException,IOException,ClassNotFoundException
con.close();
con = null;
// Method to serialize object to byte array
private byte[] serializeObj(Object obj) throws IOException
ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);
objOStream.writeObject(obj); // object must be Serializable
objOStream.flush();
objOStream.close();
return baOStream.toByteArray(); // returns stream as byte array
// Method to deserialize bytes from a byte array into an object
private Object deserializeObj(byte[] buf)
throws IOException, ClassNotFoundException
Object obj = null;
if (buf != null)
ObjectInputStream objIStream =
new ObjectInputStream(new ByteArrayInputStream(buf));
obj = objIStream.readObject(); //IOException, ClassNotFoundException
return obj;
// Methods for adding a record to a table
// add to the Student Table
public void addStudent(String IDNumber, String FirstName, String LastName)
throws SQLException, IOException, ClassNotFoundException
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO Student VALUES ('"
+IDNumber+"'"+",'"+FirstName+"'"+",'"+LastName+"')");
stmt.close();
// add to the Users table
public boolean addUser(User user) throws SQLException,IOException,
ClassNotFoundException
boolean result = false;
String dbUserID;
String dbLastName;
String dbFirstName;
Password dbPswd;
String dbemail;
boolean isAdmin;
dbUserID = user.getUserID();
if(getUser(dbUserID) == null)
dbLastName = user.getFirstName();
dbFirstName = user.getLastName();
Password pswd = user.getPassword();
// dbemail = user.getEmail();
isAdmin = user.isAdmin();
PreparedStatement pStmt = con.prepareStatement(
"INSERT INTO Users VALUES (?,?,?,?,?,?)");
pStmt.setString(1, dbUserID);
pStmt.setString(2, dbFirstName);
pStmt.setString(3, dbLastName);
pStmt.setBytes(4, serializeObj(pswd));
// pStmt.setString(5, dbemail);
pStmt.setBoolean(5, isAdmin);
pStmt.executeUpdate();
pStmt.close();
result = true;
else
throw new IOException("User exists - cannot add.");
return result;
// add to the UserStocks table
public void addStudentUserBridge(String userID, String IDNumber)
throws SQLException,IOException,ClassNotFoundException
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO StudentUserBridge VALUES ('"
+userID+"'"
+",'"+IDNumber+"')");
stmt.close();
// Methods for updating a record in a table
// updating the Users Table
public boolean updUser(User user) throws SQLException,IOException,
ClassNotFoundException
boolean result = false;
String dbUserID;
String dbLastName;
String dbFirstName;
Password dbPswd;
String dbemail;
boolean isAdmin;
dbUserID = user.getUserID();
if(getUser(dbUserID) != null)
dbLastName = user.getFirstName();
dbFirstName = user.getLastName();
Password pswd = user.getPassword();
// dbemail = user.getEmail();
isAdmin = user.isAdmin();
PreparedStatement pStmt = con.prepareStatement("UPDATE Users SET FirstName = ?,"
+" LastName = ?, pswd = ?, email = ?, admin = ? WHERE userID = ?");
pStmt.setString(1, dbFirstName);
pStmt.setString(2, dbLastName);
pStmt.setBytes(3, serializeObj(pswd));
// pStmt.setString(4, dbemail);
pStmt.setBoolean(4, isAdmin);
pStmt.setString(5, dbUserID);
pStmt.executeUpdate();
pStmt.close();
result = true;
else
throw new IOException("User does not exist - cannot update.");
return result;
// Methods for deleting a record from a table
// delete a record from the Student Table
private void delStudent(String IDNumber)
throws SQLException,IOException,ClassNotFoundException
Statement stmt = con.createStatement();
stmt.executeUpdate("DELETE FROM Student WHERE "
+"IDNumber = '"+IDNumber+"'");
stmt.close();
// delete a record from the Users Table
public void delUser(User user) throws SQLException,IOException,
ClassNotFoundException
String dbUserID;
String stockSymbol;
Statement stmt = con.createStatement();
try {
con.setAutoCommit(false);
dbUserID = user.getUserID();
if(getUser(dbUserID) != null) // verify user exists in database
ResultSet rs1 = stmt.executeQuery("SELECT userID, IDNumber "
+"FROM StudentUserBridge WHERE userID = '"+dbUserID+"'");
while(rs1.next())
try
stockSymbol = rs1.getString("IDNumber");
delUserStocks(dbUserID, stockSymbol);
catch(SQLException ex)
throw new SQLException("Deletion of user student failed: "
+ex.getMessage());
} // end of loop thru UserStocks
try
{ // holdings deleted, now delete user
stmt.executeUpdate("DELETE FROM Users WHERE "
+"userID = '"+dbUserID+"'");
catch(SQLException ex)
throw new SQLException("User deletion failed: "+ex.getMessage());
else
throw new IOException("User not found in database - cannot delete.");
try
con.commit();
catch(SQLException ex)
throw new SQLException("Transaction commit failed: "+ex.getMessage());
catch (SQLException ex)
try
con.rollback();
catch (SQLException sqx)
throw new SQLException("Transaction failed then rollback failed: "
+sqx.getMessage());
// Transaction failed, was rolled back
throw new SQLException("Transaction failed; was rolled back: "
+ex.getMessage());
stmt.close();
// delete a record from the StudentUserBridge Table
public void delUserStocks(String userID, String stockSymbol)
throws SQLException,IOException,ClassNotFoundException
Statement stmt = con.createStatement();
ResultSet rs;
stmt.executeUpdate("DELETE FROM StudentUserBridge WHERE "
+"userID = '"+userID+"'"
+"AND IDNumber = '"+stockSymbol+"'");
rs = stmt.executeQuery("SELECT IDNumber FROM StudentUserBridge "
+"WHERE IDNumber = '"+stockSymbol+"'");
if(!rs.next()) // no users have this stock
// delStock(stockSymbol);
stmt.close();
// Methods for listing record data from a table
// Ordered by:
// methods that obtain individual field(s),
// methods that obtain a complete record, and
// methods that obtain multiple records
// Methods to access one or more individual fields
// get a stock description from the Stocks Table
public String getStockDesc(String stockSymbol)
throws SQLException, IOException, ClassNotFoundException
Statement stmt = con.createStatement();
String stockDesc = null;
ResultSet rs = stmt.executeQuery("SELECT IDNumber, name FROM Student "
+"WHERE IDNumber = '"+stockSymbol+"'");
if(rs.next())
stockDesc = rs.getString("IDNumber");
rs.close();
stmt.close();
return stockDesc;
// Methods to access a complete record
// get User data from the Users Table
public User getUser(String UserID) throws SQLException, IOException,
ClassNotFoundException
Statement stmt = con.createStatement();
String dbUserID;
String dbLastName;
String dbFirstName;
Password dbPswd;
String dbemail;
boolean isAdmin;
byte[] buf = null;
User user = null;
ResultSet rs = stmt.executeQuery("SELECT * FROM Users WHERE userID = '"
+UserID+"'");
if(rs.next())
dbUserID = rs.getString("userID");
dbFirstName = rs.getString("FirstName");
dbLastName = rs.getString("LastName");
dbemail = rs.getString("email");
// Do NOT use with JDK 1.2.2 using JDBC-ODBC bridge as
// SQL NULL data value is not handled correctly.
buf = rs.getBytes("pswd");
dbPswd = (Password)deserializeObj(buf);
isAdmin = rs.getBoolean("admin");
user = new User(dbUserID,dbFirstName,dbLastName,dbPswd,isAdmin);
rs.close();
stmt.close();
return user; // User object created for userID
// Methods to access a list of records
// get list of selected fields for all records from the Users Table
public ArrayList listUsers() throws SQLException,IOException,
ClassNotFoundException
ArrayList aList = new ArrayList();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT userID, FirstName, LastName, admin "
+"FROM Users ORDER BY userID");
while(rs.next())
aList.add(rs.getString("userID"));
aList.add(rs.getString("FirstName"));
aList.add(rs.getString("LastName"));
aList.add(new Boolean(rs.getBoolean("admin")));
rs.close();
stmt.close();
return aList;
// get all fields in all records for a given user from the Userstocks Table
public ArrayList listUserStocks(String userID) throws SQLException,IOException,
saaddani wrote:
No information popped up in the console window before, during, or after the error was given. The program compiled and ran and therefore no error information was provided in the complier window either.
If I am missing what you are asking then please provide instructions as to how to find this error information. You are posting the error message for the exception but not printing the stack trace.
Far as I can tell you are printing more information with each exception (for example "Exception creating Users table") but you did not post what that was, that info would localize the problem.
As a guess the problem is when you extract the fields via the query. You are using named values rather than indexes and you use "select *" rather than specifically naming the columns. Some databases (for example Oracle), require that using names must be in exactly the same order as the query returns them. You have no idea what that order is because you use "select *"
Finally it would be a LOT easier if you wrote classes that did nothing but the database operations. NO GUI CODE. You then test that code to make sure it works. Once that code works then you write gui code which uses those classes. Besides making it easier to understand you are also more likely to get assistance since there is less code to look at.
Maybe you are looking for
-
Can you do document compare in pages, can you do document compare in pages
In that "other" word processing program, you can do a document compare to see how the documents differ. I have not found how to do that in Pages. Is it possible?
-
hi, 1 i know that f-28 is to post incoming payment from customer. normally we run F110 to make payment for vendor. may i know F110 is a payment run to make payment to customer or receive payment from customer? 2 what is the difference for f-28 and f1
-
'Missing Camera' icon with question mark!
I uploaded over one hundred movies from my camera. Some of them show up in my iMovie library but some have the 'Missing Camera' icon. The movies are in the iMovie contents folder as .mov files. so I know they are in my computer. Why won't they show u
-
Problem in IE - dependent on path to the .swf
Hey All, I try not to post questions unless I can't find the answer anywhere else, and I find myself in that situation now. I've searched Microsoft and I've searched these forums for posts from others with the same problem.....and no, it's not about
-
How would i create a constraint for date joined which has to be less than date left?
CONSTRAINT [CK_Member_DateJoined_todayorpast] CHECK (len(DateJoined)<=getdate()[DateLeft]>[DateJoined]) I tried this but it will not work someone please help :))