Validator not working properly - java

I have a JSF validator which is used to validate input from form.
When I insert simple string or duplicated string it's working properly. But when I don't enter anything the proper message will be This field cannot be empty!" : " '" + s + "' is not a valid name! but I don't get anything. Can you help me to find the problem into the code logic?
// Validate Datacenter Name
public void validateDatacenterName(FacesContext context, UIComponent component, Object value) throws ValidatorException, SQLException
{
String l;
String s = value.toString().trim();
if (s != null && s.length() > 18)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" Value is too long! (18 digits max)", null));
}
try
{
// l = Long.parseLong(s);
// if (l > Integer.MAX_VALUE)
// {
// throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
// " '" + l + "' is too large!", null));
// }
}
catch (NumberFormatException nfe)
{
l = null;
}
if (s != null)
{
if (ds == null)
{
throw new SQLException("Can't get data source");
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs;
int cnt = 0;
try
{
conn = ds.getConnection();
ps = conn.prepareStatement("SELECT count(1) from COMPONENTSTATS where NAME = ?");
ps.setString(1, s);
rs = ps.executeQuery();
while (rs.next())
{
cnt = rs.getInt(1);
}
if (cnt > 0)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" '" + s + "' is already in use!", null));
}
}
catch (SQLException x)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" SQL error!", null));
}
finally
{
if (ps != null)
{
ps.close();
}
if (conn != null)
{
conn.close();
}
}
}
else
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
s.isEmpty() ? " This field cannot be empty!" : " '" + s + "' is not a valid name!", null));
}
}

that is because you only check if you s is != null.
change if (s != null) to if (s != null && s.lenght() > 0) and try again.
btw your String s can't be null, because you initialize it with
String s = value.toString().trim();
and this would cause a NullPointerException if your value would be null.

Set inputText tag attribute required to true
<h:inputText value="#{backingBean.input}" required="true"
requiredMessage="Input is empty!">

Related

How to set properly an object attribute using reflection in Java?

Database ResultSet example
fclass,geometry,scenario
""elementary_school"","MULTIPOINT(303400.907447057 9044592.97070337)",66
""elementary_school"","MULTIPOINT(302777.056751395 9044333.43169871)",66
""elementary_school"","MULTIPOINT(304182.88271353 9042435.93276122)",66
""elementary_school"","MULTIPOINT(304592.928219703 9041564.59729198)",66
""elementary_school"","MULTIPOINT(311385.417245523 9052785.71100888)",66
""worship"","MULTIPOINT(307397.04764638 9039421.31774996)",66
""worship"","MULTIPOINT(304384.660908793 9047145.34109501)",66
""worship"","MULTIPOINT(304518.616783947 9039859.48619132)",66
""worship"","MULTIPOINT(304689.11878157 9041491.61685193)",66
""worship"","MULTIPOINT(304711.539434326 9047763.53595371)",66
""worship"","MULTIPOINT(303420.353637529 9048419.36252138)",66
Class to be accessed using reflection
public class Amenities {
public Integer amenities_id;
public Integer scenario;
public String fclass;
public String location;
public String buffer;
public TableInfo[] amenity_info;
}
Using reflection
private PostStatus getAmenities(String layerUP, String layer, String[] tableUP, String[] table, String scenarioId) {
PostStatus postStatus=new PostStatus();
String values = "";
for (int i = 0; i < tableUP.length; i++) {
if (tableUP[i].equals("location")) {
//values += "st_astext("+table[i]+")";
values += "st_astext("+table[i]+") as "+table[i];
} else if (tableUP[i].equals("scenario")) {
values += scenarioId+" as scenario";
} else {
values = "property_json->'" + table[i] + "' as "+ table[i] ;
}
if (i < tableUP.length - 1) {
values += ",";
} else {
values = values.replaceAll(",$", "");
}
}
String errorMsg = "";
String query ="";
try (
Connection connection = DriverManager.getConnection(
upURL,
upUser,
upPassword)) {
Statement statement = connection.createStatement();
query="select " + values + " from user_layer\n"
+ "inner join user_layer_data on user_layer.id = user_layer_data.user_layer_id\n"
+ "where user_layer.id=" + layer;
ResultSet data = statement.executeQuery(query);
ArrayList<Amenities> data_in = new ArrayList<>();
while (data.next()) {
Object o = new Amenities();
Class<?> c = o.getClass();
for (int i = 0; i < tableUP.length; i++) {
try {
Field f = c.getDeclaredField(tableUP[i]);
f.setAccessible(true);
if (!tableUP[i].equals("scenario") || !tableUP[i].equals("amenities_id")) {
f.set(o, data.getString(table[i]));
} else if (tableUP[i].equals("scenario")) {
Integer scen=(Integer)data.getInt(tableUP[i]);
f.set(o,scen );
} else if (tableUP[i].equals("location")) {
f.set(o, data.getString(table[i]));
} else if (tableUP[i].equals("amenities_id")) {
}
} catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException | SQLException e) {
log.error(e, errorMsg);
}
}
log.debug(o, "reflection");
data_in.add((Amenities) o);
}
Tables<Amenities> final_data = new Tables<Amenities>(data_in);
RestTemplate restTemplate = new RestTemplate();
postStatus=restTemplate.postForObject("http://" + upwsHost + ":" + upwsPort + "/amenities/", final_data, PostStatus.class);
return postStatus;
} catch (SQLException ex) {
for (Throwable e : ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
errorMsg += "SQLState: " + ((SQLException) e).getSQLState();
errorMsg += "Error Code: " + ((SQLException) e).getErrorCode();
errorMsg += "Message: " + e.getMessage();
/*Throwable t = ex.getCause();
while (t != null) {
errorMsg += "Cause: " + t;
t = t.getCause();
}*/
}
}
log.error(ex, errorMsg+query);
}catch(Exception e){
log.error(e, errorMsg+query);
}
postStatus.status="Error";
postStatus.message=errorMsg+query;
return postStatus;
}
My code is failing when it sets the value of the integer attribute of the object Amenites using the code Integer scen=(Integer)data.getInt(tableUP[i]); f.set(o,scen );, when I check the results the other values are assigned properly but the value of the field scenario remains in null.
I am sure that the values from the database ResultSet exist, also I tryied setting a static integer value 66, and It only shows the field with a 0value.
Since I am pretty new on Java, I would appreciate you help to find what am I doing wrong?

Getting Parameter value in java with symbol Apostrophe(') query

I have parameter named paramValue then I am trying to store it this is working if my paramvalue is equals to any value without apostrophe like paramvalue = 'klang#'
but if it has apostrophe it wont work like this paramvalue = 'kl'ang#'
I put some part of my code
query += "'" + paramValue + "'";
I tried this but I am getting error like '; expected' Is there any other option to do it like this below I will really appreciate any advice thank you
query += """ + paramValue + """;
below is my code
public boolean insertInto(String tableName, String paramsName[], String paramsValues[], String id) {
String query = "INSERT INTO tbl1" + tableName + " (id, dateCreated, dateModified";
for (String paramName : paramsName) {
query += ", c_" + paramName;
}
query += ") VALUES( ";
if (id == null || id.isEmpty()) {
query += "UUID(), NOW() , NOW()";
} else {
query += "'" + id + "', NOW(), NOW()";
}
for (String paramValue : paramsValues) {
query += "'" + paramValue + "'";
}
query += ")";
Connection con = null;
//myconn
try {
con = ds.getConnection();
PreparedStatement stmt = con.prepareStatement(query);
return stmt.execute();
} catch (SQLException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
}

statement.executeQuery returning resultset with no rows

My problem is that when I fire a query directly into Oracle, it returns me the rows with proper data. But when I try to fire the same query via Statement, its fetching me a resultset with no rows.
My code is as follows :
public void sendSMStoMobile() {
if (smsGatewayStatus.equals("STOPPED")) {
stringBuilder.append("The control is returning" + "\n");
jTextArea1.setText(stringBuilder.toString());
return;
}
DBCP dbcp = DBCP.getInstance(database_url, username, password);
Connection connection = null;
Statement statement = null;
try {
connection = dbcp.getConnection();
statement = connection.createStatement();
} catch (SQLException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Message : " + ex.getMessage());
} catch (InterruptedException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Message : " + ex.getMessage());
}
ResultSet resultSet = null;
try {
sql = new StringBuffer();
sql.append("SELECT SMS_ID, MOBILE_NO, SMS_CONTENT ");
sql.append("FROM SMSDATA.SMS_DATA ");
//sql.append("WHERE SENT_STATUS = 'N' AND Message_Code IN('LOANREPAY') " );
//sql.append("WHERE SENT_STATUS = 'N' AND Message_Code IN('SPECIAL') " );
sql.append("WHERE SENT_STATUS = 'N' ");
//sql.append("WHERE tranum <= (select max(tranum) -25 from smsgtway.sms_all_tran where SENT_STATUS = 'N' AND Message_Code IN('MEMDEP','MEMGRANT','SAMGRANT')) and SENT_STATUS = 'N' AND Message_Code IN('MEMDEP','MEMGRANT','SAMGRANT') " );
sql.append("ORDER BY SMS_ID desc ");
// sql.append("ORDER BY SENT_TIMSTAMP " );
// For Test
//sql.append("SELECT customer_Code,MOBILE_NO, SMS_CONTENT,SMS_ID " );
//sql.append("FROM MB_SMS_DTL ");
//sql.append("WHERE SENT_STATUS = 'N' ");
//sql.append("ORDER BY SMS_ID " );
// End Test
resultSet = statement.executeQuery(sql.toString());
System.out.println("Code comes here");
/* if(!resultSet.next()){
stringBuilder.append("No Data Found" +"\n");
jTextArea1.setText(stringBuilder.toString());
} */
if (!resultSet.next()) {
System.out.println("no data");
} else {
System.out.println("Data Found...");
do {
//statement(s)
} while (resultSet.next());
}
while (resultSet.next()) {
System.out.println("Data Found...");
String smsId = resultSet.getString(1);
String destMobileNo = resultSet.getString(2);
String message = resultSet.getString(3);
OutboundMessage sms = new OutboundMessage(destMobileNo, message);
System.out.println("Code comes here" + smsId);
//System.out.println("sms = " + sms);
try {
Service.getInstance().sendMessage(sms);
} catch (TimeoutException timeoutException) {
System.out.println("1");
stringBuilder.append("Exception : " + timeoutException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (GatewayException gatewayException) {
System.out.println("2");
stringBuilder.append("Exception : " + gatewayException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (IOException iOException) {
System.out.println("3");
stringBuilder.append("Exception : " + iOException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (InterruptedException interruptedException) {
System.out.println("4");
stringBuilder.append("Exception : " + interruptedException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (java.lang.StringIndexOutOfBoundsException siobe) {
System.out.println("5");
stringBuilder.append("Exception : " + siobe.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
}
//Update Table After Send Message
String updateQuery = "UPDATE SMSDATA.SMS_DATA SET SENT_STATUS = 'Y', SENT_DATE = sysdate WHERE SMS_ID = " + smsId;
//String updateQuery = "UPDATE MB_SMS_DTL SET SENT_STATUS = 'Y' WHERE SMS_ID = " + tranNumber ;
//System.out.println("Update Query: " + updateQuery);
if (i < 10) {
System.out.print(smsId + ": Y, ");
}
if (i == 10) {
System.out.print(smsId + ": Y, " + "\n");
i = 0;
}
statement.executeUpdate(updateQuery);
connection.commit();
i = i + 1;
}
} catch (Exception e) {
System.out.println("Message: " + e.getMessage());
System.out.println("Cause: " + e.getCause());
stringBuilder.append("Message: " + e.getMessage() + "\n");
stringBuilder.append("Cause: " + e.getCause() + "\n");
jTextArea1.setText(stringBuilder.toString());
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
dbcp.releaseConnection(connection);
//Service.getInstance().stopService();
}
}
When I call this function , "no data" is printed in Console . The sql is correct . When I run the sql in Toad , I have found 2 rows .
Please help me .

How to deal with null value in table column in java?

I am getting null pointer exception again and again while getting value from database table.....why its giving me null pointer exception?
Here is my code :
private HashSet getPlayerList() {
HashSet hs = new HashSet();
String soccername = "";
try {
conn = ConnectionProvider.getConnection();
rs = null;
pstmt = null;
String sql = "Select * from Players where deleted = false";
if (conn != null) {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
soccername = rs.getString("soccername").trim();// this line giving exception
if (soccername == null || soccername.isEmpty()) {
soccername = rs.getString("name").trim();
}
hs.add(soccername);
}
}
} catch (NamingException ex) {
System.out.println(ex);
} catch (SQLException ex) {
System.out.println(ex);
} finally {
try {
pstmt.close();
rs.close();
conn.close();
} catch (SQLException ex) {
System.out.println(ex);
}
}
return hs;
}
that is wrong:
soccername = rs.getString("soccername").trim();// this line giving exception
if (soccername == null || soccername.isEmpty()) {
if rs.getString("soccername") returns null it must leads to a NPE because it is followed by the function trim().
better is:
soccername = rs.getString("soccername");
if (soccername == null || soccername.trim().isEmpty()) {
It should be:
soccername = rs.getString("soccername");
if (soccername == null || soccername.isEmpty()) {
soccername = rs.getString("name").trim();
} else {
//now you are sure that soccername is not null
soccername = soccername.trim();
}

java connection pool autocommit

I'm using for the first time the connection pool in java. The application that I'm writing is a web application deployed on oracle glassfish 3.1 and the resource connection pool is handled by it. I set the autocommit to false on my connection object, returned by the javax.sql.DataSource, but in the code the rollback command has no effect at all. All the previous operation of write are committed automatically. Is there any other settings in java code that I have to do to disable autocommit? Or there is some configuration settings that I have to do on glassfish?
The database that I'm using is Oracle 10g.
I post here a part of the code that is giving me problem:
private int importFile(String id, String fileName, String label,
String prosumerId, String districtCodes)
throws IOException,
SQLException {
logger.debug("Importing file [" + fileName + "]");
File f = new File(fileName);
BufferedReader br = null;
Calendar cal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String query = "insert into TB_SDK_USER_FILES values ("
+ id + ", '" + label + "', '"
+ fileName.substring(fileName.lastIndexOf("/") + 1) + "', 'active', "
+ "to_date('" + sdf.format(new Date(cal.getTimeInMillis())) + "', 'dd/mm/yyyy hh24:mi:ss'), "
+ "to_date('" + sdf.format(new Date(cal.getTimeInMillis())) + "', 'dd/mm/yyyy hh24:mi:ss'), "
+ "'" + prosumerId + "'"
+ ") ";
logger.debug("Executing query [" + query + "]");
dbl.openDBConnection();
int x = dbl.set(query);
if (x <= 0) {
dbl.rollback();
dbl.closeDBConnection();
logger.error("Insert in TB_SDK_USER_FILES failed, stopping execution ");
return -3;
}
PreparedStatement ps = null;
String line = new String();
try {
br = new BufferedReader(new FileReader(f));
query = "insert into TB_SDK_CONTENTS "
+ "(id, contentCode, cli, content, contentType, PROSUMERID, cld, email) "
+ "values (?,?,?,?,?,?,?,?)";
logger.debug("Executing query [" + query + "]");
ps = dbl.getPreparedStatement(query);
while ((line = br.readLine()) != null) {
String[] tmp = line.split("\t");
if (tmp.length < 4) {
logger.debug("Sono presenti erroneamente meno di 4 valori!!!!");
br.close();
f.delete();
dbl.rollback();
ps.close();
dbl.closeDBConnection();
return -2;
}
ps.setInt(1, new Integer(id).intValue());
String test = tmp[0].replace("*", "");
logger.debug("first column: test [" + test + "]");
try {
if (test.length() > 0) {
double testDouble = Double.parseDouble(test);
//int testInt = Integer.parseInt(test);
}
} catch (NumberFormatException nfe) {
logger.error("The first column does not satisfy the format requested. Found [" + tmp[0] + "] -- NumberFormatException");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -6;
}
if (tmp[0].length() > 0) {
ps.setString(2, tmp[0].trim());
} else {
logger.error("The first column does not satisfy the format requested. Found [" + tmp[0] + "] -- length() <= 0");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -6;
}
test = tmp[1].replace("*", "").trim();
logger.debug("second column: test [" + test + "]");
try {
if (test.length() > 0) {
double testDouble = Double.parseDouble(test);
//int testInt = Integer.parseInt(test);
}
} catch (NumberFormatException nfe) {
logger.error("The second column does not satisfy the format requested. Found [" + tmp[1] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -7;
}
if (tmp[1].length() > 0) {
ps.setString(3, tmp[1].trim());
} else {
logger.error("The second column does not satisfy the format requested. Found [" + tmp[1] + "] -- length() <= 0");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -7;
}
logger.debug("third column: tmp[2] [" + tmp[2] + "]");
ps.setString(4, tmp[2]);
if ((tmp[3].length() > 0) && ((tmp[3].compareToIgnoreCase("TTS") == 0)
|| (tmp[3].compareToIgnoreCase("Audio") == 0))) {
ps.setString(5, tmp[3].trim());
logger.debug("fourth column: tmp[3] [" + tmp[3] + "]");
} else {
logger.error("The fourth column does not satisfy the format requested. Found [" + tmp[3] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -10;
}
ps.setString(6, prosumerId);
if (tmp.length > 4) {
tmp[4] = tmp[4].trim();
if ((tmp[4].length() > 0) && (tmp[4].length() <= 12) && (tmp[4].matches("^\\d*$"))) {
boolean ok = false;
logger.debug("Checking district codes...");
String[] codes = districtCodes.split(",");
for (int i = 0; i < codes.length; i++) {
if (tmp[4].startsWith(codes[i].trim())) {
ok = true;
logger.debug("District code found.");
break;
}
}
if (ok) {
ps.setString(7, tmp[4]);
logger.debug("fifth column: tmp[4] [" + tmp[4] + "]");
} else {
logger.error("The fifth column does not satisfy the format requested. Found [" + tmp[4] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -8;
}
} else if (tmp[4].length() == 0) {
ps.setString(7, "-");
logger.debug("fifth column: tmp[4] [-]");
} else {
logger.error("The fifth column does not satisfy the format requested. Found [" + tmp[4] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -8;
}
} else {
ps.setString(7, "-");
}
if (tmp.length == 6) {
tmp[5] = tmp[5].trim();
if ((tmp[5].length() > 0) && (isValidEmailAddress(tmp[5]))) {
ps.setString(8, tmp[5]);
} else if (tmp[5].length() == 0) {
ps.setString(8, "-");
} else {
logger.error("The sixth column does not satisfy the format requested. Found [" + tmp[5] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -9;
}
} else {
ps.setString(8, "-");
}
x = ps.executeUpdate();
if (x <= 0) {
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
//f.delete();
logger.error("Insert in TB_SDK_CONTENTS failed, stopping execution ");
return -3;
}
}
br.close();
//f.delete();
ps.close();
dbl.commit();
dbl.closeDBConnection();
return 0;
} catch (Exception ex) {
logger.error("An exception occured during the import of file [" + fileName + "] for line [" + line + "]", ex);
dbl.rollback();
if (br != null) {
br.close();
}
if (ps != null) {
ps.close();
}
dbl.closeDBConnection();
//f.delete();
return -1;
}
}
On the other class that handle the DB operation:
public int set(String query) {
Statement statement = null;
int ris = -1;
try {
if (connection == null || !connection.isValid(1)) connect();
logger.debug("Opening statement");
statement = connection.createStatement();
ris = statement.executeUpdate(query);
} catch (SQLException ex) {
logger.error("ERROR in execution of [" + query + "] due to: ", ex);
ris = -1;
} finally {
try {
logger.debug("Closing statement");
if (statement != null) {
statement.close();
}
} catch (SQLException ex1) {
logger.error("ERROR cannot close statement.", ex1);
}
}
return ris;
}
The connection open:
public boolean connect() {
if (dataSource != null) {
try {
connection = dataSource.getConnection();
logger.info("Connection open to DB");
return true;
} catch (SQLException ex) {
logger.error("An error occured during request of connection to datasource, due to...", ex);
return false;
}
}
String url;
if (connectionString.length() > 0) {
url = connectionString;
} else {
url = "jdbc:oracle:thin:#" + host + ":" + port + ":" + sid;
}
try {
// create an OracleDataSource
OracleDataSource ods = new OracleDataSource();
// set connection properties
Properties prop = new Properties();
prop.put("user", user);
prop.put("password", pwd);
ods.setConnectionProperties(prop);
ods.setURL(url);
// get the connection
connection = ods.getConnection();
connection.setAutoCommit(false);
((OracleConnection) connection).setDefaultRowPrefetch(10);
logger.info("Connection open to DB");
return true;
} catch (Exception ex) {
logger.info("An exception occured in execution of [connect]. ");
if (dataSource == null) {
logger.error("[" + url + ", " + user + ", " + pwd + "] ERROR in execution of [connect] due to: ", ex);
}
return false;
}
}
dataSource getConnection():
public static Connection getConnection() throws SQLException {
Connection con = dataSource.getConnection();
con.setAutoCommit(false);
return con;
}
The lookup for the data source is done in the Context Listener at context creation.
Edit:
I'm reading again the oracle tutorials about the usage of pooling connection and other links about it: every example the open and close of the connection to the pool is done in the same method. I thought that was just a need to be more simplest to explain all the steps, but I'm wondering if this is not also a need to satisfy the "transaction" at connection pool level. Can anyone confirm me this? Or give me a documentation link where this is well explained? Thank you very much!

Categories