List of usage examples for javax.net.ssl HttpsURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java
/** * Write REST request to {@link HttpsURLConnection}. * /*from w w w . jav a 2s .c o m*/ * @param endPoint String End point URL. * @param httpsMethod String HTTP method type (POST, PUT) * @param headersMap Map<String, String> Headers need to send to the end point. * @param fileName String File name of the attachment to set as binary content. * @return {@link HttpsURLConnection} object. * @throws IOException */ private HttpsURLConnection writeRequestHTTPS(String endPoint, String httpMethod, byte responseType, Map<String, String> headersMap, String fileName, boolean isBinaryContent) throws IOException { OutputStream output = null; URL url = new URL(endPoint); HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(); // Disable automatic redirects httpsConnection.setInstanceFollowRedirects(false); httpsConnection.setRequestMethod(httpMethod); //Create byte array to send binary attachment FileInputStream fileInputStream = null; File file = new File(pathToResourcesDirectory, fileName); byte[] byteArray = new byte[(int) file.length()]; fileInputStream = new FileInputStream(file); fileInputStream.read(byteArray); fileInputStream.close(); for (String key : headersMap.keySet()) { httpsConnection.setRequestProperty(key, headersMap.get(key)); } if (httpMethod.equalsIgnoreCase("POST") || httpMethod.equalsIgnoreCase("PUT")) { httpsConnection.setDoOutput(true); try { output = httpsConnection.getOutputStream(); output.write(byteArray); } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { log.error("Error while closing the connection"); } } } } return httpsConnection; }
From source file:eu.faircode.netguard.AdapterRule.java
@Override public void onBindViewHolder(final ViewHolder holder, final int position) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // Get rule//from w w w.java2s . c om final Rule rule = listFiltered.get(position); // Handle expanding/collapsing holder.llApplication.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { rule.expanded = !rule.expanded; notifyItemChanged(position); } }); // Show if non default rules holder.itemView.setBackgroundColor(rule.changed ? colorChanged : Color.TRANSPARENT); // Show expand/collapse indicator holder.ivExpander.setImageLevel(rule.expanded ? 1 : 0); // Show application icon if (rule.info.applicationInfo == null || rule.info.applicationInfo.icon == 0) Picasso.with(context).load(android.R.drawable.sym_def_app_icon).into(holder.ivIcon); else { Uri uri = Uri .parse("android.resource://" + rule.info.packageName + "/" + rule.info.applicationInfo.icon); Picasso.with(context).load(uri).resize(iconSize, iconSize).into(holder.ivIcon); } // Show application label holder.tvName.setText(rule.name); // Show application state int color = rule.system ? colorOff : colorText; if (!rule.internet || !rule.enabled) color = Color.argb(128, Color.red(color), Color.green(color), Color.blue(color)); holder.tvName.setTextColor(color); // Show rule count new AsyncTask<Object, Object, Long>() { @Override protected void onPreExecute() { holder.tvHosts.setVisibility(View.GONE); } @Override protected Long doInBackground(Object... objects) { return DatabaseHelper.getInstance(context).getRuleCount(rule.info.applicationInfo.uid); } @Override protected void onPostExecute(Long rules) { if (rules > 0) { holder.tvHosts.setVisibility(View.VISIBLE); holder.tvHosts.setText(Long.toString(rules)); } } }.execute(); // Wi-Fi settings holder.cbWifi.setEnabled(rule.apply); holder.cbWifi.setAlpha(wifiActive ? 1 : 0.5f); holder.cbWifi.setOnCheckedChangeListener(null); holder.cbWifi.setChecked(rule.wifi_blocked); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbWifi)); DrawableCompat.setTint(wrap, rule.apply ? (rule.wifi_blocked ? colorOff : colorOn) : colorGrayed); } holder.cbWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { rule.wifi_blocked = isChecked; updateRule(rule, true, listAll); } }); holder.ivScreenWifi.setEnabled(rule.apply); holder.ivScreenWifi.setAlpha(wifiActive ? 1 : 0.5f); holder.ivScreenWifi.setVisibility(rule.screen_wifi && rule.wifi_blocked ? View.VISIBLE : View.INVISIBLE); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrap = DrawableCompat.wrap(holder.ivScreenWifi.getDrawable()); DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed); } // Mobile settings holder.cbOther.setEnabled(rule.apply); holder.cbOther.setAlpha(otherActive ? 1 : 0.5f); holder.cbOther.setOnCheckedChangeListener(null); holder.cbOther.setChecked(rule.other_blocked); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbOther)); DrawableCompat.setTint(wrap, rule.apply ? (rule.other_blocked ? colorOff : colorOn) : colorGrayed); } holder.cbOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { rule.other_blocked = isChecked; updateRule(rule, true, listAll); } }); holder.ivScreenOther.setEnabled(rule.apply); holder.ivScreenOther.setAlpha(otherActive ? 1 : 0.5f); holder.ivScreenOther.setVisibility(rule.screen_other && rule.other_blocked ? View.VISIBLE : View.INVISIBLE); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrap = DrawableCompat.wrap(holder.ivScreenOther.getDrawable()); DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed); } holder.tvRoaming.setTextColor(rule.apply ? colorOff : colorGrayed); holder.tvRoaming.setAlpha(otherActive ? 1 : 0.5f); holder.tvRoaming.setVisibility( rule.roaming && (!rule.other_blocked || rule.screen_other) ? View.VISIBLE : View.INVISIBLE); // Expanded configuration section holder.llConfiguration.setVisibility(rule.expanded ? View.VISIBLE : View.GONE); // Show application details holder.tvUid .setText(rule.info.applicationInfo == null ? "?" : Integer.toString(rule.info.applicationInfo.uid)); holder.tvPackage.setText(rule.info.packageName); holder.tvVersion.setText(rule.info.versionName + '/' + rule.info.versionCode); holder.tvDescription.setVisibility(rule.description == null ? View.GONE : View.VISIBLE); holder.tvDescription.setText(rule.description); // Show application state holder.tvInternet.setVisibility(rule.internet ? View.GONE : View.VISIBLE); holder.tvDisabled.setVisibility(rule.enabled ? View.GONE : View.VISIBLE); // Show traffic statistics holder.tvStatistics.setText(context.getString(R.string.msg_mbday, rule.upspeed, rule.downspeed)); // Apply holder.cbApply.setEnabled(rule.pkg); holder.cbApply.setOnCheckedChangeListener(null); holder.cbApply.setChecked(rule.apply); holder.cbApply.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { rule.apply = isChecked; updateRule(rule, true, listAll); } }); // Show related holder.btnRelated.setVisibility(rule.relateduids ? View.VISIBLE : View.GONE); holder.btnRelated.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent main = new Intent(context, ActivityMain.class); main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(rule.info.applicationInfo.uid)); context.startActivity(main); } }); // Fetch settings holder.ibFetch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new AsyncTask<Object, Object, Object>() { @Override protected void onPreExecute() { holder.ibFetch.setEnabled(false); } @Override protected Object doInBackground(Object... args) { HttpsURLConnection urlConnection = null; try { JSONObject json = new JSONObject(); json.put("type", "fetch"); json.put("country", Locale.getDefault().getCountry()); json.put("netguard", Util.getSelfVersionCode(context)); json.put("fingerprint", Util.getFingerprint(context)); JSONObject pkg = new JSONObject(); pkg.put("name", rule.info.packageName); pkg.put("version_code", rule.info.versionCode); pkg.put("version_name", rule.info.versionName); JSONArray pkgs = new JSONArray(); pkgs.put(pkg); json.put("package", pkgs); urlConnection = (HttpsURLConnection) new URL(cUrl).openConnection(); urlConnection.setConnectTimeout(cTimeOutMs); urlConnection.setReadTimeout(cTimeOutMs); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("Content-type", "application/json"); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); Log.i(TAG, "Request=" + json.toString()); OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(json.toString().getBytes()); // UTF-8 out.flush(); int code = urlConnection.getResponseCode(); if (code != HttpsURLConnection.HTTP_OK) throw new IOException("HTTP " + code); InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream()); String response = Util.readString(isr).toString(); Log.i(TAG, "Response=" + response); JSONObject jfetched = new JSONObject(response); JSONArray jpkgs = jfetched.getJSONArray("package"); for (int i = 0; i < jpkgs.length(); i++) { JSONObject jpkg = jpkgs.getJSONObject(i); String name = jpkg.getString("name"); int wifi = jpkg.getInt("wifi"); int wifi_screen = jpkg.getInt("wifi_screen"); int other = jpkg.getInt("other"); int other_screen = jpkg.getInt("other_screen"); int roaming = jpkg.getInt("roaming"); int devices = jpkg.getInt("devices"); double conf_wifi; boolean block_wifi; if (rule.wifi_default) { conf_wifi = confidence(devices - wifi, devices); block_wifi = !(devices - wifi > wifi && conf_wifi > cConfidence); } else { conf_wifi = confidence(wifi, devices); block_wifi = (wifi > devices - wifi && conf_wifi > cConfidence); } boolean allow_wifi_screen = rule.screen_wifi_default; if (block_wifi) allow_wifi_screen = (wifi_screen > wifi / 2); double conf_other; boolean block_other; if (rule.other_default) { conf_other = confidence(devices - other, devices); block_other = !(devices - other > other && conf_other > cConfidence); } else { conf_other = confidence(other, devices); block_other = (other > devices - other && conf_other > cConfidence); } boolean allow_other_screen = rule.screen_other_default; if (block_other) allow_other_screen = (other_screen > other / 2); boolean block_roaming = rule.roaming_default; if (!block_other || allow_other_screen) block_roaming = (roaming > (devices - other) / 2); Log.i(TAG, "pkg=" + name + " wifi=" + wifi + "/" + wifi_screen + "=" + block_wifi + "/" + allow_wifi_screen + " " + Math.round(100 * conf_wifi) + "%" + " other=" + other + "/" + other_screen + "/" + roaming + "=" + block_other + "/" + allow_other_screen + "/" + block_roaming + " " + Math.round(100 * conf_other) + "%" + " devices=" + devices); rule.wifi_blocked = block_wifi; rule.screen_wifi = allow_wifi_screen; rule.other_blocked = block_other; rule.screen_other = allow_other_screen; rule.roaming = block_roaming; } } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); return ex; } finally { if (urlConnection != null) urlConnection.disconnect(); } return null; } @Override protected void onPostExecute(Object result) { holder.ibFetch.setEnabled(true); updateRule(rule, true, listAll); } }.execute(rule); } }); // Launch application settings final Intent settings = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS); settings.setData(Uri.parse("package:" + rule.info.packageName)); holder.ibSettings.setVisibility( settings.resolveActivity(context.getPackageManager()) == null ? View.GONE : View.VISIBLE); holder.ibSettings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { context.startActivity(settings); } }); // Launch application holder.ibLaunch.setVisibility(rule.intent == null ? View.GONE : View.VISIBLE); holder.ibLaunch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { context.startActivity(rule.intent); } }); // Show Wi-Fi screen on condition holder.cbScreenWifi.setEnabled(rule.wifi_blocked && rule.apply); holder.cbScreenWifi.setOnCheckedChangeListener(null); holder.cbScreenWifi.setChecked(rule.screen_wifi); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrap = DrawableCompat.wrap(holder.ivWifiLegend.getDrawable()); DrawableCompat.setTint(wrap, colorOn); } holder.cbScreenWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { rule.screen_wifi = isChecked; updateRule(rule, true, listAll); } }); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrap = DrawableCompat.wrap(holder.ivOtherLegend.getDrawable()); DrawableCompat.setTint(wrap, colorOn); } // Show mobile screen on condition holder.cbScreenOther.setEnabled(rule.other_blocked && rule.apply); holder.cbScreenOther.setOnCheckedChangeListener(null); holder.cbScreenOther.setChecked(rule.screen_other); holder.cbScreenOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { rule.screen_other = isChecked; updateRule(rule, true, listAll); } }); // Show roaming condition holder.cbRoaming.setEnabled((!rule.other_blocked || rule.screen_other) && rule.apply); holder.cbRoaming.setOnCheckedChangeListener(null); holder.cbRoaming.setChecked(rule.roaming); holder.cbRoaming.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override @TargetApi(Build.VERSION_CODES.M) public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { rule.roaming = isChecked; updateRule(rule, true, listAll); // Request permissions if (isChecked && !Util.hasPhoneStatePermission(context)) context.requestPermissions(new String[] { Manifest.permission.READ_PHONE_STATE }, ActivityMain.REQUEST_ROAMING); } }); // Reset rule holder.btnClear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Util.areYouSure(view.getContext(), R.string.msg_clear_rules, new Util.DoubtListener() { @Override public void onSure() { holder.cbApply.setChecked(true); holder.cbWifi.setChecked(rule.wifi_default); holder.cbOther.setChecked(rule.other_default); holder.cbScreenWifi.setChecked(rule.screen_wifi_default); holder.cbScreenOther.setChecked(rule.screen_other_default); holder.cbRoaming.setChecked(rule.roaming_default); } }); } }); // Show logging is disabled boolean log_app = prefs.getBoolean("log_app", false); holder.tvNoLog.setVisibility(log_app ? View.GONE : View.VISIBLE); holder.tvNoLog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { context.startActivity(new Intent(context, ActivitySettings.class)); } }); // Show filtering is disabled boolean filter = prefs.getBoolean("filter", false); holder.tvNoFilter.setVisibility(filter ? View.GONE : View.VISIBLE); holder.tvNoFilter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { context.startActivity(new Intent(context, ActivitySettings.class)); } }); // Show access rules if (rule.expanded) { // Access the database when expanded only final AdapterAccess badapter = new AdapterAccess(context, DatabaseHelper.getInstance(context).getAccess(rule.info.applicationInfo.uid)); holder.lvAccess.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int bposition, long bid) { PackageManager pm = context.getPackageManager(); Cursor cursor = (Cursor) badapter.getItem(bposition); final long id = cursor.getLong(cursor.getColumnIndex("ID")); final int version = cursor.getInt(cursor.getColumnIndex("version")); final int protocol = cursor.getInt(cursor.getColumnIndex("protocol")); final String daddr = cursor.getString(cursor.getColumnIndex("daddr")); final int dport = cursor.getInt(cursor.getColumnIndex("dport")); long time = cursor.getLong(cursor.getColumnIndex("time")); int block = cursor.getInt(cursor.getColumnIndex("block")); PopupMenu popup = new PopupMenu(context, context.findViewById(R.id.vwPopupAnchor)); popup.inflate(R.menu.access); popup.getMenu().findItem(R.id.menu_host).setTitle(Util.getProtocolName(protocol, version, false) + " " + daddr + (dport > 0 ? "/" + dport : "")); // Whois final Intent lookupIP = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.tcpiputils.com/whois-lookup/" + daddr)); if (pm.resolveActivity(lookupIP, 0) == null) popup.getMenu().removeItem(R.id.menu_whois); else popup.getMenu().findItem(R.id.menu_whois) .setTitle(context.getString(R.string.title_log_whois, daddr)); // Lookup port final Intent lookupPort = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.speedguide.net/port.php?port=" + dport)); if (dport <= 0 || pm.resolveActivity(lookupPort, 0) == null) popup.getMenu().removeItem(R.id.menu_port); else popup.getMenu().findItem(R.id.menu_port) .setTitle(context.getString(R.string.title_log_port, dport)); popup.getMenu().findItem(R.id.menu_time) .setTitle(SimpleDateFormat.getDateTimeInstance().format(time)); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.menu_whois: context.startActivity(lookupIP); return true; case R.id.menu_port: context.startActivity(lookupPort); return true; case R.id.menu_allow: if (IAB.isPurchased(ActivityPro.SKU_FILTER, context)) { DatabaseHelper.getInstance(context).setAccess(id, 0); ServiceSinkhole.reload("allow host", context); if (rule.submit) ServiceJob.submit(rule, version, protocol, daddr, dport, 0, context); } else context.startActivity(new Intent(context, ActivityPro.class)); return true; case R.id.menu_block: if (IAB.isPurchased(ActivityPro.SKU_FILTER, context)) { DatabaseHelper.getInstance(context).setAccess(id, 1); ServiceSinkhole.reload("block host", context); if (rule.submit) ServiceJob.submit(rule, version, protocol, daddr, dport, 1, context); } else context.startActivity(new Intent(context, ActivityPro.class)); return true; case R.id.menu_reset: DatabaseHelper.getInstance(context).setAccess(id, -1); ServiceSinkhole.reload("reset host", context); if (rule.submit) ServiceJob.submit(rule, version, protocol, daddr, dport, -1, context); return true; } return false; } }); if (block == 0) popup.getMenu().removeItem(R.id.menu_allow); else if (block == 1) popup.getMenu().removeItem(R.id.menu_block); popup.show(); } }); holder.lvAccess.setAdapter(badapter); } else { holder.lvAccess.setAdapter(null); holder.lvAccess.setOnItemClickListener(null); } // Clear access log holder.btnClearAccess.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Util.areYouSure(view.getContext(), R.string.msg_reset_access, new Util.DoubtListener() { @Override public void onSure() { DatabaseHelper.getInstance(context).clearAccess(rule.info.applicationInfo.uid, true); if (rv != null) rv.scrollToPosition(position); } }); } }); // Notify on access holder.cbNotify.setEnabled(prefs.getBoolean("notify_access", false) && rule.apply); holder.cbNotify.setOnCheckedChangeListener(null); holder.cbNotify.setChecked(rule.notify); holder.cbNotify.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { rule.notify = isChecked; updateRule(rule, true, listAll); } }); // Usage data sharing holder.cbSubmit .setVisibility(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? View.VISIBLE : View.GONE); holder.cbSubmit.setOnCheckedChangeListener(null); holder.cbSubmit.setChecked(rule.submit); holder.cbSubmit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { rule.submit = isChecked; updateRule(rule, true, listAll); } }); }
From source file:com.kimbrelk.da.oauth2.OAuth2.java
protected final JSONObject requestJSON(Verb verb, String url, String postData) { try {//from ww w .j a va 2 s .co m mLog.append("SEND:\n"); HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); connection.setRequestProperty("User-Agent", mUserAgent); connection.setRequestProperty("dA-minor-version", "" + VERSION.getMinor()); connection.setReadTimeout(30000); connection.setConnectTimeout(30000); mLog.append(verb.toString() + " "); mLog.append(url); mLog.append("\n"); connection.setRequestMethod(verb.toString()); if (verb == Verb.POST) { mLog.append(postData); mLog.append("\n"); connection.setDoOutput(true); connection.setDoInput(true); //connection.setRequestProperty("Authorization", "Basic " + base64(CLIENT_ID + ":" + loadLast())); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + postData.length()); connection.connect(); OutputStream os = connection.getOutputStream(); os.write(postData.getBytes()); os.flush(); } else if (verb == Verb.GET) { connection.setDoOutput(false); connection.setDoInput(true); connection.connect(); } mLog.append("\nRECV:\n"); try { InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader in = new BufferedReader(isr); String line = ""; String page = ""; while ((line = in.readLine()) != null) { page += line; } mLog.append(page); mLog.append("\n\n"); return new JSONObject(page); } catch (Exception e) { try { JSONObject json = new JSONObject(); json.put("status", "error"); try { InputStream is = connection.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader in = new BufferedReader(isr); String line = ""; String page = ""; while ((line = in.readLine()) != null) { page += line; } mLog.append(page); mLog.append("\n\n"); return new JSONObject(page); } catch (Exception err) { } try { if (connection.getResponseCode() == 403 || connection.getResponseCode() == 429) { json.put("error_description", RespError.RATE_LIMIT.getDescription()); json.put("error", RespError.RATE_LIMIT.getType()); return json; } } catch (IOException er) { } String str = ""; str += "URL: " + url.split("[?]+")[0] + "\n"; //str += "POST Data: " + postData + "\n"; str += "\n"; for (int a = 0; a < connection.getHeaderFields().size() - 1; a++) { str += connection.getHeaderFieldKey(a) + ": " + connection.getHeaderField(a) + "\n"; } json.put("error_description", str); json.put("error", RespError.REQUEST_FAILED.getType()); return json; } catch (Exception er) { throw e; } } finally { connection.disconnect(); } } catch (Exception e) { try { e.printStackTrace(); JSONObject json = new JSONObject(); json.put("status", "error"); json.put("error", RespError.REQUEST_FAILED.getType()); json.put("error_description", RespError.REQUEST_FAILED.getDescription() + " : " + e); return json; } catch (JSONException er) { er.printStackTrace(); return null; } } }
From source file:io.teak.sdk.Request.java
@Override public void run() { HttpsURLConnection connection = null; SecretKeySpec keySpec = new SecretKeySpec(this.session.appConfiguration.apiKey.getBytes(), "HmacSHA256"); String requestBody;/* ww w . ja v a 2 s . c om*/ String hostnameForEndpoint = this.hostname; if (hostnameForEndpoint == null) { hostnameForEndpoint = this.session.remoteConfiguration.getHostnameForEndpoint(this.endpoint); } try { ArrayList<String> payloadKeys = new ArrayList<>(this.payload.keySet()); Collections.sort(payloadKeys); StringBuilder builder = new StringBuilder(); for (String key : payloadKeys) { Object value = this.payload.get(key); if (value != null) { String valueString; if (value instanceof Map) { valueString = new JSONObject((Map) value).toString(); } else if (value instanceof Array) { valueString = new JSONArray(Collections.singletonList(value)).toString(); } else if (value instanceof Collection) { valueString = new JSONArray((Collection) value).toString(); } else { valueString = value.toString(); } builder.append(key).append("=").append(valueString).append("&"); } else { Log.e(LOG_TAG, "Value for key: " + key + " is null."); } } builder.deleteCharAt(builder.length() - 1); String stringToSign = "POST\n" + hostnameForEndpoint + "\n" + this.endpoint + "\n" + builder.toString(); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(keySpec); byte[] result = mac.doFinal(stringToSign.getBytes()); builder = new StringBuilder(); for (String key : payloadKeys) { Object value = this.payload.get(key); String valueString; if (value instanceof Map) { valueString = new JSONObject((Map) value).toString(); } else if (value instanceof Array) { valueString = new JSONArray(Collections.singletonList(value)).toString(); } else if (value instanceof Collection) { valueString = new JSONArray((Collection) value).toString(); } else { valueString = value.toString(); } builder.append(key).append("=").append(URLEncoder.encode(valueString, "UTF-8")).append("&"); } builder.append("sig=") .append(URLEncoder.encode(Base64.encodeToString(result, Base64.NO_WRAP), "UTF-8")); requestBody = builder.toString(); } catch (Exception e) { Log.e(LOG_TAG, "Error signing payload: " + Log.getStackTraceString(e)); return; } try { if (Teak.isDebug) { Log.d(LOG_TAG, "Submitting request to '" + this.endpoint + "': " + new JSONObject(this.payload).toString(2)); } URL url = new URL("https://" + hostnameForEndpoint + this.endpoint); connection = (HttpsURLConnection) url.openConnection(); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setUseCaches(false); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(requestBody.getBytes().length)); // Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(requestBody); wr.flush(); wr.close(); // Get Response InputStream is; if (connection.getResponseCode() < 400) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); if (Teak.isDebug) { String responseText = response.toString(); try { responseText = new JSONObject(response.toString()).toString(2); } catch (Exception ignored) { } Log.d(LOG_TAG, "Reply from '" + this.endpoint + "': " + responseText); } // For extending classes done(connection.getResponseCode(), response.toString()); } catch (Exception e) { Log.e(LOG_TAG, Log.getStackTraceString(e)); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java
public HttpsURLConnection makeRequest(String verb, String url, @Nullable String postData, boolean json, boolean autoredirect, @Nullable Map<String, String> customHeaders) throws IOException, URISyntaxException { String currentUrl = url;// w w w .j a v a 2s . co m for (int i = 0; i < 30; i++) // loop for handling redirect, using automatic redirect is not possible, because // all response headers must be catched { int code; HttpsURLConnection connection = null; try { logger.debug("Make request to {}", url); connection = (HttpsURLConnection) new URL(currentUrl).openConnection(); connection.setRequestMethod(verb); connection.setRequestProperty("Accept-Language", "en-US"); if (customHeaders == null || !customHeaders.containsKey("User-Agent")) { connection.setRequestProperty("User-Agent", userAgent); } connection.setRequestProperty("Accept-Encoding", "gzip"); connection.setRequestProperty("DNT", "1"); connection.setRequestProperty("Upgrade-Insecure-Requests", "1"); if (customHeaders != null) { for (String key : customHeaders.keySet()) { String value = customHeaders.get(key); if (StringUtils.isNotEmpty(value)) { connection.setRequestProperty(key, value); } } } connection.setInstanceFollowRedirects(false); // add cookies URI uri = connection.getURL().toURI(); if (customHeaders == null || !customHeaders.containsKey("Cookie")) { StringBuilder cookieHeaderBuilder = new StringBuilder(); for (HttpCookie cookie : cookieManager.getCookieStore().get(uri)) { if (cookieHeaderBuilder.length() > 0) { cookieHeaderBuilder.append(";"); } cookieHeaderBuilder.append(cookie.getName()); cookieHeaderBuilder.append("="); cookieHeaderBuilder.append(cookie.getValue()); if (cookie.getName().equals("csrf")) { connection.setRequestProperty("csrf", cookie.getValue()); } } if (cookieHeaderBuilder.length() > 0) { String cookies = cookieHeaderBuilder.toString(); connection.setRequestProperty("Cookie", cookies); } } if (postData != null) { logger.debug("{}: {}", verb, postData); // post data byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8); int postDataLength = postDataBytes.length; connection.setFixedLengthStreamingMode(postDataLength); if (json) { connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); } else { connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); if (verb == "POST") { connection.setRequestProperty("Expect", "100-continue"); } connection.setDoOutput(true); OutputStream outputStream = connection.getOutputStream(); outputStream.write(postDataBytes); outputStream.close(); } // handle result code = connection.getResponseCode(); String location = null; // handle response headers Map<String, List<String>> headerFields = connection.getHeaderFields(); for (Map.Entry<String, List<String>> header : headerFields.entrySet()) { String key = header.getKey(); if (StringUtils.isNotEmpty(key)) { if (key.equalsIgnoreCase("Set-Cookie")) { // store cookie for (String cookieHeader : header.getValue()) { if (StringUtils.isNotEmpty(cookieHeader)) { List<HttpCookie> cookies = HttpCookie.parse(cookieHeader); for (HttpCookie cookie : cookies) { cookieManager.getCookieStore().add(uri, cookie); } } } } if (key.equalsIgnoreCase("Location")) { // get redirect location location = header.getValue().get(0); if (StringUtils.isNotEmpty(location)) { location = uri.resolve(location).toString(); // check for https if (location.toLowerCase().startsWith("http://")) { // always use https location = "https://" + location.substring(7); logger.debug("Redirect corrected to {}", location); } } } } } if (code == 200) { logger.debug("Call to {} succeeded", url); return connection; } if (code == 302 && location != null) { logger.debug("Redirected to {}", location); currentUrl = location; if (autoredirect) { continue; } return connection; } } catch (IOException e) { if (connection != null) { connection.disconnect(); } logger.warn("Request to url '{}' fails with unkown error", url, e); throw e; } catch (Exception e) { if (connection != null) { connection.disconnect(); } throw e; } if (code != 200) { throw new HttpException(code, verb + " url '" + url + "' failed: " + connection.getResponseMessage()); } } throw new ConnectionException("Too many redirects"); }
From source file:org.csp.everyaware.internet.StoreAndForwardService.java
public int postSecureData() throws IllegalArgumentException, ClientProtocolException, HttpHostConnectException, IOException { Log.d("StoreAndForwardService", "postSecureData()"); //get size of array of records to send and reference to the last record int size = mToSendRecords.size(); if (size == 0) return -1; int sepIndex = 1; //default is '.' separator (see Constants.separators array) if ((Utils.report_country != null) && (Utils.report_country.equals("IT"))) sepIndex = 0; //0 is for '-' separator (for italian CSP server) Record lastToSendRecord = mToSendRecords.get(size - 1); Log.d("StoreAndForwardService", "postSecureData()--> # of records: " + size); //save timestamp long lastTimestamp = 0; if (lastToSendRecord.mSysTimestamp > 0) lastTimestamp = lastToSendRecord.mSysTimestamp; else/*from w w w . j av a 2s . c o m*/ lastTimestamp = lastToSendRecord.mBoxTimestamp; String lastTsFormatted = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSSz", Locale.US) .format(new Date(lastTimestamp)); //********* MAKING OF HTTP HEADER ************** URL url = new URL(Utils.report_url); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setUseCaches(false); con.setDoInput(true); con.setDoOutput(true); con.setRequestProperty("Content-Encoding", "gzip"); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("User-Agent", "AirProbe" + Utils.appVer); //******** authorization bearer header ******** //air probe can be used also anymously. If account activation state is true (--> AirProbe activated) add this header if (Utils.getAccountActivationState(getApplicationContext())) con.setRequestProperty("Authorization", "Bearer " + Utils.getAccessToken(getApplicationContext())); else if (Utils.getAccountActivationStateForClient(getApplicationContext())) con.setRequestProperty("Authorization", "Bearer " + Utils.getAccessTokenForClient(getApplicationContext())); //******** meta header (for new version API V1) con.setRequestProperty("meta" + Constants.separators[sepIndex] + "timestampRecorded", lastTsFormatted); //con.setRequestProperty("meta"+Constants.separators[sepIndex]+"sessionId", lastToSendRecord.mSessionId); //deprecated from AP 1.4 con.setRequestProperty("meta" + Constants.separators[sepIndex] + "deviceId", Utils.deviceID); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "installId", Utils.installID); //con.setRequestProperty("meta"+Constants.separators[sepIndex]+"userFeedId", ""); //con.setRequestProperty("meta"+Constants.separators[sepIndex]+"eventFeedId", ""); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "visibilityEvent", Constants.DATA_VISIBILITY[0]); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "visibilityGlobal", Constants.DATA_VISIBILITY[0]); //set meta.visibilityGlobal=DETAILS for testing (to retrieve data after insertion) /* from AP 1.4 */ if ((lastToSendRecord.mBoxMac != null) && (!lastToSendRecord.mBoxMac.equals(""))) { Log.d("StoreAndForwardService", "postSecureData()--> box mac address: " + lastToSendRecord.mBoxMac); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceId", lastToSendRecord.mBoxMac); } else con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceId", Utils.getDeviceAddress(getApplicationContext())); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceSessionId" + Constants.separators[sepIndex] + "seed", lastToSendRecord.mSourceSessionSeed); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceSessionId" + Constants.separators[sepIndex] + "number", String.valueOf(lastToSendRecord.mSourceSessionNumber)); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceSessionPointNumber", String.valueOf(lastToSendRecord.mSourcePointNumber)); if ((lastToSendRecord.mSemanticSessionSeed != null) && (!lastToSendRecord.mSemanticSessionSeed.equals(""))) { con.setRequestProperty("meta" + Constants.separators[sepIndex] + "semanticSessionId" + Constants.separators[sepIndex] + "seed", lastToSendRecord.mSemanticSessionSeed); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "semanticSessionId" + Constants.separators[sepIndex] + "number", String.valueOf(lastToSendRecord.mSemanticSessionNumber)); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "semanticSessionPointNumber", String.valueOf(lastToSendRecord.mSemanticPointNumber)); } con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "typeVersion", "30"); //update by increment this field on header changes /* end of from AP 1.4 */ //******** data header (for new version API V1) con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "type", "airprobe_report"); con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "format", "json"); //con.setRequestProperty("data"+Constants.separators[sepIndex]+"contentDetails"+Constants.separators[sepIndex]+"specification", "a-3"); //deprecated from AP 1.4 if (size > 1) con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "list", "true"); else con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "list", "false"); con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "listSize", String.valueOf(size)); //******** geo header (for new version API V1) //add the right provider to header if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[0])) //sensor box { con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude", String.valueOf(lastToSendRecord.mBoxLon)); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude", String.valueOf(lastToSendRecord.mBoxLat)); if (lastToSendRecord.mBoxAcc != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "hdop", String.valueOf(lastToSendRecord.mBoxAcc)); //from AP 1.4 if (lastToSendRecord.mBoxAltitude != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "altitude", String.valueOf(lastToSendRecord.mBoxAltitude)); //from AP 1.4 if (lastToSendRecord.mBoxSpeed != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "speed", String.valueOf(lastToSendRecord.mBoxSpeed)); //from AP 1.4 if (lastToSendRecord.mBoxBear != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "bearing", String.valueOf(lastToSendRecord.mBoxBear)); //from AP 1.4 con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider", lastToSendRecord.mGpsProvider); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted); } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[1])) //phone { con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude", String.valueOf(lastToSendRecord.mPhoneLon)); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude", String.valueOf(lastToSendRecord.mPhoneLat)); if (lastToSendRecord.mPhoneAcc != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "accuracy", String.valueOf(lastToSendRecord.mPhoneAcc)); if (lastToSendRecord.mPhoneAltitude != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "altitude", String.valueOf(lastToSendRecord.mPhoneAltitude)); //from AP 1.4 if (lastToSendRecord.mPhoneSpeed != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "speed", String.valueOf(lastToSendRecord.mPhoneSpeed)); //from AP 1.4 if (lastToSendRecord.mPhoneBear != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "bearing", String.valueOf(lastToSendRecord.mPhoneBear)); //from AP 1.4 con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider", lastToSendRecord.mGpsProvider); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted); } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[2])) //network { con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude", String.valueOf(lastToSendRecord.mNetworkLon)); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude", String.valueOf(lastToSendRecord.mNetworkLat)); if (lastToSendRecord.mNetworkAcc != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "accuracy", String.valueOf(lastToSendRecord.mNetworkAcc)); if (lastToSendRecord.mNetworkAltitude != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "altitude", String.valueOf(lastToSendRecord.mNetworkAltitude)); //from AP 1.4 if (lastToSendRecord.mNetworkSpeed != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "speed", String.valueOf(lastToSendRecord.mNetworkSpeed)); //from AP 1.4 if (lastToSendRecord.mNetworkBear != 0) con.setRequestProperty("geo" + Constants.separators[sepIndex] + "bearing", String.valueOf(lastToSendRecord.mNetworkBear)); //from AP 1.4 con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider", lastToSendRecord.mGpsProvider); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted); } //******** MAKING OF HTTP CONTENT (JSON) ************* //writing string content as an array of json object StringBuilder sb = new StringBuilder(); sb.append("["); for (int i = 0; i < mToSendRecords.size(); i++) { sb.append(mToSendRecords.get(i).toJson().toString()); if ((size != 0) && (i != size - 1)) sb.append(","); sb.append("\n"); } sb.append("]"); //Log.d("StoreAndForwardService", "postSecureData()--> json: " +sb.toString()); //Log.d("StoreAndForwardService", "postSecureData()--> access token: "+Utils.getAccessToken(getApplicationContext())); //compress json content into byte array entity byte[] contentGzippedBytes = zipStringToBytes(sb.toString()); //write json compressed content into output stream OutputStream outputStream = con.getOutputStream(); outputStream.write(contentGzippedBytes); outputStream.flush(); outputStream.close(); int responseCode = con.getResponseCode(); Log.d("StoreAndForwardService", "postSecureData()--> response code: " + responseCode); sb = null; return responseCode; }
From source file:org.csp.everyaware.internet.StoreAndForwardService.java
public void postSecureTags() throws IllegalArgumentException, ClientProtocolException, HttpHostConnectException, IOException { Log.d("StoreAndForwardService", "postSecureTags()"); int sepIndex = 1; //default is '.' separator (see Constants.separators array) if ((Utils.report_country != null) && (Utils.report_country.equals("IT"))) sepIndex = 0; //0 is for '-' separator (for italian CSP server) List<String> sids = mDbManager.getSidsOfRecordsWithTags(); if ((sids != null) && (sids.size() > 0)) { for (int i = 0; i < sids.size(); i++) { String sessionId = (String) sids.get(i); //load records containing user tags with actual session id List<Record> recordsWithTags = mDbManager.loadRecordsWithTagBySessionId(sessionId); if ((recordsWithTags != null) && (recordsWithTags.size() > 0)) { //get size of array of records containing tags and reference to the last record int size = recordsWithTags.size(); //obtain reference to the last record of serie Record lastToSendRecord = recordsWithTags.get(size - 1); Log.d("StoreAndForwardService", "postSecureTags()--> # of records containing tags: " + size); //save timestamp of last record containing tags long lastTimestamp = 0; if (lastToSendRecord.mSysTimestamp > 0) lastTimestamp = lastToSendRecord.mSysTimestamp; else lastTimestamp = lastToSendRecord.mBoxTimestamp; String lastTsFormatted = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSSz", Locale.US) .format(new Date(lastTimestamp)); //********* MAKING OF HTTP HEADER ************** URL url = new URL(Utils.report_url); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setUseCaches(false); con.setDoInput(true);// w w w .ja v a 2s . c om con.setDoOutput(true); con.setRequestProperty("Content-Encoding", "gzip"); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("User-Agent", "AirProbe" + Utils.appVer); //******** authorization bearer header ******** if (Utils.getAccountActivationState(getApplicationContext())) con.setRequestProperty("Authorization", "Bearer " + Utils.getAccessToken(getApplicationContext())); else if (Utils.getAccountActivationStateForClient(getApplicationContext())) con.setRequestProperty("Authorization", "Bearer " + Utils.getAccessTokenForClient(getApplicationContext())); //******** meta header (for new version API V1) con.setRequestProperty("meta" + Constants.separators[sepIndex] + "timestampRecorded", lastTsFormatted); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "deviceId", Utils.deviceID); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "installId", Utils.installID); //******** data header (for new version API V1) //con.setRequestProperty("data"+Constants.separators[sepIndex]+"extendedPacketId", ""); //con.setRequestProperty("data"+Constants.separators[sepIndex]+"extendedPacketPointId", ""); //con.setRequestProperty("data"+Constants.separators[sepIndex]+"extendedSessionId", ""); //deprecated from AP 1.4 con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "type", "airprobe_tags"); con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "format", "json"); //con.setRequestProperty("data"+Constants.separators[sepIndex]+"contentDetails"+Constants.separators[sepIndex]+"specification", "at-3"); //update by increment this field on header changes if (size > 1) con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "list", "true"); else con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "list", "false"); con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "listSize", String.valueOf(size)); /* from AP 1.4 */ if ((lastToSendRecord.mBoxMac != null) && (!lastToSendRecord.mBoxMac.equals(""))) { Log.d("StoreAndForwardService", "postSecureData()--> box mac address: " + lastToSendRecord.mBoxMac); con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceId", lastToSendRecord.mBoxMac); } else con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceId", Utils.getDeviceAddress(getApplicationContext())); con.setRequestProperty("data" + Constants.separators[sepIndex] + "extendedSourceSessionId" + Constants.separators[sepIndex] + "seed", lastToSendRecord.mSourceSessionSeed); con.setRequestProperty( "data" + Constants.separators[sepIndex] + "extendedSourceSessionId" + Constants.separators[sepIndex] + "number", String.valueOf(lastToSendRecord.mSourceSessionNumber)); if ((lastToSendRecord.mSemanticSessionSeed != null) && (!lastToSendRecord.mSemanticSessionSeed.equals(""))) { con.setRequestProperty( "data" + Constants.separators[sepIndex] + "extendedSemanticSessionId" + Constants.separators[sepIndex] + "seed", lastToSendRecord.mSemanticSessionSeed); con.setRequestProperty( "data" + Constants.separators[sepIndex] + "extendedSemanticSessionId" + Constants.separators[sepIndex] + "number", String.valueOf(lastToSendRecord.mSemanticSessionNumber)); } con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails" + Constants.separators[sepIndex] + "typeVersion", "30"); //update by increment this field on header changes /* end of from AP 1.4 */ //******** geo header (for new version API V1) //add the right provider to header if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[0])) //sensor box { con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude", String.valueOf(lastToSendRecord.mBoxLon)); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude", String.valueOf(lastToSendRecord.mBoxLat)); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider", lastToSendRecord.mGpsProvider); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted); } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[1])) //phone { con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude", String.valueOf(lastToSendRecord.mPhoneLon)); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude", String.valueOf(lastToSendRecord.mPhoneLat)); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "accuracy", String.valueOf(lastToSendRecord.mPhoneAcc)); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "altitude", String.valueOf(lastToSendRecord.mPhoneAltitude)); //from AP 1.4 con.setRequestProperty("geo" + Constants.separators[sepIndex] + "speed", String.valueOf(lastToSendRecord.mPhoneSpeed)); //from AP 1.4 con.setRequestProperty("geo" + Constants.separators[sepIndex] + "bearing", String.valueOf(lastToSendRecord.mPhoneBear)); //from AP 1.4 con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider", lastToSendRecord.mGpsProvider); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted); } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[2])) //network { con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude", String.valueOf(lastToSendRecord.mNetworkLon)); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude", String.valueOf(lastToSendRecord.mNetworkLat)); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "accuracy", String.valueOf(lastToSendRecord.mNetworkAcc)); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "altitude", String.valueOf(lastToSendRecord.mNetworkAltitude)); //from AP 1.4 con.setRequestProperty("geo" + Constants.separators[sepIndex] + "speed", String.valueOf(lastToSendRecord.mNetworkSpeed)); //from AP 1.4 con.setRequestProperty("geo" + Constants.separators[sepIndex] + "bearing", String.valueOf(lastToSendRecord.mNetworkBear)); //from AP 1.4 con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider", lastToSendRecord.mGpsProvider); con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted); } //******** MAKING OF HTTP CONTENT (JSON) ************* //writing string content as an array of json object StringBuilder sb = new StringBuilder(); sb.append("["); JSONObject object = new JSONObject(); try { object.put("timestamp", lastTimestamp); JSONArray locations = new JSONArray(); //sensor box gps data if (lastToSendRecord.mBoxLat != 0) { JSONObject boxLocation = new JSONObject(); boxLocation.put("latitude", lastToSendRecord.mBoxLat); boxLocation.put("longitude", lastToSendRecord.mBoxLon); //boxLocation.put("accuracy", "null"); //boxLocation.put("altitude", "null"); //boxLocation.put("speed", "null"); //boxLocation.put("bearing", "null"); boxLocation.put("provider", Constants.GPS_PROVIDERS[0]); boxLocation.put("timestamp", lastToSendRecord.mBoxTimestamp); locations.put(0, boxLocation); } //phone gps data if (lastToSendRecord.mPhoneLat != 0) { JSONObject phoneLocation = new JSONObject(); phoneLocation.put("latitude", lastToSendRecord.mPhoneLat); phoneLocation.put("longitude", lastToSendRecord.mPhoneLon); phoneLocation.put("accuracy", lastToSendRecord.mAccuracy); phoneLocation.put("altitude", lastToSendRecord.mPhoneAltitude); phoneLocation.put("speed", lastToSendRecord.mPhoneSpeed); phoneLocation.put("bearing", lastToSendRecord.mPhoneBear); phoneLocation.put("provider", Constants.GPS_PROVIDERS[1]); phoneLocation.put("timestamp", lastToSendRecord.mPhoneTimestamp); locations.put(1, phoneLocation); } //network gps data if (lastToSendRecord.mNetworkLat != 0) { JSONObject netLocation = new JSONObject(); netLocation.put("latitude", lastToSendRecord.mNetworkLat); netLocation.put("longitude", lastToSendRecord.mNetworkLon); netLocation.put("accuracy", lastToSendRecord.mNetworkAcc); netLocation.put("altitude", lastToSendRecord.mNetworkAltitude); netLocation.put("speed", lastToSendRecord.mNetworkSpeed); netLocation.put("bearing", lastToSendRecord.mNetworkBear); netLocation.put("provider", Constants.GPS_PROVIDERS[2]); netLocation.put("timestamp", lastToSendRecord.mNetworkTimestamp); locations.put(2, netLocation); } object.put("locations", locations); } catch (JSONException e) { e.printStackTrace(); } String concatOfTags = ""; //put the tags of all records in concatOfTags string for (int j = 0; j < recordsWithTags.size(); j++) { if ((recordsWithTags.get(j).mUserData1 != null) && (!recordsWithTags.get(j).mUserData1.equals(""))) concatOfTags += recordsWithTags.get(j).mUserData1 + " "; } Log.d("StoreAndForwardService", "postSecureTags()--> concat of tags: " + concatOfTags); try { String[] tags = concatOfTags.split(" "); JSONArray tagsArray = new JSONArray(); if ((tags != null) && (tags.length > 0)) { for (int k = 0; k < tags.length; k++) { if (!tags[k].equals("")) tagsArray.put(k, tags[k]); } } object.put("tags", tagsArray); //object.put("tags_cause", null); //object.put("tags_location", null); //object.put("tags_perception", null); } catch (JSONException e) { e.printStackTrace(); } sb.append(object.toString()); sb.append("]"); Log.d("StoreAndForwardService", "postSecureTags()--> json to string: " + sb.toString()); //compress json content into byte array entity byte[] contentGzippedBytes = zipStringToBytes(sb.toString()); //write json compressed content into output stream OutputStream outputStream = con.getOutputStream(); outputStream.write(contentGzippedBytes); outputStream.flush(); outputStream.close(); int responseCode = con.getResponseCode(); Log.d("StoreAndForwardService", "postSecureTags()--> response code: " + responseCode); sb = null; if (responseCode == Constants.STATUS_OK) { Log.d("StoreAndForwardService", "postSecureTags()--> STATUS OK"); mDbManager.deleteRecordsWithTagsBySessionId(sessionId); } else Log.d("StoreAndForwardService", "postSecureTags()--> status error code: " + responseCode); } else Log.d("StoreAndForwardService", "postTags()--> no tags to send"); } } }