List of usage examples for android.util Base64 encodeToString
public static String encodeToString(byte[] input, int flags)
From source file:com.harshad.linconnectclient.NotificationUtilities.java
public static boolean sendData(Context c, Notification n, String packageName) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); ConnectivityManager connManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); // Check Wifi state, whether notifications are enabled globally, and // whether notifications are enabled for specific application if (prefs.getBoolean("pref_toggle", true) && prefs.getBoolean(packageName, true) && mWifi.isConnected()) { String ip = prefs.getString("pref_ip", "0.0.0.0:9090"); // Magically extract text from notification ArrayList<String> notificationData = NotificationUtilities.getNotificationText(n); // Use PackageManager to get application name and icon final PackageManager pm = c.getPackageManager(); ApplicationInfo ai;/* w ww. j a v a 2 s . c o m*/ try { ai = pm.getApplicationInfo(packageName, 0); } catch (final NameNotFoundException e) { ai = null; } String notificationBody = ""; String notificationHeader = ""; // Create header and body of notification if (notificationData.size() > 0) { notificationHeader = notificationData.get(0); if (notificationData.size() > 1) { notificationBody = notificationData.get(1); } } else { return false; } for (int i = 2; i < notificationData.size(); i++) { notificationBody += "\n" + notificationData.get(i); } // Append application name to body if (pm.getApplicationLabel(ai) != null) { if (notificationBody.isEmpty()) { notificationBody = "via " + pm.getApplicationLabel(ai); } else { notificationBody += " (via " + pm.getApplicationLabel(ai) + ")"; } } // Setup HTTP request MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // If the notification contains an icon, use it if (n.largeIcon != null) { entity.addPart("notificon", new InputStreamBody(ImageUtilities.bitmapToInputStream(n.largeIcon), "drawable.png")); } // Otherwise, use the application's icon else { entity.addPart("notificon", new InputStreamBody( ImageUtilities.bitmapToInputStream( ImageUtilities.drawableToBitmap(pm.getApplicationIcon(ai))), "drawable.png")); } HttpPost post = new HttpPost("http://" + ip + "/notif"); post.setEntity(entity); try { post.addHeader("notifheader", Base64.encodeToString(notificationHeader.getBytes("UTF-8"), Base64.URL_SAFE | Base64.NO_WRAP)); post.addHeader("notifdescription", Base64.encodeToString(notificationBody.getBytes("UTF-8"), Base64.URL_SAFE | Base64.NO_WRAP)); } catch (UnsupportedEncodingException e) { post.addHeader("notifheader", Base64.encodeToString(notificationHeader.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP)); post.addHeader("notifdescription", Base64.encodeToString(notificationBody.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP)); } // Send HTTP request HttpClient client = new DefaultHttpClient(); HttpResponse response; try { response = client.execute(post); String html = EntityUtils.toString(response.getEntity()); if (html.contains("true")) { return true; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return false; }
From source file:com.letsgood.synergykitsdkandroid.requestmethods.PostFile.java
@Override public BufferedReader execute() { String uri = null;/*from ww w . jav a2s . c o m*/ //init check if (!Synergykit.isInit()) { SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED); statusCode = Errors.SC_SK_NOT_INITIALIZED; return null; } //URI check uri = getUri().toString(); if (uri == null) { statusCode = Errors.SC_URI_NOT_VALID; return null; } //session token check if (sessionTokenRequired && sessionToken == null) { statusCode = Errors.SC_NO_SESSION_TOKEN; return null; } try { url = new URL(uri); // init url httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property accept httpURLConnection.addRequestProperty(PROPERTY_ACCEPT, ACCEPT_APPLICATION_VALUE); //set property accept httpURLConnection.addRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); httpURLConnection.addRequestProperty("Connection", "Keep-Alive"); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION, "Basic " + Base64.encodeToString( (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(), Base64.NO_WRAP)); //set authorization if (Synergykit.getSessionToken() != null) httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken()); httpURLConnection.connect(); //write data if (data != null) { dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream()); dataOutputStream.writeBytes(TWO_HYPHENS + BOUNDARY + CRLF); dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + ATTACHMENT_NAME + "\";filename=\"" + ATTACHMENT_FILE_NAME + "\"" + CRLF); dataOutputStream.writeBytes(CRLF); dataOutputStream.write(data); dataOutputStream.writeBytes(CRLF); dataOutputStream.writeBytes(TWO_HYPHENS + BOUNDARY + TWO_HYPHENS + CRLF); dataOutputStream.flush(); dataOutputStream.close(); } statusCode = httpURLConnection.getResponseCode(); //get status code SynergykitLog.print(Integer.toString(statusCode)); //read stream if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) { return readStream(httpURLConnection.getInputStream()); } else { return readStream(httpURLConnection.getErrorStream()); } } catch (Exception e) { statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE; e.printStackTrace(); return null; } }
From source file:com.letsgood.synergykitsdkandroid.requestmethods.Get.java
public InputStream halfExecute() { String uri = null;/*from ww w . j a va 2s. com*/ //init check if (!Synergykit.isInit()) { SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED); statusCode = Errors.SC_SK_NOT_INITIALIZED; return null; } //URI check uri = getUri().toString(); if (uri == null) { statusCode = Errors.SC_URI_NOT_VALID; return null; } //session token check if (sessionTokenRequired && sessionToken == null) { statusCode = Errors.SC_NO_SESSION_TOKEN; return null; } try { url = new URL(uri); // init url httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property httpURLConnection.addRequestProperty("Cache-Control", "max-stale=120"); httpURLConnection.addRequestProperty(PROPERTY_CONTENT_TYPE, ACCEPT_APPLICATION_VALUE); httpURLConnection.setDoInput(true); httpURLConnection.setUseCaches(true); httpURLConnection.setDefaultUseCaches(true); if (isAuthorizationEnabled()) { httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION, "Basic " + Base64.encodeToString( (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(), Base64.NO_WRAP)); //set authorization } if (Synergykit.getSessionToken() != null) httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken()); statusCode = httpURLConnection.getResponseCode(); //get status code //read stream if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) { return httpURLConnection.getInputStream(); } else { return httpURLConnection.getErrorStream(); } } catch (Exception e) { statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE; e.printStackTrace(); return null; } }
From source file:com.webXells.ImageResizer.ImageResizePlugin.java
@Override public boolean execute(String action, JSONArray data, CallbackContext callbackContext) { JSONObject params;/*from ww w . j av a 2 s .com*/ String imageData; String imageDataType; String format; Bitmap bmp; Log.d("PLUGIN", action); try { // parameters (forst object of the json array) params = data.getJSONObject(0); // image data, either base64 or url imageData = params.getString("data"); // which data type is that, defaults to base64 imageDataType = params.has("imageDataType") ? params.getString("imageDataType") : DEFAULT_IMAGE_DATA_TYPE; // which format should be used, defaults to jpg format = params.has("format") ? params.getString("format") : DEFAULT_FORMAT; // create the Bitmap object, needed for all functions bmp = getBitmap(imageData, imageDataType); } catch (JSONException e) { callbackContext.error(e.getMessage()); return false; } catch (IOException e) { callbackContext.error(e.getMessage()); return false; } // resize the image Log.d("PLUGIN", "passed init"); if (action.equals("resizeImage")) { try { double widthFactor; double heightFactor; // compression quality int quality = params.getInt("quality"); // Pixels or Factor resize String resizeType = params.getString("resizeType"); // Get width and height parameters double width = params.getDouble("width"); double height = params.getDouble("height"); if (resizeType.equals(RESIZE_TYPE_PIXEL)) { widthFactor = width / ((double) bmp.getWidth()); heightFactor = height / ((double) bmp.getHeight()); } else { widthFactor = width; heightFactor = height; } Bitmap resized = getResizedBitmap(bmp, (float) widthFactor, (float) heightFactor); ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (format.equals(FORMAT_PNG)) { resized.compress(Bitmap.CompressFormat.PNG, quality, baos); } else { resized.compress(Bitmap.CompressFormat.JPEG, quality, baos); } byte[] b = baos.toByteArray(); String returnString = Base64.encodeToString(b, Base64.DEFAULT); // return object JSONObject res = new JSONObject(); res.put("imageData", returnString); res.put("width", resized.getWidth()); res.put("height", resized.getHeight()); callbackContext.success(res); return true; } catch (JSONException e) { callbackContext.error(e.getMessage()); return false; } } else if (action.equals("imageSize")) { try { JSONObject res = new JSONObject(); res.put("width", bmp.getWidth()); res.put("height", bmp.getHeight()); Log.d("PLUGIN", "finished get image size"); callbackContext.success(res); return true; } catch (JSONException e) { callbackContext.error(e.getMessage()); return false; } } else if (action.equals("storeImage")) { try { // Obligatory Parameters, throw JSONException if not found String filename = params.getString("filename"); filename = (filename.contains(".")) ? filename : filename + "." + format; String directory = params.getString("directory"); directory = directory.startsWith("/") ? directory : "/" + directory; int quality = params.getInt("quality"); OutputStream outStream; // store the file locally using the external storage directory File file = new File(Environment.getExternalStorageDirectory().toString() + directory, filename); try { outStream = new FileOutputStream(file); if (format.equals(FORMAT_PNG)) { bmp.compress(Bitmap.CompressFormat.PNG, quality, outStream); } else { bmp.compress(Bitmap.CompressFormat.JPEG, quality, outStream); } outStream.flush(); outStream.close(); JSONObject res = new JSONObject(); res.put("url", "file://" + file.getAbsolutePath()); callbackContext.success(res); return true; } catch (IOException e) { callbackContext.error(e.getMessage()); return false; } } catch (JSONException e) { callbackContext.error(e.getMessage()); return false; } } Log.d("PLUGIN", "unknown action"); return false; }
From source file:com.hg.development.apps.messagenotifier_v1.Utils.Utility.java
/** * Permet de convertir une photo d'un contact un objet String. * @param bitmap photo du contact convertir. * @return/* w w w . ja v a 2 s .c o m*/ */ public static String BitMapToString(Bitmap bitmap) { try { ByteArrayOutputStream ByteStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, ByteStream); byte[] b = ByteStream.toByteArray(); String temp = Base64.encodeToString(b, Base64.DEFAULT); return temp; } catch (Exception ex) { return null; } }
From source file:com.honeywell.printer.net.autobaln_websocket.WebSocketWriter.java
/** * Create new key for WebSockets handshake. * * @return WebSockets handshake key (Base64 encoded). */// w ww. ja v a 2s . co m private String newHandshakeKey() { final byte[] ba = new byte[16]; mRandom.nextBytes(ba); return Base64.encodeToString(ba, Base64.NO_WRAP); }
From source file:com.pbi.dvb.websocket.WebSocketWriter.java
/** * Create new key for WebSockets handshake. * * @return WebSockets handshake key (Base64 encoded). *///w w w . ja va 2s .c om public String newHandshakeKey() { final byte[] ba = new byte[16]; mRng.nextBytes(ba); return Base64.encodeToString(ba, Base64.NO_WRAP); }
From source file:eu.codeplumbers.cosi.services.CosiContactService.java
@Override protected void onHandleIntent(Intent intent) { // Do the task here Log.i(CosiContactService.class.getName(), "Cosi Service running"); // Release the wake lock provided by the WakefulBroadcastReceiver. WakefulBroadcastReceiver.completeWakefulIntent(intent); allContacts = new ArrayList<>(); Device device = Device.registeredDevice(); // cozy register device url designUrl = device.getUrl() + "/ds-api/request/contact/all/"; syncUrl = device.getUrl() + "/ds-api/data/"; // concatenate username and password with colon for authentication final String credentials = device.getLogin() + ":" + device.getPassword(); authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); showNotification();/*from www .j av a 2s. co m*/ if (isNetworkAvailable()) { try { // read local sms log first readContactDatabase(); EventBus.getDefault().post(new CallSyncEvent(SYNC_MESSAGE, "Getting remote contacts from Cozy...")); getRemoteContacts(); mBuilder.setContentText(getString(R.string.lbl_contacts_sync_done)); mBuilder.setProgress(0, 0, false); mNotifyManager.notify(notification_id, mBuilder.build()); mNotifyManager.cancel(notification_id); sendChangesToCozy(); mNotifyManager.cancel(notification_id); EventBus.getDefault().post(new ContactSyncEvent(REFRESH, "Sync OK")); } catch (Exception e) { e.printStackTrace(); mSyncRunning = false; EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); } } else { mSyncRunning = false; EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, "No Internet connection")); mBuilder.setContentText("Sync failed because no Internet connection was available"); mNotifyManager.notify(notification_id, mBuilder.build()); } }
From source file:autobahn.WebSocketWriter.java
/** * Create new key for WebSockets handshake. * * @return WebSockets handshake key (Base64 encoded). *//*from w ww . j a v a 2s . c o m*/ private String newHandshakeKey() { final byte[] ba = new byte[16]; mRng.nextBytes(ba); return Base64.encodeToString(ba, Base64.NO_WRAP); }
From source file:com.nextgis.maplib.map.NGWVectorLayer.java
public String download() { if (!mNet.isNetworkAvailable()) { //return tile from cache return mContext.getString(R.string.error_network_unavailable); }//from ww w . j av a2 s . co m try { final HttpGet get = new HttpGet(mURL); //basic auth if (null != mLogin && mLogin.length() > 0 && null != mPassword && mPassword.length() > 0) { get.setHeader("Accept", "*/*"); final String basicAuth = "Basic " + Base64.encodeToString((mLogin + ":" + mPassword).getBytes(), Base64.NO_WRAP); get.setHeader("Authorization", basicAuth); } final DefaultHttpClient HTTPClient = mNet.getHttpClient(); final HttpResponse response = HTTPClient.execute(get); // Check to see if we got success final org.apache.http.StatusLine line = response.getStatusLine(); if (line.getStatusCode() != 200) { Log.d(TAG, "Problem downloading GeoJSON: " + mURL + " HTTP response: " + line); return mContext.getString(R.string.error_download_data); } final HttpEntity entity = response.getEntity(); if (entity == null) { Log.d(TAG, "No content downloading GeoJSON: " + mURL); return mContext.getString(R.string.error_download_data); } String data = EntityUtils.toString(entity); JSONObject geoJSONObject = new JSONObject(data); return createFromGeoJSON(geoJSONObject); } catch (IOException e) { Log.d(TAG, "Problem downloading GeoJSON: " + mURL + " Error: " + e.getLocalizedMessage()); return mContext.getString(R.string.error_download_data); } catch (JSONException e) { e.printStackTrace(); return mContext.getString(R.string.error_download_data); } }