List of usage examples for java.util ArrayList isEmpty
public boolean isEmpty()
From source file:com.ngdata.hbaseindexer.indexer.FusionPipelineClient.java
public void postBatchToPipeline(List docs) throws Exception { int numDocs = docs.size(); int requestId = requestCounter.incrementAndGet(); ArrayList<String> mutable = getAvailableEndpoints(); if (mutable.size() > 1) { Exception lastExc = null; // try all the endpoints until success is reached ... or we run out of endpoints to try ... while (!mutable.isEmpty()) { String endpoint = getLbEndpoint(mutable); if (endpoint == null) { // no more endpoints available ... fail if (lastExc != null) { log.error("No more endpoints available to retry failed request (" + requestId + ")! raising last seen error: " + lastExc); throw lastExc; } else { throw new RuntimeException("No Fusion pipeline endpoints available to process request " + requestId + "! Check logs for previous errors."); }//from ww w . j a va2 s . c o m } if (log.isDebugEnabled()) log.debug("POSTing batch of " + numDocs + " input docs to " + endpoint + " as request " + requestId); Exception retryAfterException = postJsonToPipelineWithRetry(endpoint, docs, mutable, lastExc, requestId); if (retryAfterException == null) { lastExc = null; break; // request succeeded ... } lastExc = retryAfterException; // try next endpoint (if available) after seeing an exception } if (lastExc != null) { // request failed and we exhausted the list of endpoints to try ... log.error("Failing request " + requestId + " due to: " + lastExc); throw lastExc; } } else { String endpoint = getLbEndpoint(mutable); if (log.isDebugEnabled()) log.debug( "POSTing batch of " + numDocs + " input docs to " + endpoint + " as request " + requestId); Exception exc = postJsonToPipelineWithRetry(endpoint, docs, mutable, null, requestId); if (exc != null) throw exc; } }
From source file:com.slp.rss_api.activity.EditFeedActivity.java
public void onClickOk(View view) { // only in insert mode final String name = mNameEditText.getText().toString().trim(); final String urlOrSearch = mUrlEditText.getText().toString().trim(); if (urlOrSearch.isEmpty()) { Toast.makeText(this, R.string.error_feed_error, Toast.LENGTH_SHORT).show(); }/*from w w w . j a va 2s . com*/ if (!urlOrSearch.contains(".") || !urlOrSearch.contains("/") || urlOrSearch.contains(" ")) { final ProgressDialog pd = new ProgressDialog(EditFeedActivity.this); pd.setMessage(getString(R.string.loading)); pd.setCancelable(true); pd.setIndeterminate(true); pd.show(); getLoaderManager().restartLoader(1, null, new LoaderManager.LoaderCallbacks<ArrayList<HashMap<String, String>>>() { @Override public Loader<ArrayList<HashMap<String, String>>> onCreateLoader(int id, Bundle args) { String encodedSearchText = urlOrSearch; try { encodedSearchText = URLEncoder.encode(urlOrSearch, Constants.UTF8); } catch (UnsupportedEncodingException ignored) { } return new GetFeedSearchResultsLoader(EditFeedActivity.this, encodedSearchText); } @Override public void onLoadFinished(Loader<ArrayList<HashMap<String, String>>> loader, final ArrayList<HashMap<String, String>> data) { pd.cancel(); if (data == null) { Toast.makeText(EditFeedActivity.this, R.string.error, Toast.LENGTH_SHORT).show(); } else if (data.isEmpty()) { Toast.makeText(EditFeedActivity.this, R.string.no_result, Toast.LENGTH_SHORT) .show(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(EditFeedActivity.this); builder.setTitle(R.string.feed_search); // create the grid item mapping String[] from = new String[] { FEED_SEARCH_TITLE, FEED_SEARCH_DESC }; int[] to = new int[] { android.R.id.text1, android.R.id.text2 }; // fill in the grid_item layout SimpleAdapter adapter = new SimpleAdapter(EditFeedActivity.this, data, R.layout.item_search_result, from, to); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { FeedDataContentProvider.addFeed(EditFeedActivity.this, data.get(which).get(FEED_SEARCH_URL), name.isEmpty() ? data.get(which).get(FEED_SEARCH_TITLE) : name, mRetrieveFulltextCb.isChecked()); setResult(RESULT_OK); finish(); } }); builder.show(); } } @Override public void onLoaderReset(Loader<ArrayList<HashMap<String, String>>> loader) { } }); } else { FeedDataContentProvider.addFeed(EditFeedActivity.this, urlOrSearch, name, mRetrieveFulltextCb.isChecked()); setResult(RESULT_OK); finish(); } }
From source file:fr.paris.lutece.plugins.workflow.modules.notifygru.service.Validator.java
/** * Checks if is valide build agent.//from w w w. ja v a 2 s .com * * @param request the request * @param config the config * @param providerService the _provider service * @param locale the locale * @param strApply the str apply * @return the string */ public static String isValideBuildAgent(HttpServletRequest request, TaskNotifyGruConfig config, AbstractServiceProvider providerService, Locale locale, String strApply) { String strUrlRedirector = ""; /*Agent*/ ArrayList<String> errors = new ArrayList<String>(); String strMessageAgent = request.getParameter(Constants.PARAMETER_STATUS_MESSAGE_AGENT); String strStatutTextAgent = request.getParameter(Constants.PARAMETER_STATUS_TEXT_AGENT); if (StringUtils.isBlank(strApply)) { if (StringUtils.isNotBlank( Validator.mandotoryParams(strMessageAgent, Constants.MESSAGE_AGENT_FIELD_MESSAGE, locale))) { errors.add( Validator.mandotoryParams(strMessageAgent, Constants.MESSAGE_AGENT_FIELD_MESSAGE, locale)); } if (StringUtils.isNotBlank( Validator.mandotoryParams(strStatutTextAgent, Constants.MESSAGE_AGENT_FIELD_STATUS, locale))) { errors.add(Validator.mandotoryParams(strStatutTextAgent, Constants.MESSAGE_AGENT_FIELD_STATUS, locale)); } if (!Validator.isFreemarkerValid(strMessageAgent, locale, providerService.getInfos(-1))) { Object[] tabRequiredFields = { I18nService.getLocalizedString(Constants.MESSAGE_ERROR_FREEMARKER, locale), }; strUrlRedirector = AdminMessageService.getMessageUrl(request, Constants.MESSAGE_ERROR_FREEMARKER, tabRequiredFields, AdminMessage.TYPE_STOP); } } if (!errors.isEmpty()) { strUrlRedirector = ServiceConfigTaskForm.displayErrorMessage(errors, request); } if (StringUtils.isBlank(strUrlRedirector)) { config.setMessageAgent(strMessageAgent); config.setStatustextAgent(strStatutTextAgent); } return strUrlRedirector; }
From source file:gov.nih.nci.cabig.caaers.datamigrator.MedicalDeviceDataMigrator.java
/** * Will associate the medical devices to Study device after creating equivalent * StudyDevices (of type other). //from w w w .j av a 2s . co m * Step 1: Find the study, and medical device projection. * Step 2: Create unique study device per-study * Step 3: Associate Medical Device to Study Device * @param context */ //NOTE : BJ : Assumed that the number of records to migrate will be less than 100. @Override public void migrate(CaaersDataMigrationContext context) { String query = "select so.study_id, md.id, md.brand_name, md.common_name, md.device_type,md.manufacturer_name, " + "md.manufacturer_city, md.manufacturer_state, md.model_number, md.catalog_number " + "from ae_medical_devices md " + "join ae_reports r on r.id = md.report_id " + "join ae_reporting_periods rp on rp.id = r.reporting_period_id " + "join participant_assignments a on rp.assignment_id=a.id " + "join study_organizations so on so.id = a.study_site_id " + "order by so.study_id"; HashMap<String, ArrayList<StudyDeviceWrapper>> studyDeviceMap = (HashMap<String, ArrayList<StudyDeviceWrapper>>) getJdbcTemplate() .query(query, new ResultSetExtractor() { public Object extractData(ResultSet rs) throws SQLException, DataAccessException { //a data structure to hold the merged study device -to- medical device mapping. final HashMap<String, ArrayList<StudyDeviceWrapper>> studyDeviceMap = new HashMap<String, ArrayList<StudyDeviceWrapper>>(); String studyId = null; ArrayList<StudyDeviceWrapper> studyDeviceWrapperList = null; while (rs.next()) { studyId = getString(rs, 1); String mdId = getString(rs, 2); StudyDevice sd = new StudyDevice(); sd.setOtherBrandName(getString(rs, 3)); sd.setOtherCommonName(getString(rs, 4)); sd.setOtherDeviceType(getString(rs, 5)); sd.setManufacturerName(getString(rs, 6)); sd.setManufacturerCity(getString(rs, 7)); sd.setManufacturerState(getString(rs, 8)); sd.setModelNumber(getString(rs, 9)); sd.setCatalogNumber(getString(rs, 10)); studyDeviceWrapperList = studyDeviceMap.get(studyId); if (studyDeviceWrapperList == null) { //new study studyDeviceWrapperList = new ArrayList<StudyDeviceWrapper>(); studyDeviceMap.put(studyId, studyDeviceWrapperList); } StudyDeviceWrapper wrapper = StudyDeviceWrapper .findStudyDeviceWrapper(studyDeviceWrapperList, sd); if (wrapper == null) { //new study device wrapper = new StudyDeviceWrapper(studyId, sd, mdId); studyDeviceWrapperList.add(wrapper); } else { //merge to existing study device wrapper.addMedicalDeviceId(mdId); } } return studyDeviceMap; } //some PostgresSQL driver will throw NPE when column is SQL NULL // so this workaround.... public String getString(ResultSet rs, int index) throws SQLException { Object o = rs.getObject(index); if (o == null) return null; return String.valueOf(o); } }); //now generate the batch statements. ArrayList<String> sqls = new ArrayList<String>(); for (String key : studyDeviceMap.keySet()) { ArrayList<StudyDeviceWrapper> wrapperList = studyDeviceMap.get(key); for (StudyDeviceWrapper wrapper : wrapperList) { sqls.add(generateInsertStudyDeviceSQL(context, wrapper)); //insert study device. sqls.addAll(generateUpdateMedicalDeviceSQL(wrapper)); // scripts to udpate the medical device } } if (log.isDebugEnabled()) { log.debug("SQLs to run [MedicalDeviceDataMigrator] ..."); for (String sql : sqls) log.debug(" >>> " + sql); } if (!sqls.isEmpty()) getJdbcTemplate().batchUpdate(sqls.toArray(new String[] {})); }
From source file:info.savestate.saveybot.JSONFileManipulator.java
public String chainall(boolean verbose, int sentenceSize) { JSONArray json = getJSON();//www. ja v a 2 s . c om ArrayList<String> words = new ArrayList<>(); for (int i = 0; i < json.length(); i++) { JSONObject savestate = json.getJSONObject(i); String[] splitMessage = savestate.getString("message").split("\\s+"); words.addAll(Arrays.asList(splitMessage)); } if (words.isEmpty()) { return "lmao WTF this ERROR should never happen!!! (ZERO SAVESTATES ??? WTF)"; } StringBuilder sb = new StringBuilder(); // all words are in "words" // pick a word out at random! int wordIndex = (int) (Math.random() * words.size()); if (sentenceSize <= 0) sentenceSize = ((int) (Math.random() * 12)) + 3; if (sentenceSize > 50) sentenceSize = 50; for (int i = 0; i < sentenceSize; i++) { // get current word sb.append(words.get(wordIndex)).append(' '); // 40% chance we'll stay on the same sentence. if (Math.random() > 0.40) { // different sentence // make an array of all the .toLowerCase() matches of the current word ArrayList<Integer> wordIndexes = new ArrayList<>(); for (int j = 0; j < words.size(); j++) { if (words.get(j).equalsIgnoreCase(words.get(wordIndex))) wordIndexes.add(j); } // we have all the word indexes in wordIndexes // ... if there are none, we'll just follow the current word (since it'll match) int sameWordIndex = (int) (Math.random() * wordIndexes.size()); wordIndex = wordIndexes.get(sameWordIndex) + 1; } else { wordIndex++; } if (wordIndex >= words.size()) { // in case we go over!!! // new random number wordIndex = (int) (Math.random() * words.size()); } } return sb.toString(); }
From source file:com.facebook.FacebookActivityTestCase.java
protected TestGraphRequestAsyncTask createAsyncTaskOnUiThread(final GraphRequest... requests) throws Throwable { final ArrayList<TestGraphRequestAsyncTask> result = new ArrayList<TestGraphRequestAsyncTask>(); runTestOnUiThread(new Runnable() { @Override/*from www . j a v a2 s . c om*/ public void run() { result.add(new TestGraphRequestAsyncTask(requests)); } }); return result.isEmpty() ? null : result.get(0); }
From source file:com.willwinder.universalgcodesender.GrblController.java
@Override public void returnToHome() throws Exception { if (this.isCommOpen()) { ArrayList<String> commands = GrblUtils.getReturnToHomeCommands(this.grblVersion, this.grblVersionLetter, this.controllerStatus.getWorkCoord().z); if (!commands.isEmpty()) { Iterator<String> iter = commands.iterator(); // Perform the homing commands while (iter.hasNext()) { String gcode = iter.next(); GcodeCommand command = createCommand(gcode); this.sendCommandImmediately(command); }//from w w w . jav a 2 s .c o m return; } restoreParserModalState(); } // Throw exception super.returnToHome(); }
From source file:com.erudika.para.persistence.CassandraDAO.java
@Override public <P extends ParaObject> void deleteAll(String appid, List<P> objects) { if (objects == null || objects.isEmpty() || StringUtils.isBlank(appid)) { return;/*from www .j a v a2 s . c o m*/ } try { ArrayList<String> values = new ArrayList<String>(objects.size()); StringBuilder batch = new StringBuilder("BEGIN BATCH "); for (ParaObject so : objects) { if (so != null) { so.setAppid(appid); batch.append("DELETE FROM ").append(CassandraUtils.getTableNameForAppid(appid)) .append(" WHERE id = ?;"); values.add(so.getId()); } } if (!values.isEmpty()) { batch.append("APPLY BATCH"); PreparedStatement ps = getClient().prepare(batch.toString()); getClient().execute(ps.bind(values.toArray())); } } catch (Exception e) { logger.error(null, e); } logger.debug("DAO.deleteAll() {}", objects.size()); }
From source file:net.fred.feedex.activity.EditFeedActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish();/* w ww .j a v a2 s .co m*/ return true; case R.id.menu_validate: // only in insert mode final String name = mNameEditText.getText().toString().trim(); final String urlOrSearch = mUrlEditText.getText().toString().trim(); if (urlOrSearch.isEmpty()) { UiUtils.showMessage(EditFeedActivity.this, R.string.error_feed_error); } if (!urlOrSearch.contains(".") || !urlOrSearch.contains("/") || urlOrSearch.contains(" ")) { final ProgressDialog pd = new ProgressDialog(EditFeedActivity.this); pd.setMessage(getString(R.string.loading)); pd.setCancelable(true); pd.setIndeterminate(true); pd.show(); getLoaderManager().restartLoader(1, null, new LoaderManager.LoaderCallbacks<ArrayList<HashMap<String, String>>>() { @Override public Loader<ArrayList<HashMap<String, String>>> onCreateLoader(int id, Bundle args) { String encodedSearchText = urlOrSearch; try { encodedSearchText = URLEncoder.encode(urlOrSearch, Constants.UTF8); } catch (UnsupportedEncodingException ignored) { } return new GetFeedSearchResultsLoader(EditFeedActivity.this, encodedSearchText); } @Override public void onLoadFinished(Loader<ArrayList<HashMap<String, String>>> loader, final ArrayList<HashMap<String, String>> data) { pd.cancel(); if (data == null) { UiUtils.showMessage(EditFeedActivity.this, R.string.error); } else if (data.isEmpty()) { UiUtils.showMessage(EditFeedActivity.this, R.string.no_result); } else { AlertDialog.Builder builder = new AlertDialog.Builder(EditFeedActivity.this); builder.setTitle(R.string.feed_search); // create the grid item mapping String[] from = new String[] { FEED_SEARCH_TITLE, FEED_SEARCH_DESC }; int[] to = new int[] { android.R.id.text1, android.R.id.text2 }; // fill in the grid_item layout SimpleAdapter adapter = new SimpleAdapter(EditFeedActivity.this, data, R.layout.item_search_result, from, to); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { FeedDataContentProvider.addFeed(EditFeedActivity.this, data.get(which).get(FEED_SEARCH_URL), name.isEmpty() ? data.get(which).get(FEED_SEARCH_TITLE) : name, mRetrieveFulltextCb.isChecked()); setResult(RESULT_OK); finish(); } }); builder.show(); } } @Override public void onLoaderReset(Loader<ArrayList<HashMap<String, String>>> loader) { } }); } else { FeedDataContentProvider.addFeed(EditFeedActivity.this, urlOrSearch, name, mRetrieveFulltextCb.isChecked()); setResult(RESULT_OK); finish(); } return true; case R.id.menu_add_filter: { final View dialogView = getLayoutInflater().inflate(R.layout.dialog_filter_edit, null); new AlertDialog.Builder(this) // .setTitle(R.string.filter_add_title) // .setView(dialogView) // .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { String filterText = ((EditText) dialogView.findViewById(R.id.filterText)).getText() .toString(); if (filterText.length() != 0) { String feedId = getIntent().getData().getLastPathSegment(); ContentValues values = new ContentValues(); values.put(FilterColumns.FILTER_TEXT, filterText); values.put(FilterColumns.IS_REGEX, ((CheckBox) dialogView.findViewById(R.id.regexCheckBox)).isChecked()); values.put(FilterColumns.IS_APPLIED_TO_TITLE, ((RadioButton) dialogView.findViewById(R.id.applyTitleRadio)).isChecked()); values.put(FilterColumns.IS_ACCEPT_RULE, ((RadioButton) dialogView.findViewById(R.id.acceptRadio)).isChecked()); ContentResolver cr = getContentResolver(); cr.insert(FilterColumns.FILTERS_FOR_FEED_CONTENT_URI(feedId), values); } } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }).show(); return true; } default: return super.onOptionsItemSelected(item); } }
From source file:it.grid.storm.namespace.config.xml.XMLNamespaceParser.java
/** * @param poolMembers//from w w w.j av a 2 s . c o m * @throws NamespaceException */ private void verifyPoolIsValid(ArrayList<PoolMember> poolMembers) throws NamespaceException { if (poolMembers.isEmpty()) { throw new NamespaceException("POOL Defined is EMPTY!"); } Protocol prot = poolMembers.get(0).getMemberProtocol().getProtocol(); for (PoolMember member : poolMembers) { if (!(member.getMemberProtocol().getProtocol().equals(prot))) { throw new NamespaceException("Defined Pool is NOT HOMOGENEOUS! Protocols " + prot.toString() + " and " + member.toString() + " differs"); } } }