I've a JSONObject that I've converted to a JSON array then parsed it further to its separate strings. I've concatenated these to form one new string. Here is the code that I've used.
for(int n = 0; n<newtrs_array.length();n++){
JSONObject object = newtrs_array.getJSONObject(n);
String newcompanyid = object.getString("companyid");
String newusername = object.getString("username");
String newdate = object.getString("date");
String newClientId = object.getString("clientid");
String newprojectId = object.getString("projectid");
String newniv1 = object.getString("niv1");
String newniv2 = object.getString("niv2");
String newworktypeid = object.getString("worktypeid");
String newtimetypeid = object.getString("timetypeid");
String newhours = object.getString("hours");
String newcomment = object.getString("comment");
String newprivatecomment = object.getString("privatecomment");
String newopen = object.getString("open");
String newreportid = object.getString("reportid");
newtrsArray += newcompanyid+"#"+newusername+"#"+newdate+"#"
+newClientId+"#"+newprojectId
+"#"+newniv1+"#"+newniv2+"#"+newworktypeid
+"#"+newtimetypeid+"#"+newhours+"#"+newcomment
+"#"+newprivatecomment+"#"+newopen+"#"+newreportid;
}
}
This is the code that is used to split the newtrsarray
for(int n=0; n<split_frombufferedValue.length; n++){
if(split_frombufferedValue[n] != null){
try{
//Log.i(TAG, "***********%%%%%%%%%"+split_frombufferedValue[1]);
newtrsArray = split_frombufferedValue[0].toString();
newschemaArray = split_frombufferedValue[1].toString();
Log.i(TAG, "************* "+newschemaArray);
newdeletedtrsArray = split_frombufferedValue[2].toString();
String newcreatedtrs_array = split_frombufferedValue[3].toString();
String newsync_reponse = split_frombufferedValue[4].toString();
String newmodtrs_array = split_frombufferedValue[5].toString();
} catch(Exception e){
e.printStackTrace();
}
}
}
split_newtrsArray = newtrsArray.split("#");
split_newdeletedtrsArray = newdeletedtrsArray.split("####");
split_newschemaArray = newschemaArray.split("%%%%");
Log.i(TAG, "############# "+split_newtrsArray[0]+" -length "+split_newtrsArray.length);
}
My PROBLEM is that: newtrsarray is about 4000chars or more in size. This is causing the "#" to be inserted twice or even thrice at times. As shown below
&&--Second activty:HTTPClient--**(824): !!!!!------UTB17#DA#2011-10-10#1000#363636#10##105#30#5###no#30667UTB17#DA#2011-09-12#1000#363636#10##100##6##Not Available#yes#31659UTB17#DA#2011-09-13#1000#363636#10##100##2###yes#31665
How can I work around this problem. The values must be concatenated to one string and then split at an another function. These must be then inserted into a database. Hope I was able to explain my problem clearly.
Cheers !
I think your problem comes when you are inserting it again which is when the array has a null element check out an if statement and check if its null or not. Do it as so:
if(newcompanyid.equals("") || newcompanyid == null || newusername.equals("") || newusername == null
|| newdate.equals("") || newdate == null || newClientId.equals("") || newClientId == null ||
newprojectId.equals("") || newprojectId == null || newniv1.equals("") || newniv1 == null ||
newniv2.equals("") || newworktypeid.equals("") || newworktypeid == null ||newtimetypeid.equals("")
|| newtimetypeid == null || newhours.equals("") ||newhours == null ||newcomment.equals("")
||newcomment == null ||newprivatecomment.equals("") ||newprivatecomment == null||newopen.equals("")
||newopen == null||newreportid.equals("") || newreportid == null)
Related
I want to compare 2 objects and create a new one with the values of the second if its values are not null. Otherwise the values of the first one should be copied to the object created.
My problem is that I don't know how to set the value which I want to copy. I know that to get the name of the attribute I can use field.getName(), but how can I do the set of that attribute on the new object?
Example:
Test t1 = new Test();
t1.name = "Maria";
t1.age = 30;
t1.street = "somewhere";
Test t2 = new Test();
t2.name = "Maria";
t2.age = ;
t2.street = "here and here";
Test resultIwant = new Test();
t2.name = "Maria";
t2.age = 30;
t2.street = "here and here";
Code:
Test resultIwant = new Test(t2);
for(Field field : t1.getClass().getDeclaredFields()) {
field.setAccessible(true);
Object value1= field.get(t1);
Object value2= field.get(t2);
if ((value2 == null && value1 == null) || (value2 == value1))
continue;
else {
if(value2 != null && value1 == null)
continue;
else if(value2 == null && value1 != null) {
resultIwant.set???? = value1; <----------- this is my problem
}
}
}
The Java Reflection API not only allows you to read but also to set a field value.
In your code you can try the following:
Test resultIwant = new Test(t2);
for(Field field : t1.getClass().getDeclaredFields()) {
field.setAccessible(true);
Object value1= field.get(t1);
Object value2= field.get(t2);
if ((value2 == null && value1 == null) || (value2 == value1))
continue;
else {
if(value2 != null && value1 == null)
continue;
else if(value2 == null && value1 != null) {
String fieldName = field.getName();
Field fieldOnResultIwant =
resultIwant.getClass().getDeclaredField(fieldName);
fieldOnResultIwant.setAccessible(true);
// Honestly, I do not remember... Perhaps also will work:
// field.set(resultIwant, value1);
fieldOnResultIwant.set(resultIwant, value1);
}
}
}
I posted a more complete, but related, answer here.
I need to find best matched employee salary in the DB records as:
Name: City: State:
A (null) (null)
A (null) DEL
(null) (null) (null)
A SAKET DEL
Match order should be:
1. NAME = name, STATE = state, CITY = city
2. NAME = name, STATE = state , CITY = NULL
3. NAME = name, STATE = NULL, CITY = NULL
4. NAME = NULL, STATE = NULL, CITY = NULL
Means if in a row where all attributes matches – it should be selected, if we do not have that kind of data we should go to next best option like select state and city as NULL, etc.
My code as below, is giving me correct results but I need a more efficient way.
private static BigDecimal getsalaryForBestMatch(ResultSet results, EmployeeRq request) throws Exception{
BigDecimal salary = null;
BigDecimal salaryWithState = null;
BigDecimal salaryWithName = null;
BigDecimal salaryWithNoMatch = null;
while (results.next()) {
String billerName = results.getString("EMP_NAME") != null ? results.getString("EMP_NAME").trim() : null;
String city = results.getString("CITY") != null ? results.getString("CITY").trim() : null;
String state = results.getString("STATE") != null ? results.getString("STATE").trim() : null;
BigDecimal salaryRslt = null;
if(results.getString("SALARY") != null){
salaryRslt = BigDecimal.valueOf(results.getDouble("SALARY"));
}
if(billerName != null && !billerName.equals("") && billerName.equals(request.getBillPaymentsalaryCalculateInfo().getBillerName())){
if(city != null && !city.equals("") && city.equals(request.getMsgRqHdr().getCity()) &&
state != null && !state.equals("") && state.equalsIgnoreCase(request.getMsgRqHdr().getstate())){
salary = salaryRslt;
break;
} else if((city == null || city.equals("")) && state != null && !state.equals("") &&
state.equalsIgnoreCase(request.getMsgRqHdr().getState())){
salaryWithState = salaryRslt;
} else if((city == null || city.equals("")) && (state == null || state.equals(""))){
salaryWithName = salaryRslt;
}
} else if((billerName == null || billerName.equals("")) && (city == null || city.equals("")) &&
(state == null || state.equals(""))){
salaryWithNoMatch = salaryRslt;
}
}
if(salary != null){
return salary;
} else if(salaryWithState != null){
salary = salaryWithState;
} else if(salaryWithName != null){
salary = salaryWithName;
} else if(salaryWithNoMatch != null){
salary = salaryWithNoMatch;
}
return salary;
}
EDIT: I dont want to use 3 extra variables: salaryWithState, salaryWithName, salaryWithNoMatch.
I want just to give the general idea how this can be implemented, so I haven't actually tested and checked if it will give you the right salary.
public BigDecimal getSalaryForBestMatch(ResultSet resultSet, PaymentSalaryInfo paymentSalaryInfo) {
Map<String, Supplier<String>> m1 = new HashMap<>();
m1.put("EMP_NAME", paymentSalaryInfo::getBillerName);
m1.put("STATE", paymentSalaryInfo::getState);
m1.put("CITY", paymentSalaryInfo::getCity);
Map<String, Supplier<String>> m2 = new HashMap<>();
m2.put("STATE", paymentSalaryInfo::getState);
m2.put("CITY", paymentSalaryInfo::getCity);
Map<String, Supplier<String>> m3 = new HashMap<>();
m3.put("CITY", paymentSalaryInfo::getCity);
Optional<String> salary = Optional.empty();
while(resultSet.next() && !salary.isPresent()) {
salary = apply(m1, resultSet);
//check salary and then apply(m2, resultSet) ....
}
return salary.isPresent() ? new BigDecimal(salary.get()) : null;
}
public Optional<String> apply(Map<String, Supplier<String>> filter, ResultSet resultSet) {
boolean allMatch = filter.entrySet().stream().allMatch(entry -> {
String value = resultSet.getString(entry.getKey());
return value != null && value.equals(entry.getValue().get());
});
return allMatch ? Optional.of(resultSet.getString("salary")) : Optional.empty();
}
I have written the same logic in a different way with using arrays. If your environment can afford to use arrays, you can use this code. But I have not tested the code.
private static BigDecimal getsalaryForBestMatch(ResultSet results, EmployeeRq request) throws Exception{
BigDecimal salary = null;
int matchCount = 0;
String rBillerName = request.getBillPaymentsalaryCalculateInfo().getBillerName();
String rCity = request.getMsgRqHdr().getCity();
String rState = request.getMsgRqHdr().getstate();
String [] truthArray = new String[] {rBillerName, rCity, rState};
while (results.next()) {
String billerName = results.getString("EMP_NAME") != null ? results.getString("EMP_NAME").trim() : null;
String city = results.getString("CITY") != null ? results.getString("CITY").trim() : null;
String state = results.getString("STATE") != null ? results.getString("STATE").trim() : null;
BigDecimal salaryRslt = results.getString("SALARY") != null ? BigDecimal.valueOf(results.getDouble("SALARY")): null;
String [] testArray = new String[] {billerName, city, state};
int localMatchCount = 0;
for(int i = 0; i < testArray.length; i++) {
if(testArray[i] != null && testArray[i].equals(truthArray[i]))
localMatchCount++;
else {
break;
}
}
if(localMatchCount >= matchCount){
matchCount = localMatchCount;
salary = salaryRslt;
}
}
return salary;
}
When I'm compiling and running my tests,
this message appears:
StringIndexOutOfBoundsException: String index out of range: -3
I think I've done something wrong with the substrings, but I can't figure out where.
This should be tested:
Argument for parsePathname: .mp3
Output getAuthor: empty String
Output getTitle: empty String
This is my code:
public void parseFilename(String filename)
{
//Dateiendung entfernen
int ending;
ending = filename.lastIndexOf('.');
filename = filename.substring(0,ending);
filetype = filename.substring(filename.length()-3);
//Abfrage, ob Bindestrich(hyphen) vorhanden
//i+1 ist Position vom Bindestrich
boolean has_hyphen = false;
int i;
for(i=0; i<filename.length(); i++)
{
if(filename.charAt(i) == ' ' && filename.charAt(i+1) == '-' && filename.charAt(i+2) == ' ')
{
has_hyphen = true;
break;
}
}
if (!has_hyphen || (filename.length() == 1 && filename.charAt(0) == '-'))
{
author ="";
title = filename;
}
if (filename.length() == 0 || (filename.charAt(0) == ' ' && filename.charAt(1) == '-' && filename.charAt(2) == ' '))
{
author = "";
title = "";
}
if (has_hyphen)
{
author = filename.substring(0,i);
author = author.trim();
title = filename.substring(i+2);
title = title.trim();
}
}
My guess would be that your exception occurs here:
ending = filename.lastIndexOf('.');
filename = filename.substring(0,ending);
filetype = filename.substring(filename.length()-3); //<- Here
If . is the first char of the filename (eg. ".mp3"), the index will be 0 and the substring afterwards will be a string of size 0.
Then you call substring with -3 and it throws a IndexOutOfBoundsException. Make sure the string contain more than just the file type.
If you know that the input parameter always will contain a file extension you could prevent it like this:
ending = filename.lastIndexOf('.');
if(ending == 0) {
filetype = filename;
filename = "";
} else {
...
You should get the filetype before you remove it to get the filename. After this line:
filename = filename.substring(0,ending);
filename no longer contains the file extension.
Currently I am checking a string for the following:
if(parseCommand.contains("vlan1")
|| parseCommand.contains("Fa0/1i") || parseCommand.contains("Fa0/1o")
|| parseCommand.contains("Fa1/0") || parseCommand.contains("Fa1/1")
|| parseCommand.contains("Fa1/2") || parseCommand.contains("Fa1/3")
|| parseCommand.contains("Fa1/4") || parseCommand.contains("Fa1/5")
|| parseCommand.contains("Fa1/6") || parseCommand.contains("Fa1/7")
|| parseCommand.contains("Fa1/8") || parseCommand.contains("Fa1/9")
|| parseCommand.contains("Fa1/11") || parseCommand.contains("Gi0"))
{
//do things here
}
However it may contain vlan1 up to vlan4094 and i have to check for these. What is the simplest way to do this, do I have to stick it all in a for loop incrementing to 4094 I guess?
for (int i = 1; i <= 4094; i++)
{
if(parseCommand.contains("vlan"[i]))
{
//do stuff here
}
}
if(other conditions from above)
{
//do same stuff again here
}
Or else I could stick all the conditions in the for loop and do everything inside there. This all seems messy, is there a non-messy way of doing it?
I think this regex should do it:
String parseCommand = "vlan4094";
if (parseCommand.matches(".*?vlan([1-3][0-9]{3}|" +
"[1-9][0-9]{0,2}|" +
"40(9[0-4]|[0-8][0-9])).*"))
System.out.println("matches");
[1-3][0-9]{3} - 1000-3999
[1-9][0-9]{0,2} - 1-999
9[0-4] - 90-94
[0-8][0-9] - 00-89
40(9[0-4]|[0-8][0-9]) - 4000-4094
Something like this is probably simpler:
String parseCommand = "vlan4094";
if (parseCommand.startsWith("vlan"))
{
int v = Integer.parseInt(parseCommand.substring(4));
if (v >= 1 && v <= 4094)
/* do stuff */
}
Suggested change:
Replace:
parseCommand.contains("Fa1/0") || parseCommand.contains("Fa1/1")
|| parseCommand.contains("Fa1/2") || parseCommand.contains("Fa1/3")
|| parseCommand.contains("Fa1/4") || parseCommand.contains("Fa1/5")
|| parseCommand.contains("Fa1/6") || parseCommand.contains("Fa1/7")
|| parseCommand.contains("Fa1/8") || parseCommand.contains("Fa1/9")
with
parseCommand.matches(".*?Fa1/[0-9].*")
You can combie them into one boolean
boolean b = false;
for(int i = 1 ; i < 4094 ; i ++){
b = b || parseCommand.contains("vlan" + i);
}
Then check your boolean value
If the only problem is with "vlanXXX" you can remove the "vlan" part of the string:
parseCommand = parseCommand.replaceFirst("vlan", "");
and then cast it to int
int value = Integer.parseInt(parseCommand);
and then comparing this result with that whaat you want
if((value >= 1) && (value <= 4094)){....}
This will only work for the given case and you have to handle the case where parseCommand cannot be cast to int. And it is much more understandable than using whatever regular expresion
I am trying to return a String value located in double quotes, in java for instance
"Home Lone". I am writing a test script to match whats on my UI and that in database.
here is sample code
public String getMonitorKeywords(String keywords1, String keywords2, String keywords3) {
String words = "";
if (keywords2 != null && keywords1 == null && keywords3 == null) {
return words = keywords2.replaceAll("\\s+", " AND ");
}
else if(keywords2 == null && keywords1 == null && keywords3 != null){
keywords2 = keywords3.replaceAll("\\s+", " OR ");
words = keywords3;
Util.println("From databse we have third keywords{}: " + words);
return words;
}
else if(keywords2 != null && keywords1 != null && keywords3 == null){
words = keywords1;
Util.println("From databse we have first keywords{}: " + words);
return words;
}
else if(keywords2 == null && keywords1 != null && keywords3 == null){
words = keywords1;
return words;
}
else {
return null;
}
}
Problem with my method, when keywords2 has words with double quotes {""}, it increments AND into it which i dont want for those particular sets of words. Thanks i know its to do with regex expression to filter out such words with quotes. not all words have quotes.
Don't get it...
"foo \"bar\" or something else".replaceAll("\\s+", " AND ")
produces
foo AND "bar" AND or AND something AND else
Is that not your intention?
Try:
("[^"]+?")|(\w+?)\b
and replace with "$1$2 AND".
This will leave an extra " AND" at the end of the result, so you'll need to trim that off.