Compare a String reconstructed from a byte array with another String - java

Can somebody please point me to the right direction?
I am receiving a datagram packet, which I store to a string.
When I compare that string, to another one, it will result in false.
Here is the code:
private static String KEY = "Iamastring";
String sentence = new String( receivePacket.getData(), "UTF-8"); //Reconstruct the string
sentence.trim();
System.out.println("RECEIVED: " + sentence + " test " + KEY + " test ");
System.out.println("Length: " + sentence.length() + " " + KEY.equals(sentence));
And this is my output:
RECEIVED: Iamastring
Length: 1024 false
The expected comparison of KEY.equals(sentence) is true.

Strings aren't mutable :p
Therefore you must assign sentence.trim() to a variable, then use that variable for the comparison and the sysouts
sentence=sentence.trim();

If you expect trim() to help you, you must do
sentence = sentence.trim();
because trim() itself does not modify original string.

Related

Convert HOCON string into Java object

One of my webservice return below Java string:
[
{
id=5d93532e77490b00013d8862,
app=null,
manufacturer=pearsonEducation,
bookUid=bookIsbn,
model=2019,
firmware=[1.0],
bookName=devotional,
accountLinking=mandatory
}
]
I have the equivalent Java object for the above string. I would like to typecast or convert the above java string into Java Object.
I couldn't type-cast it since it's a String, not an object. So, I was trying to convert the Java string to JSON string then I can write that string into Java object but no luck getting invalid character "=" exception.
Can you change the web service to return JSON?
That's not possible. They are not changing their contracts. It would be super easy if they returned JSON.
The format your web-service returns has it's own name HOCON. (You can read more about it here)
You do not need your custom parser. Do not try to reinvent the wheel.
Use an existing one instead.
Add this maven dependency to your project:
<dependency>
<groupId>com.typesafe</groupId>
<artifactId>config</artifactId>
<version>1.3.0</version>
</dependency>
Then parse the response as follows:
Config config = ConfigFactory.parseString(text);
String id = config.getString("id");
Long model = config.getLong("model");
There is also an option to parse the whole string into a POJO:
MyResponsePojo response = ConfigBeanFactory.create(config, MyResponsePojo.class);
Unfortunately this parser does not allow null values. So you'll need to handle exceptions of type com.typesafe.config.ConfigException.Null.
Another option is to convert the HOCON string into JSON:
String hoconString = "...";
String jsonString = ConfigFactory.parseString(hoconString)
.root()
.render(ConfigRenderOptions.concise());
Then you can use any JSON-to-POJO mapper.
Well, this is definitely not the best answer to be given here, but it is possible, at least…
Manipulate the String in small steps like this in order to get a Map<String, String> which can be processed. See this example, it's very basic:
public static void main(String[] args) {
String data = "[\r\n"
+ " {\r\n"
+ " id=5d93532e77490b00013d8862, \r\n"
+ " app=null,\r\n"
+ " manufacturer=pearsonEducation, \r\n"
+ " bookUid=bookIsbn, \r\n"
+ " model=2019,\r\n"
+ " firmware=[1.0], \r\n"
+ " bookName=devotional, \r\n"
+ " accountLinking=mandatory\r\n"
+ " }\r\n"
+ "]";
// manipulate the String in order to have
String[] splitData = data
// no leading and trailing [ ] - cut the first and last char
.substring(1, data.length() - 1)
// no linebreaks
.replace("\n", "")
// no windows linebreaks
.replace("\r", "")
// no opening curly brackets
.replace("{", "")
// and no closing curly brackets.
.replace("}", "")
// Then split it by comma
.split(",");
// create a map to store the keys and values
Map<String, String> dataMap = new HashMap<>();
// iterate the key-value pairs connected with '='
for (String s : splitData) {
// split them by the equality symbol
String[] keyVal = s.trim().split("=");
// then take the key
String key = keyVal[0];
// and the value
String val = keyVal[1];
// and store them in the map ——> could be done directly, of course
dataMap.put(key, val);
}
// print the map content
dataMap.forEach((key, value) -> System.out.println(key + " ——> " + value));
}
Please note that I just copied your example String which may have caused the line breaks and I think it is not smart to just replace() all square brackets because the value firmware seems to include those as content.
In my opinion, we split the parse process in two step.
Format the output data to JSON.
Parse text by JSON utils.
In this demo code, i choose regex as format method, and fastjson as JSON tool. you can choose jackson or gson. Furthermore, I remove the [ ], you can put it back, then parse it into array.
import com.alibaba.fastjson.JSON;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SerializedObject {
private String id;
private String app;
static Pattern compile = Pattern.compile("([a-zA-Z0-9.]+)");
public static void main(String[] args) {
String str =
" {\n" +
" id=5d93532e77490b00013d8862, \n" +
" app=null,\n" +
" manufacturer=pearsonEducation, \n" +
" bookUid=bookIsbn, \n" +
" model=2019,\n" +
" firmware=[1.0], \n" +
" bookName=devotional, \n" +
" accountLinking=mandatory\n" +
" }\n";
String s1 = str.replaceAll("=", ":");
StringBuffer sb = new StringBuffer();
Matcher matcher = compile.matcher(s1);
while (matcher.find()) {
matcher.appendReplacement(sb, "\"" + matcher.group(1) + "\"");
}
matcher.appendTail(sb);
System.out.println(sb.toString());
SerializedObject serializedObject = JSON.parseObject(sb.toString(), SerializedObject.class);
System.out.println(serializedObject);
}
}

Splitting array in string does not give last element

Hi I am splitting and storing string with use of array but does not give result
String str = "123456";
String[] arrOfStr = str.split("");
String otpnum1 = arrOfStr[0];
String otpnum2 = arrOfStr[1];
String otpnum3 = arrOfStr[2];
String otpnum4 = arrOfStr[3];
String otpnum5 = arrOfStr[4];
String otpnum6 = arrOfStr[5];
System.out.println("otp"+otpnum1+otpnum2+otpnum3+otpnum4+otpnum5+otpnum6);
OUTPUT
System.out: otp12345
You are printing without any space or newline, which is the reason you are not able to interpret individual variables. Use this
System.out.println("otp " + otpnum1+ " " + otpnum2+" " + " "+ otpnum3+ " " + otpnum4+ " " + otpnum5+ " " + otpnum6);
I understand, the output is 12345, and expected 123456 for the result.
But, looking your code looks like correct.
I have try your code here, for test, and works fine.
The output was: otp123456

Java string split gives array index out of bounds error

I came across this unusual error today. Can anyone explain me what I am doing wrong. Below is the code:
AreStringsPermuted checkStringPerObj = new AreStringsPermuted();
String[] inputStrings = {"siddu$isdud", "siddu$siddarth", "siddu$sidde"};
for(String inputString : inputStrings){
String[] stringArray = inputString.split("$");
if(checkStringPerObj.areStringsPermuted(stringArray[0],stringArray[1]))
System.out.println("Strings : " + stringArray[0] + " ," + stringArray[1] + " are permuted");
else
System.out.println("Strings : " + stringArray[0] + " ," + stringArray[1] + " are not permuted");
}
The above code errors out at when i try to split the string. For some reason split does not work when I try to divide each string using "$". Can any one explain me what I am doing wrong here?
Below is the error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at arraysAndStrings.TestClass.checkStringsPermuted(TestClass.java:24)
at arraysAndStrings.TestClass.main(TestClass.java:43)
String.split() takes a regular expression, so you need to quote strings that contain characters that have special meanings in regular expressions.
String regularExpression = Pattern.quote("$");
for (String inputString : inputStrings) {
String[] stringArray = inputString.split(regularExpression);
String.split( ) uses regex partern and $ has special meaning in regex(the end of line).
In your case, use "\$" instead of "$".
String []arrayString = inputString.split("\\$");
For more information,
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

Java empty String split ArrayIndexOutOfBoundsException [duplicate]

This question already has answers here:
Java String split is not working
(3 answers)
Closed 7 years ago.
I have come across an unexpected feature in the split function of String in Java, here is my code:
final String line = "####";
final String[] lineData = line.split("#");
System.out.println("data: " + lineData[0] + " -- " + lineData[1]);
This code gives me an ArrayIndexOutOfBoundsException, whereas I would expect it to print "" and "" (two empty Strings), or maybe null and null (two null Strings).
If I change my code for
final String line = " # # # #";
final String[] lineData = line.split("#");
System.out.println("data: " + lineData[0] + " -- " + lineData[1]);
Then it prints " " and " " (the expected behaviour).
How can I make my first code not throwing an exception, and giving me an array of empty Strings?
Thanks
You can use the limit attribute of split method to achieve this. Try
final String line = "####";
final String[] lineData = line.split("#", -1);
System.out.println("Array length : " + lineData.length);
System.out.println("data: " + lineData[0] + " -- " + lineData[1]);
As always, answer is written in the Javadoc
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
Since your array is composed only by empty strings, they are not added to it, thus trying to access the values result in an ArrayOutOfBoundException.
If I understand your question, this would do it -
final String line = " # ";
final String[] lineData = line.split("#");
System.out.println("data: " + lineData[0] + " -- " + lineData[1]);
The problem is that the empty string isn't a character.

Using HTML code in Swing

I can't figure out how to use variables in HTML, string is a variable in this case.
JOptionPane.showMessageDialog(null,"<html>Error #1<br> + string +</html>","Error",JOptionPane.PLAIN_MESSAGE);
this output: Error #1 + string
JOptionPane.showMessageDialog(null,"<html>Error #1<br></html>" + string ,"Error",JOptionPane.PLAIN_MESSAGE);
this output: Error #1
is there a way to use string variables in HTML?
Do you want something like
"<html>Error #1<br>" + string + "</html>"
?
If you want to concatenate the string variable to the html you have there, it must be outside the quotes, otherwise it will be treated as a literal, as in your example.
JOptionPane.showMessageDialog(
null,
"<html>Error #1<br>" + string + "</html>",
"Error",
JOptionPane.PLAIN_MESSAGE);
Though note that logically JOptionPane.PLAIN_MESSAGE should be JOptionPane.ERROR_MESSAGE.
You need to do: "<html>Error #1<br>" + string + "</html>"
A string literal in java consists of zero or more characters enclosed in double quotes. So anything satisfies this condition will also be regarded as string too. You will need to close the String before appending the string.
So if the string = "Hi to stack":
Then "<html>Error #1<br>" + string + "</html>" will result in:
"<html>Error #1<br>Hi to stack</html>"

Categories