I'm given a base64 string (I've no control over what string I'm given):
PD94bWwgdmVyc2lvbj0iMS4wIj8+CjxzYW1scDpSZXNwb25zZSB4bWxuczpzYW1scD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOnByb3RvY29sIg==
When I decode it, in Java, it yields:
<?xml version="1.0"?>
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
When I base64 encode that (again, in Java) it yields:
PD94bWwgdmVyc2lvbj0iMS4wIj8+DQo8c2FtbHA6UmVzcG9uc2UgeG1sbnM6c2FtbHA9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpwcm90b2NvbCI=
These strings are different, but they should be the same.
During my search I stumbled upon this site here: https://www.base64encode.org
While on this site, if I click the encode button I get the same results as my java base64 encode.
However, if instead of hitting the encode button, I click on the "Live Mode On" button, I get the original base64-encoded string I received--which is exactly what I want!
Any idea how I can achieve these same results in my own code?
public String getEncodedSAMLMessage(String message) {
byte[] byteMessage;
try {
byteMessage = message.getBytes("UTF-8");
String base64Encoded = helpers.base64Encode(byteMessage);
return URLEncoder.encode(base64Encoded, "UTF-8");
} catch (UnsupportedEncodingException e1) {
}
return null;
}
public String getDecodedSAMLMessage(String message) {
String urlDecoded = helpers.urlDecode(message);
byte[] base64Decoded = helpers.base64Decode(urlDecoded);
try {
return new String(base64Decoded, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
return null;
}
Try using Apache Commons Codec.
import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.binary.Base64;
public class Base64Encoder {
private Base64 b64 = new Base64();
public String encode(String message) {
return b64.encodeAsString(message.getBytes());
}
public String decode(String message) {
return new String(b64.decode(message), Charsets.UTF_8);
}
}
Related
I got a .eml file, and some attachments inside
one of attachments - is .rar file
I using Tika to extract this rar, but sometimes Tika cant correctly convert some names of files, for example - such a name
=?koi8-r?Q?6=5F=F4=ED=5F15=2E05=2Erar?=
So i was looking for an answer, how to convert such a string to correctly readed value
Is there any libraries in java, to do this?
I guess it happends cause string got =?koi8-r?Q? in the start, so maybe, if i convert string to something like this, i will get move convertable value, like this 6=5F=F4=ED=5F15=2E05=2E, but if i will do so, i finnaly couldnt find a solution to convert
Does anybody know how to convert such a string correctly?
I spend a lot of time to make it, but still - no results...
Here is a code
public class EncodingUtils {
private EncodingUtils() {
}
public static String decodeKoi8r(String text) {
String decode;
try {
decode = MimeUtility.decodeText(text);
} catch (UnsupportedEncodingException e) {
decode = text;
}
if (isQuotedKoi8r(decode)) {
decode = decode(text, "KOI8-R", "quoted-printable", "KOI8-R");
}
return decode;
}
public static boolean isQuotedKoi8r(String text) {
return text.contains("=") || text.toLowerCase().contains("koi8-r");
}
public static String decode(String text, String textEncoding, String encoding, String resultCharset) {
if (text.length() == 0) {
return text;
}
try {
byte[] bytes = text.getBytes(textEncoding);
InputStream decodedStream = MimeUtility.decode(new ByteArrayInputStream(bytes), encoding);
byte[] tmp = new byte[bytes.length];
int n = decodedStream.read(tmp);
byte[] res = new byte[n];
System.arraycopy(tmp, 0, res, 0, n);
return new String(res, resultCharset);
} catch (IOException | MessagingException e) {
return text;
}
}
}
And test:
public class EncodingUtilsTest {
#Test
public void koi8r() {
String input = "=?koi8-r?Q?11=5F=F4=ED=5F21=2E05=2Erar?=";
String decode = EncodingUtils.decodeKoi8r(input);
Assertions.assertEquals("11_ТМ_21.05.rar", decode);
}
#Test
public void koi8rWithoutStartTag() {
String input = "=CF=D4=C4=C5=CC=D8=CE=D9=CD =D4=D2=C1=CE=DB=C5=CD =D2=C5=DA=C0=CD=.eml";
String decode = EncodingUtils.decodeKoi8r(input);
Assertions.assertEquals("отдельным траншем резюм=.eml", decode);
}
}
Good day!
I keep getting the following error from the code below
error:
AccountController.java:55: error: cannot find symbol
return encoded;
^
symbol: variable encoded
location: class AccountController
1 error
code:
public static String hash(String password) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] byteOfTextToHash = password.getBytes(StandardCharsets.UTF_8);
byte[] hashedByetArray = digest.digest(byteOfTextToHash);
String encoded;
encoded = Base64.getEncoder().encodeToString(hashedByetArray);
} catch(NoSuchAlgorithmException e) {
e.printStackTrace();
};
return encoded;
}
Thanks for the help!
Your encoded variable is out of scope. Move it outside the try will fix this like:
public static String hash(String password) {
String encoded = null;
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] byteOfTextToHash = password.getBytes(StandardCharsets.UTF_8);
byte[] hashedByetArray = digest.digest(byteOfTextToHash);
encoded = Base64.getEncoder().encodeToString(hashedByetArray);
} catch(NoSuchAlgorithmException e) {
e.printStackTrace();
};
return encoded;
}
Declare the varibale encoded outside try and initialize it with null or empty string as below
String encoded = "";
try {
....
}catch(Exception exc):\{
....
}
return encoded
;
My web service publish push notification to APNs and APNs send to destination IOS device.
When apns contain Unicode emoji on alert body push notification and Iphone os can't decode my Unicode emoji '\uD83D\uDE0A' app already kill.
Push notification show same '\uD83D\uDE0A', No emoji shown on banner notification bar on top.
Android application works fine by GCM dispatches push notification But IOS not support.
Iphone-Ios supports only this format '\ue415'
Here code that from ActiveMQ subscribe chat payload get into web-service
public void onPublish(UTF8Buffer topic, Buffer msg, Runnable ack) {
try {
String body = msg.utf8().toString();
if (logger.isInfoEnabled()) {
logger.info("MQTT connection.listener.onPublish(), msg Received ["
+ body + "]");
}
if (body.contains("\"cmd\":\"chat\"")
&& body.contains("\"is_sender_msg\":true")) {
QueueMgr.addToChatQueue(body); //Changed true to false
}
else if(body.contains("\"cmd\":\"msg_seen\"")){
QueueMgr.addToChatReadSeenQueue(body);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ack.run();
}
}
My code for create push notification on java
public static JSONObject constructePushJson(JSONObject jsonObject,String[] cloudkeyWithDevice) throws JSONException {
if(cloudkeyWithDevice[0] != null){
JSONObject pnAPIdata = new JSONObject();
if(cloudkeyWithDevice[1].equals("a") || cloudkeyWithDevice[1].equals("d")){
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_CMD, com.anyorg.constants.AppConstants.CMD_ANDROID_PUSH);
}
else{
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_CMD, com.anyorg.constants.AppConstants.CMD_IOS_PUSH);
}
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_APP_TOKEN, com.anyorg.constants.AppConstants.DEFAULT_APP_TOKEN);
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_DEVICE_TOKEN, cloudkeyWithDevice[0]);
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_USER_ID, jsonObject.getInt(com.anyorg.constants.AppConstants.FLD_TO_USER_ID));
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_DEVICE_ID, 0);
String alertMsg=StringEscapeUtils.unescapeJava(jsonObject.getString(com.anyorg.constants.AppConstants.FLD_BODY));
jsonObject.put(com.anyorg.constants.AppConstants.FLD_BODY,alertMsg);
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_ALERT_MSG, "AryaConnect: "+alertMsg);//(jsonObject.isNull("body")) ? jsonObject.getString("from_user_name")+": Sent a file" : jsonObject.getString("from_user_name")+": "+jsonObject.getString("body")
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_MSG, jsonObject);//jsonObject.getString(com.anyorg.constants.AppConstants.FLD_BODY)
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_CALLBACK_URL, callbackUrl);
pnAPIdata.put(com.anyorg.constants.AppConstants.MAC_ADDRESS_ID, jsonObject.getString("mobile_rec_id"));
return pnAPIdata;
}
else{
return null;
}
}
Publish to APNs code
public class ANSNotificationDispatcher implements NotificationDispatcher {
protected static final Logger logger = Logger
.getLogger(ANSNotificationDispatcher.class);
public static final String OS_NAME = AppConstants.OS_TYPE_IPHONE;
String keystore;
String password;
boolean production;
public ANSNotificationDispatcher() {
try {
keystore = AppConfig.getAPNKeystore();
password = AppConfig.getAPNKeystorePassword();
PushyAPNMgr.init(keystore, password, AppConfig.isAPNProdcution());
} catch (Throwable e) {
e.printStackTrace();
}
}
private void push(Payload payload, String token, String userId,
String deviceId) throws ConfigurationException,
DeviceUnregisteredException {
// QueueManager.addToIOsQueue(payLoad, token, userId, ivUserDeviceId);
long stime = System.currentTimeMillis();
try {
PushyAPNMgr.push(token, payload.toString());
if (logger.isInfoEnabled())
logger.info("push(): APN PN userId [" + userId
+ "], device id [" + deviceId + "] payoad [" + payload
+ "] Response time ["
+ (System.currentTimeMillis() - stime) + "]ms");
} catch (Exception e) {
e.printStackTrace();
throw new ConfigurationException();
}
}
public static Payload createComplexPayload(JSONObject jsonObject) {
PushNotificationPayload complexPayload = null;
try {
complexPayload = createPayload(jsonObject);
String msg = Common.getStringAsNull(jsonObject,
AppConstants.FLD_MSG);
if (!Common.isEmpty(msg)) {
complexPayload.addCustomDictionary(AppConstants.FLD_MSG, msg);
}
if (logger.isInfoEnabled()) {
logger.info("createComplexPayloadV2(): payload ["
+ complexPayload.getPayload().toString() + "]");
}
} catch (JSONException e) {
e.printStackTrace();
}
return complexPayload;
}
public void dispatch(JSONObject jsonObject, String jsonData)
throws NotificationException, DeviceUnregisteredException,
MultipleRegistartionIdException, ConfigurationException {
String deviceToken = Common.getStringAsNull(jsonObject,
AppConstants.FLD_DEVICE_TOKEN);
if (Common.isEmpty(deviceToken)) {
logger.error("dispatch(): device token is null, cmd [" + jsonData
+ "]");
return;
}
Payload payload = createComplexPayload(jsonObject);
String userId = Common.getStringAsNull(jsonObject,
AppConstants.FLD_USER_ID);
String deviceId = Common.getStringAsNull(jsonObject,
AppConstants.FLD_DEVICE_ID);
push(payload, deviceToken, userId, deviceId);
}
public static void handleInvalidTokeException(String token) {
}
public static void handleDeviceUnregisteredException(String token) {
}
}
Ios push notification managed by Ios OS
My Apache Catalina log
I am a web service cloud developer faceing this issue last one days for only Ios app. So please, if some body have knowledge or done before. please advise and refer me some idea.
Emoji in my push notifications link.
https://mixpanel.com/help/questions/articles/how-do-i-send-custom-parameters-like-emoji-in-my-push-notifications
Thanks
Finally, APNs issue resolve in (Ios app) on java web service code by this Unicode encode and decode process. (unescapeJava and escapeJava) from lib commons-lang-2.6.jar and class org.apache.commons.lang.StringEscapeUtils
emojiBytes = alertMsg.getBytes("UTF-8"); text = new String(emojiBytes, "UTF-8");
private static PushNotificationPayload createPayload(JSONObject jsonObject)
throws JSONException {
String alertMsg = Common.getStringUnicodeAsNull1(jsonObject,
AppConstants.FLD_ALERT_MSG);
byte[] emojiBytes=null;
String text=null;
try {
emojiBytes = alertMsg.getBytes("UTF-8");
text = new String(emojiBytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//String emojiAsString = new String(emojiBytes, Charset.forName("UTF-8"));
//System.out.println("#####alertMsg: "+text);
Integer badgeCnt;
if (jsonObject.has(AppConstants.FLD_BADGE_CNT)){
badgeCnt = Common.getIntegerAsNull(jsonObject,
AppConstants.FLD_BADGE_CNT);
}else{
badgeCnt = AppConstants.VAL_ZERO;
}
PushNotificationPayload payload = createPayload(badgeCnt, text);
return payload;
}
String alertMsg = Common.getStringUnicodeAsNull1(jsonObject,
AppConstants.FLD_ALERT_MSG);
public static String getStringUnicodeAsNull1(JSONObject jsonObject,
String key) {
try {
if(jsonObject.isNull(key))
return null;
else
return StringEscapeUtils.unescapeJava(jsonObject.getString(key));
} catch (JSONException je) {
return null;
}
}
Respected sir and ma'am, If there is any other solution of java APNs emoji Unicode on IOS Push Notification.
Then please give me some hints.Thanks
you shouldn't need to mess about with html decoding. As you say the code point for smiling face is \u263A. In PHP you can represent that in a UTF8-encoded string as "\xE2\x98\xBA"
Lightning bolt (actually 'high voltage sign') is \u26A1 or "\xE2\x9A\xA1" in UTF-8.
Both these characters are present in some non-emoji fonts as regular Unicode symbols. You can see with:
<?php
header('Content-type: text/html; charset=utf-8');
echo "\xE2\x9A\xA1";
echo "\xE2\x98\xBA";
or other things...
for the googlers. json_encode() adds double \
$message = "\ue04a";
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'type' => $type,
'param' => $param
);
$payload = json_encode($body);
$payload = str_replace("\", "\\", $payload);
Please check with this two way... i think this is helpfull for you.
I have a function that returns map value (String) as a generic Object. How do I convert it back to string. I tried toString() but all i get is end[Ljava.lang.String;#ff2413
public Object getParameterValue(String key)
{
Iterator iterator=params.entrySet().iterator();
while(iterator.hasNext())
{
Map.Entry me=(Map.Entry)iterator.next();
String[] arr=(String[])me.getValue();
log.info(me.getKey().toString()+"="+arr[0]);
}
if(params.containsKey(key))
{
log.info(key+"="+params.get(key));
return params.get(key);
}
return null;
}
Receiving end
String temp=data.getParameterValue("request").toString();
log.info("end"+temp);
log.info(me.getKey().toString()+"="+arr[0]); give me an output
email=x#as.com
request=login
projectid=as
I'm afraid your map contains something other than String objects. If you call toString() on a String object, you obtain the string itself.
What you get [Ljava.lang.String indicates you might have a String array.
Might not be so related to the issue above. However if you are looking for a way to serialize Java object as string, this could come in hand
package pt.iol.security;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64;
public class ObjectUtil {
static final Base64 base64 = new Base64();
public static String serializeObjectToString(Object object) throws IOException {
try (
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(arrayOutputStream);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(gzipOutputStream);) {
objectOutputStream.writeObject(object);
objectOutputStream.flush();
return new String(base64.encode(arrayOutputStream.toByteArray()));
}
}
public static Object deserializeObjectFromString(String objectString) throws IOException, ClassNotFoundException {
try (
ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(base64.decode(objectString));
GZIPInputStream gzipInputStream = new GZIPInputStream(arrayInputStream);
ObjectInputStream objectInputStream = new ObjectInputStream(gzipInputStream)) {
return objectInputStream.readObject();
}
}
}
maybe you benefit from converting it to JSON string
String jsonString = new com.google.gson.Gson().toJson(myObject);
in my case, I wanted to add an object to the response headers but you cant add objects to the headers,
so to solve this I convert my object to JSON string and in the client side I will return that string to JSON again
Looking at the output, it seems that your "temp" is a String array. You need to loop across the array to display each value.
The result is not a String but a String[]. That's why you get this unsuspected printout.
[Ljava.lang.String is a signature of an array of String:
System.out.println(new String[]{});
The question how do I convert an object to a String, despite the several answers you see here, and despite the existence of the Object.toString method, is unanswerable, or has infinitely many answers. Because what is being asked for is some kind of text representation or description of the object, and there are infinitely many possible representations. Each representation encodes a particular object instance using a special purpose language (probably a very limited language) or format that is expressive enough to encode all possible object instances.
Before code can be written to convert an object to a String, you must decide on the language/format to be used.
To convert serialize object to String and String to Object
stringToBean(beanToString(new LoginMdp()), LoginMdp.class);
public static String beanToString(Object object) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
StringWriter stringEmp = new StringWriter();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
objectMapper.writeValue(stringEmp, object);
return stringEmp.toString();
}
public static <T> T stringToBean(String content, Class<T> valueType) throws IOException {
return new ObjectMapper().readValue(content, valueType);
}
Solution 1: cast
String temp=(String)data.getParameterValue("request");
Solution 2: use typed map:
Map<String, String> param;
So you change Change the return type of your function
public String getParameterValue(String key)
{
if(params.containsKey(key))
{
return params.get(key);
}
return null;
}
and then no need for cast or toString
String temp=data.getParameterValue("request");
toString() is a debug info string. The default implementation returns the class name and the system identity hash. Collections return all elements but arrays not.
Also be aware of NullPointerException creating the log!
In this case a Arrays.toString() may help:
Object temp = data.getParameterValue("request");
String log = temp == null ? "null" : (temp.getClass().isArray() ? Arrays.toString((Object[])temp) : temp.toString());
log.info("end " + temp);
You can also use Arrays.asList():
Object temp = data.getParameterValue("request");
Object log = temp == null ? null : (temp.getClass().isArray() ? Arrays.asList((Object[])temp) : temp);
log.info("end " + temp);
This may result in a ClassCastException for primitive arrays (int[], ...).
/** * This toString-Method works for every Class, where you want to display all the fields and its values */ public String toString() {
StringBuffer sb = new StringBuffer();
Field[] fields = getClass().getDeclaredFields(); //Get all fields incl. private ones
for (Field field : fields){
try {
field.setAccessible(true);
String key=field.getName();
String value;
try{
value = (String) field.get(this);
} catch (ClassCastException e){
value="";
}
sb.append(key).append(": ").append(value).append("\n");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return sb.toString(); }
You can create toString() method to convert object to string.
int bid;
String bname;
double bprice;
Book(String str)
{
String[] s1 = str.split("-");
bid = Integer.parseInt(s1[0]);
bname = s1[1];
bprice = Double.parseDouble(s1[2]);
}
public String toString()
{
return bid+"-"+bname+"-"+bprice;
}
public static void main(String[] s)
{
Book b1 = new Book("12-JAVA-200.50");
System.out.println(b1);
}
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Generate MD5 hash in Java
Can some one tell me how to convert a string into MD5 format in Java?
I have code like this, but I want in MD5 format with 32 characters.
UUID uuid = UUID.randomUUID();
String token = uuid.toString().substring(0,12);
Implemenation
import java.security.MessageDigest;
import java.math.BigInteger;
import java.lang.String
public class SecurityUtil {
public static String stringToMD5(String string) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(string.getBytes(Charset.forName("UTF-8")),0,string.length());
return new BigInteger(1,messageDigest.digest()).toString(16);
}
}
Usage:
System.out.println(String.format("MD5: %s", stringToMD5("P#$$\\/\\/R|)")));
Output:
MD5: 91162629d258a876ee994e9233b2ad87*
In this sample was used the coding UTF-8.
What is Charset ?
What is MessageDigest ?
What is UTF-8 >
*md5 is example from Wikipedia.
I got bored again...
/**
* #author BjornS
* #created 2. sep. 2010
*/
public enum HashUtil {
SHA1("SHA1"), MD5("MD5"), MD2("MD2"), SHA256("SHA-256"), SHA384("SHA-384"), SHA512("SHA-512");
private final MessageDigest digester;
HashUtil(String algorithm) {
try {
digester = MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public String hash(byte[] in) {
return toHexString(digester.digest(in));
}
public String hash(String in) {
return hash(in.getBytes());
}
public String hash(String in, Charset characterSet) {
return hash(in.getBytes(characterSet));
}
public byte[] hashToByteArray(String in) {
return digester.digest(in.getBytes());
}
public byte[] hashToByteArray(String in, Charset characterSet) {
return digester.digest(in.getBytes(characterSet));
}
public byte[] hashToByteArray(byte[] in) {
return digester.digest(in);
}
private String toHexString(byte[] digest) {
StringBuffer hexStr = new StringBuffer(40);
for (byte b : digest) {
hexStr.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
}
return hexStr.toString();
}
}
-
/*** ***/
// Use Charsets from Google Guava rather than manually code the charset request, you also don't have to catch exceptions this way! :)
pulic static void main(String... args) {
UUID uuid = UUID.randomUUID();
String uuidString = uuid.toString().substring(0,12);
String token = HashUtil.MD5.hash(uuidString,Charsets.UTF_8);
}
This worked for me..
UUID uuid = UUID.randomUUID();
String token = MD5.digest(uuid.toString().substring(0,12));
thanks for all the answers guys.