I have a problem getting all the data in jtable. The last data that display is always "null" even though i enter data in that cell. Can anyone help me
for (int i = 0; i < model_1.getRowCount(); i++) {
if (String.valueOf(model_1.getValueAt(i, 0)) != null && !String.valueOf(model_1.getValueAt(i, 0)).isEmpty()) {
date = String.valueOf(model_1.getValueAt(i, 0));
}
if (String.valueOf(model_1.getValueAt(i, 1)) != null && !String.valueOf(model_1.getValueAt(i, 1)).isEmpty()) {
meal = String.valueOf(model_1.getValueAt(i, 1));
}
if (String.valueOf(model_1.getValueAt(i, 2)) != null && !String.valueOf(model_1.getValueAt(i, 2)).isEmpty()) {
time = String.valueOf(model_1.getValueAt(i, 2));
}
if (String.valueOf(model_1.getValueAt(i, 3)) != null && !String.valueOf(model_1.getValueAt(i, 3)).isEmpty()) {
activity = String.valueOf(model_1.getValueAt(i, 3));
}
try {
System.out.println(date + " " + meal + " " + time + " " + activity);
}
}
here is my sample output:
2017-10-02 sdfsd 01:30 sdfsdfsf
2017-10-03 dsfdfs 01:00 null
I guess your jtable is still active so the data hasn't been saved to the model yet.
Try to add this before your code:
if (table.isEditing())
table.getCellEditor().stopCellEditing();
I am getting a string response from server like this..
[
Anchor{anchorName='&loreal_lip_balm',
clientName='loreal india',
anchorPrice=10,
campaigns=[
Campaign{
campaignId='loreal_camp1',
question='How to Turn Your Melted Lipstick into a Tinted Lip Balm',
startDate=2015-08-04,
endDate=2015-08-04,
imageURL='null',
regionCountry='ALL',
rewardInfo='null',
campaignPrice=20,
options=null
}
]},
Anchor{
anchorName='&loreal_total_repair_5',
clientName='loreal india',
anchorPrice=125,
campaigns=[
Campaign{
campaignId='loreal_camp2',
question='Is it a good
product to buy?',
startDate=2015-08-04,
endDate=2015-08-04,
imageURL='null',
regionCountry='ALL',
rewardInfo='null',
campaignPrice=20,
options=null
}
]
}
].
can anybody tell me how to parse this.It is not a json response.
I used hand coded parsers for simple languages where I felt that using http://www.antlr.org/ or https://javacc.java.net to be a bit heavy. I used the same structure for parsing JSON, CSS a simple template. Modified it to parse your response. See whether it helps.
package snippet;
import java.io.IOException;
import java.io.PushbackReader;
import java.io.Reader;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import snippet.RecursiveDescentParser.Token.TokenType;
public class RecursiveDescentParser {
// #formatter:off
final static String text = "" +
"[" +
" Anchor{anchorName='&loreal_lip_balm'," +
" clientName='loreal india'," +
"" +
" anchorPrice=10," +
" campaigns=[" +
" Campaign{" +
" campaignId='loreal_camp1'," +
"" +
" question='How to Turn Your Melted Lipstick into a Tinted Lip Balm'," +
"" +
" startDate=2015-08-04," +
" endDate=2015-08-04," +
" imageURL='null'," +
"" +
" regionCountry='ALL'," +
" rewardInfo='null'," +
" campaignPrice=20," +
"" +
" options=null" +
" }" +
" ]}," +
" Anchor{" +
"" +
" anchorName='&loreal_total_repair_5'," +
" clientName='loreal india'," +
" anchorPrice=125," +
"" +
" campaigns=[" +
" Campaign{" +
" campaignId='loreal_camp2'," +
" question='Is it a good" +
" product to buy?'," +
" startDate=2015-08-04," +
" endDate=2015-08-04," +
"" +
" imageURL='null'," +
" regionCountry='ALL'," +
" rewardInfo='null'," +
"" +
" campaignPrice=20," +
" options=null" +
" }" +
" ]" +
" }" +
" ]" +
"";
// #formatter:on
static class Token {
enum TokenType {
OPEN_BRACKET, CLOSE_BRACKET, OPEN_BRACE, CLOSE_BRACE, STRING, NAME, COMMA, EQUALS, INTEGER, DATE, EOF, NULL;
}
private String text;
private TokenType type;
public Token(TokenType type) {
this(type, null);
}
public Token(TokenType type, String text) {
this.type = type;
this.text = text;
}
public TokenType getType() {
return type;
}
public String getText() {
return text;
}
#Override public String toString() {
return "Token [text=" + text + ", type=" + type + "]";
}
}
static class TokenReader {
private PushbackReader reader;
public TokenReader(Reader reader) {
this.reader = new PushbackReader(reader);
}
public Token nextToken() throws IOException {
Token t = nextTokenx();
System.out.println("Got: " + t);
return t;
}
public Token nextTokenx() throws IOException {
int c;
while ((c = reader.read()) != -1 && Character.isWhitespace((char) c))
;
if (c == -1)
return new Token(TokenType.EOF);
switch (c) {
case '[':
return new Token(TokenType.OPEN_BRACKET);
case ']':
return new Token(TokenType.CLOSE_BRACKET);
case '{':
return new Token(TokenType.OPEN_BRACE);
case '}':
return new Token(TokenType.CLOSE_BRACE);
case ',':
return new Token(TokenType.COMMA);
case '=':
return new Token(TokenType.EQUALS);
default:
if (Character.isDigit(c))
return readIntegerOrDate(c);
if (c == '\'')
return readString(c);
if (Character.isJavaIdentifierStart(c))
return readName(c);
throw new RuntimeException("Invalid character '" + ((char) c) + "' in input");
}
}
private Token readName(int c) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append((char) c);
while ((c = reader.read()) != -1 && Character.isJavaIdentifierPart(c))
sb.append((char) c);
if (c != -1)
reader.unread(c);
if ("null".equals(sb.toString()))
return new Token(TokenType.NULL);
return new Token(TokenType.NAME, sb.toString());
}
private Token readString(int end) throws IOException {
StringBuilder sb = new StringBuilder();
int c;
while ((c = reader.read()) != -1 && c != end)
sb.append((char) c);
return new Token(TokenType.STRING, sb.toString());
}
private Token readIntegerOrDate(int c) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append((char) c);
while ((c = reader.read()) != -1 && Character.isDigit((char) c))
sb.append((char) c);
if (c == '-') {
sb.append((char) c);
return readDate(sb);
}
if (c != -1)
reader.unread(c);
return new Token(TokenType.INTEGER, sb.toString());
}
private Token readDate(StringBuilder sb) throws IOException {
int c;
while ((c = reader.read()) != -1 && Character.isDigit((char) c))
sb.append((char) c);
if (c == -1)
throw new RuntimeException("EOF while reading date");
if (c != '-')
throw new RuntimeException("Invalid character '" + (char) c + "' while reading date");
sb.append((char) c);
while ((c = reader.read()) != -1 && Character.isDigit((char) c))
sb.append((char) c);
if (c != -1)
reader.unread(c);
return new Token(TokenType.DATE, sb.toString());
}
}
static class Lexer {
private TokenReader reader;
private Token current;
public Lexer(Reader reader) {
this.reader = new TokenReader(reader);
}
public Token expect(TokenType... tt) throws IOException {
if (current == null)
current = reader.nextToken();
for (TokenType tokenType : tt) {
if (current.getType() == tokenType) {
Token r = current;
current = null;
return r;
}
}
throw new RuntimeException("Expecting one of " + Arrays.asList(tt) + " but got " + current);
}
public Token expect1or0(TokenType... tt) throws IOException {
if (current == null)
current = reader.nextToken();
for (TokenType tokenType : tt) {
if (current.getType() == tokenType) {
Token r = current;
current = null;
return r;
}
}
return null;
}
}
public Object parse(String text) throws IOException {
return parse(new StringReader(text));
}
private Object parse(Reader reader) throws IOException {
Lexer lexer = new Lexer(reader);
return parse(lexer);
}
private Object parse(Lexer lexer) throws IOException {
Token t = lexer.expect1or0(TokenType.OPEN_BRACE, TokenType.OPEN_BRACKET, TokenType.EOF);
if (t == null || t.getType() == TokenType.EOF)
return null;
else if (t.getType() == TokenType.OPEN_BRACKET) {
return parseList(lexer);
} else {
return parseMap(null, lexer);
}
}
private List<Object> parseList(Lexer lexer) throws IOException {
ArrayList<Object> result = new ArrayList<Object>();
Token tName = lexer.expect1or0(TokenType.NAME);
while (tName != null) {
lexer.expect(TokenType.OPEN_BRACE);
result.add(parseMap(tName.getText(), lexer));
if (lexer.expect1or0(TokenType.COMMA) != null)
tName = lexer.expect(TokenType.NAME);
else
tName = null;
}
lexer.expect(TokenType.CLOSE_BRACKET);
return result;
}
private Object parseMap(String oname, Lexer lexer) throws IOException {
Map<String, Object> result = new HashMap<String, Object>();
if (oname != null)
result.put("objectName", oname);
Token tName = lexer.expect1or0(TokenType.NAME);
while (tName != null) {
String name = tName.getText();
lexer.expect(TokenType.EQUALS);
Token next = lexer.expect(TokenType.STRING, TokenType.DATE, TokenType.INTEGER, TokenType.OPEN_BRACKET,
TokenType.OPEN_BRACE, TokenType.NULL);
TokenType tt = next.getType();
if (tt == TokenType.STRING) {
result.put(name, next.getText());
} else if (tt == TokenType.DATE) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
result.put(name, sdf.parse(next.getText()));
} catch (ParseException e) {
return new RuntimeException(e);
}
} else if (tt == TokenType.INTEGER) {
result.put(name, Integer.valueOf(next.getText()));
} else if (tt == TokenType.OPEN_BRACKET) {
result.put(name, parseList(lexer));
} else if (tt == TokenType.OPEN_BRACE) {
result.put(name, parseMap(null, lexer));
} else {
result.put(name, null);
}
if (lexer.expect1or0(TokenType.COMMA) != null)
tName = lexer.expect(TokenType.NAME);
else
tName = null;
}
lexer.expect(TokenType.CLOSE_BRACE);
return result;
}
public static void main(String[] args) throws IOException {
RecursiveDescentParser parser = new RecursiveDescentParser();
Object o = parser.parse(text);
System.out.println(o);
}
}
Here is my suggestion.
I assume as you said that your input from the server is String.
I have build a little method that return the value of the required key.
public String valueFinder(String data, String key){
int keyValueStart = data.indexOf(key) + key.length() + 1;
String keyValueRaw = data.substring(keyValueStart, data.length());
int keyValueEnd = keyValueRaw.indexOf(",");
String keyValue = keyValueRaw.substring(0, keyValueEnd);
String value = keyValue.replaceAll("^\'|\'$", "");
return value;
}
So if you pass the String data generated by the server to the method and the ask for the required key for example for "clientName" it will return loreal india, if you pass/look-for "anchorName" it will return &loreal_lip_balm.
Now you have the concept, you are welcome to change/modify/customize it as you wish to fetch more detailed information in your campaigns or other scenarios.
It is possible to further develop the method to return single key value, a set of keys and values, convert keys and values to JSON or Array, and just name it.
All this can be done on the same concept.
There is a tool called ANTLR which is useful to read data like this.
I'm generating an SQL statement by checking if each of the column fields submitted to the query are empty (== null) or not. It seems that my approach is pretty naive so I'm wondering what can be done about handling null parameters elegantly. When something isn't specified it should simply match anything.
Here is the code:
public List<Flight> findMatchingFlights(Flight flight)
{
List<Flight> foundFlights = new ArrayList<>();
StringBuilder sqlQueryBuilder = new StringBuilder();
sqlQueryBuilder.append("SELECT * FROM Flights");
boolean emptyQuery = true;
if(flight.getDeparture() != null)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
emptyQuery = false;
}
sqlQueryBuilder.append("Departure = '" + flight.getDeparture() + "'");
}
if(flight.getArrival() != null)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
emptyQuery = false;
}
else
{
sqlQueryBuilder.append(" AND ");
}
sqlQueryBuilder.append("Arrival = '" + flight.getArrival() + "'");
}
if(flight.getFlightNumber() != null)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
emptyQuery = false;
}
else
{
sqlQueryBuilder.append(" AND ");
}
sqlQueryBuilder.append("Number = '" + flight.getFlightNumber() + "'");
}
if(flight.getFlightMinutes() != 0)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
emptyQuery = false;
}
else
{
sqlQueryBuilder.append(" AND ");
}
sqlQueryBuilder.append("Duration = " + flight.getFlightMinutes());
}
/*
...
A bunch more fields
*/
if(flight.getAirplane() != null)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
}
else
{
sqlQueryBuilder.append(" AND ");
}
sqlQueryBuilder.append("Airplane = '" + flight.getAirplane() + "'");
}
sqlQueryBuilder.append(";");
// Execute sql and fill list with rows that match
}
You can create the common method for the below block and call the method by passing the arguments.
if(flight.getArrival() != null)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
emptyQuery = false;
}
else
{
sqlQueryBuilder.append(" AND ");
}
sqlQueryBuilder.append("Arrival = '" + flight.getArrival() + "'");
}
Best approach would be to do the trick in SQL than checking for null in Java. This is how you can do it.
sqlQueryBuilder.append("(Number = '" + flight.getFlightNumber() + "' OR " + flight.getFlightNumber() + " IS NULL)");
This way you wont have to check null in java, if the flight.getFlightNumber() is null then this where clause will always return true which is what you would want.
The only drawback to this method is that the clause will be included in the query, but since you are intending to use these columns to query the table incase they are not null, i would assume the table would be indexed likewise.
sqlQueryBuilder.append("SELECT * FROM Flights WHERE 1 = 1");
then you don't need emptyQuery flag and checks and many if else constractions.
List<Flight> foundFlights = new ArrayList<>();
StringBuilder sqlQueryBuilder = new StringBuilder();
sqlQueryBuilder.append("SELECT * FROM Flights WHERE 1 = 1");
if(flight.getDeparture() != null) {
sqlQueryBuilder.append("AND Departure = '" + flight.getDeparture() + "'");
}
Hi I'm trying to filter records on the basis of Brand,Flavor,Price,Size,Type. i am using a single form to handle this so if user filter only by brand then rest of options like price,flavor will be unchecked so i am checking if Brand or flavor or price is null.I got the solution but i have make lot of comparisons for all cases. i need a solution by which i have make less comparisons.I am using following code
public List<Products> Filter_Items(String[] Brand, String[] Flavour,Float Price,String Size,String Type)
{
ResultSet rs;
List<Products> data = null;
PreparedStatement stmt;
try {
StringBuilder param = new StringBuilder();
if (Brand != null) {
for (String str : Brand) {
param.append("'").append(str).append("', ");
}
}
StringBuilder param1 = new StringBuilder();
if (Flavour != null) {
for (String str : Flavour) {
param1.append("'").append(str).append("', ");
}
}
String prm = param.toString().length() > 2 ? param.toString()
.substring(0, param.toString().length() - 2) : null;
String prm1 = param1.toString().length() > 2 ? param1.toString()
.substring(0, param1.toString().length() - 2) : null;
String query = "select * from products where ";
if (prm != null && prm1 != null) {
query += "Brand in (" + prm + ") and Flavour in (" + prm1 + ")";
} else if (prm != null && prm1 == null) {
query += "Brand in (" + prm + ")";
} else if (prm1 != null && prm == null) {
query += "Flavour in (" + prm1 + ")";
}
stmt = DataBaseConnection.DBConn.getConnection().prepareStatement(query);
rs = stmt.executeQuery();
if (rs != null) {
data = new ArrayList<Products>();
while (rs.next()) {
Products p = new Products();
p.setTitle(rs.getString("Ttile"));
p.setCategory(rs.getString("Category"));
p.setSubCategory(rs.getString("SubCategory"));
p.setSubCategoryTwo(rs.getString("SubCategorytwo"));
p.setPrice(rs.getInt("Price"));
p.setFlavour(rs.getString("Flavour"));
p.setSize(rs.getString("Size"));
p.setImage(rs.getString("image"));
p.setBrand(rs.getString("Brand"));
p.setInstock(rs.getString("instock"));
p.setInstockQty(rs.getInt("instockqty"));
data.add(p);
}
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
return null;
}
return data;
}
}
You can use as always third party libraries for validation like javax validation or any other more specialized on this.
You could create a bean of your data with all the getters and setters and apply validation on your bean.
To pass arrays you need getters and setters like this one:
public class Foo {
private int[] array;
public Foo(int[] array) {
this.array = Arrays.copyOf(array, array.length);
}
/** #param the array to use */
public setArray(int[] array) {
this.array = Arrays.copyOf(array, array.length);
}
/** #return a copy of the array */
public int[] getArray() {
return Arrays.copyOf(array, array.length);
}
}
To validate a bean see this tutorial.
What you really need is to start naming variables according to what they are logically. Names like prm and prm1 are meaningless, while brand and flavor make more sense as variable names since that's what's in them.
I don't see the number of comparisons as a problem. But giving everything generic variable names and then not even indenting the if-statements makes my eyes glaze over.
How about something like this:
if (brand != null && flavor != null)
{
query += "Brand in (" + brand + ") and Flavour in (" + flavor + ")";
}
else if (brand != null && flavor == null)
{
query += "Brand in (" + brand + ")";
}
else if (flavor != null && brand == null)
{
query += "Flavour in (" + flavor + ")";
}
Edit: One thing you can do is split your SQL into two variables, one for the main query and one for the where clause, then just add to the where clause like this:
private String addToWhereClause(String currentWhereClause, String fieldname, String value)
{
String returnValue = "";
if (value != null)
{
if(!"".equals(currentWhereClause))
{
returnValue += " AND ";
}
returnValue += " "+fieldname+" IN(" + value + ") ";
}
return returnValue;
}
String whereClause = "";
whereClause += addToWhereClause(whereClause, "Brand", brand);
whereClause += addToWhereClause(whereClause, "Flavour", flavor);
query = query + " " + whereClause;
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
my code:
public static void loanenquiry(String ApplicationID,String LoanNumber,String RIMNumber,String custname,String fromdate,String todate) {
String wherestring = "SELECT * FROM bf_loanmaster WHERE";
try {
if(ApplicationID != null) {
wherestring = wherestring + "ApplicationID ="+BillAction.StringtoInt(ApplicationID)+"";
}
if(LoanNumber != null ) {
if(ApplicationID != null) {
wherestring = wherestring + "AND LoanNumber = "+BillAction.StringtoInt(LoanNumber)+" ";
} else {
wherestring = wherestring + "LoanNumber = "+BillAction.StringtoInt(LoanNumber)+" ";
}
}
if(RIMNumber != null ) {
if(ApplicationID != null && LoanNumber != null) {
wherestring = wherestring + "AND AdvparyRIM = "+RIMNumber+" ";
} else {
wherestring = wherestring + "AdvparyRIM = "+RIMNumber+"";
}
}
if(custname != null ){
if(ApplicationID != null && LoanNumber != null && RIMNumber != null ) {
wherestring = wherestring + "AND custName = "+custname+"";
} else {
wherestring = wherestring + "custName = "+custname+"";
}
}
if(fromdate != null ) {
if(ApplicationID != null && LoanNumber != null && RIMNumber != null && custname != null ) {
wherestring = wherestring + "AND ApplicationDt >= "+BillAction.StringtoDate(fromdate)+" ";
} else {
wherestring = wherestring + "ApplicationDt = "+BillAction.StringtoDate(fromdate)+"";
}
}
if(todate != null ) {
if(ApplicationID != null && LoanNumber != null && RIMNumber != null && custname != null && fromdate != null) {
wherestring = wherestring + "AND ApplicationDt >= "+BillAction.StringtoDate(fromdate)+" AND ApplicationDt <= "+BillAction.StringtoDate(todate)+"";
} else {
wherestring = wherestring + "ApplicationDt >= "+BillAction.StringtoDate(todate)+"";
}
}
Connection conn = BillFinanceDB.getDBConnection();
PreparedStatement psloanenquiry= conn.prepareStatement(wherestring + ";");
ResultSet rs = psloanenquiry.executeQuery();
while(rs.next()) {
System.out.println("loan number"+rs.getInt("LoanNumber"));
}
} catch(SQLException e) {
e.printStackTrace();
}
}
Any ideas?
thanks for the help.
My guess: you're missing a space after WHERE in your constructed string. Try this:
String wherestring = "SELECT * FROM bf_loanmaster WHERE ";
The best way to debug these kinds of errors is to print out the SQL query you have constructed before it is executed so that you can manually inspect it for problems.
The WHERE is most likely a problem. The second problem that you could have is not putting your strings in quotation marks. For example it probably should be wherestring = wherestring + "custName = '"+custname+"' ";
Also things to note:
All this appending is terribly inefficient, use a StringBuilder or StringBuffer instead. You could also use PreparedStatements which would make your code perform better and possibly even make it easier to read.
Add a space after where.. You have to seperate keywords like where..
give a space in your query
String wherestring = "SELECT * FROM bf_loanmaster WHERE";
there is no space between WHERE statement and condition.