List of usage examples for android.text TextUtils join
public static String join(@NonNull CharSequence delimiter, @NonNull Iterable tokens)
From source file:cm.aptoide.com.facebook.android.Facebook.java
/** * Internal method to handle single sign-on backend for authorize(). * * @param activity/*from w w w . j a v a 2 s . c om*/ * The Android Activity that will parent the ProxyAuth Activity. * @param applicationId * The Facebook application identifier. * @param permissions * A list of permissions required for this application. If you do * not require any permissions, pass an empty String array. * @param activityCode * Activity code to uniquely identify the result Intent in the * callback. */ private boolean startSingleSignOn(Activity activity, String applicationId, String[] permissions, int activityCode) { boolean didSucceed = true; Intent intent = new Intent(); intent.setClassName("com.facebook.katana", "com.facebook.katana.ProxyAuth"); intent.putExtra("client_id", applicationId); if (permissions.length > 0) { intent.putExtra("scope", TextUtils.join(",", permissions)); } // Verify that the application whose package name is // com.facebook.katana.ProxyAuth // has the expected FB app signature. if (!validateActivityIntent(activity, intent)) { return false; } mAuthActivity = activity; mAuthPermissions = permissions; mAuthActivityCode = activityCode; try { activity.startActivityForResult(intent, activityCode); } catch (ActivityNotFoundException e) { didSucceed = false; } return didSucceed; }
From source file:com.microsoft.services.msa.LiveAuthClient.java
/** * Constructs a new {@code LiveAuthClient} instance and initializes its member variables. * * @param context Context of the Application used to save any refresh_token. * @param clientId The client_id of the Live Connect Application to login to. * @param scopes to initialize the {@link LiveConnectSession} with. * See <a href="http://msdn.microsoft.com/en-us/library/hh243646.aspx">MSDN Live Connect * Reference's Scopes and permissions</a> for a list of scopes and explanations. *///from ww w . java 2 s .c om public LiveAuthClient(final Context context, final String clientId, final Iterable<String> scopes, final OAuthConfig oAuthConfig) { LiveConnectUtils.assertNotNull(context, "context"); LiveConnectUtils.assertNotNullOrEmpty(clientId, "clientId"); this.applicationContext = context.getApplicationContext(); this.clientId = clientId; if (oAuthConfig == null) { this.mOAuthConfig = MicrosoftOAuthConfig.getInstance(); } else { this.mOAuthConfig = oAuthConfig; } // copy scopes for login Iterable<String> tempScopes = scopes; if (tempScopes == null) { tempScopes = Arrays.asList(new String[0]); } this.baseScopes = new HashSet<>(); for (final String scope : tempScopes) { this.baseScopes.add(scope); } this.baseScopes = Collections.unmodifiableSet(this.baseScopes); final String refreshToken = this.getRefreshTokenFromPreferences(); if (!TextUtils.isEmpty(refreshToken)) { final String scopeAsString = TextUtils.join(OAuth.SCOPE_DELIMITER, this.baseScopes); RefreshAccessTokenRequest request = new RefreshAccessTokenRequest(this.httpClient, this.clientId, refreshToken, scopeAsString, this.mOAuthConfig); TokenRequestAsync requestAsync = new TokenRequestAsync(request); requestAsync.addObserver(new RefreshTokenWriter()); requestAsync.execute(); } }
From source file:org.odk.collect.android.views.ODKView.java
/** * Builds a string representing the 'path' of the list of groups. * Each level is separated by `>`./*w ww.j av a 2 s .c om*/ * * Some views (e.g. the repeat picker) may want to hide the multiplicity of the last item, * i.e. show `Friends` instead of `Friends > 1`. */ @NonNull public static String getGroupsPath(FormEntryCaption[] groups, boolean hideLastMultiplicity) { if (groups == null) { return ""; } List<String> segments = new ArrayList<>(); int index = 1; for (FormEntryCaption group : groups) { String text = group.getLongText(); if (text != null) { segments.add(text); boolean isMultiplicityAllowed = !(hideLastMultiplicity && index == groups.length); if (group.repeats() && isMultiplicityAllowed) { segments.add(Integer.toString(group.getMultiplicity() + 1)); } } index++; } return TextUtils.join(" > ", segments); }
From source file:com.odo.kcl.mobileminer.ProcSocketSet.java
/** * Search in /proc/<pid>/net for open network sockets. * http://www.tldp.org/LDP/Linux-Filesystem-Hierarchy/html/proc.html * http://www.onlamp.com/pub/a/linux/2000/11/16/LinuxAdmin.html *//* w ww .ja v a 2 s . co m*/ // /proc/<pid>/net/tcp example: // sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode // 0: 00000000:445C 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 15353 1 0000000000000000 100 0 0 10 0 // 1: 00000000:01BD 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 12341 1 0000000000000000 100 0 0 10 0 // ... // 12: 4F01A8C0:E1D0 B422C2AD:0050 01 00000000:00000000 02:000003A3 00000000 1000 0 154153 2 0000000000000000 23 4 28 10 -1 // 13: 0100007F:13AD 0100007F:B3B6 01 00000000:00000000 00:00000000 00000000 1000 0 34682 1 0000000000000000 20 4 1 10 -1 public void scan() { List<ActivityManager.RunningAppProcessInfo> procs = am.getRunningAppProcesses(); Integer j, digitCount, digitInc; ArrayList<String> pids = new ArrayList<String>(); // Process IDs. ArrayList<String> names = new ArrayList<String>(); // Process names. ArrayList<String> uids = new ArrayList<String>(); // User IDs. HashMap<String, String> namesByUid = new HashMap<String, String>(); HashMap<String, String> namesByPid = new HashMap<String, String>(); HashMap<String, String> pidsByUid = new HashMap<String, String>(); HashMap<String, String> pidsByName = new HashMap<String, String>(); String thisUid, thisPid, thisName; BufferedReader reader; boolean ipv6 = false; String line; String[] tokens, remote; String remoteAddr, remoteIP, remotePort; HashMap<String, ArrayList<String>> discoveredSockets; ArrayList<Integer> remoteIPchunks; updated = false; // Populate the HashmMaps and create the process objects. for (ActivityManager.RunningAppProcessInfo p : procs) { thisPid = Integer.toString(p.pid); pids.add(thisPid); names.add(p.processName); namesByPid.put(thisPid, p.processName); thisUid = Integer.toString(p.uid); uids.add(thisUid); namesByUid.put(thisUid, p.processName); pidsByUid.put(thisUid, thisPid); pidsByName.put(p.processName, thisPid); if (processes.get(p.processName) == null) processes.put(p.processName, new Process(p.processName, thisPid)); } // Purge any processes that have stopped. for (String name : processes.keySet()) { if (!names.contains(name)) { processes.get(name).closeAll(); } } for (String prot : protocols) { if (ipv6) { // How many HEX digits specify each chunk of an ip address? digitCount = 4; digitInc = 3; } else { digitCount = 2; digitInc = 1; } ipv6 = !ipv6; // Protocols array alternates between ipv4 and ipv6. discoveredSockets = new HashMap<String, ArrayList<String>>(); for (String scannedPid : pids) { // For each process ID... try { line = null; // Are we allowed to read /proc/<pid>/net/<protocol> ? reader = new BufferedReader(new FileReader("/proc/" + scannedPid + "/net/" + prot)); while ((line = reader.readLine()) != null) { tokens = line.split("\\s+"); // Split on whitespace... remote = tokens[3].split(":"); // Maybe the fourth token is the remote address... remoteAddr = remote[0]; if (remote.length > 1) { // ...if there are two tokens seperated by a ":". thisUid = tokens[8]; thisPid = pidsByUid.get(thisUid); thisName = namesByUid.get(thisUid); if (thisName != null && thisPid != null) { remotePort = Integer.valueOf(remote[1], 16).toString(); // Get the port from the HEX string. remoteIPchunks = new ArrayList<Integer>(); for (j = 0; j < remoteAddr.length(); j += digitCount) { // Get each part of the ip address as a string... remoteIPchunks.add(Integer .valueOf(remoteAddr.subSequence(j, j + digitInc).toString(), 16)); } if (remoteIPchunks.get(0) != 0) { remoteIP = TextUtils.join(".", remoteIPchunks); // ...then assemble it and add the socket. if (discoveredSockets.get(thisName) == null) discoveredSockets.put(thisName, new ArrayList<String>()); discoveredSockets.get(thisName).add(remoteIP + ":" + remotePort); } } } } for (String name : names) { // See which of the old sockets are still open. if (processes.get(name) != null) { if (discoveredSockets.get(name) != null) { // Do we need to broadcast any changes? updated |= processes.get(name).checkSockets(prot, discoveredSockets.get(name)); for (String addr : discoveredSockets.get(name)) updated |= addSocket(prot, pidsByName.get(name), name, addr); } else { processes.get(name).closeAll(prot); } } } } catch (IOException e) { //Log.i("MinerService","Can't open /proc/<pid>/net"); } } } if (updated) broadcast(); }
From source file:fr.s13d.photobackup.preferences.PBPreferenceFragment.java
private void setSummaries() { final String wifiOnly = preferences.getString(PBConstants.PREF_WIFI_ONLY, getResources().getString(R.string.only_wifi_default)); // default final ListPreference wifiPreference = (ListPreference) findPreference(PBConstants.PREF_WIFI_ONLY); wifiPreference.setSummary(wifiOnly); final String recentUploadOnly = preferences.getString(PBConstants.PREF_RECENT_UPLOAD_ONLY, getResources().getString(R.string.only_recent_upload_default)); // default final ListPreference recentUploadPreference = (ListPreference) findPreference( PBConstants.PREF_RECENT_UPLOAD_ONLY); recentUploadPreference.setSummary(recentUploadOnly); final String serverUrl = preferences.getString(PBServerPreferenceFragment.PREF_SERVER_URL, null); if (serverUrl != null) { final String serverName = preferences.getString(PBConstants.PREF_SERVER, null); if (serverName != null) { final PBServerListPreference serverPreference = (PBServerListPreference) findPreference( PBConstants.PREF_SERVER); serverPreference.setSummary(serverName + " @ " + serverUrl); // bonus: left icon of the server final int serverNamesId = getResources().getIdentifier("pref_server_names", "array", getActivity().getPackageName()); final String[] serverNames = getResources().getStringArray(serverNamesId); final int serverPosition = Arrays.asList(serverNames).indexOf(serverName); final int serverIconsId = getResources().getIdentifier("pref_server_icons", "array", getActivity().getPackageName()); final String[] serverIcons = getResources().getStringArray(serverIconsId); final String serverIcon = serverIcons[serverPosition]; final String[] parts = serverIcon.split("\\."); final String drawableName = parts[parts.length - 1]; final int id = getResources().getIdentifier(drawableName, "drawable", getActivity().getPackageName()); if (id != 0) { serverPreference.setIcon(id); }/*from w ww.j a va 2s. c om*/ } } String bucketSummary = ""; final Set<String> selectedBuckets = preferences.getStringSet(PBConstants.PREF_PICTURE_FOLDER_LIST, null); if (selectedBuckets != null && bucketNames != null) { final ArrayList<String> selectedBucketNames = new ArrayList<>(); for (String entry : selectedBuckets) { String oneName = bucketNames.get(entry); if (oneName != null) { oneName = oneName.substring(0, oneName.lastIndexOf('(') - 1); selectedBucketNames.add(oneName); } } bucketSummary = TextUtils.join(", ", selectedBucketNames); } final MultiSelectListPreference bucketListPreference = (MultiSelectListPreference) findPreference( PBConstants.PREF_PICTURE_FOLDER_LIST); bucketListPreference.setSummary(bucketSummary); }
From source file:pl.selvin.android.syncframework.content.TableInfo.java
final public String CreateStatement() { StringBuilder sb = new StringBuilder("CREATE TABLE IF NOT EXISTS "); sb.append(name);/* www. j av a 2s.c om*/ sb.append(" (["); for (final ColumnInfo column : columns) { sb.append(column.name); sb.append("] "); sb.append(ColumnType.getName(column.type)); sb.append(' '); sb.append(column.extras); if (!column.nullable) sb.append(" NOT NULL "); sb.append(", ["); } sb.append(_.uri + "] varchar, [" + _.tempId + "] GUID, [" + _.isDeleted + "] INTEGER NOT NULL DEFAULT (0)" + " , [" + _.isDirty + "] INTEGER NOT NULL DEFAULT (0), PRIMARY KEY ("); sb.append(TextUtils.join(", ", primaryKeyStrings)); sb.append("));"); String ret = sb.toString(); if (BuildConfig.DEBUG) { Log.d(BaseContentProvider.TAG, "DB-C: " + ret); } return ret; }
From source file:com.chaosinmotion.securechat.network.SCNetwork.java
private HttpURLConnection requestWith(Request req) throws IOException { String path = server + req.requestURI; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); if (cookies.getCookieStore().getCookies().size() > 0) { conn.setRequestProperty("Cookie", TextUtils.join(";", cookies.getCookieStore().getCookies())); }/*from w w w . j a v a2 s . c om*/ conn.setDoInput(true); if (req.params != null) { String jsonString = req.params.toString(); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(jsonString.getBytes("UTF-8")); os.close(); } return conn; }
From source file:com.lillicoder.newsblurry.net.PreferenceCookieStore.java
/** * Updates this store's persistent index of cookie IDs to contain * the given collection of cookie IDs./*from w w w . java 2 s . c o m*/ */ private void updateCookieIds(Set<String> cookieIds) { SharedPreferences.Editor editor = this.getPreferences().edit(); String joinedCookieIds = TextUtils.join(PREFERENCE_COOKIE_IDS_DELIMITER, cookieIds); editor.putString(PREFERENCE_COOKIE_IDS, joinedCookieIds); editor.commit(); }
From source file:it.geosolutions.geocollect.android.core.mission.utils.MissionUtils.java
/** * get "created" {@link MissionFeature} from the database, adding the distance property if possible * @param tableName//from w ww. j a va2 s .c o m * @param db * @return a list of created {@link MissionFeature} */ public static ArrayList<MissionFeature> getMissionFeatures(final String mTableName, final Database db, Context ctx) { ArrayList<MissionFeature> mFeaturesList = new ArrayList<MissionFeature>(); String tableName = mTableName; // Reader for the Geometry field WKBReader wkbReader = new WKBReader(); //create query //////////////////////////////////////////////////////////////// // SQLite Geometry cannot be read with direct wkbreader // We must do a double conversion with ST_AsBinary and CastToXY //////////////////////////////////////////////////////////////// // Cycle all the columns to find the "Point" type one HashMap<String, String> columns = SpatialiteUtils.getPropertiesFields(db, tableName); if (columns == null) { if (BuildConfig.DEBUG) { Log.w(TAG, "Cannot retrieve columns from database"); } return mFeaturesList; } List<String> selectFields = new ArrayList<String>(); for (String columnName : columns.keySet()) { //Spatialite custom field point if ("point".equalsIgnoreCase(columns.get(columnName))) { selectFields.add("ST_AsBinary(CastToXY(" + columnName + ")) AS GEOMETRY"); } else { selectFields.add(columnName); } } // Merge all the column names String selectString = TextUtils.join(",", selectFields); if (ctx != null) { SharedPreferences prefs = ctx.getSharedPreferences(SQLiteCascadeFeatureLoader.PREF_NAME, Context.MODE_PRIVATE); boolean useDistance = prefs.getBoolean(SQLiteCascadeFeatureLoader.ORDER_BY_DISTANCE, false); double posX = Double.longBitsToDouble( prefs.getLong(SQLiteCascadeFeatureLoader.LOCATION_X, Double.doubleToLongBits(0))); double posY = Double.longBitsToDouble( prefs.getLong(SQLiteCascadeFeatureLoader.LOCATION_Y, Double.doubleToLongBits(0))); if (useDistance) { selectString = selectString + ", Distance(ST_Transform(GEOMETRY,4326), MakePoint(" + posX + "," + posY + ", 4326)) * 111195 AS '" + MissionFeature.DISTANCE_VALUE_ALIAS + "'"; } //Add Spatial filtering int filterSrid = prefs.getInt(SQLiteCascadeFeatureLoader.FILTER_SRID, -1); // If the SRID is not defined, skip the filter if (filterSrid != -1) { double filterN = Double.longBitsToDouble( prefs.getLong(SQLiteCascadeFeatureLoader.FILTER_N, Double.doubleToLongBits(0))); double filterS = Double.longBitsToDouble( prefs.getLong(SQLiteCascadeFeatureLoader.FILTER_S, Double.doubleToLongBits(0))); double filterW = Double.longBitsToDouble( prefs.getLong(SQLiteCascadeFeatureLoader.FILTER_W, Double.doubleToLongBits(0))); double filterE = Double.longBitsToDouble( prefs.getLong(SQLiteCascadeFeatureLoader.FILTER_E, Double.doubleToLongBits(0))); tableName += " WHERE MbrIntersects(GEOMETRY, BuildMbr(" + filterW + ", " + filterN + ", " + filterE + ", " + filterS + ")) "; } } // Build the query StringWriter queryWriter = new StringWriter(); queryWriter.append("SELECT ").append(selectString).append(" FROM ").append(tableName).append(";"); // The resulting query String query = queryWriter.toString(); Stmt stmt; //do the query if (jsqlite.Database.complete(query)) { try { if (BuildConfig.DEBUG) { Log.i("getCreatedMissionFeatures", "Loading from query: " + query); } stmt = db.prepare(query); MissionFeature f; while (stmt.step()) { f = new MissionFeature(); SpatialiteUtils.populateFeatureFromStmt(wkbReader, stmt, f); if (f.geometry == null) { //workaround for a bug which does not read out the "Point" geometry in WKBreader //read single x and y coordinates instead and create the geometry by hand double[] xy = PersistenceUtils.getXYCoord(db, tableName, f.id); if (xy != null) { GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), 4326); f.geometry = geometryFactory.createPoint(new Coordinate(xy[0], xy[1])); } } f.typeName = mTableName; mFeaturesList.add(f); } stmt.close(); } catch (Exception e) { Log.d(TAG, "Error getCreatedMissions", e); } } else { if (BuildConfig.DEBUG) { Log.w(TAG, "Query is not complete: " + query); } } return mFeaturesList; }
From source file:org.apps8os.logger.android.fragment.LoggerPanelFragment.java
private void updateEventList() { if (mShownContent == null) { mShownContent = new ArrayList<HashMap<String, Object>>(); } else {/*from ww w . j av a 2s.com*/ if (!mShownContent.isEmpty()) { mShownContent.clear(); } } // read data out List<String> list = new ArrayList<String>(); try { list = AppManager.getEventTagsFromAsset(getApplicationContext(), AppManager.getEventTagsJsonFileResId(), R.string.event_json_first_tag, R.string.event_json_second_tag); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String tags = LoggerApp.getInstance().getEventTags(); if (!TextUtils.isEmpty(tags)) { String[] strArray = tags.split(";"); for (String str : strArray) { list.add(str); } } list.add(getString(R.string.add_your_own_event)); for (int i = 0; i < list.size(); i++) { String event = list.get(i); HashMap<String, Object> data = new HashMap<String, Object>(); data.put(ActionEventListAdapter.EVENT, event); data.put(ActionEventListAdapter.DURATION, ""); data.put(ActionEventListAdapter.CHECK, false); if ((i == (list.size() - 1)) || (i < AppManager.getPreCount())) { data.put(ActionEventListAdapter.CUSTOM, false); } else { data.put(ActionEventListAdapter.CUSTOM, true); } mShownContent.add(data); } mAdapter = new ActionEventListAdapter(getApplicationContext(), mShownContent, new OnCustomEventChangeListener() { @Override public void onRemove(final String tag) { if (TextUtils.isEmpty(tag)) return; ActivityNameDeletionDialogFragment.newInstance(new AlertDialogListener() { @Override public void onPositiveClick() { LoggerApp app = LoggerApp.getInstance(); String tags = app.getEventTags(); if (!TextUtils.isEmpty(tags)) { String[] strArray = tags.split(";"); ArrayList<String> tagList = new ArrayList<String>(Arrays.asList(strArray)); tagList.remove(tag); app.saveEventTag( tagList.isEmpty() ? null : TextUtils.join(";", tagList.toArray())); new Handler().postDelayed(new Runnable() { @Override public void run() { updateEventList(); } }, 50L); } } @Override public void onNegativeClick() { } @Override public void onCancel() { } }, tag).show(getFragmentManager()); } }); mListView.setAdapter(mAdapter); mAdapter.notifyDataSetChanged(); mListView.invalidate(); mActionEventList = AppManager.getAllLiveEvents(); }