Java String contains not working with string parsed from file - java

I'm currently facing a string encoding problem.
ListItemType liste = new ListItemType();
String toBChecked=(String)table.getValueAt(row,0);
System.out.print(toBChecked);
toBChecked = "Angelic";
for(String s : liste.sets){
if(toBChecked.contains(s)){
setBackground(Color.GREEN);
}
}
When I copy/paste the string "Angelic" from logs and put it in toBChecked it doesn't work, but when I type it in my code it does work.
Of course, when I directly check table's value (which has the "Angelic" word in its string) it doesn't work.
Table's content is parsed from a file encoded in UTF-16-LE, is it the problem?
How can I fix it?

Related

GROOVY I am getting random backslashes when creating JSON file in Folder

I am having trouble compiling the JSON file. This is my method (the main method just has the name of the method I am writing this code in it so I did not include the main method in here.)
static void buildJSONFiles() {
String commandJson = "C:/Users/Name/Desktop/docfiles/command_config.json"
def data = [
commands:
JsonOutput.toJson([new Commands(name:"upload", path:"\${BUILTIN_EXE(command)}", includeCommandName: true),
new Commands(name:"file_info", path:"\${BUILTIN_EXE(command)}", includeCommandName: true)])
]
println(data)
def json_str = JsonOutput.toJson(data)
def json_beauty = JsonOutput.prettyPrint(json_str)
File file = new File(commandJson)
file.write(json_beauty)
println(json_str)
}
static class Commands {
String name
String path
boolean includeCommandName
}
my output in the console does come out right like this
[commands:[{"includeCommandName":true,"path":"${BUILTIN_EXE(command)}","name":"upload"},{"includeCommandName":true,"path":"${BUILTIN_EXE(command)}","name":"file_info"}]]
but sending it to the JSON file it comes out like this
{"commands":"[{\"includeCommandName\":true,\"path\":\"${BUILTIN_EXE(command)}\",\"name\":\"upload\"},{\"includeCommandName\":true,\"path\":\"${BUILTIN_EXE(command)}\",\"name\":\"file_info\"}]"}
I understand that JSON backslash is a special character so I expected it to be only around the :"${BUILTIN_EXE(command)} but it is showing up everywhere where I did not even have a backslash.
You don't have "random backslashes", you have double-quoted JSON, since you're using JsonOutput twice. json_str is a string with JSON in it, and then you're wrapping that as a JSON value inside more JSON.

Java insert text line above specifice text in string from file with string indentation

i have simple text im reading from file and I'm getting its content as string
String pomxml = "c:\\foo\\test.json";
String content = FileUtils.readFileToString(file);
the string content (example) is :
"email_settings": {
"email.starttls.enable":"true",
"email.port":"111",
"email.host":"xxxx",
"email.auth":"true",
}
i like to insert new string above "email.host":"xxxx", only if it finds it.
so it will look like :
"email_settings": {
"email.starttls.enable":"true",
"email.port":"111",
"email.name":"myTest",
"email.host":"xxxx",
"email.auth":"true",
}
My question is how to insert this new line into the string
UPDATE
in this example it is JSON , but it can be also simple text or XML file
so i can't rely on JSON providers
You could try doing a regex replacement here:
String input = "\"email_settings\": {\n \"email.starttls.enable\":\"true\",\n \"email.port\":\"111\",\n \"email.host\":\"xxxx\",\n \"email.auth\":\"true\",\n}";
String output = input.replaceAll("([ ]*\"email.host\":\".*?\")", " \"email.name\":\"myTest\",\n$1");
System.out.println(output);
This prints:
"email_settings": {
"email.starttls.enable":"true",
"email.port":"111",
"email.name":"myTest",
"email.host":"xxxx",
"email.auth":"true",
}
However, if you are dealing with proper JSON content, then you should consider using a JSON parser instead. Parse the JSON text into a Java POJO and then write out with the new field.
content = content.replace("\"email.host\":", "\"email.name\":\"myTest\",\n" + " \"email.host\":");
Or you could look in to libraries which parse json files.

Preserving the <br> tags when cleaning with Jsoup

For the input text:
<p>Arbit string <b>of</b><br><br>text. <em>What</em> to <strong>do</strong> with it?
I run the following code:
Whitelist list = Whitelist.simpleText().addTags("br");
// Some other code...
// plaintext is the string shown above
retVal = Jsoup.clean(plaintext, StringUtils.EMPTY, list,
new Document.OutputSettings().prettyPrint(false));
I get the output:
Arbit string <b>of</b>
text. <em>What</em> to <strong>do</strong> with it?
I don't want Jsoup to convert the <br> tags to line breaks, I want to keep them as-is. How can I do that?
Try this:
Document doc2deal = Jsoup.parse(inputText);
doc2deal.select("br").append("br"); //or append("<br>")
This is not reproducible for me. Using Jsoup 1.8.3 and this code:
String html = "<p>Arbit string <b>of</b><br><br>text. <em>What</em> to <strong>do</strong> with it?";
String cleaned = Jsoup.clean(html,
"",
Whitelist.simpleText().addTags("br"),
new Document.OutputSettings().prettyPrint(false));
System.out.println(cleaned);
I get the following output:
Arbit string <b>of</b><br><br>text. <em>What</em> to <strong>do</strong> with it?
Your problem must be somewhere else I guess.

JSONException: no value for XYZ when trying to getString("XYZ")

I am doing JSON parsing in Android by the following steps:
Get an XML response from a web-service using HttpPost object.
Convert this XML to JSON string then JSON object.
Now the problem is that sometimes the XML response has null string or Null tag.
For Example:
<data>
<name>Martin Clark</name>
<city>London</city>
<country>XYZ</country> or <country /> <!-- Sometimes it will blank string like this if country is not available -->
<age>27</age>
</data>
Parsing style:
jsonObject.getString("country"); // It is working perfect when xml is this : <country>XYZ<country/>
jsonObject.getString("country"); // It is giving Exception key is not found when xml is this : <country />
i don't understand why the parser is not giving me BLANK string for blank XML object.
By deep level debugging i have found that XML to JSON converter not produce object corresponding to blank xml object.
Please help me.
Use optString instead, catching the Exception is costly and unnecessary.
public String optString (String name)
Added in API level 1 Returns the value mapped by name if it exists,
coercing it if necessary. Returns the empty string if no such mapping
exists.
public String optString (String name, String fallback)
Added in API level 1 Returns the value mapped by name if it exists,
coercing it if necessary. Returns fallback if no such mapping exists.
Documentation
You can use ths logical solution for your problem.
Try this once.
public static String getStringFromJSON(JSONObject json, String key){
String value = ""; // Blank string by default.
try {
String value = json.getString(key);
return value;
}
catch(JSONException exp){
exp.getMessage();
}
return value; // this wil return BLANk string if object is not prasent.
}
You can you this method for getting String from json object,

How to read data from CSV if contains more than excepted separators?

I use CsvJDBC for read data from a CSV. I get CSV from web service request, so not loaded from file. I adjust these properties:
Properties props = new java.util.Properties();
props.put("separator", ";"); // separator is a semicolon
props.put("fileExtension", ".txt"); // file extension is .txt
props.put("charset", "UTF-8"); // UTF-8
My sample1.txt contains these datas:
code;description
c01;d01
c02;d02
my sample2.txt contains these datas:
code;description
c01;d01
c02;d0;;;;;2
It is optional for me deleted headers from CSV. But not optional for me change semi-colon separator.
EDIT: My query for resultSet: SELECT * FROM myCSV
I want to read code column in sample1.txt and sample2.txt with:
resultSet.getString(1)
and read full description column with many semi-colons (d0;;;;;2). Is it possible with CsvJdbc driver or need to change driver?
Thank you any advice!
This is a problem that occurs when you have messy, invalid input, which you need to try to interpret, that's being read by a too-high-level package that only handles clean input. A similar example is trying to read arbitrary HTML with an XML parser - close, but no cigar.
You can guess where I'm going: you need to pre-process your input.
The preprocessing may be very easy if you can make some assumptions about the data - for example, if there are guaranteed to be no quoted semi-colons in the first column.
You could try supercsv. We have implemented such a solution in our project. More on this can be found in http://supercsv.sourceforge.net/
and
Using CsvBeanReader to read a CSV file with a variable number of columns
Finally this problem solved without a CSVJdbc or SuperCSV driver. These drivers works fine. There are possible query data form CSV file and many features content. In my case I don't need query data from CSV. Unfortunately, sometimes the description column content one or more semi-colons and which it is my separator.
First I check code in answer of #Maher Abuthraa and modified to:
private String createDescriptionFromResult(ResultSet resultSet, int columnCount) throws SQLException {
if (columnCount > 2) {
StringBuilder data_list = new StringBuilder();
for (int ii = 2; ii <= columnCount; ii++) {
data_list.append(resultSet.getString(ii));
if (ii != columnCount)
data_list.append(";");
}
// data_list has all data from all index you are looking for ..
return data_list.toString();
} else {
// use standard way
return resultSet.getString(2);
}
}
The loop started from 2, because 1 column is code and only description column content many semi-colons. The CSVJdbc driver split columns by separator ; and these semi-colons disappears from columns data. So, I explicit add semi-colons to description, except the last column, because it is not relevant in my case.
This code work fine. But not solved my all problem. When I adjusted two columns in header of CSV I get error in row, which content more than two semi-colons. So I try adjust ignore of headers or add many column name (or simple ;) to a header. In superCSV ignore of headers option work fine.
My colleague opinion was: you are don't need CSV driver, because try load CSV which not would be CSV, if separator is sometimes relevant data.
I think my colleague has right and I loaded CSV data whith following code:
InputStream in = null;
try {
in = new ByteArrayInputStream(csvData);
List lines = IOUtils.readLines(in, "UTF-8");
Iterator it = lines.iterator();
String line = "";
while (it.hasNext()) {
line = (String) it.next();
String description = null;
String code = null;
String[] columns = line.split(";");
if (columns.length >= 2) {
code = columns[0];
String[] dest = new String[columns.length - 1];
System.arraycopy(columns, 1, dest, 0, columns.length - 1);
description = org.apache.commons.lang.StringUtils.join(dest, ";");
(...)
ok.. my solution to go and read all fields if columns are more than 2 ... like:
int ccc = meta.getColumnCount();
if (ccc > 2) {
ArrayList<String> data_list = new ArrayList<String>();
for (int ii = 1; ii < ccc; ii++) {
data_list.add(resultSet.getString(i));
}
//data_list has all data from all index you are looking for ..
} else {
//use standard way
resultSet.getString(1);
}
If the table is defined to have as many columns as there could be semi-colons in the source, ignoring the initial column definitions, then the excess semi-colons would be consumed by the database driver automatically.
The most likely reason for them to appear in the final column is because the parser returns the balance of the row to the terminator in the field.
Simply increasing the number of columns in the table to match the maximum possible in the input will avoid the need for custom parsing in the program. Try:
code;description;dummy1;dummy2;dummy3;dummy4;dummy5
c01;d01
c02;d0;;;;;2
Then, the additional ';' delimiters will be consumed by the parser correctly.

Categories