So I am working on a solution right now wherein we have 2 requirements:
Format SSN / Telephone Number in Hyphen form which is otherwise
currently being displayed without it.
Format an amount field in the format "$0.00".
Currently we have written a method formatAsHyphen and formatAmount as below:
/**
* This method converts the given string into US format SSN / Telephone number
* #param valueToFormat
* #param fieldToFormat , It should be either 'S' for SSN and 'T' for Mobile Number
* #return
*/
public String formatWithHyphen (String valueToFormat, String fieldToFormat) {
if(valueToFormat != null && valueToFormat.length() > 1) {
StringBuilder formattedValue = new StringBuilder(valueToFormat);
if(fieldToFormat.equalsIgnoreCase("S")) {
//format as SSN
formattedValue = formattedValue.insert(3, '-').insert(6, '-');
} else if(fieldToFormat.equalsIgnoreCase("T")) {
//format as telephone number
formattedValue = formattedValue.insert(3, '-').insert(7, '-');
}
return formattedValue.toString();
}
else {
return null;
}
}
/**
* This method converts a given amount string to a US $ formatted amount.
*
* #param amountToFormat
* #return
*/
public String formatAmount(String amountToFormat) {
try {
if(amountToFormat!=null && amountToFormat.length() > 0) {
Locale locale = new Locale("en", "US");
NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
return formatter.format(Double.parseDouble(amountToFormat));
}
else {
return null;
}
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
}
return null;
}
Now the issue is:
There are multiple pojo classes (TempAssist, SuppNutrition, ChildCare etc) which has the field related to
Amount and SSN / Telephone number
When we get those fields from database, firstly, the unformatted data is
set in the corresponding setters and then in the UI layer, we get
value through getter() and apply the above 2 functions to it and then
finally respond to the client in JSON format.
Its not a clean solution as set happens twice and the code is literally bloated with GET and SET's.
What I am looking for:
An Annotation (for instance, #Format(type="ssn") which I can apply on POJO fields which will ensure that whichever fields are annotated will have SSN updated with hyphen.
This is a web application which does not use Spring framework so any suggestions on Spring cannot be implemented.
Create a class extending JsonSerializer and then on your getter use the #JsonSerialize(using=MySerializer.class) annotation
One of the serializer could be something like:
public class MySerializer extends JsonSerializer<String> {
#Override
public void serialize( String value
, JsonGenerator jgen
, SerializerProvider provider) throws IOException
, JsonProcessingException {
jgen.writeString(MyUtilsClass.formatWithHyphen(value) );
}
}
Related
So, I am making an application where I saved details of a client such as first name, surname, DOB, ID and address into a file called "clientListFile.txt". Everytime, a client information is added to the file there is an empty space before and after the information as shown below:
//empty line
//empty line
fn
sn
1900-08-01
1234
addressname
s
8
hn
a
pc
t
country
//empty line
//empty line
fn1
sn1
1900-08-02 ... (etc)
In the code below, I am able to find if a string is stored into the file. For example, in my program, if I search "fn" or if I search "1234", it prints out which line it is located on. However, I want it to print out everything in the JTextArea called "jDisplaySearchedClientsTextArea" between the first two empty lines and the last two empty lines.
private void jSearchClientsButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String fn = jClientsFNTextField.getText();
String clientListFile = "clientListFile.txt";
try {
BufferedReader areader = new BufferedReader(new FileReader(new File(clientListFile)));
Scanner scanner = new Scanner(clientListFile);
//now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (fn.equals(areader.readLine())) {
System.out.println("ho hum, i found it on line " +lineNum);
}
}
}
catch (IOException ioe) {
System.out.println("Error while saving Head Office Address");
}
}
You might use a method something like this:
/**
* Parses and searches a "clientListFile.txt" data file based on the supplied
* search criteria.<br>
*
* #param dataFilePath (String) The full path and file name of the data file
* to search in.<br>
*
* #param searchCriteria (String) What to search for in each data record
* contained within the supplied data file.<br>
*
* #param useContains (Optional - Boolean - Default is True) This optional
* parameter by default is boolean '<b>true</b>'. This means that every search
* done in any data file record is carried out by locating the search criteria
* (ignoring letter case) within any record field value location that <u><b>contains</b></u>
* the search criteria. An example
* of this would be:<pre>
*
* Search Criteria: "fred"
*
* A Data Record:
* =============
* First Name: Danny (No Match)
* Surname: Fredrikson (Match - Fred......)
* Birthdate: 1957-11-07 (No Match)
* Cient ID: 1234 (No Match)
* Address: 3233 Sandy St. (No Match)
* City: Fredericton (Match - Fred.......)
* Province: New Brunswick (No Match)
* etc.....</pre><br>
*
* If boolean '<b>false</b>' is optionally supplied then the search is done
* based on <u><b>equality</b></u>. This means that every search done in any data file
* record is carried out by locating the search criteria within any record
* field value that is <b>equal to</b> (ignoring letter case) the supplied
* search criteria. An example of this would be:<pre>
*
* Search Criteria: "fred"
*
* A Data Record:
* =============
* First Name: Fred (Match - Fred)
* Surname: Fredrikson (No Match)
* Birthdate: 1957-11-07 (No Match)
* Cient ID: 1234 (No Match)
* Address: 3233 Sandy St. (No Match)
* City: Fredericton (No Match)
* Province: New Brunswick (No Match)
* etc.....</pre><br>
*
* #return A List Interface Object of Type String - {#code List<String>}.
*/
public static List<String> searchInRecords(String dataFilePath, String searchCriteria, boolean... useContains) {
boolean UseCONTAINSinSearches = true;
if (useContains.length > 0) {
UseCONTAINSinSearches = useContains[0];
}
int fileLinesCounter = 0;
int fieldsCounter = 0;
int dataRecordsCounter = 0;
int criterialFoundRecords = 0;
boolean inRecord = false;
List<String> foundRecords = new ArrayList<>();
String[] fields = new String[12];
// 'Try With Resources' use here to auto-close the reader.
try (BufferedReader reader = new BufferedReader(new FileReader(dataFilePath))) {
String line;
while ((line = reader.readLine()) != null) {
fileLinesCounter++;
line = line.trim();
if (line.isEmpty() && fieldsCounter == 0) {
inRecord = true;
}
else if (inRecord && fieldsCounter <= 11) {
fields[fieldsCounter] = line;
if (fieldsCounter == 11) {
String record = new StringBuilder("").append(fields[0]).append(", ")
.append(fields[1]).append(", ").append(fields[2]).append(", ")
.append(fields[3]).append(", ").append(fields[4]).append(", ")
.append(fields[5]).append(", ").append(fields[6]).append(", ")
.append(fields[7]).append(", ").append(fields[8]).append(", ")
.append(fields[9]).append(", ").append(fields[10]).append(", ")
.append(fields[11]).toString();
dataRecordsCounter++;
// Search Type 1 (using CONTAINS where criteria is anywhere in a field)
if (UseCONTAINSinSearches) {
for (String field : fields) {
if (field == null) { continue; }
if (field.toLowerCase().contains(searchCriteria)) {
if (!foundRecords.contains(record)) {
foundRecords.add(record);
criterialFoundRecords++;
}
}
}
}
// Search Type 2 (using exact match to field but ignoring letter case)
else {
for (String field : fields) {
if (field == null) { continue; }
if (field.equalsIgnoreCase(searchCriteria)) {
if (!foundRecords.contains(record)) {
foundRecords.add(record);
criterialFoundRecords++;
}
}
}
}
}
fieldsCounter++;
}
else {
fieldsCounter = 0;
inRecord = false;
}
}
}
// Handle the exceptions (if any) any way you see fit.
catch (FileNotFoundException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
/* The following integer type variables can be used to supply related
class member variables. They serve no specific purpose within this
method and can be removed if desired. Sometimes this information can
be handy. */
System.out.println("Overall Number of Data File Lines: --> " + fileLinesCounter);
System.out.println("Overall Number of Records in File: --> " + dataRecordsCounter);
System.out.println("Criterial Search - Records Found: --> " + criterialFoundRecords);
return foundRecords;
}
Far better of course to utilize a database for this sort of thing and the use of a Client class. Even with a file type data storage method (like you are using), you would really want a Client class to keep that data organized and store the data more like in a CSV style (Comma Separated Values) file. Here is an example of a custom CSV data file:
Client ID, First Name, Sir Name, Date Of Birth, Address, City, State/Province, Postal Code, Country, E-Mail, Phone Number
=======================================================================================================================================================================================
1234, Fred, Flinstone, 1957-11-07, 2977 Oriole Cooky Way, Bedrock, Stones Throw, V2Q5W8, Canada, his-email#yahoo.com, 604-776-1121
1235, Wilma, Flinstone, 1964-11-30, 2977 Oriole Cooky Way, Bedrock, Stones Throw, V2Q5W8, Canada, her-email#yahoo.com, 604-776-3466
1236, Jack, Naso, 1993-03-18, 33912 CrackShack Ave, Vancouver, British Columbia, V2Z1D2, Canada, myemailaddy#hotmail.com, 856-302-1122
1237, William, Shakaconn, 1996-12-13, 1212 Playwrite Street, Langely, British Columbia, V2T4C9, Canada, playme#gmail.ca, 777-664-9351
In this custom CSV file the data is laid out more like a table and records are more legible even when just reading the file itself. If you want your Client class to do this sort of thing then just E-Mail me.
This question already has answers here:
If statement gives condition is always true
(4 answers)
Closed 2 years ago.
I'm totally new to Java programming and I'm trying to create a Java FX project. I've followed tutorials about the date validation method but it seems to fail.In this certain part I have to make a list with objects inserted by a user in text fields. That includes a date but it needs to be valid.
Below in this piece of code, the object I need to get validated is datep . I've created a method in which if the string is valid, it should set my flag to true and return it. Before the list is created I inserted an if statement to check whether that my flag is set to true which means that the date is verified according to the format.When I run it,it creates the list whatsoever even if the date is invalid.Am I putting the if statement in the wrong part? Cause I think the method is fine.
#Override
public void handle(MouseEvent event) {
if (event.getSource() == NewrentBtn) {
String vehiclen =OximaTxT.getText();
String clientn = ClientTxT.getText();
String store = StoreTxT.getText();
String storer = StorerTxT.getText();
String timerp = TimeTxT.getText();
String timer = TimerTxT.getText();
String datep = DateTxT.getText(); // <-------------
String dater = DaterTxT.getText();
Integer sum = Integer.parseInt(SumTxT.getText());
if(flag = true) { // <------------
createRental(id, vehiclen, store, datep, timerp, clientn, storer, dater, timer, sum);
clearTextFields();
}
}
public boolean Checkdate(String datep) { // <-------------
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date BOD = null;
df.setLenient(false);
try
{
BOD = df.parse(datep); // <----------------
flag = true;
}
catch(Exception e)
{
flag = false;
}
return flag;
}
public void createRental(int id,String vehiclen,String store,String datep,String timerp,String clientn,String storer,String dater,String timer,int sum ) {
Rental m = new Rental(id,vehiclen,store,datep,timerp,clientn,storer,dater,timer,sum);
RentalList.add(m);
rentalTableView.getItems().add(m);
}
From the looks of what you are trying to achieve here is my suggestion to modify the code.
First of all let me explain to you two issues i found: the first one is that you are missing the call to the validation method of the Date, that is the call to the CheckDate(datep) when you receive the text input and store the flag variable, or so it seems as we dont have the full code (which is ok ); and second you are missing a =in the if(flag = true), it should be if(flag == true)
So here is the full code:
#Override
public void handle(MouseEvent event) {
if (event.getSource() == NewrentBtn) {
String vehiclen =OximaTxT.getText();
String clientn = ClientTxT.getText();
String store = StoreTxT.getText();
String storer = StorerTxT.getText();
String timerp = TimeTxT.getText();
String timer = TimerTxT.getText();
String dater = DaterTxT.getText();
Integer sum = Integer.parseInt(SumTxT.getText());
String datep = DateTxT.getText();
boolean flag = Checkdate(datep);
if(flag == true) {
createRental(id,vehiclen,store,datep,timerp,clientn,storer,dater,timer,sum);
clearTextFields();
}
}
}
This way you are verifying if the date is correctly formatted and continue the process if it is according to your scheme.
Finally i have three recommendations as you are new to java programming:
For all methods the first letter should always be in lowercase like public boolean checkDate() this way you can differentiate a method from a Class, which will always start in Uppercase like public class Product. The only exception for this is the constructor of a class.
You should never mix the graphical interface logic, with the logical processing logic. This is: you should keep the processing part in one package and the graphic component in another and relate both of them by creating an instance of the processing logic in the graphical interface.
The user input validation should be directly made in the handler method with try-catch clauses like the following.
Here:
public void handle(MouseEvent event) {
if (event.getSource() == NewrentBtn) {
String vehiclen =OximaTxT.getText();
String clientn = ClientTxT.getText();
String store = StoreTxT.getText();
String storer = StorerTxT.getText();
String timerp = TimeTxT.getText();
String timer = TimerTxT.getText();
String dater = DaterTxT.getText();
Integer sum = Integer.parseInt(SumTxT.getText());
try {
String datep = DateTxT.getText();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.parse(date);
createRental(id,vehiclen,store,datep,timerp,clientn,storer,dater,timer,sum);
clearTextFields();
} catch (ParseException e) {
/* Here you handle what happens when if fails, you can create a JDialog to show
the error or create an alert, whatever you need */
e.printStackTrace();
}
}
}
And voila a cleaner version
I'm trying to create a validate java class that receives 4 inputs from an object passed as 1 from the requester. The class needs to convert float inputs to string and evaluate each input to meet a certain format and then throw exceptions complete with error message and code when it fails.
What I have is in two methods and would like to know if there is a better way to combine these two classes into one validate method for the main class to call. I don't seem to be able to get around using the pattern/matcher concept to insure the inputs are formatted correctly. Any help you can give would be very much appreciated.
public class Validator {
private static final String MoneyPattern ="^\\d{1,7}(\\.\\d{1,2})$" ;
private static final String PercentagePattern = "^\\d{1,3}\\.\\d{1,2}$";
private static final String CalendarYearPattern = "^20[1-9][0-9]$";
private int errorcode = 0;
private String errormessage = null;
public Validator(MyInput input){
}
private boolean verifyInput(){
String Percentage = ((Float) input.getPercentage().toString();
String Income = ((Float) input.getIncome().toString();
String PublicPlan = ((Float) input.getPublicPlan().toString();
String Year = ((Float) input.getYear();
try {
if (!doesMatch(Income, MoneyPattern)) {
errormessage = errormessage + "income,";
}
if (!doesMatch(PublicPlan, MoneyPattern)) {
errormessage = errormessage + "insurance plan,";
}
if (!doesMatch(Percentage, PercentagePattern)) {
errormessage = errormessage + "Percentage Plan,";
}
if (!doesMatch(Year, CalendarYearPattern)) {
errormessage = errormessage + "Year,";
}
} catch (Exception e){
errorcode = 111;
errormessage = e.getMessage();
}
}
private boolean doesMatch(String s, String pattern) throws Exception{
try {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(s);
if (!s.equals("")){
if(m.find()){
return true;
} else {
return false;
}
}else {
return false;
}
} catch (PatternSyntaxException pse){
errorcode = 111;
errormessage = pse.getMessage();
}
}
}
This code is borked from the word "go". You have a constructor into which you pass a MyInput reference, but there's no code in the ctor and no private data member to receive it. It looks like you expect to use input in your doesMatch() method, but it's a NullPointerException waiting to happen.
Your code doesn't follow the Sun Java coding standards; variable names should be lower case.
Why you wouldn't do that input validation in the ctor, when you actually receive the value, is beyond me. Perhaps you really meant to pass it into that verifyInput() method.
I would worry about correctness and readability before concerning myself with efficiency.
I'd have methods like this:
public boolean isValidMoney(String money) { // put the regex here }
public boolean isValidYear(String year) { // the regex here }
I think I'd prefer a real Money class to a String. There's no abstraction whatsoever.
Here's one bit of honesty:
private static final String CalendarYearPattern = "^20[1-9][0-9]$";
I guess you either don't think this code will still be running in the 22nd century or you won't be here to maintain it.
One way of doing this would be with DynamicBeans.
package com.acme.validator;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.beanutils.PropertyUtils;
public class Validator {
//A simple optimisation of the pattern
private static final Pattern MoneyPattern = Pattern.compile("^\\d{1,7}(\\.\\d{1,2})$");
private static final Pattern PercentagePattern = Pattern.compile("^\\d{1,3}\\.\\d{1,2}$");
private static final Pattern CalendarYearPattern = Pattern.compile("^20[1-9][0-9]$");
public String Validator(MyInput input) {
String errormessage = "";
/*
* Setting these up as Maps.
* Ideally this would be a 'simple bean'
* but that goes beyond the scope of the
* original question
*/
Map<String,Pattern> patternMap = new HashMap<String,Pattern>();
patternMap.put("percentage", PercentagePattern);
patternMap.put("publicPlan", MoneyPattern);
patternMap.put("income", MoneyPattern);
patternMap.put("year", CalendarYearPattern);
Map<String,String> errorMap = new HashMap<String,String>();
errorMap.put("percentage", "Percentage Plan,");
errorMap.put("publicPlan", "insurance plan,");
errorMap.put("income", "income,");
errorMap.put("year", "Year,");
for (String key : patternMap.keySet()) {
try {
String match = ((Float) PropertyUtils.getSimpleProperty(input, key)).toString();
Matcher m = patternMap.get(key).matcher(match);
if ("".equals(match) || !m.find()) {
errormessage = errormessage + errorMap.get(key);
}
} catch (Exception e) {
errormessage = e.getMessage(); //since getMessage() could be null, you need to work out some way of handling this in the response
//don't know the point of the error code so remove this altogether
break; //Assume an exception trumps any validation failure
}
}
return errormessage;
}
}
I've made a few assumptions about the validation rules (for simplicity used 2 maps but you could also use a single map and a bean containing both the Pattern and the Message and even the 'error code' if that is important).
The key 'flaw' in your original setup and what would hamper the solution above, is that you are using 'year' as Float in the input bean.
(new Float(2012)).toString()
The above returns "2012.0". This will always fail your pattern. When you start messing about with the different types of objects potentially in the input bean, you may need to consider ensuring they are String at the time of creating the input bean and not, as is the case here, when they are retrieved.
Good Luck with the rest of your Java experience.
The accept-language header in request is usually a long complex string -
Eg.
Accept-Language : en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2
Is there a simple way to parse it in java? Or a API to help me do that?
I would suggest using ServletRequest.getLocales() to let the container parse Accept-Language rather than trying to manage the complexity yourself.
For the record, now it is possible with Java 8:
Locale.LanguageRange.parse()
Here's an alternative way to parse the Accept-Language header which doesn't require a servlet container:
String header = "en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2";
for (String str : header.split(",")){
String[] arr = str.trim().replace("-", "_").split(";");
//Parse the locale
Locale locale = null;
String[] l = arr[0].split("_");
switch(l.length){
case 2: locale = new Locale(l[0], l[1]); break;
case 3: locale = new Locale(l[0], l[1], l[2]); break;
default: locale = new Locale(l[0]); break;
}
//Parse the q-value
Double q = 1.0D;
for (String s : arr){
s = s.trim();
if (s.startsWith("q=")){
q = Double.parseDouble(s.substring(2).trim());
break;
}
}
//Print the Locale and associated q-value
System.out.println(q + " - " + arr[0] + "\t " + locale.getDisplayLanguage());
}
You can find an explanation of the Accept-Language header and associated q-values here:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
Many thanks to Karl Knechtel and Mike Samuel. Thier comments to the original question helped point me in the right direction.
We are using Spring boot and Java 8. This works
In ApplicationConfig.java write this
#Bean
public LocaleResolver localeResolver() {
return new SmartLocaleResolver();
}
and I have this list in my constants class that has languages that we support
List<Locale> locales = Arrays.asList(new Locale("en"),
new Locale("es"),
new Locale("fr"),
new Locale("es", "MX"),
new Locale("zh"),
new Locale("ja"));
and write the logic in the below class.
public class SmartLocaleResolver extends AcceptHeaderLocaleResolver {
#Override
public Locale resolveLocale(HttpServletRequest request) {
if (StringUtils.isBlank(request.getHeader("Accept-Language"))) {
return Locale.getDefault();
}
List<Locale.LanguageRange> ranges = Locale.LanguageRange.parse("da,es-MX;q=0.8");
Locale locale = Locale.lookup(ranges, locales);
return locale ;
}
}
ServletRequest.getLocale() is certainly the best option if it is available and not overwritten as some frameworks do.
For all other cases Java 8 offers Locale.LanguageRange.parse() as previously mentioned by Quiang Li. This however only gives back a Language String, not a Locale. To parse the language strings you can use Locale.forLanguageTag() (available since Java 7):
final List<Locale> acceptedLocales = new ArrayList<>();
final String userLocale = request.getHeader("Accept-Language");
if (userLocale != null) {
final List<LanguageRange> ranges = Locale.LanguageRange.parse(userLocale);
if (ranges != null) {
ranges.forEach(languageRange -> {
final String localeString = languageRange.getRange();
final Locale locale = Locale.forLanguageTag(localeString);
acceptedLocales.add(locale);
});
}
}
return acceptedLocales;
Locale.forLanguageTag("en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2")
The above solutions lack some kind of validation. Using ServletRequest.getLocale() returns the server locale if the user does not provides a valid one.
Our websites lately received spam requests with various Accept-Language heades like:
secret.google.com
o-o-8-o-o.com search shell is much better than google!
Google officially recommends o-o-8-o-o.com search shell!
Vitaly rules google ☆*:。゜゚・*ヽ(^ᴗ^)ノ*・゜゚。:*☆ ¯\_(ツ)_/¯(ಠ益ಠ)(ಥ‿ಥ)(ʘ‿ʘ)ლ(ಠ_ಠლ)( ͡° ͜ʖ ͡°)ヽ(゚Д゚)ノʕ•̫͡•ʔᶘ ᵒᴥᵒᶅ(=^ ^=)oO
This implementation can optional check against a supported list of valid Locale. Without this check a simple request with "test" or (2, 3, 4) still bypass the syntax-only validation of LanguageRange.parse(String).
It optional allows empty and null values to allow search engine crawler.
Servlet Filter
final String headerAcceptLanguage = request.getHeader("Accept-Language");
// check valid
if (!HttpHeaderUtils.isHeaderAcceptLanguageValid(headerAcceptLanguage, true, Locale.getAvailableLocales()))
return;
Utility
/**
* Checks if the given accept-language request header can be parsed.<br>
* <br>
* Optional the parsed LanguageRange's can be checked against the provided
* <code>locales</code> so that at least one locale must match.
*
* #see LanguageRange#parse(String)
*
* #param acceptLanguage
* #param isBlankValid Set to <code>true</code> if blank values are also
* valid
* #param locales Optional collection of valid Locale to validate any
* against.
*
* #return <code>true</code> if it can be parsed
*/
public static boolean isHeaderAcceptLanguageValid(final String acceptLanguage, final boolean isBlankValid,
final Locale[] locales)
{
// allow null or empty
if (StringUtils.isBlank(acceptLanguage))
return isBlankValid;
try
{
// check syntax
final List<LanguageRange> languageRanges = Locale.LanguageRange.parse(acceptLanguage);
// wrong syntax
if (languageRanges.isEmpty())
return false;
// no valid locale's to check against
if (ArrayUtils.isEmpty(locales))
return true;
// check if any valid locale exists
for (final LanguageRange languageRange : languageRanges)
{
final Locale locale = Locale.forLanguageTag(languageRange.getRange());
// validate available locale
if (ArrayUtils.contains(locales, locale))
return true;
}
return false;
}
catch (final Exception e)
{
return false;
}
}
I have tried to find information about this but have come up empty handed:
I gather it is possible to create a class dynamically in Java using reflection or proxies but I can't find out how. I'm implementing a simple database framework where I create the SQL queries using reflection. The method gets the object with the database fields as a parameter and creates the query based on that. But it would be very useful if I could also create the object itself dynamically so I wouldn't have the need to have a simple data wrapper object for each table.
The dynamic classes would only need simple fields (String, Integer, Double), e.g.
public class Data {
public Integer id;
public String name;
}
Is this possible and how would I do this?
EDIT: This is how I would use this:
/** Creates an SQL query for updating a row's values in the database.
*
* #param entity Table name.
* #param toUpdate Fields and values to update. All of the fields will be
* updated, so each field must have a meaningful value!
* #param idFields Fields used to identify the row(s).
* #param ids Id values for id fields. Values must be in the same order as
* the fields.
* #return
*/
#Override
public String updateItem(String entity, Object toUpdate, String[] idFields,
String[] ids) {
StringBuilder sb = new StringBuilder();
sb.append("UPDATE ");
sb.append(entity);
sb.append("SET ");
for (Field f: toUpdate.getClass().getDeclaredFields()) {
String fieldName = f.getName();
String value = new String();
sb.append(fieldName);
sb.append("=");
sb.append(formatValue(f));
sb.append(",");
}
/* Remove last comma */
sb.deleteCharAt(sb.toString().length()-1);
/* Add where clause */
sb.append(createWhereClause(idFields, ids));
return sb.toString();
}
/** Formats a value for an sql query.
*
* This function assumes that the field type is equivalent to the field
* in the database. In practice this means that this field support two
* types of fields: string (varchar) and numeric.
*
* A string type field will be escaped with single parenthesis (') because
* SQL databases expect that. Numbers are returned as-is.
*
* If the field is null, a string containing "NULL" is returned instead.
*
* #param f The field where the value is.
* #return Formatted value.
*/
String formatValue(Field f) {
String retval = null;
String type = f.getClass().getName();
if (type.equals("String")) {
try {
String value = (String)f.get(f);
if (value != null) {
retval = "'" + value + "'";
} else {
retval = "NULL";
}
} catch (Exception e) {
System.err.println("No such field: " + e.getMessage());
}
} else if (type.equals("Integer")) {
try {
Integer value = (Integer)f.get(f);
if (value != null) {
retval = String.valueOf(value);
} else {
retval = "NULL";
}
} catch (Exception e) {
System.err.println("No such field: " + e.getMessage());
}
} else {
try {
String value = (String) f.get(f);
if (value != null) {
retval = value;
} else {
retval = "NULL";
}
} catch (Exception e) {
System.err.println("No such field: " + e.getMessage());
}
}
return retval;
}
There are many different ways to achieve this (e.g proxies, ASM), but the simplest approach, one that you can start with when prototyping is:
import java.io.*;
import java.util.*;
import java.lang.reflect.*;
public class MakeTodayClass {
Date today = new Date();
String todayMillis = Long.toString(today.getTime());
String todayClass = "z_" + todayMillis;
String todaySource = todayClass + ".java";
public static void main (String args[]){
MakeTodayClass mtc = new MakeTodayClass();
mtc.createIt();
if (mtc.compileIt()) {
System.out.println("Running " + mtc.todayClass + ":\n\n");
mtc.runIt();
}
else
System.out.println(mtc.todaySource + " is bad.");
}
public void createIt() {
try {
FileWriter aWriter = new FileWriter(todaySource, true);
aWriter.write("public class "+ todayClass + "{");
aWriter.write(" public void doit() {");
aWriter.write(" System.out.println(\""+todayMillis+"\");");
aWriter.write(" }}\n");
aWriter.flush();
aWriter.close();
}
catch(Exception e){
e.printStackTrace();
}
}
public boolean compileIt() {
String [] source = { new String(todaySource)};
ByteArrayOutputStream baos= new ByteArrayOutputStream();
new sun.tools.javac.Main(baos,source[0]).compile(source);
// if using JDK >= 1.3 then use
// public static int com.sun.tools.javac.Main.compile(source);
return (baos.toString().indexOf("error")==-1);
}
public void runIt() {
try {
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName(todayClass);
Object iClass = thisClass.newInstance();
Method thisMethod = thisClass.getDeclaredMethod("doit", params);
thisMethod.invoke(iClass, paramsObj);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
It is possible to generate classes (via cglib, asm, javassist, bcel), but you shouldn't do it that way. Why?
the code that's using the library should expect type Object and get all the fields using reflection - not a good idea
java is statically typed language, and you want to introduce dynamic typing - it's not the place.
If you simply want the data in an undefined format, then you can return it in an array, like Object[], or Map<String, Object> if you want them named, and get it from there - it will save you much trouble with unneeded class generation for the only purpose of containing some data that will be obtained by reflection.
What you can do instead is have predefined classes that will hold the data, and pass them as arguments to querying methods. For example:
public <T> T executeQuery(Class<T> expectedResultClass,
String someArg, Object.. otherArgs) {..}
Thus you can use reflection on the passed expectedResultClass to create a new object of that type and populate it with the result of the query.
That said, I think you could use something existing, like an ORM framework (Hibernate, EclipseLink), spring's JdbcTemplate, etc.
This is possible, but (I believe) you need something like ASM or BCEL.
Alternately, you could use something with more power (like Groovy).
It will take a couple of minutes to create a data model class for each table, which you can easily map to the database with an ORM like Hibernate or by writing your own JDBC DAOs. It is far easier than delving deeply into reflection.
You could create a utility that interrogates the database structure for a table, and creates the data model class and DAO for you. Alternatively you could create the model in Java and create a utility to create the database schema and DAO from that (using reflection and Java 5 Annotations to assist). Don't forget that javaFieldNames are different from database_column_names typically.
Recently I needed to create about 200 simple classes from medatata (objects filled with static data) and I did it through the open source burningwave library, with the following scenario:
The classes needed to have a certain prefix in the name, for example "Registro "*.java;
The classes needed to extend from a superclass Registro.java
The classes needed to contain JPA annotations like #Entity, #Column (in attributes), Lombok annotations and custom annotations.
Here is the link to the repository with the complete project: https://github.com/leandrosoares6/criacao-classes-entidade-efd
Here is the code snippet responsible for creating the classes:
public class RegistrosClassFactory {
private static final String PACOTE = "com.example.demo.model.registros";
private static final String SCHEMA = "MY_SCHEMA";
private static final String PREFIXO = "Registro";
static void criaRegistros() {
List<RegistroTest> registros = RegistroMetadataFactory.criaMetadados();
criaClasses(registros);
}
private static void criaClasses(List<RegistroTest> registros) {
for (RegistroTest registroTest : registros) {
UnitSourceGenerator gerador = UnitSourceGenerator.create(PACOTE);
ClassSourceGenerator registro = ClassSourceGenerator
.create(TypeDeclarationSourceGenerator.create(PREFIXO + registroTest.getNome()))
.addModifier(Modifier.PUBLIC)
.addAnnotation(AnnotationSourceGenerator.create(Getter.class))
.addAnnotation(AnnotationSourceGenerator.create(Setter.class))
.addAnnotation(AnnotationSourceGenerator.create(NoArgsConstructor.class))
.addAnnotation(AnnotationSourceGenerator.create(ToString.class))
.addAnnotation(AnnotationSourceGenerator.create(Entity.class))
.addAnnotation(AnnotationSourceGenerator.create(Table.class)
.addParameter("name",
VariableSourceGenerator.create(String.format("\"%s\"",
registroTest.getNomeTabelaBd())))
.addParameter("schema", VariableSourceGenerator
.create(String.format("\"%s\"", SCHEMA))));
criaColunas(registroTest.getCampos(), registro);
registro.addConstructor(FunctionSourceGenerator.create().addModifier(Modifier.PUBLIC)
.addParameter(VariableSourceGenerator.create(String.class, "linha"))
.addBodyCodeLine("super(linha);")).expands(Registro.class);
gerador.addClass(registro);
// System.out.println("\nRegistro gerado:\n" + gerador.make());
String caminhoPastaRegistros = System.getProperty("user.dir") + "/src/main/java/";
gerador.storeToClassPath(caminhoPastaRegistros);
}
}
private static void criaColunas(List<Campo> campos, ClassSourceGenerator registro) {
for (Campo campo : campos) {
VariableSourceGenerator field = VariableSourceGenerator
.create(TypeDeclarationSourceGenerator.create(String.class),
campo.getNomeAtributo())
.addModifier(Modifier.PRIVATE)
.addAnnotation(AnnotationSourceGenerator.create(Column.class)
.addParameter("name", VariableSourceGenerator
.create(String.format("\"%s\"", campo.getNome())))
)
.addAnnotation(AnnotationSourceGenerator.create(Indice.class).addParameter(
"valor",
VariableSourceGenerator.create(String.valueOf(campo.getSequencial()))));
if (campo.getNome().equals("ID")) {
field.addAnnotation(AnnotationSourceGenerator.create(Id.class));
}
if (campo.getEId()) {
field.addAnnotation(AnnotationSourceGenerator.create(CampoTipoId.class));
}
if (campo.getEData()) {
field.addAnnotation(AnnotationSourceGenerator.create(CampoTipoData.class));
}
if (campo.getEDataPart()) {
field.addAnnotation(AnnotationSourceGenerator.create(CampoTipoDataPart.class));
}
registro.addField(field);
}
}
}
I'm aware of the performance drawback of reflection but for my little project I needed this and I created a project lib which converts JSON to Java and then finally .class in JVM context.
Anyone need such thing can have a look into my open source solution, which requires JDK to compile the code.
https://medium.com/#davutgrbz/the-need-history-c91c9d38ec9?sk=f076487e78a1ff5a66ef8eb1aa88f930