Fill an XML file with test data - java

I have an XML file looks like the attached image:
The attributes (commitId, author, date, and time) in I got it from Git open source repository using "blame" command.
However, for my evaluation, I need to fill these attributes randomly with data I have. For example, I have Junio, Peter, Jiang, Jens, Jeff, Ramkumar, and Linus as authors, and date is ranged between 2010 and 2012.
what is the best way to fill this data using Java?

You can start by placing the values you need into arrays like this:
String names[] = {Junio, Peter, Jiang, Jens, Jeff, Ramkumar, Linus};
String dates[] = {2010, 2011, 2012};
Then using the Random class you can do this:
Random ran = new Random();
String name = names[ran.nextInt(7)];
String date = dates[ran.nextInt(3)];
That will give you a random name and date. Rinse. Repeat.
Note that to get a random number between 0 and n inclusive you need nextInt(n + 1).

Related

Java string indexing make me confused

So i need to gather data from my db, it's holiday date in my country, the data comes like this
Example 1 : THU 21 May Ascension Day of Jesus Christ *ICDX GOLD open for
Example 2 : MON-THU 28-31 Dec Substitute for Commemoration of Idul Fitri Festival
So i need to get data from days, dates, and the holiday name, for get data from example 1 i'm using code like this
public static void main(String[] args) {
String ex1 = "THU 21 May Ascension Day of Jesus Christ *ICDX GOLD open for";
String ex2 = "MON-THU 28-31 Dec Substitute for Commemoration of Idul Fitri Festival ";
String[] trim1 = ex1.trim().split("\\s+"); //to split by space
String[] trim2 = ex1.trim().split(" "); //to split by 3 space so i got the data from multiple space as delimiter
System.out.println("DAY " +trim1[0]);//display day
System.out.println("DATE " +trim1[1] +trim1[2]+"2020");//display date
System.out.println("HOLIDAY NAME " +trim2[3]);//dispay holiday name
}
The Output come like this
DAY MON
DATE 21May2020
HOLIDAY NAME Ascension Day of Jesus Christ
and just like what i need, but when come to example 2, i can't use same code because the space is different, how to get the data i need with example 1 and 2 with same code.
i am new in java so i'm sorry if my question looking dumb, i hope you can help me.Thanks
.split("\\s+") will split at any space, including multiple spaces. Eg. it will split at 1 space or more.
This means that you are able to split at any amount of spaces (what you want). However, this will also split your text comments. You are able to limit the length of the array produced (the amount of times it is split) using .split(regex, n), which will result in an array of n-1 size at most. See this for more details
As for splitting out your two textual comments, I cannot see a way to do this.
Substitute for Commemoration of Idul Fitri Festival "; contains no way of telling what is the first text comment and the second.
It seems quite strange to me that you receive information from your database like this, I would recommend seeing if there are other options for doing this. There is almost certainly a way to get seperate fields.
If have the ability to change all the information in the database, you could put single quotes (') or some other seperator, which you would then be able to split out the two pieces of text.
This is basically what #DanielBarbarian suggested: Since the information seems to always start at the same indexes, you can just use those to get what you need.
String ex1 = "THU 21 May Ascension Day of Jesus Christ *ICDX GOLD open for";
String ex2 = "MON-THU 28-31 Dec Substitute for Commemoration of Idul Fitri Festival ";
String day = ex2.substring(0, 8).trim();
String date = ex2.substring(8, 14).trim() + ex2.substring(14, 22).trim() + "2020";
String name = ex2.substring(22);
System.out.println("DAY " + day);// display day
System.out.println("DATE " + date);// display date
System.out.println("HOLIDAY NAME " + name);// dispay holiday name

Localizing numeric values in excel

BigDecimal myNumber = new BigDecimal(1234.56);
NumberFormat instance = NumberFormat.getInstance(Locale.GERMAN);
String localizedNumber = instance.format(myNumber);
System.out.print("\nformatting " + localizedNumber); o/p ->1.234,56
Till here code works fine but below line gives NumberFormatter exception as given string contains comma in it.
BigDecimal bigDecimal = new BigDecimal(localizedNumber);
I want numeric values to be localized but I cannot return string as putting number as string shows below error in excel
Number in this cell is formatter as text or preceded by an apostrophe
Is there any way by which I can return back numeric value(BigDecimal / Integer / BigInteger etc) in localized format
So that I won't get above error in excel and I can perform filter operations on excel data.
I've also tried new BigDecimalType().valueToString(value, locale); and new BigDecimalType().stringToValue(s, locale); of dynamic jasper reports api.
Happy to answer this question which asked me only and quite surprised that no one replied to this.
Actually we don't have to do anything for number localization in excel export because it's done by our operating system settings automatically.
Go to "Region and Language" -> Format -> Select language/country name -> Apply and check your excel earlier generated in English.
You will see numbers in currently selected country's number format. :)

Arranging text inside saved txt file

I have made an app that takes some values and adds them to a txt file.
It does something like this,they are strings[] :
product[1] quantity[1] price[1]
product[2] quantity[2] price[2]
.....
product[n] quantity[n] price[n]
The problem is,most of the time product[1] won't have the same lenght as product[2] or the other products and the same goes for quantities and prices.This results in a messy text layout,something like this.
ww 2 4
wwww 1 2.5
w 1.2 1.1
Is there any way i can make it tidier ? Something like creating a table or columns?
Thanks !
EDIT : To make it a bit clearer,i want to find a way for the stuff in the txt file to be arranged like this,instead of how it is in the above example
ww 2 4
wwww 1 2.5
w 1.2 1.1
At the moment i'm using this
pw.println(prod[n]+" "+cant[n]+" "+pret[n]);}
But this is making the text in the txt file be unaligned(example 1)
Use the format Method of the String class like this:
Declare a String with the format
String yourFormat = "%-10s %-10s %-10s%n"; //choose optimal ranges.
//if you exceed them, it will always automatically make one space
//between the next column
write the output with that format:
output.write(String.format(yourFormat, firstString, secondString, thirdString));
first string are your w's, second and third are the columns with numbers.
for your example:
String myFormat = "%-10s %-10s %-10s%n";
for(int i=0;i<prod.length();i++){
pw.println(String.format(myFormat, prod[n], cant[n], pret[n]));
}
more info here and here

save user data during a day (the same day -> many user data)

I have an application where the user enters data in edittext and presses the save button.
By pressing 'save' I save in a file the user data (in one column) and the current date (in the other column).
Then , I press another button and make the plot (using achartengine) date (x axis) data (y axis).
So, entering data during a day ,results in saving for example: "1" (user data) -> 20/4/2013 , "2" -> 20/4/2013 , "3" -> 20/4/2013.
And in plot I have 3 points in y axis (ok) and 3 points in x axis (not ok).
I want to have one point in x axis because the data where entered in the same day.
I save data :
public void savefunc(){
SimpleDateFormat thedate = new SimpleDateFormat("dd/MM/yyyy");
Date d=new Date();
String formattedDate=thedate.format(d);
Log.d("tag","format"+formattedDate);
dates_Strings.add(formattedDate);
double thedata=Double.parseDouble(value.getText().toString().trim());
mydata.add(thedata);
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
directory.mkdirs();
File file = new File(directory, filename);
FileOutputStream fos;
//saving them
try {
fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for (int i=0;i<mydata.size();i++){
bw.write(mydata.get(i)+","+dates_Strings.get(i)+"\n");
}
...
How can I save the user data during a day ?
Maybe some check here : Date d=new Date(); ? To check if it is the same day.
Or here : bw.write(mydata.get(i)+","+dates_Strings.get(i)+"\n");
But I can't figure.
For example I enter data " 1" , "2" ,"3" in date "20/4/2013".
This is what I get now using my code:
But i require graph like below: data entered on same day should be put together::
---------------UPDATE--------------------------------------------------
mRenderer.setXLabels(0);
for (int i=0;i<mydata.size();i++){
mRenderer.addXTextLabel(i,dates_Strings.get(i));
Date lastDate=null;
String lastdate="";
try{
// the initial date
Date initialDate=formatter.parse(dates_Strings.get(mydata.size()-1));
Calendar c = Calendar.getInstance();
c.setTime(initialDate);
c.add(Calendar.DATE, 1); // increase date by one
lastDate =c.getTime();
}catch ...
}
mRenderer.setXAxisMax(lastDate.getTime());
mRenderer.addXTextLabel(i,dates_Strings.get(i));
}
This is an AChartEngine issue indeed. The internal model used to be kept in ArrayLists and these issues didn't exist. At some point there was a community effort to make AChartEngine faster with a lot of data points. At that point, the model started to use a Map instead of an ArrayList. This implementation prevented having the same X value added several times. However, in order to fix this, I add a very small value to X, if it already exists. In your example, the first value is 20/04/2013 00:00:00.0, the second one is at 20/04/2013 00:00:00.001 and the third is 20/04/2013 00:00:00.002.
Now, the solution to your problem is to have a wider range on the X axis.
renderer.setXAxisMax(someDate.getTime());
where someDate can be something like 21/04/2013.
ok.
When you call new Date(), you also determine time of creation (default format is: January 1, 1970, 00:00:00 GMT). Because your points are created in different time but same date, your points are not aligned.
So you should do it like this:
Calendar thisDay = Calendar.getInstance();
thisDay.set(Calendar.HOUR, 0);
thisDay.set(Calendar.MINUTE, 0);
thisDay.set(Calendar.SECOND, 0);
Date d=thisDay.getTime();//this returns Date :) - it is funny but true
then you can use d as current date :).
Hope it is true and it helps,
Toni
There are a few possible solutions for this problem:
instead of a date, put the unix time of the date (long value) . in order to show it, you can convert the unix time to formatted date .
since excel can handle dates, edit the output file and use "=Date(year,month,day)" or "=DATEVALUE("2013/4/20")"
this is all because the problem isn't even related to android. it's about showing the data. the data is ok. it's just how you show it.
If I am not very much mistaken this is not a problem of saving or loading the data but simply of displaying the data. Your graph algorithm should recognize equal dates and do not make a new entry for it.
As it is, it seem like the date is treated as label, not as x-axis value, which would be reasonable because the date string is not numeric.
I suggest to check achartengine if there is a way to additional provide x-values and then let them only increase if the date string of the next entry is different of the previous entry.
You probably have to give a different model to achartengine.
I don't think it is a save problem because well the date stored is the right one, so any behavior there is mostly as expected.

extracting a substring to use in simple date format

I am reading log files and need to extract the date and year from certain lines in order to then use simple date format and find out the average time in between 2 actions. An example of what a line that I would need the date from looks like this.
(INFO ) [07 Feb 2013 08:04:39,161] -- ua, navigation, fault
I can't figure out if I should split the the line twice or use the substring function. Also I don't think I need to include that last number when converting to simple date format (the 161).
I would suggest you to use regex to extract the required data from log files.
Consider using regex groups to extract the String you want. You can use
Pattern p = Pattern.compile("you regex pattern with () around the bit you wanna extract");
Matcher m = p.matcher(theLine);
if (m.find()) {
String date = m.group(1);
}
I'd go for using substring:
final int from = line.indexOf('[') + 1;
final int to = line.indexOf(']', from); // or , if you do not want to have the last number included
final String timestampAsString = line.substring(from, to);
BTW: Add some from/to-checks if valid indices have been found - for example to detect errors early on when the log format changed.

Categories

Resources