Java enum for use across class - java

I am having trouble declaring an enumeration for DB field types that I can use across all functions of a particular class. With the following code I get "cannot resolve USERNAME to a variable type":
public class SQL_access {
public enum DBfields { BLANK, USERNAME, ID, PASSWORD, FIRSTNAME, LASTNAME };
public boolean loginValidate( String username, String password ){
String DBuser, DBpass;
PreparedStatement table = connectToTable( "firstsql", "users");
ResultSet row = table.executeQuery();;
while(row.next()){
DBuser = row.getString(USERNAME);
if(DBuser.equals(username)){
DBpass = row.getString(PASSWORD);
break;
}
}
}
};

You need to use DBfields.USERNAME.
UPDATE:
in order to use with the getString(String) method, you need to use the name of the enum, like: Dbfields.USERNAME.name().
if you are using the enums only for the jdbc API access, you would be better off just using a String constant:
public static final String DBFIELD_USERNAME = "USERNAME";

You need to reference the enum Type: DBfields.USERNAME, or statically import the enum like:
import static mypackage.SQL_access.DBfields.*;
Also, in your case, this is not enough. You need to pass the column name -- a String -- or the column position -- an int -- to the ResultSet:
row.getString(DBfields.USERNAME.name());
Used like this, you loose the main advantage of enums which is it's static nature, but it can still be useful in other places in your code if you refer to these values as a "bag".

You should access the enum by using DBfields.USERNAME.
See the Oracle Docs for more information.

Try qualifying the enumerator with the enum type:
while(row.next()){
DBuser = row.getString( DBfields.USERNAME);
if(DBuser.equals(username)){
DBpass = row.getString( DBfields.PASSWORD);
break;
}
}

When you reference an enumeration it is always in this form EnumName.Field. In your example you need the following:
DBUser = row.getString(DBfields.USERNAME);
DBpass=row.getString(DBfields.PASSWORD);

to access your enumbs use DBfields.USERNAME, but this will not help you, bacuse row.getString() needs an int as argument. Your Enumbs are of the Type DBFields not int.
better use public static final int USERNAME = the int value here; and call with row.getString(USERNAME);.

Wrong way.You need to call the enum using DBfields.PASSWORD.

You need to call like this: DBfields.PASSWORD

Related

Having trouble reading String from MySQL table to Eclipse

I have a project of coupons but I have an issue when trying to read a coupon to Eclipse. I have a table of categories which are connected to my coupons table in row "CATEGORY_ID" which is an int. when using add Method I convert my ENUM to int in order to add it to CATEGORY_ID with no problem.
my issue is when trying to read it, I try and convert it to STRING to get a text value, however, I get an exception.
here is my code:
ENUM CLASS:
public enum Category {
FOOD(1), ELECTRICITY(2), RESTAURANT(3), VACATION(4), HOTEL(5);
private Category(final int cat) {
this.cat = cat;
}
private int cat;
public int getIDX() {
return cat;
}
private Category(String cat1) {
this.cat1 = cat1;
}
private String cat1;
public String getName() {
return cat1;
}
}
A Method to add coupon to table COUPONS:
// sql = "INSERT INTO `couponsystem`.`coupons` (`COMPANY_ID`,`CATEGORY_ID`,`TITLE`, `DESCRIPTION`,
`START_DATE`, `END_DATE`, `AMOUNT`, `PRICE`, `IMAGE`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);";
#Override
public void addCoupon(Coupon coupon) throws SQLException {
Connection connection = pool.getConnection();
try {
PreparedStatement statement = connection.prepareStatement(ADD_COUPON);
statement.setInt(1, coupon.getCompanyID());
statement.setInt(2, coupon.getCategory().getIDX());
statement.setString(3, coupon.getTitle());
statement.setString(4, coupon.getDescription());
statement.setDate(5, (Date) coupon.getStartDate());
statement.setDate(6, (Date) coupon.getEndDate());
statement.setInt(7, coupon.getAmount());
statement.setDouble(8, coupon.getPrice());
statement.setString(9, coupon.getImage());
statement.execute();
} finally {
pool.restoreConnection(connection);
}
}
Method to get coupon:
// GET_ONE_COUPON = "SELECT * FROM `couponsystem`.`coupons` WHERE (`id` = ?);";
#Override
public Coupon getOneCoupon(int couponID) throws SQLException {
Connection connection = pool.getConnection();
Coupon result = null;
List<Category> cats = new ArrayList<Category>(EnumSet.allOf(Category.class));
try {
PreparedStatement statement = connection.prepareStatement(GET_ONE_COUPON);
statement.setInt(1, couponID);
ResultSet resultSet = statement.executeQuery();
resultSet.next();
result = new Coupon(resultSet.getInt(1), resultSet.getInt(2), Category.valueOf(resultSet.getString(3)),
resultSet.getString(4), resultSet.getString(5), resultSet.getDate(6), resultSet.getDate(7),
resultSet.getInt(8), resultSet.getDouble(9), resultSet.getString(10));
} finally {
pool.restoreConnection(connection);
}
return result;
on column index (3) I try a and convert ENUM to string to get a text value, here is where I get an exception.
EXCEPTION:
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant coupon.beans.Category.5
at java.base/java.lang.Enum.valueOf(Enum.java:240)
at coupon.beans.Category.valueOf(Category.java:1)
at coupon.dbdao.CouponsDBDAO.getOneCoupon(CouponsDBDAO.java:125)
at coupon.Program.main(Program.java:65)
Hope I am clear with my question. I have no issue adding any more information.
valueOf expects a string that corresponds to the name of the enum element, like "FOOD" but it looks like you pass a number. If you want to pass the id (number) from your enum you need a method to translate between the number and the enum element. Something like this
//in the enum Category
public static Category categoryFor(int id) {
switch (id) {
case 1:
return FOOD;
case 2:
return ELECTRICITY;
//... more case
default:
return HOTEL;
}
}
and then call it like
Category.categoryFor(resultSet.getInt(2))
or you need to store the actual name of the element in your table.
Also you shouldn't use *, "SELECT * ...", in your query but a list of column names so it is clear what column you map in your java code, "SELECT COMPANY_ID, CATEGORY_ID,TITLE,..."
As I understood correctly you're storing the category in your coupon as an enum constant in your code model. While storing it to the database you're mapping it to an integer value with the methods provided by you.
The culprit is in the Category.valueOf(resultSet.getString(3)) method/ part. The Enum.valueOf method is a default method on enums provided by Java and it's working with a String as a parameter - probably therefore you're also using resultSet.getString(3) instead of resultSet.getInt(3) which would have been more intuitive.
From the JavaDoc (which you can find here) it says:
... The name must match exactly an identifier used to declare an enum
constant in this type. (Extraneous whitespace characters are not
permitted.) ...
This means for to get the valueOf method working you need to call it exactly with one of the following values as its arguments: FOOD, ELECTRICITY, RESTAURANT, VACATION, HOTEL. Calling it with the int values like 1, 2, ... or 5 will lead to the IllegalArgumentException you face.
There a two solutions to fix the problem:
Either change your database model to store the enum values/ constants as strings in the table by calling the toString method on the category value before the insert into the database (then your code reading the coupons from the database can stay unchanged).
Or you need to provide your own custom implementation of the "valueOf" method - e.g. findCategoryById - which will work with integer values as its arguments. By writing your own findCategoryById method your code inserting the coupons into the database can remain unchanged.
To implement your own findCategoryById the signature of the method in the Category enum should look like:
public static Category findCategoryById(int index)
Then you can iterate through all available constants by Category.values() and compare the cat with the argument passed to the method and return the matching value based on it.
In case none matches you can simply return null or also throw an IllegalArgumentException. The latter one I'd personally prefer since it follows the "fail fast" approach and can avoid nasty and time consuming search for bugs.
Note: Enums in Java also have an auto generated/ auto assigned ordinal. You can simply request it by calling the ordinal method on a value of your enum. In your case the ordinals are matching the self assigned cat values, so that you could make use of them, instead of maintaining the cat attributes yourself.
When working with the ordinals it's worth mentioning that the order in which you specify your constants in the enum matters! When you change the order of the constants so the ordinals will. Therefore you also need to be careful when working with ordinals. Therefore you might prefer sticking with your current approach (which is not bad at all and widely used), since it avoids the ordering problems ordinals have.

Java object to URL params

I have Java POJO object and my goal is to convert it to URL parameters and use it in POST method.
...
public class PayseraRequest {
private int projectid = 123;
private int orderid = 987;
private String accepturl = "http://www.test.com";
...
My goal is convert object PayseraRequest to String urlParams
urlParams -> projectid=123&orderid=987&http%3A%2F%2Fwww.test.com&...`
Yes, write a method to do this, but you should URLEncode each parameter. projectid and orderid do not need URLencoding but it doesn't hurt. accepturl must definitely be UrlEncoded. It is good practice to encode anything you want to put into the query string of a URL.
See https://docs.oracle.com/javase/7/docs/api/index.html?java/net/URLEncoder.html
you can override the toString method of that class and with a say so StringBuilder get what you need.
You can check an example I have here:
https://github.com/lmpampaletakis/datumBoxSpringMVC/tree/master/datumBoxSpringMVC/src/main/java/com/lebab/datumbox
Your answer might be at SendRequest.java
You can replace the values of each parameter you want from your pojo

Java : Getter /setter for Arraylist<Object>

so i have :
ArrayList<data> mi = new ArrayList<data>();
i have a Query which do following :
while (rs.next()) {
mi.add(new users());
mi.get(i).name= rs.getString("name");
mi.get(i).pass= rs.getString("pass");
}
It works but i want it with Getter/setters like :
mi.get(i).setname( rs.getString("name"));
Edit : Misspelling i had it so
Why cant i call the methode?
Use
mi.get(i).setname(rs.getString("name"));
Your users class should have a public setname(String name) method, which sets the name field of user class
then, mi.get(i).setname(rs.getString("name")); will work
Because it is java. You cannot have such assignment
setname() = rs.getString("name")
It does not make sense. You shall set it as argument:
object.setName(rs.getString("name"))
Also please respect java naming conventions: Class has CamelCase, methods start with lower first character and then continue with camel case as well: setUserName
with
mi.get(i).setname()
you call the method setname(). The result (if any) is not a variable name and you cannot assign a value to it.
If your class has a method setname(String s) then use it as usual in Java:
mi.get(i).setname(rs.getString("name"))
I would recommend using the below approach
while (rs.next()) {
Users user = new Users();
user.setName(rs.getString("name"));
user.setPass(rs.getString("pass"));
mi.add(user);
}
Seems neater to set the values in your object and then adding them to the list.

take the value of enum and covert it to String

I should take from a variable enum its value and transform it to string.how can i do?
here it is the type enum:
public enum State{
b,c,p;
};
now i have to insert into an object String one value.
You might use enum.name orenum.toString to get the name of the enum constant, or enum.ordinal to get the ordinal position.
you can use name() or toString(), so :
State aState = State.c;
String strState = aState.name();
See here the official java reference for more information...
State.b.toString() will return "b". The same goes for the other ones.
Usually,
State state = ...;
String string = state.toString();
should work, but it is not recommended since someone might override toString for some other purpose.
Instead the method you are looking for is
String string = state.name();
As an aside, your enumerated stated should always be all in capitals, and they should have descriptive names. It's not a language rule, but a convention. For example enum State { ON, OFF, PAUSED; }.
I tend to do something more complicated, but I find that it's more flexible:
public enum MyEnumeration {
SOME_NAME("Some Name"),
OTHER_THING("Other Thing"),
...
MORE_VALUES("More Values"),
private final String displayName;
private MyEnumeration(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
}
This way, I use standard capitalization for my enums in code, but can have a more presentable name for them.
This trick can also be used to replace ordinal, by initializing a number, and then you don't need to worry about rearranging your enums.
Method #1: Using the built-in toString() and name() methods
If you want to print a String that is the same as the value of the State, then you can use the toString() method, or the name() method.
System.out.println(State.b); // Prints "b"
System.out.println(State.c); // Prints "c"
System.out.println(State.p); // Prints "p"
Method #2: Using a constructor to create a custom mapping
If you want to have a custom String associated with each of those states, you can use a constructor to associate a particular value with each enum value:
public enum State{
b("State B"), c("State C"), p("State P");
private String longName;
private State(String longName) {
this.longName = longName;
}
#Override
public String toString() {
return this.longName;
}
};
Of course, if you don't want to break the default toString() usage, you can create a different method called getFullName(), for example, to return the custom value.

Dynamic variable names Java

How will I be able to retrieve the value of a variable which has a dynamic name
For Example I have list of constants
public class Constant{
public static final String S_R = "Standard(240)";
public static final String S_W = "Standard(180)";
public static final String L_R = "Large(360)";
public static final String L_W = "Large(280)";
}
Based on database I build a variable name
String varName = "S" + "_" +"R"; // This can be S_R , S_W , L_R or L_W
String varVal = // How do i get value of S_R
Use a normal HashMap with variable names as strings against their values. Or use a EnumMap with enums as key and your value as values. AFAIK, that's the closest you can get when using Java. Sure, you can mess around with reflection but IMO the map approach is much more logical.
You can use a Map<String, String> and locate the value by its key.
Even better, you can have an enum:
public enum Foo {
S_R("Standard", 240),
S_W("Standard", 180),...;
private String type;
private String duration;
// constructor and getters
}
And then call Foo.valueOf(name)
(You can also do this via reflection - Constants.class.getField(fieldName) and then call field.get(null) (null for static). But that's not really a good approach.)
If you really must do this (and it's unlikely), you would have to use the Java "reflection" APIs.

Categories

Resources