How to resolve Russian language encoding in java? - java

Constructing a String with value as ФФХЧЯЯЯЯэшЩтЯ .The string value is in Russian Language.
String russian=new String("ФФХЧЯЯЯЯэшЩтЯ");
Printing the string as below.
ФФХЧЯЯЯЯ�?шЩтЯ
so the э in the character set is not able to convert.
Tried with all the possible encoding types like, UTF-8,ISO-8859-1,ISO-8859-2,ISO-8859-3 and many things i have tried
public void setter(String attachment) {
try {
filename=new String(filename.getBytes(),"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.filename= filename;
}

Related

Inject Hexadecimal Java

well, i am having problems with the code i made, i want to inject hexadecimal in a certain file, but when compiling comes an error message saying that some symbols are missing
String str = "rw";
String str2 = "test.so";
try {
raf = new RandomAccessFile(str2, str);
write(0x1234, "0100A0E3");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
public void write(int i, String str) {
try {
raf.seek((long) i);
raf.write(Hex2b(str));
} catch (IOException e) {
e.printStackTrace();
}
could anyone tell which symbols are missing? I'm new to programming
Hex2b isn't a thing. I don't know where you got that from. Info on how to convert a string such as "0100A0E3" into bytes so that you can pass it as argument to raf.write can be found at this SO answer.

arabic string in JSONObject is not readable [duplicate]

In Java, I want to convert this:
https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type
To this:
https://mywebsite/docs/english/site/mybook.do&request_type
This is what I have so far:
class StringUTF
{
public static void main(String[] args)
{
try{
String url =
"https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do" +
"%3Frequest_type%3D%26type%3Dprivate";
System.out.println(url+"Hello World!------->" +
new String(url.getBytes("UTF-8"),"ASCII"));
}
catch(Exception E){
}
}
}
But it doesn't work right. What are these %3A and %2F formats called and how do I convert them?
This does not have anything to do with character encodings such as UTF-8 or ASCII. The string you have there is URL encoded. This kind of encoding is something entirely different than character encoding.
Try something like this:
try {
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
// not going to happen - value came from JDK's own StandardCharsets
}
Java 10 added direct support for Charset to the API, meaning there's no need to catch UnsupportedEncodingException:
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8);
Note that a character encoding (such as UTF-8 or ASCII) is what determines the mapping of characters to raw bytes. For a good intro to character encodings, see this article.
The string you've got is in application/x-www-form-urlencoded encoding.
Use URLDecoder to convert it to Java String.
URLDecoder.decode( url, "UTF-8" );
This has been answered before (although this question was first!):
"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
As URL class documentation states:
The recommended way to manage the encoding and decoding of URLs is to
use URI, and to convert between these two classes using toURI() and
URI.toURL().
The URLEncoder and URLDecoder classes can also be used, but only for
HTML form encoding, which is not the same as the encoding scheme
defined in RFC2396.
Basically:
String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
System.out.println(new java.net.URI(url).getPath());
will give you:
https://mywebsite/docs/english/site/mybook.do?request_type
%3A and %2F are URL encoded characters. Use this java code to convert them back into : and /
String decoded = java.net.URLDecoder.decode(url, "UTF-8");
public String decodeString(String URL)
{
String urlString="";
try {
urlString = URLDecoder.decode(URL,"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
}
return urlString;
}
I use apache commons
String decodedUrl = new URLCodec().decode(url);
The default charset is UTF-8
try {
String result = URLDecoder.decode(urlString, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
public class URLDecoding {
String decoded = "";
public String decodeMethod(String url) throws UnsupportedEncodingException
{
decoded = java.net.URLDecoder.decode(url, "UTF-8");
return decoded;
//"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
}
public String getPathMethod(String url) throws URISyntaxException
{
decoded = new java.net.URI(url).getPath();
return decoded;
}
public static void main(String[] args) throws UnsupportedEncodingException, URISyntaxException
{
System.out.println(" Here is your Decoded url with decode method : "+ new URLDecoding().decodeMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type"));
System.out.println("Here is your Decoded url with getPath method : "+ new URLDecoding().getPathMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest"));
}
}
You can select your method wisely :)
If it is integer value, we have to catch NumberFormatException also.
try {
Integer result = Integer.valueOf(URLDecoder.decode(urlNumber, "UTF-8"));
} catch (NumberFormatException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Using java.net.URI class:
public String getDecodedURL(String encodedUrl) {
try {
URI uri = new URI(encodedUrl);
return uri.getScheme() + ":" + uri.getSchemeSpecificPart();
} catch (Exception e) {
return "";
}
}
Please note that exception handling can be better, but it's not much relevant for this example.
I was having this problem too and came here as an answer. But I used the code of the friend whose question was approved, it didn't work. I tried something different and it worked, so I'm sharing the following line of code in case it helps.
URLDecoder.decode(URLDecoder.decode(url, StandardCharsets.UTF_8)))

Java : 64 based string decode / parse failed

I am trying to convert this 64 based encoded JSON string and convert received JSON into POJO using flexjson API.
First try block, converts direct JSON as string into object which is success. This string is decoded using online tool.
Now second try block, try to convert 64 based string into an object in a similar way but converting the 64based string on the run which is throwing exception flexjson.JSONException: Expected a ',' or ']' at character 10
try {
AsyncResponseDO asyncResponseDO = new JSONDeserializer<AsyncResponseDO>().deserialize("{\"relatesTo\":\"7_Sept2017_IF01\"}", AsyncResponseDO.class);
System.out.println(asyncResponseDO.getRelatesTo());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
AsyncResponseDO asyncResponseDO = new JSONDeserializer<AsyncResponseDO>().deserialize(Base64.decodeBase64("eyJyZWxhdGVzVG8iOiI3X1NlcHQyMDE3X0lGMDEifQ==".getBytes()).toString(), AsyncResponseDO.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
POJO class :
public class AsyncResponseDO {
private String relatesTo;
public String getRelatesTo() {
return relatesTo;
}
public void setRelatesTo(String relatesTo) {
this.relatesTo = relatesTo;
}
}
new String(Base64.decodeBase64("eyJyZWxhdGVzVG8iOiI3X1NlcHQyMDE3‌X0lGMDEifQ==".getByt‌es()));
This will convert into a proper string.
I referred to https://www.mkyong.com/java/how-do-convert-byte-array-to-string-in-java/

JMeter does not execute Java code correctly if it's ran as .jar file from command line

I'm designing JMeter scenario which implies executing a certain .jar file via OS Process Sampler element. My Java code has while loop which basically checks a certain mailbox for a letter with a certain subject. Loop waits until finds one (emails are always delivered with roughly 3 minutes delay), parses it and writes some data to .txt file.
If I run this .jar directly from cmd then the code works as expected. But if I run it via JMeter OS Process Sampler then it never creates a file for me. I do see that email is delivered to inbox, so expect it to be parsed and .txt created.
At first I suspected that JMeter finishes Java scenario without waiting for while loop to execute. Then I put OS Process Sampler in a separate Thread and added a huge delay for this thread in order to wait and make 100% sure that email is delivered and Java only need to parse it but it does not help.
View Results Tree never shows any errors.
Here is my OS Process Sampler: https://www.screencast.com/t/LomYGShJHAkS
This is what I execute via cmd and it works as expected: java -jar mailosaurJavaRun.jar email533.druzey1a#mailosaur.in
And here is my code (it does not looks good but it works):
public class Run {
public static void main(String[] args) {
MailosaurHelper ms = new MailosaurHelper();
String arg1 = ms.getFirstLinkInEmail(args[0]);
BufferedWriter output = null;
try {
File file = new File("url.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(arg1);
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( output != null ) {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class MailosaurHelper {
protected final String API_KEY = "b3e4d2b193b5eb2";
protected final String MAILBOX_ID = "d1uzey1a";
public MailboxApi getEmailBox() {
return new MailboxApi(MAILBOX_ID, API_KEY);
}
public String getFirstLinkInEmail(String email) {
MailosaurHelper ms = new MailosaurHelper();
String link = "";
if (link.equals("") || link.isEmpty()) {
try {
Thread.sleep(3000);
link = ms.getAllEmailsByReceipent(email)[0].html.links[0]
.toString();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return link;
}
public Email[] getAllEmailsByReceipent(String recepient) {
try {
int ifArrayIsEmpty = getEmailBox().getEmailsByRecipient(recepient).length;
while (ifArrayIsEmpty == 0) {
try {
Thread.sleep(3000);
ifArrayIsEmpty = getEmailBox().getEmailsByRecipient(
recepient).length;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (MailosaurException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Email[] listOfEmails = null;
try {
listOfEmails = getEmailBox().getEmailsByRecipient(recepient);
} catch (MailosaurException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listOfEmails;
}
The bottom line is that I need to parse Mailosaur email, retrieve URL from it and use it further. Any other suggestion on how to do that using Jmeter/Java/Mailosaur are appreciated.
You don't need cmd in here, but if you're adamant to stick with it - use /C key when you call it.
Then, are your sure you're looking for your file in the right place?
According to documentation:
By default the classes in the java.io package always resolve relative
pathnames against the current user directory. This directory is named
by the system property user.dir, and is typically the directory in
which the Java virtual machine was invoked.
Check it thoroughly, BTW - you should see it in your sampler result.

Converting ASCII characters to UTF-8 within a Java String [duplicate]

In Java, I want to convert this:
https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type
To this:
https://mywebsite/docs/english/site/mybook.do&request_type
This is what I have so far:
class StringUTF
{
public static void main(String[] args)
{
try{
String url =
"https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do" +
"%3Frequest_type%3D%26type%3Dprivate";
System.out.println(url+"Hello World!------->" +
new String(url.getBytes("UTF-8"),"ASCII"));
}
catch(Exception E){
}
}
}
But it doesn't work right. What are these %3A and %2F formats called and how do I convert them?
This does not have anything to do with character encodings such as UTF-8 or ASCII. The string you have there is URL encoded. This kind of encoding is something entirely different than character encoding.
Try something like this:
try {
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
// not going to happen - value came from JDK's own StandardCharsets
}
Java 10 added direct support for Charset to the API, meaning there's no need to catch UnsupportedEncodingException:
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8);
Note that a character encoding (such as UTF-8 or ASCII) is what determines the mapping of characters to raw bytes. For a good intro to character encodings, see this article.
The string you've got is in application/x-www-form-urlencoded encoding.
Use URLDecoder to convert it to Java String.
URLDecoder.decode( url, "UTF-8" );
This has been answered before (although this question was first!):
"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
As URL class documentation states:
The recommended way to manage the encoding and decoding of URLs is to
use URI, and to convert between these two classes using toURI() and
URI.toURL().
The URLEncoder and URLDecoder classes can also be used, but only for
HTML form encoding, which is not the same as the encoding scheme
defined in RFC2396.
Basically:
String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
System.out.println(new java.net.URI(url).getPath());
will give you:
https://mywebsite/docs/english/site/mybook.do?request_type
%3A and %2F are URL encoded characters. Use this java code to convert them back into : and /
String decoded = java.net.URLDecoder.decode(url, "UTF-8");
public String decodeString(String URL)
{
String urlString="";
try {
urlString = URLDecoder.decode(URL,"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
}
return urlString;
}
I use apache commons
String decodedUrl = new URLCodec().decode(url);
The default charset is UTF-8
try {
String result = URLDecoder.decode(urlString, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
public class URLDecoding {
String decoded = "";
public String decodeMethod(String url) throws UnsupportedEncodingException
{
decoded = java.net.URLDecoder.decode(url, "UTF-8");
return decoded;
//"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
}
public String getPathMethod(String url) throws URISyntaxException
{
decoded = new java.net.URI(url).getPath();
return decoded;
}
public static void main(String[] args) throws UnsupportedEncodingException, URISyntaxException
{
System.out.println(" Here is your Decoded url with decode method : "+ new URLDecoding().decodeMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type"));
System.out.println("Here is your Decoded url with getPath method : "+ new URLDecoding().getPathMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest"));
}
}
You can select your method wisely :)
If it is integer value, we have to catch NumberFormatException also.
try {
Integer result = Integer.valueOf(URLDecoder.decode(urlNumber, "UTF-8"));
} catch (NumberFormatException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Using java.net.URI class:
public String getDecodedURL(String encodedUrl) {
try {
URI uri = new URI(encodedUrl);
return uri.getScheme() + ":" + uri.getSchemeSpecificPart();
} catch (Exception e) {
return "";
}
}
Please note that exception handling can be better, but it's not much relevant for this example.
I was having this problem too and came here as an answer. But I used the code of the friend whose question was approved, it didn't work. I tried something different and it worked, so I'm sharing the following line of code in case it helps.
URLDecoder.decode(URLDecoder.decode(url, StandardCharsets.UTF_8)))

Categories