Base64 does not encode the entire string - java

When I encode tex, for some reason it cuts off part of the string ... What could be the problem?
DateFormat dateFormat =
new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a", Locale.ENGLISH);
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR,+ 9);
String server_time = dateFormat.format(calendar.getTime());
String wmsAuthSign = "server_time=" + server_time + "&hash_value=U2QK9TLB55JWTZr3OKZHtg==&validminutes=120";
wmsAuthSign = "?wmsAuthSign=" + Base64.encodeToString(wmsAuthSign.getBytes(), Base64.DEFAULT);
I am submitting something like this:
server_time=02/18/2019 23:38:43 PM&hash_value=U2QK9TLB55JWTZr3OKZHtg==&validminutes=120
And if you decode the encoded text, you get a trimmed result:
server_time=02/18/2019 23:38:43 PM&hash_value=U2QK9TLB55J

Because of RFC-2045:
(5) (Soft Line Breaks) The Quoted-Printable encoding
REQUIRES that encoded lines be no more than 76
characters long. If longer lines are to be encoded
with the Quoted-Printable encoding, "soft" line breaks
source data string:
server_time=02/18/2019 23:38:43 PM&hash_value=U2QK9TLB55JWTZr3OKZHtg==&validminutes=120
Base64 encoded to string:
c2VydmVyX3RpbWU9MDIvMTgvMjAxOSAyMzoxMjo1NiBQTSZoYXNoX3ZhbHVlPVUyUUs5VExCNTVK
V1RacjNPS1pIdGc9PSZ2YWxpZG1pbnV0ZXM9MTIw
exactly like it shown above: with line break. But on receiver side you probably decode only first line
c2VydmVyX3RpbWU9MDIvMTgvMjAxOSAyMzoxMjo1NiBQTSZoYXNoX3ZhbHVlPVUyUUs5VExCNTVK
that is server_time=02/18/2019 23:12:21 PM&hash_value=U2QK9TLB55J
So decode on receiver side whole received data, not only first line.
Or you may be sent to receiver side only first line of encoded Base64.
Also take a look at this answer of Mohammad Adil:
On android, Use Base64.NO_WRAP instead of Base64.DEFAULT

Related

Java scan a log file and get the time information then calculate the elapsed time

I have a txt file with a line like below:
0 Apr 12 08:42:44.000009 (+0.000009) *** START ***
The information I want to get is:
Apr 12 08:42:44
The current method I'm using use is using a scanner to read this line:
public void getTime() throws IOException {
String time = "";
Scanner scan = new Scanner(location);
String firstLine = scan.nextLine();
String[] splitString = firstLine.split("\\.");
String[] rebootTime = splitString[0].split(" ");
for(int i = 0; i < rebootTime.length; i++) {
if(i != 0) {
time = time + rebootTime[i] + " ";
}
}
System.out.println(time);
}
Is there a smarter way to get the time information?
After I get the time, how do I transfer it to a date format then calculate the duration?
I'm trying to use JAVA 8 Instant with this method, how can I transfer the time value to a Instant type?
If I understand you properly your goal is to extract reboot time from each string of a log file. Using Scanner is ok to my mind. After extracting a line from log file you might as well use regular expressions on it, like this:
String firstLine = scan.nextLine();
Pattern pattern = Pattern.compile("[a-zA-Z]{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}");
Matcher matcher = pattern.matcher(firstLine);
if (matcher.find()) {
String rebootTime = matcher.group();
}
This regexp is not perfect but it works on your line. You can make it more or less strict.
As to formatting the string to a LocalDateTime, you can use following method:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("MMM dd HH:mm:ss")
.parseDefaulting(ChronoField.YEAR, 1)
.toFormatter();
LocalDateTime date = LocalDateTime.parse(rebootTime, formatter);
So parseDefaulting(ChronoField.YEAR, 1) means that you ignore year in string and set it as 1 in resulting LocalDateTime. After that you can calculate durations using LocalDateTimes.
I like Mongwo's elegant solution.
There are many ways to skin this cat. Other than regular expression, you can simply use a quick-n-dirty one liner, if it is in fixed length and always starting from the fixed index of a string:
String rawStr = "0 Apr 12 08:42:44.000009 (+0.000009) *** START ***";
System.out.println(rawStr.substring(5, 20));
If the file is small enough that you are ok with reading the whole thing, it is generated by another process so that you can guarantee the format, and the line you want is first (which from the question I think all above things should be true), your solution can be as simple as
private SimpleDateFormat format = new SimpleDateFormat("MMM dd HH:mm:ss");
public Date read(String filePath) throws URISyntaxException, IOException, ParseException {
Path fileLocation = Paths.get(filePath);
byte[] data = Files.readAllBytes(fileLocation);
return format.parse(new String(data, 5, 15));
}
If the file is longer, you may want to use a scanner if you dont want to read the whole thing, but imho it is still simplest to use indices to get the part of the string that you want.
If you want a very elegant solution maybe you could use a regex, but I really dont think there is much of a need.
My try here is:-
First let's extract value before dot(".") and then value after double space(" ").
public static void main(String[] args) {
String str = "0 Apr 12 08:42:44.000009 (+0.000009) *** START ***";
String[] str1 = str.split("\\.");
String[] str2 = str1[0].split("\\s{2,}");
System.out.println((str2[1]));
}
To understand \\s{2,} you can look into saved regex.
regex to match 2 spaces

decode base64 utf-8 string java

I have this string
"=?UTF-8?B?VGLNBGNDQA==?="
to decode in a standard java String.
I wrote this quick and dirty main to get the String, but I'm having troubles
String s = "=?UTF-8?B?VGLNBGNDQA==?=";
s = s.split("=\\?UTF-8\\?B\\?")[1].split("\\?=")[0];
System.out.println(s);
byte[] decoded = Base64.getDecoder().decode(s);
String x = new String(decoded, "UTF8");
System.out.println(decoded);
System.out.println(x);
It is actually printing a strange string
"Tb�cC#"
I do not know what is the text behind the encoded string, but I can assume my program works, since I can convert without problems any other encoded string, for example
"=?UTF-8?B?SGlfR3V5cyE="
That is "Hi_Guys!".
Should I assume that string is malformed?

How to show heart sign in android using Html.fromHtml

In my app I am fetching some data from the server, the data might contain some unicode characters like heart, etc.
Now I can show a black heart symbol using unicode format, this way
String str = "\u2764";//unicode character for black heart
TextView txtv = (TextView)findViewById(R.id.txtv);
txtv.setText(txtv.getText()+str);
but I'm setting the text like this:
holder.txt_cardDesc.setText(Html.fromHtml(cardsDataClass.getCarddesc()));
cardsDataClass.getCarddesc() returns "âÂÂ¥All is changing soon, Christmas coming and we pray to God for all to..."
and I'm supposed to get 'âÂÂ¥' as the heart symbol from the service.
how to show this special character in unicode format, or in heart symbol as it is required?
which format is this text showing?? Is it HTML/XML format or Klingonese character, I don't have any idea about this.
How to show the heart sign using Html.fromHtml in android?
EDIT: From the service I may get different special characters like " ' " or "&" but what I'm getting is "’" instead of " ' ", "âÂÂ¥" instead of " ♥ "
Is there any way to check all the text and show the correct special character in android?
EDIT 2: Can anyone tell me how to show a heart symbol and apostrophe at their position from this string
String desc = "âÂÂ¥heart icon check, €™ apostrophe check";
i have already used all these procedures:
byte[] bytes = desc.getBytes("UTF-8");
String s2 = new String(bytes, "UTF-8"); // Charset with which bytes were encoded
txtv.setText(s2);
final String s2 = new String(desc.getBytes(), "UTF-8");
txtv.setText(s2);
String s2 = URLDecoder.decode(desc, "UTF-8");
txtv.setText(s2);
byte[] data = desc.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
byte[] data1 = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data1, "UTF-8");
txtv.setText(text);
but none of them are working, how to show UTF-8 text format in its actual format
Thanks
You maybe confused with Java Character & Android Character.
let your cardsDataClass.getCarddesc() returns:
"\u2764All is changing soon, Christmas coming and we pray to God for all to..."
and the heart should be shown just fine.

What's the difference between new String(byte[]) and DatatypeConverter.printBase64Binary(byte[])?

I need to pass base64 encoded data into xml as a string value. I noticed that code below prints different string representation. Which one is correct and why?
String example = "Hello universe!";
byte[] base64data = Base64.encodeBase64(example.getBytes());
System.out.println(new String(base64data));
System.out.println(DatatypeConverter.printBase64Binary(base64data));
System.out.println(new String(Base64.decodeBase64(base64data), "UTF-8"));
And what I get as a result:
SGVsbG8gdW5pdmVyc2Uh
U0dWc2JHOGdkVzVwZG1WeWMyVWg=
Hello universe!
U0dWc2JHOGdkVzVwZG1WeWMyVWg= decoded is SGVsbG8gdW5pdmVyc2Uh which is Hello universe! encoded. So you did the encoding twice.
There is no difference. You are using the API the wrong way. Don't encode the already encoded data again.

Truncate a String from a file name

I have previously written a code where I have added a time stamp to a file once it has been save in a directory.
Now I wanna to be able to truncate the time stamp from the file which comes after the extension .txt
note that my time stamp format is:_yyyy-mm-dd.
If you have the date after your extension in the form _yyyy-mm-dd just can use
String strippedFileName = fileName.substring(0, fileName.length() - 11);
or a bit nicer
String dateFormatString = "_yyyy-mm-dd";
String strippedFileName = fileName.substring(0, fileName.length() - dateFormatString.length());
You could also do this:
String trimmed = filename.replaceAll(".{11}$", "");

Categories