Insert data into mysql table in proper format from java servlet - java

I am getting cart items and cart price from cart javascript to jsp and then transferring same from jsp to servlet as follows:
String a= request.getParameter("cartitems");//but it prints like Jan-2019Feb-2019March-2019
String b=request.getParameter("cartprice");//prints like $100,$200,$400
I need to store data in my database as follows:
Cart Price
Jan-2019 $100
Feb-2019 $200
March-2019 $400
I am trying to separate this Jan-2019Feb-2019March-2019 so that it can be stored in my table but unable to do so, Jan-2019Feb-2019March-2019 need not to be separated by date format, it can be separated in any suitable regex if possible.
I tried to separate string a as follows but its not working.
String[] result = a.split(",");
out.println(Arrays.toString(result));// prints [June-2019March-2019]
How can I store datas like above in my databse table, please help ! Many thanks in advance!

Get parameter from your servlet request:
String cartItemsParameter= request.getParameter("cartitems");
use mehod:
findRexExpList(cartItemParameter, "\\D+\\d+");
method code:
private static List<String> findRexExpList(String text, String regExp) {
List<String> result = new ArrayList<>();
Pattern pattern = Pattern.compile(regExp);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String group = matcher.group();
result.add(group);
}
return result;
}
this method return List with separated string
For store data:
List<String> carts = findRexExpList(cartItemParameter, "\\D+\\d+");
String[] cartPrices = request.getParameter("cartprice").split(",");
for(int i=0; i<cartPrices.length; i++){
String cart = carts.get(i);
String price = cartPrices[i];
//insert cart and price
}

Related

Trying to get the Text inside a <ul> tag but its only returning the First item Selenium

this is the structure of the unodered list
structure of the unodered list
i want to get the value of "var" and "time" to two strings and save them in a ArrayList
List<String[]> finalResult = new ArrayList<>();
This is what i tried
List<WebElement> typeElements =driver.findElements(By.xpath("//*[#id=\"container\"]/section[2]/div/div[2]/div[2]/ul/li"));
for(int i=0;i<typeElements.size();i++){
WebElement typeSingle = typeElements.get(i);
String stName = typeSingle.findElement(By.xpath("//div/a/var")).getText();
String stTime = typeSingle.findElement(By.xpath("//div/a/time")).getText();
String singleType[] =stName,stTime};
finalResult.add(singleType);
}
im getting total of 13 items in the
finalResult
variable. but all the items are same
{"title1","00:23"}
{"title1","00:23"}
{"title1","00:23"}....
i want them to be like this
{"title1","00:23"}
{"title2","00:31"}.....
what am i doing wrong?
***Edit*
On each itterations inside the for loop typeSingle
is refering to different id's,
but stName , stTime variables are same
To get child element with xpath you need to use ./:
String stName = typeSingle.findElement(By.xpath("./div/a/var")).getText();
String stTime = typeSingle.findElement(By.xpath("./div/a/time")).getText();
Or use css selector:
String stName = typeSingle.findElement(By.cssSelector("var")).getText();
String stTime = typeSingle.findElement(By.cssSelector("time")).getText();
Changing this
String stName = typeSingle.findElement(By.xpath("//div/a/var")).getText();
String stTime = typeSingle.findElement(By.xpath("//div/a/time")).getText();
to this solved the issue
String stName = typeSingle.findElement(By.xpath("div/a/var")).getText();
String stTime = typeSingle.findElement(By.xpath("div/a/time")).getText();

How to get data from SQL with sql2o?

I'm trying to get data from mySQL to List in java using sql2o lib.
But for some reason I just fail to understand how to use it properly (it looks like).
Here is the faulty code:
List<String> returning = new ArrayList<String>();
String date = "";
String playerList = "";
String playerCount = "";
String playerMax = "";
con.createQuery(sql)
.throwOnMappingFailure(true).addColumnMapping("date", date)
.addColumnMapping("playerList", playerList)
.addColumnMapping("playerCount", playerCount)
.addColumnMapping("playerMax", playerMax).executeAndFetch(String.class);
returning.add(date);
returning.add(playerList);
returning.add(playerCount);
returning.add(playerMax);
And here is error I get:
org.sql2o.Sql2oException: Could not map date to any property.
at org.sql2o.DefaultResultSetHandlerFactory.newResultSetHandler0(DefaultResultSetHandlerFactory.java:199)
at org.sql2o.DefaultResultSetHandlerFactory.access$200(DefaultResultSetHandlerFactory.java:17)
at org.sql2o.DefaultResultSetHandlerFactory$5.evaluate(DefaultResultSetHandlerFactory.java:160)
at org.sql2o.DefaultResultSetHandlerFactory$5.evaluate(DefaultResultSetHandlerFactory.java:156)
at org.sql2o.tools.AbstractCache.get(AbstractCache.java:49)
at org.sql2o.DefaultResultSetHandlerFactory.newResultSetHandler(DefaultResultSetHandlerFactory.java:173)
at org.sql2o.PojoResultSetIterator.<init>(PojoResultSetIterator.java:20)
at org.sql2o.Query$14.iterator(Query.java:547)
at org.sql2o.Query.executeAndFetch(Query.java:588)
at org.sql2o.Query.executeAndFetch(Query.java:574)
at lol.discordbot.database.QueryServerInfo.getCurrent(QueryServerInfo.java:31)
at lol.discordbot.command.Query.execute(Query.java:20)
at lol.discordbot.command.CommandsListener.onMessageReceived(CommandsListener.java:39)
I think you misunderstand what column mappings are. Column mappings are used to map column names to object-field names.
You should first create a data class to hold the result of your query. From your code above, I assume that you are trying to fetch players.
public class Player {
public String date;
public String playerList;
public String playerCount;
public String playerMax
}
(Consider to use better data types. Date for dates, int for counts, etc)
Then you can use sql2o to fetch data
List<Player> players = con.createQuery(sql).executeAndFetch(Player.class);
There is a much better way now.
.setAutoDeriveColumnNames(true)
Example
try (Connection con = sql2o.open()) {
List<Player> l = con.createQuery(sql)
.setAutoDeriveColumnNames(true)
.executeAndFetch(Player.class);
}
https://groups.google.com/g/sql2o/c/3H4XJIv-i04

android- convert arraylist to one string in custom format

i have data in sqlit database so i use it to store categoreis and items
and i get it in arraylist like this:
public ArrayList showDataItems(String id_cate){
ArrayList<Items> arrayListItems = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cr = db.rawQuery("select * from items where id_cate = "+id_cate,null);
cr.moveToFirst();
while (cr.isAfterLast() == false){
String item_id = cr.getString(0);
String ItemName = cr.getString(1);
String Item_quantity = cr.getString(2);
String icon = cr.getString(3);
int isDone = Integer.parseInt(cr.getString(5));
arrayListItems.add(new Items(item_id,ItemName,Item_quantity,R.drawable.shopicon,icon,isDone));
cr.moveToNext();
}
return arrayListItems;
}
so i need to get this data and convert it to string and share it to other application like whatsapp in custom format for example :
1- first one *
2- second one *
3-....
so i use this code for send data
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT,"hello world");
intent.setType("text/plain");
startActivity(Intent.createChooser(intent,"send items i need all
data here"));
so we can use string builder or some thing to get data in one string
please help me!
As you said, there is a StringBuilder class who can help formatting strings.
Here are the java docs
From StringBuilder, see the append(..) method. For your example:
int size = list.size();
for(int i = 0; i< size-1;i++){
stringBuilder.append(i+1).append("- ").append(list.get(i)).append('\n');
}
stringBuilder.append(size).append("- ").append(list.get(size-1));
The last call to append is different from the firstone by not appending the end line

Vaadin access content of sql container

EDITED!
I retriev data from a mysql DB using Vaadin, SQLContainer and the Freeformquery. Now I want to get all Descriptions in one String (later each string will printed/added to a text file).
....
String text ="";
FreeformQuery subcatExtractionQuery = new FreeformQuery("select Description from customers", connectionPool);
SQLConateiner s = new SQLContainer(subcatExtractionQuery);
Collection<?> c = s.getContainerPropertyIds();
for(Object o : c){
Property<?> p = s.getContainerProperty(o, "Description");
text+=(String)p.getValue();
}
System.out.println(text);
I get the Error: java.lang.NullPointerException
Problem line is the text+=...if I remove it, no error appears. BUT The Query returns Data!
These descriptions are Strings. I need to have all words of each string in ony single list of tokens (i already have a method to create a token list of a file.)
(Don't ask if this makes sense, it's just an example).
How can I access the Strings of my sql container? Till now I only used the container als data source of a table and didn't access the single items/strings.
I need a for loop to get each String...how does this work?
Its getItemIds insted of getContainerPropertyIds. So this words
....
String text ="";
FreeformQuery subcatExtractionQuery = new FreeformQuery("select Description from customers", connectionPool);
SQLConateiner s = new SQLContainer(subcatExtractionQuery);
Collection<?> c = s.getItemIds();
for(Object o : c){
Property<?> p = s.getContainerProperty(o, "Description");
text+=(String)p.getValue();
}
System.out.println(text);

How to parse name=value^^name=value^^name=value

My Question: It's very specific. I'm trying to think of the easiest way to parse the following text:
^^domain=domain_value^^version=version_value^^account_type=account_type_value^^username=username_value^^password=password_value^^type=type_value^^location=location_value^^id=xxx^^cuid=cuid_value^^
It will appear exactly like that every time. A few requirements:
Not all of those key-value pairs will appear every time.
They may be in a different order
I'm looking for code something like this:
private String[] getKeyValueInfo(String allStuff) {
String domain = someAwesomeMethod("domain", allStuff);
String version = someAwesomeMethod("version", allStuff);
String account_type = someAwesomeMethod("account_type", allStuff);
String username = someAwesomeMethod("username", allStuff);
String password = someAwesomeMethod("password", allStuff);
String type = someAwesomeMethod("password", allStuff);
String location = someAwesomeMethod("location", allStuff);
String id = someAwesomeMethod("id", allStuff);
String cuid = someAwesomeMethod("cuid", allStuff);
return new String[] {domain, version, account_type, username, password, type, location, id, cuid};
}
What I don't know is what someAwesomeMethod(String key, String allStuff) should contain.
What I was thinking: Something like this:
private String someAwesomeMethod(String key, String allStuff) {
Pattern patt = Pattern.compile("(?i)^^" + key + "=(.*?)^^", Pattern.DOTALL);
Matcher matcher = patt.matcher(allStuff);
if (matcher.find()) {
return matcher.group(1);
}
return null;
}
What's wrong with that:
I'm worried it'd be a little slow/cumbersome if I had to do this a lot. So I'm looking for any tips/suggestions.
If you have to do it a lot, i'd make a map, something along the lines of
Map<String, String> m = new HashMap<String, String>();
for (String s : stuff.split("\\^\\^")) // caret needs escaping
{
String[] kv = s.split("=");
m.put(kv[0]) = kv[1];
}
then to lookup a key you'd just do m.get("key")
String.split() will work for that
strVar = /* Your big long string */
String[] vars = strVar.split("\\^\\^"); // needs escaping

Categories