Java String appending with comma as a separator - java

I have a requirement where I need to append multiple values from multiple web service calls into one final string with comma as a separator.
Some of the values might be null, in that case I need to check for not null and then append it as empty string.
If there is no value for one of the string, comma should not get appended.
Please help me resolving this. here is the code what I did.
StringBuilder sb = new StringBuilder();
if (usersList.totalCount != 0 && usersList.totalCount >= 1) {
logger.info("usersList.totalCount ----->"
+ usersList.totalCount);
for (KalturaUser user : usersList.objects) {
if (user.id != null) {
sb.append(userId);
}
if (user.firstName != null) {
sb.append(",").append(userFirstName);
}
if (user.lastName != null) {
sb.append(",").append(user.lastName);
}
if (user.email != null) {
sb.append(",").append(user.email);
}
if (user.roleNames != null) {
sb.append(",").append(user.roleNames);
}
if (user.partnerData != null) {
sb.append(",").append(user.partnerData);
}
}
System.out.println(sb);
}
Thanks,
Raji

I think you are looking for something like this:
public static String asString(Object value) {
return value == null ? "" : value.toString();
}
for (KalturaUser user : usersList.objects) {
sb.append(asString(user.id));
sb.append(",").append(asString(user.firstName));
sb.append(",").append(asString(user.lastName));
sb.append(",").append(asString(user.email));
sb.append(",").append(asString(user.roleNames));
sb.append(",").append(asString(user.partnerData));
}

Well, in your tests like
if (user.id != null) {
sb.append(userId);
}
you are checking user.id but appending userId. These are two different variables.
You should probably change it into
if (user.id != null) {
sb.append(user.id); //instead of sb.append(userId);
}

It is not clear what your problem is, but if you are looking for a better or different approach, I found that it is best to append to a List<String> and then use StringUtils.join to produce the final string.

You can use a class from a google library called Joiner.
String concatenedString = Joiner.on(",").skipNulls().join(itemToAdd);
You can find this class on google-collections-1.0.jar

I would do something like that. It's based on Java8 streams, but here you don't need to do the non-null check on every property(.filter does this for you). I assumed that users.object is an array list, if it's not you might need to convert it into stream in other way
if (userList.totalCount > 0) {
logger.info("usersList.totalCount ----->" + usersList.totalCount);
String result = userList
.objects
.stream()
.map(user -> {
return Stream.of(user.firstName, user.id, user.lastName, user.email, user.roleNames, user.partnerData) //get the properties you need into the stream
.filter(property -> property != null) // filter out null properties
.collect(Collector.joining(",")); //join them by comma
})
.collect(Collector.joining(",")); //join user strings with comma
System.out.println(result);
}

Related

Set default value, if exist in config.properties use that, if overridden on command line use that

Untested code (just thinking out loud), but I'm thinking there must be a more elegant way to do this.
So there's three ways to set a variable:
just assign it
read it from a properties file (might not be there)
read it from the command line (could be more than one argument or none)
Higher number takes precedence. How would I approach this?
public static final String APP_DOWNLOAD_PATH;
[...]
// If download path is not defined in config.properties, set it to the app dir.
String download = properties.getProperty("download", System.getProperty("user.dir"));
// Override if download path is set via command line.
String override = null;
try {
override = System.getProperty("download");
} catch (NullPointerException | IllegalArgumentException ok) {
// property is either not found or empty.
}
String APP_DOWNLOAD_PATH = (override == null || override.isEmpty()) ? download : override;
E: Added restrictions.
The straight forward approach is the best in my opinion. For example:
public static final String APP_DOWNLOAD_PATH = "foo";
public static void main(String... args) {
String dwnPath = null;
if(args.length > 0) {
dwnPath = args[0];
} else if(System.getProperty("download") != null) { // don't need try-catch, "download" is not null and not empty ("")
// not DRY at all
dwnPath = System.getProperty("download");
} else {
dwnPath = APP_DOWNLOAD_PATH;
}
// rest of program
}
The above could also be extracted to it's own function leading to a one liner:
String dwnPath = getDownloadPath(args, System.getProperty("download"), APP_DOWNLOAD_PATH);
The extracted function can also be more elegant than the code above:
/** Documentation */
public static String getDownloadPath(String[] args, String property, String default) {
return (args.length > 0) ? args[0] : (property != null) ? property : default;
}
If it is ok to use a external library, then this apache commons method could be useful -
StringUtils.firstNonEmpty(System.getProperty("download"),
properties.getProperty("download", System.getProperty("user.dir")),
"some value");

Checking which parameter is missing from file content

I have a TransferReader class which reads a file containing transfer data from bank account to another using the following form:
SenderAccountID,ReceiverAccountID,Amount,TransferDate
"473728292,474728298,1500.00,2019-10-17 12:34:12" (unmodified string)
Suppose that the file has been modified before being read so that one of the above mentioned paramaters are missing, and I want to check which of those are missing.
"474728298,1500.00,2019-10-17 12:34:12" (modified string)
I am using a BufferedReader to read each line, and then splitting each element into a String[] using String.split(",") as delimeter.
As already realized, because the Sender Account ID and Receiver Account ID are right next to one another within a record there is no real way of knowing which ID might be missing unless a delimiter remains in its' place indicating a Null value. There are however mechanisms available to determine that it is indeed one of the two that is missing, which one will need to be carried out through User scrutiny and even then, that may not be good enough. The other record column fields like Amount and Transfer Date can be easily validated or if missing can be implicated within a specific File Data Status Log.
Below is some code that will read a data file (named Data.csv) and log potential data line (record) errors into a List Interface object which is iterated through and displayed within the Console Window when the read is complete. There are also some small helper methods. Here is the code:
private void checkDataFile(String filePath) {
String ls = System.lineSeparator();
List<String> validationFailures = new ArrayList<>();
StringBuilder sb = new StringBuilder();
// 'Try With Resources' used here to auto-close reader.
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
int lineCount = 0;
// Read the file line-by-line.
while ((line = reader.readLine()) != null) {
line = line.trim();
lineCount++;
if (lineCount == 1 || line.equals("")) {
continue;
}
sb.delete(0, sb.capacity()); // Clear the StringBuilder object
// Start the Status Log
sb.append("File Line Number: ").append(lineCount)
.append(" (\"").append(line).append("\")").append(ls);
// Split line into an Array based on a comma delimiter
// reguardless of the delimiter's spacing situation.
String[] lineParts = line.split("\\s{0,},\\s{0,}");
/* Validate each file line. Log any line that fails
any validation for any record column data into a
List Interface object named: validationFailures
*/
// Are there 4 Columns of data in each line...
if (lineParts.length < 4) {
sb.append("\t- Invalid Column Count!").append(ls);
// Which column is missing...
// *** You may need to add more conditions to suit your needs. ***
if (checkAccountIDs(lineParts[0]) && lineParts.length >= 2 && !checkAccountIDs(lineParts[1])) {
sb.append("\t- Either the 'Sender Account ID' or the "
+ "'ReceiverAccountID' is missing!").append(ls);
}
else if (lineParts.length >= 3 && !checkAmount(lineParts[2])) {
sb.append("\t- The 'Amount' value is missing!").append(ls);
}
else if (lineParts.length < 4) {
sb.append("\t- The 'Transfer Date' is missing!").append(ls);
}
}
else {
// Is SenderAccountID data valid...
if (!checkAccountIDs(lineParts[0])) {
sb.append("\t- Invalid Sender Account ID in column 1! (")
.append(lineParts[0].equals("") ? "Null" :
lineParts[0]).append(")");
if (lineParts[0].length() < 9) {
sb.append(" <-- Not Enough Or No Digits!").append(ls);
}
else if (lineParts[0].length() > 9) {
sb.append(" <-- Too Many Digits!").append(ls);
}
else {
sb.append(" <-- Not All Digits!").append(ls);
}
}
// Is ReceiverAccountID data valid...
if (!checkAccountIDs(lineParts[1])) {
sb.append("\t- Invalid Receiver Account ID in coloun 2! (")
.append(lineParts[1].equals("") ? "Null" :
lineParts[1]).append(")");
if (lineParts[1].length() < 9) {
sb.append(" <-- Not Enough Or No Digits!").append(ls);
}
else if (lineParts[1].length() > 9) {
sb.append(" <-- Too Many Digits!").append(ls);
}
else {
sb.append(" <-- Not All Digits!").append(ls);
}
}
// Is Amount data valid...
if (!checkAmount(lineParts[2])) {
sb.append("\t- Invalid Amount Value in column 3! (")
.append(lineParts[2].equals("") ? "Null" :
lineParts[2]).append(")").append(ls);
}
// Is TransferDate data valid...
if (!checkTransferDate(lineParts[3], "yyyy-MM-dd HH:mm:ss")) {
sb.append("\t- Invalid Transfer Date Timestamp in column 4! (")
.append(lineParts[3].equals("") ? "Null" :
lineParts[3]).append(")").append(ls);
}
}
if (!sb.toString().equals("")) {
validationFailures.add(sb.toString());
}
}
}
catch (FileNotFoundException ex) {
System.err.println(ex.getMessage());
}
catch (IOException ex) {
System.err.println(ex.getMessage());
}
// Display the Log...
String timeStamp = new SimpleDateFormat("yyyy/MM/dd - hh:mm:ssa").
format(new Timestamp(System.currentTimeMillis()));
String dispTitle = "File Data Status at " + timeStamp.toLowerCase()
+ " <:-:> (" + filePath + "):";
System.out.println(dispTitle + ls + String.join("",
Collections.nCopies(dispTitle.length(), "=")) + ls);
if (validationFailures.size() > 0) {
for (String str : validationFailures) {
if (str.split(ls).length > 1) {
System.out.println(str);
System.out.println(String.join("", Collections.nCopies(80, "-")) + ls);
}
}
}
else {
System.out.println("No Issues Detected!" + ls);
}
}
private boolean checkAccountIDs(String accountID) {
return (accountID.matches("\\d+") && accountID.length() == 9);
}
private boolean checkAmount(String amount) {
return amount.matches("-?\\d+(\\.\\d+)?");
}
private boolean checkTransferDate(String transferDate, String format) {
return isValidDateString(transferDate, format);
}
private boolean isValidDateString(String dateToValidate, String dateFromat) {
if (dateToValidate == null || dateToValidate.equals("")) {
return false;
}
SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
sdf.setLenient(false);
try {
// If not valid, it will throw a ParseException
Date date = sdf.parse(dateToValidate);
return true;
}
catch (ParseException e) {
return false;
}
}
I'm not exactly sure what your particular application process will ultimately entail but if other processes are accessing the file and making modifications to it then it may be wise utilize a locking mechanism to Lock the file during your particular process and Unlock the file when it is done. This however will most likely require you to utilize a different reading algorithm since locking a file must be done through a writable channel. Using the FileChannel and FileLock classes from the java.nio package could possibly assist you here. There would be examples of how to utilize these classes within the StackOverflow forum.

How to check if string is empty

I have an activity 'B'. I have 2 more activities A and C. Both the activities lead to B. But i pass different Data from A and C. So while fetching
String dataFromA = getIntent.getStringExtra("SomethingA");
String dataFromC = getIntent.getStringExtra("SomethingC");
How to not get an error. I wont know from where the user is getting to activity B So how do i add an If statement or seomthing to not get an error while fetching as Either line A or C will get a NullPOinterException
You can use hasExtra method to check if that String exists.
if (getIntent().hasExtra("SomethingA")) {
String dataFromA = getIntent.getStringExtra("SomethingA");
} else if (getIntent().hasExtra("SomethingC")) {
String dataFromC = getIntent.getStringExtra("SomethingC");
}
You can try this code.
Bundle arguments = getArguments();
if (arguments != null){
if (arguments.containsKey("SomethingA")) {
String somethingA = arguments.getString("SomethingA");
if (TextUtils.isEmpty(somethingA)){
// Your codes comes here
}
}
}
Bundle (arguments) can be null if there is no data passed.
To check if string is empty or not use below code :
if(TextUtils.isEmpty(yourString))
{
// String empty
}
else
{
// string not empty
}
In your case you check it as :
if (getIntent()!=null && getIntent().getStringExtra!=null )
{
if (getIntent().hasExtra("SomethingA") && getIntent().hasExtra("SomethingB"))
String dataFromA = getIntent.getStringExtra("SomethingA");
String dataFromB = getIntent.getStringExtra("SomethingB");
}

How to get null and filled values from database using hibernate

I am using hibernate to get data from oracle.I have Criterion object to make filter for hibernate select like this
Criterion cr6=null;
if(reqrrn != null)
{
cr6=Restrictions.eq("rrn", reqrrn);//o
}
else{
cr6=Restrictions.like("rrn", "",MatchMode.ANYWHERE);
}
Criterion cr20=null;
if(cardPrefix != null && cardPrefix != "")
{
cr20=Restrictions.eq("prefix", cardPrefix);
}
else{
cr20=Restrictions.like("prefix", "",MatchMode.ANYWHERE);
}
criteria.add(Restrictions.and(cr6, cr20));
i have filters like this, but it is usseless when value is null, for example
cardPrefix value is null in database i want to get all values for cardPrefix ,which are filled and null too, how can i do this ?
i solved it. it will be for all parameters like
if(cardPrefix != null && cardPrefix != "")
{
cr20=Restrictions.eq("prefix", cardPrefix);
}
else{
cr20=Restrictions.like("prefix", "",MatchMode.ANYWHERE);
cr1=Restrictions.isNull("prefix");
cr20=Restrictions.or(cr20, cr1);
}

How to flexibly generate string in Java as hibernate does

In my query I can't use hibernate and I need to generate a String as follows:
I have Map<String, String> restrictions instance with 3 keys (id, name and value) and I want to get the entry (String).
if (restrictions.get("id") != null && restrictions.get("name") == null && restrictions.get("value") == null){
return "ID = " + restrictions.get("id");
} else if (restrictions.get("id") != null && restrictions.get("name") != null && restrictions.get("value" != null)){
return "ID = " + restrictions.get("id") + " and Name = " + restrictions.get("name");
}
And so forth...
Explicitly writting the if-else clauses is very unflexible and hardly maintainable way. Any ideas?
Use java.util.StringJoiner:
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;
public class SOPlayground {
public static void main(String[] args) throws Exception {
Map<String, String> restrictions = new HashMap<>();
restrictions.put("id", "foo");
restrictions.put("name", "bar");
restrictions.put("not set", null);
StringJoiner joiner = new StringJoiner(" AND ");
restrictions.keySet().stream().filter((column) -> (restrictions.get(column) != null)).map((column) -> {
StringBuilder builder = new StringBuilder();
builder.append(column).append("='").append(restrictions.get(column)).append("'");
return builder;
}).map((builder) -> builder.toString()).forEach((term) -> {
joiner.add(term);
});
System.out.println(joiner.toString());
}
}
Output:
id='foo' AND name='bar'
Just try to search for questions on "how to iterate over a map in java". How to efficiently iterate over each Entry in a Map? should give you an example.
As for comment, below can be the code, though you can easily optimize it:
StringBuffer clause = new StringBuffer();
for(Map.Entry<String, String> entry : restrictions.entrySet()) {
clause.append(entry.getKey()).append(\"=\").append(entry.getValue());
clause.append(" AND ");
}
String strClause = clause.toString();
strClause = strCluase.subString(0, strClause.length() - 5); //5 is length of " AND "
This question has been answered before. I would prefer using Colin Hebert answer in my opinion.
Your if-else would be fine but you could always override the functions to meet your needs thanks to OOP (code re-usability).
What you want to achieve could be done in various ways and everyone has his own way of coding.

Categories