List of usage examples for java.util ArrayList isEmpty
public boolean isEmpty()
From source file:com.predic8.membrane.core.interceptor.apimanagement.statistics.AMStatisticsCollector.java
private String combineJsons(String name, ArrayList<String> jsonStatisticsForRequests) throws IOException { JsonGenerator gen = getAndResetJsonGenerator(); try {//from w ww. j a va 2 s. c o m gen.writeStartObject(); gen.writeArrayFieldStart(name); if (!jsonStatisticsForRequests.isEmpty()) gen.writeRaw(jsonStatisticsForRequests.get(0)); for (int i = 1; i < jsonStatisticsForRequests.size(); i++) { gen.writeRaw("," + jsonStatisticsForRequests.get(i)); } gen.writeEndArray(); gen.writeEndObject(); } catch (IOException e) { e.printStackTrace(); } return getStringFromJsonGenerator(); }
From source file:msgclient.MsgClient.java
public void listUsers() throws Exception { System.out.println("Getting list of user IDs from server..."); ArrayList<String> users = mServerConnection.lookupUsers(); if (users == null) { System.out.println("Could not reach the server"); return;//from w w w . j a v a 2 s . com } else if (users.isEmpty()) { System.out.println("No users yet"); return; } // Display the list of users for (int i = 0; i < users.size(); i++) { System.out.println(i + ":" + users.get(i)); } System.out.println(""); return; }
From source file:co.carlosandresjimenez.gotit.backend.controller.GotItSvc.java
@RequestMapping(value = ANSWER_PATH, method = RequestMethod.POST) public @ResponseBody int saveAnswers(@RequestBody ArrayList<Answer> answers, HttpServletRequest request) { if (answers == null || answers.isEmpty()) { return RESPONSE_STATUS_NOT_SAVED; }//from w ww . j a v a2 s . com Checkin checkin; String email = (String) request.getAttribute("email"); if (email == null || email.isEmpty()) { return RESPONSE_STATUS_AUTH_REQUIRED; } int lastAnswerPosition = answers.size() - 1; Answer lastAnswer = answers.get(lastAnswerPosition); try { checkin = checkinRepository.save( new Checkin(null, email, Utility.getDatetime(), Boolean.parseBoolean(lastAnswer.getValue()))); } catch (JDOException e) { e.printStackTrace(); return RESPONSE_STATUS_NOT_SAVED; } answers.remove(lastAnswerPosition); for (Answer answer : answers) { answer.setCheckinId(checkin.getCheckinId()); } ArrayList<Answer> result; try { result = (ArrayList<Answer>) answerRepository.save(answers); } catch (JDOException e) { e.printStackTrace(); return RESPONSE_STATUS_NOT_SAVED; } if (result == null || result.isEmpty()) { return RESPONSE_STATUS_NOT_SAVED; } if (result.size() != answers.size()) { return RESPONSE_STATUS_NOT_SAVED; } return RESPONSE_STATUS_OK; }
From source file:cn.webwheel.DefaultMain.java
private Action getAction(Class cls, Method method) { if (Modifier.isStatic(method.getModifiers())) { return method.getAnnotation(Action.class); }/*from w ww .j a v a 2 s . c om*/ ArrayList<Action> actions = new ArrayList<Action>(); getActions(actions, new HashSet<Class>(), cls, method); if (actions.isEmpty()) return null; if (actions.get(0).disabled()) return null; if (actions.size() == 1) return actions.get(0); ActionImpl action = new ActionImpl(); for (Action act : actions) { if (action.merge(act)) { return action; } } return action; }
From source file:com.foxykeep.datadroid.internal.network.NetworkConnectionImplF.java
/** * Call the webservice using the given parameters to construct the request and return the * result./*w w w . ja va 2s . com*/ * * @param context The context to use for this operation. Used to generate the user agent if * needed. * @param urlValue The webservice URL. * @param method The request method to use. * @param parameterList The parameters to add to the request. * @param headerMap The headers to add to the request. * @param isGzipEnabled Whether the request will use gzip compression if available on the * server. * @param userAgent The user agent to set in the request. If null, a default Android one will be * created. * @param postText The POSTDATA text to add in the request. * @param credentials The credentials to use for authentication. * @param isSslValidationEnabled Whether the request will validate the SSL certificates. * @return The result of the webservice call. */ public static ConnectionResult execute(Context context, String urlValue, Method method, ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled, String userAgent, String postText, UsernamePasswordCredentials credentials, boolean isSslValidationEnabled, File file) throws ConnectionException { HttpURLConnection connection = null; try { // Prepare the request information if (userAgent == null) { userAgent = UserAgentUtils.get(context); } if (headerMap == null) { headerMap = new HashMap<String, String>(); } headerMap.put(HTTP.USER_AGENT, userAgent); if (isGzipEnabled) { headerMap.put(ACCEPT_ENCODING_HEADER, "gzip"); } headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET); if (credentials != null) { headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials)); } StringBuilder paramBuilder = new StringBuilder(); if (parameterList != null && !parameterList.isEmpty()) { for (int i = 0, size = parameterList.size(); i < size; i++) { BasicNameValuePair parameter = parameterList.get(i); String name = parameter.getName(); String value = parameter.getValue(); if (TextUtils.isEmpty(name)) { // Empty parameter name. Check the next one. continue; } if (value == null) { value = ""; } paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET)); paramBuilder.append("="); paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET)); paramBuilder.append("&"); } } // Log the request if (DataDroidLog.canLog(Log.DEBUG)) { DataDroidLog.d(TAG, "Request url: " + urlValue); DataDroidLog.d(TAG, "Method: " + method.toString()); if (parameterList != null && !parameterList.isEmpty()) { DataDroidLog.d(TAG, "Parameters:"); for (int i = 0, size = parameterList.size(); i < size; i++) { BasicNameValuePair parameter = parameterList.get(i); String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\""; DataDroidLog.d(TAG, message); } DataDroidLog.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\""); } if (postText != null) { DataDroidLog.d(TAG, "Post data: " + postText); } if (headerMap != null && !headerMap.isEmpty()) { DataDroidLog.d(TAG, "Headers:"); for (Entry<String, String> header : headerMap.entrySet()) { DataDroidLog.d(TAG, "- " + header.getKey() + " = " + header.getValue()); } } } // Create the connection object URL url = null; String outputText = null; switch (method) { case GET: case DELETE: String fullUrlValue = urlValue; if (paramBuilder.length() > 0) { fullUrlValue += "?" + paramBuilder.toString(); } url = new URL(fullUrlValue); connection = (HttpURLConnection) url.openConnection(); break; case PUT: case POST: url = new URL(urlValue); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); if (paramBuilder.length() > 0) { outputText = paramBuilder.toString(); headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length)); } else if (postText != null) { outputText = postText; } break; } // Set the request method connection.setRequestMethod(method.toString()); // If it's an HTTPS request and the SSL Validation is disabled if (url.getProtocol().equals("https") && !isSslValidationEnabled) { HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory()); httpsConnection.setHostnameVerifier(getAllHostsValidVerifier()); } // Add the headers if (!headerMap.isEmpty()) { for (Entry<String, String> header : headerMap.entrySet()) { connection.addRequestProperty(header.getKey(), header.getValue()); } } // Set the connection and read timeout connection.setConnectTimeout(OPERATION_TIMEOUT); connection.setReadTimeout(READ_OPERATION_TIMEOUT); // Set the outputStream content for POST and PUT requests if ((method == Method.POST || method == Method.PUT) && outputText != null) { OutputStream output = null; try { output = connection.getOutputStream(); output.write(outputText.getBytes()); } finally { if (output != null) { try { output.close(); } catch (IOException e) { // Already catching the first IOException so nothing to do here. } } } } String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING); int responseCode = connection.getResponseCode(); boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip"); DataDroidLog.d(TAG, "Response code: " + responseCode); if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) { String redirectionUrl = connection.getHeaderField(LOCATION_HEADER); throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl); } InputStream errorStream = connection.getErrorStream(); if (errorStream != null) { throw new ConnectionException("error", responseCode); } String body = convertStreamToString(connection.getInputStream(), isGzip, file, context); return new ConnectionResult(connection.getHeaderFields(), body); } catch (IOException e) { DataDroidLog.e(TAG, "IOException", e); throw new ConnectionException(e); } catch (KeyManagementException e) { DataDroidLog.e(TAG, "KeyManagementException", e); throw new ConnectionException(e); } catch (NoSuchAlgorithmException e) { DataDroidLog.e(TAG, "NoSuchAlgorithmException", e); throw new ConnectionException(e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:SportsBroadcastsSpeechlet.java
/** * Prepares the speech to reply to the user. Obtain events from Wikipedia for the date specified * by the user (or for today's date, if no date is specified), and return those events in both * speech and SimpleCard format./* ww w . j a v a 2 s . c o m*/ * * @param intent * the intent object which contains the date slot * @param session * the session object * @return SpeechletResponse object with voice/card response to return to the user */ private SpeechletResponse handleFirstEventRequest(Intent intent, Session session) { Calendar calendar = getCalendar(intent); String month = MONTH_NAMES[calendar.get(Calendar.MONTH)]; String date = Integer.toString(calendar.get(Calendar.DATE)); String speechPrefixContent = "<p>For " + month + " " + date + "</p> "; String cardPrefixContent = "For " + month + " " + date + ", "; String cardTitle = "Events on " + month + " " + date; ArrayList<String> events = getJsonEventsFromWikipedia(month, date); String speechOutput = ""; if (events.isEmpty()) { speechOutput = "There is a problem connecting to Wikipedia at this time." + " Please try again later."; // Create the plain text output SsmlOutputSpeech outputSpeech = new SsmlOutputSpeech(); outputSpeech.setSsml("<speak>" + speechOutput + "</speak>"); return SpeechletResponse.newTellResponse(outputSpeech); } else { StringBuilder speechOutputBuilder = new StringBuilder(); speechOutputBuilder.append(speechPrefixContent); StringBuilder cardOutputBuilder = new StringBuilder(); cardOutputBuilder.append(cardPrefixContent); for (int i = 0; i < PAGINATION_SIZE; i++) { speechOutputBuilder.append("<p>"); speechOutputBuilder.append(events.get(i)); speechOutputBuilder.append("</p> "); cardOutputBuilder.append(events.get(i)); cardOutputBuilder.append("\n"); } speechOutputBuilder.append(" Wanna go deeper in history?"); cardOutputBuilder.append(" Wanna go deeper in history?"); speechOutput = speechOutputBuilder.toString(); String repromptText = "With History Buff, you can get historical events for any day of the year." + " For example, you could say today, or August thirtieth." + " Now, which day do you want?"; // Create the Simple card content. SimpleCard card = new SimpleCard(); card.setTitle(cardTitle); card.setContent(cardOutputBuilder.toString()); // After reading the first 3 events, set the count to 3 and add the events // to the session attributes session.setAttribute(SESSION_INDEX, PAGINATION_SIZE); session.setAttribute(SESSION_TEXT, events); SpeechletResponse response = newAskResponse("<speak>" + speechOutput + "</speak>", true, repromptText, false); response.setCard(card); return response; } }
From source file:MSUmpire.LCMSPeakStructure.LCMSPeakMS1.java
public void AssignMappedPepQuant() throws SQLException, IOException { if (IDsummary == null || IDsummary.GetMappedPepIonList().isEmpty()) { return;/* w w w .j a va2 s .c o m*/ } if (!FilenameUtils.getBaseName(IDsummary.mzXMLFileName) .equals(FilenameUtils.getBaseName(ScanCollectionName))) { return; } Logger.getRootLogger().info("Assigning peak cluster to mapped peptide IDs......"); for (PepIonID pepIonID : IDsummary.GetMappedPepIonList().values()) { pepIonID.CreateQuantInstance(MaxNoPeakCluster); ArrayList<PeakCluster> clusterList = FindAllPeakClustersForMappedPep(pepIonID); if (!clusterList.isEmpty()) { PeakCluster targetCluster = null; float Score = 0f; for (int i = 0; i < clusterList.size(); i++) { PeakCluster cluster = clusterList.get(i); if ("".equals(cluster.AssignedPepIon)) { Score = cluster.PeakHeight[0] * cluster.MS1Score; if (targetCluster == null || clusterList.get(i).MS1Score > Score) { targetCluster = cluster; Score = cluster.MS1Score; } } } if (targetCluster != null) { pepIonID.PeakArea = targetCluster.PeakArea; pepIonID.PeakHeight = targetCluster.PeakHeight; pepIonID.MS1PeakClusters.add(targetCluster); pepIonID.PeakClusterScore = targetCluster.MS1Score; pepIonID.PeakRT = targetCluster.PeakHeightRT[0]; pepIonID.ObservedMz = targetCluster.mz[0]; targetCluster.AssignedPepIon = pepIonID.GetKey(); } } } }
From source file:main.ScorePipeline.java
/** * This method calculates similarities bin-based between yeast_human spectra * on the first data set against all yeast spectra on the second data set * * @param min_mz//from w ww.j av a 2s. co m * @param max_mz * @param topN * @param percentage * @param yeast_and_human_file * @param is_precursor_peak_removal * @param fragment_tolerance * @param noiseFiltering * @param transformation * @param intensities_sum_or_mean_or_median * @param yeast_spectra * @param bw * @param charge * @param charge_situation * @throws IllegalArgumentException * @throws ClassNotFoundException * @throws IOException * @throws MzMLUnmarshallerException * @throws NumberFormatException * @throws ExecutionException * @throws InterruptedException */ private static void calculate_BinBasedScores(ArrayList<BinMSnSpectrum> yeast_spectra, ArrayList<BinMSnSpectrum> yeast_human_spectra, BufferedWriter bw, int charge, double precursorTol, double fragTol, String scoreType) throws IllegalArgumentException, ClassNotFoundException, IOException, MzMLUnmarshallerException, NumberFormatException, InterruptedException { ExecutorService excService = Executors .newFixedThreadPool(ConfigHolder.getInstance().getInt("thread.numbers")); List<Future<SimilarityResult>> futureList = new ArrayList<>(); for (BinMSnSpectrum binYeastHumanSp : yeast_human_spectra) { int tmpMSCharge = binYeastHumanSp.getSpectrum().getPrecursor().getPossibleCharges().get(0).value; if (charge == 0 || tmpMSCharge == charge) { if (!binYeastHumanSp.getSpectrum().getPeakList().isEmpty() && !yeast_spectra.isEmpty()) { Calculate_Similarity similarity = new Calculate_Similarity(binYeastHumanSp, yeast_spectra, fragTol, precursorTol); Future future = excService.submit(similarity); futureList.add(future); } } } SimilarityMethods method = SimilarityMethods.NORMALIZED_DOT_PRODUCT_STANDARD; if (scoreType.equals("spearman")) { method = SimilarityMethods.SPEARMANS_CORRELATION; } else if (scoreType.equals("pearson")) { method = SimilarityMethods.PEARSONS_CORRELATION; } for (Future<SimilarityResult> future : futureList) { try { SimilarityResult get = future.get(); String tmp_charge = get.getSpectrumChargeAsString(), spectrum = get.getSpectrumName(); double tmpPrecMZ = get.getSpectrumPrecursorMZ(), score = get.getScores().get(method); if (score == Double.MIN_VALUE) { LOGGER.info("The similarity for the spectrum " + spectrum + " is too small to keep the record, therefore score is not computed."); // Means that score has not been calculated! // bw.write(tmp_Name + "\t" + tmp_charge + "\t" + tmpPrecMZ + "\t"); // bw.write("NA" + "\t" + "NA" + "\t" + "NA" + "\t" + "NA"); } else { bw.write(spectrum + "\t" + tmp_charge + "\t" + tmpPrecMZ + "\t" + get.getSpectrumToCompare() + "\t" + score + "\n"); } } catch (InterruptedException | ExecutionException e) { LOGGER.error(e); } } }
From source file:com.karmick.android.citizenalert.alarm.AlarmAddActivity.java
protected void validateAndSaveAlarm() { // All alarm data is created here ArrayList<String> errs = setAlarmData(); if (errs != null && !errs.isEmpty()) { String errs_str = "\n"; for (String s : errs) { errs_str += "" + s + "\n"; }// ww w . j a v a2 s. c o m Popups.showOkPopup(AlarmAddActivity.this, errs_str, new CustomDialogCallback() { @Override public void onOkClick() { } }); } else { AlarmDatabase maDb = new AlarmDatabase(this); maDb.createDatabase(); maDb.open(); if (getMathAlarm().getId() < 1) { maDb.create(getMathAlarm()); } else { maDb.update(getMathAlarm()); } maDb.close(); callMathAlarmScheduleService(); Toast.makeText(AlarmAddActivity.this, getMathAlarm().getTimeUntilNextAlarmMessage(), Toast.LENGTH_LONG) .show(); finish(); } }
From source file:co.carlosandresjimenez.gotit.backend.controller.GotItSvc.java
@RequestMapping(value = FOLLOWING_TIMELINE_PATH, method = RequestMethod.GET) public @ResponseBody ArrayList<Checkin> getFollowingTimeline(HttpServletRequest request) { String userEmail = (String) request.getAttribute("email"); if (userEmail == null || userEmail.isEmpty()) { return null; // RESPONSE_STATUS_AUTH_REQUIRED; }/* w w w. j av a2s. c om*/ ArrayList<String> followingUsers = Lists .newArrayList(followingRepository.findFollowingUsersEmails(userEmail)); if (followingUsers.isEmpty()) return null; return Lists.newArrayList(checkinRepository.findByListOfEmails(followingUsers)); }