List of usage examples for java.util ArrayList clear
public void clear()
From source file:com.android.mms.transaction.MessagingNotification.java
/** * updateNotification is *the* main function for building the actual notification handed to * the NotificationManager/*from ww w . ja va2 s. c om*/ * @param context * @param newThreadId the new thread id * @param uniqueThreadCount * @param notificationSet the set of notifications to display */ private static void updateNotification(Context context, long newThreadId, int uniqueThreadCount, SortedSet<NotificationInfo> notificationSet) { boolean isNew = newThreadId != THREAD_NONE; CMConversationSettings conversationSettings = CMConversationSettings.getOrNew(context, newThreadId); // If the user has turned off notifications in settings, don't do any notifying. if ((isNew && !conversationSettings.getNotificationEnabled()) || !MessagingPreferenceActivity.getNotificationEnabled(context)) { if (DEBUG) { Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing"); } return; } // Figure out what we've got -- whether all sms's, mms's, or a mixture of both. final int messageCount = notificationSet.size(); NotificationInfo mostRecentNotification = notificationSet.first(); final NotificationCompat.Builder noti = new NotificationCompat.Builder(context) .setWhen(mostRecentNotification.mTimeMillis); if (isNew) { noti.setTicker(mostRecentNotification.mTicker); } // If we have more than one unique thread, change the title (which would // normally be the contact who sent the message) to a generic one that // makes sense for multiple senders, and change the Intent to take the // user to the conversation list instead of the specific thread. // Cases: // 1) single message from single thread - intent goes to ComposeMessageActivity // 2) multiple messages from single thread - intent goes to ComposeMessageActivity // 3) messages from multiple threads - intent goes to ConversationList final Resources res = context.getResources(); String title = null; Bitmap avatar = null; PendingIntent pendingIntent = null; boolean isMultiNewMessages = MessageUtils.isMailboxMode() ? messageCount > 1 : uniqueThreadCount > 1; if (isMultiNewMessages) { // messages from multiple threads Intent mainActivityIntent = getMultiThreadsViewIntent(context); pendingIntent = PendingIntent.getActivity(context, 0, mainActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT); title = context.getString(R.string.message_count_notification, messageCount); } else { // same thread, single or multiple messages title = mostRecentNotification.mTitle; avatar = mostRecentNotification.mSender.getAvatar(context); noti.setSubText(mostRecentNotification.mSimName); // no-op in single SIM case if (avatar != null) { // Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we // have to scale 'em up to 128x128 to fill the whole notification large icon. final int idealIconHeight = res .getDimensionPixelSize(android.R.dimen.notification_large_icon_height); final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width); noti.setLargeIcon(BitmapUtil.getRoundedBitmap(avatar, idealIconWidth, idealIconHeight)); } pendingIntent = PendingIntent.getActivity(context, 0, mostRecentNotification.mClickIntent, PendingIntent.FLAG_UPDATE_CURRENT); } // Always have to set the small icon or the notification is ignored noti.setSmallIcon(R.drawable.stat_notify_sms); NotificationManagerCompat nm = NotificationManagerCompat.from(context); // Update the notification. noti.setContentTitle(title).setContentIntent(pendingIntent) .setColor(context.getResources().getColor(R.color.mms_theme_color)) .setCategory(Notification.CATEGORY_MESSAGE).setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming // from a favorite. // Tag notification with all senders. for (NotificationInfo info : notificationSet) { Uri peopleReferenceUri = info.mSender.getPeopleReferenceUri(); if (peopleReferenceUri != null) { noti.addPerson(peopleReferenceUri.toString()); } } int defaults = 0; if (isNew) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); if (conversationSettings.getVibrateEnabled()) { String pattern = conversationSettings.getVibratePattern(); if (!TextUtils.isEmpty(pattern)) { noti.setVibrate(parseVibratePattern(pattern)); } else { defaults |= Notification.DEFAULT_VIBRATE; } } String ringtoneStr = conversationSettings.getNotificationTone(); noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr)); Log.d(TAG, "updateNotification: new message, adding sound to the notification"); } defaults |= Notification.DEFAULT_LIGHTS; noti.setDefaults(defaults); // set up delete intent noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0)); // See if QuickMessage pop-up support is enabled in preferences boolean qmPopupEnabled = MessagingPreferenceActivity.getQuickMessageEnabled(context); // Set up the QuickMessage intent Intent qmIntent = null; if (mostRecentNotification.mIsSms) { // QuickMessage support is only for SMS qmIntent = new Intent(); qmIntent.setClass(context, QuickMessagePopup.class); qmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NAME_EXTRA, mostRecentNotification.mSender.getName()); qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NUMBER_EXTRA, mostRecentNotification.mSender.getNumber()); qmIntent.putExtra(QuickMessagePopup.SMS_NOTIFICATION_OBJECT_EXTRA, mostRecentNotification); } // Start getting the notification ready final Notification notification; //Create a WearableExtender to add actions too WearableExtender wearableExtender = new WearableExtender(); if (messageCount == 1 || uniqueThreadCount == 1) { // Add the Quick Reply action only if the pop-up won't be shown already if (!qmPopupEnabled && qmIntent != null) { // This is a QR, we should show the keyboard when the user taps to reply qmIntent.putExtra(QuickMessagePopup.QR_SHOW_KEYBOARD_EXTRA, true); // Create the pending intent and add it to the notification CharSequence qmText = context.getText(R.string.menu_reply); PendingIntent qmPendingIntent = PendingIntent.getActivity(context, 0, qmIntent, PendingIntent.FLAG_UPDATE_CURRENT); noti.addAction(R.drawable.ic_reply, qmText, qmPendingIntent); //Wearable noti.extend(wearableExtender.addAction( new NotificationCompat.Action.Builder(R.drawable.ic_reply, qmText, qmPendingIntent) .build())); } // Add the 'Mark as read' action CharSequence markReadText = context.getText(R.string.qm_mark_read); Intent mrIntent = new Intent(); mrIntent.setClass(context, QmMarkRead.class); mrIntent.putExtra(QmMarkRead.SMS_THREAD_ID, mostRecentNotification.mThreadId); PendingIntent mrPendingIntent = PendingIntent.getBroadcast(context, 0, mrIntent, PendingIntent.FLAG_UPDATE_CURRENT); noti.addAction(R.drawable.ic_mark_read, markReadText, mrPendingIntent); // Add the Call action CharSequence callText = context.getText(R.string.menu_call); Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:" + mostRecentNotification.mSender.getNumber())); PendingIntent callPendingIntent = PendingIntent.getActivity(context, 0, callIntent, PendingIntent.FLAG_UPDATE_CURRENT); noti.addAction(R.drawable.ic_menu_call, callText, callPendingIntent); //Wearable noti.extend(wearableExtender.addAction( new NotificationCompat.Action.Builder(R.drawable.ic_menu_call, callText, callPendingIntent) .build())); //Set up remote input String replyLabel = context.getString(R.string.qm_wear_voice_reply); RemoteInput remoteInput = new RemoteInput.Builder(QuickMessageWear.EXTRA_VOICE_REPLY) .setLabel(replyLabel).build(); //Set up pending intent for voice reply Intent voiceReplyIntent = new Intent(context, QuickMessageWear.class); voiceReplyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); voiceReplyIntent.putExtra(QuickMessageWear.SMS_CONATCT, mostRecentNotification.mSender.getName()); voiceReplyIntent.putExtra(QuickMessageWear.SMS_SENDER, mostRecentNotification.mSender.getNumber()); voiceReplyIntent.putExtra(QuickMessageWear.SMS_THEAD_ID, mostRecentNotification.mThreadId); PendingIntent voiceReplyPendingIntent = PendingIntent.getActivity(context, 0, voiceReplyIntent, PendingIntent.FLAG_UPDATE_CURRENT); //Wearable voice reply action NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_reply, context.getString(R.string.qm_wear_reply_by_voice), voiceReplyPendingIntent) .addRemoteInput(remoteInput).build(); noti.extend(wearableExtender.addAction(action)); } if (messageCount == 1) { // We've got a single message // This sets the text for the collapsed form: noti.setContentText(mostRecentNotification.formatBigMessage(context)); if (mostRecentNotification.mAttachmentBitmap != null) { // The message has a picture, show that NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle(noti) .bigPicture(mostRecentNotification.mAttachmentBitmap) .setSummaryText(mostRecentNotification.formatPictureMessage(context)); notification = noti.setStyle(bigPictureStyle).build(); } else { // Show a single notification -- big style with the text of the whole message NotificationCompat.BigTextStyle bigTextStyle1 = new NotificationCompat.BigTextStyle(noti) .bigText(mostRecentNotification.formatBigMessage(context)); notification = noti.setStyle(bigTextStyle1).build(); } if (DEBUG) { Log.d(TAG, "updateNotification: single message notification"); } } else { // We've got multiple messages if (!isMultiNewMessages) { // We've got multiple messages for the same thread. // Starting with the oldest new message, display the full text of each message. // Begin a line for each subsequent message. SpannableStringBuilder buf = new SpannableStringBuilder(); NotificationInfo infos[] = notificationSet.toArray(new NotificationInfo[messageCount]); int len = infos.length; for (int i = len - 1; i >= 0; i--) { NotificationInfo info = infos[i]; buf.append(info.formatBigMessage(context)); if (i != 0) { buf.append('\n'); } } noti.setContentText(context.getString(R.string.message_count_notification, messageCount)); // Show a single notification -- big style with the text of all the messages NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle(); bigTextStyle.bigText(buf) // Forcibly show the last line, with the app's smallIcon in it, if we // kicked the smallIcon out with an avatar bitmap .setSummaryText((avatar == null) ? null : " "); notification = noti.setStyle(bigTextStyle).build(); if (DEBUG) { Log.d(TAG, "updateNotification: multi messages for single thread"); } } else { // Build a set of the most recent notification per threadId. HashSet<Long> uniqueThreads = new HashSet<Long>(messageCount); ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>(); Iterator<NotificationInfo> notifications = notificationSet.iterator(); while (notifications.hasNext()) { NotificationInfo notificationInfo = notifications.next(); if (!uniqueThreads.contains(notificationInfo.mThreadId)) { uniqueThreads.add(notificationInfo.mThreadId); mostRecentNotifPerThread.add(notificationInfo); } } // When collapsed, show all the senders like this: // Fred Flinstone, Barry Manilow, Pete... noti.setContentText(formatSenders(context, mostRecentNotifPerThread)); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(noti); // We have to set the summary text to non-empty so the content text doesn't show // up when expanded. inboxStyle.setSummaryText(" "); // At this point we've got multiple messages in multiple threads. We only // want to show the most recent message per thread, which are in // mostRecentNotifPerThread. int uniqueThreadMessageCount = mostRecentNotifPerThread.size(); int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount); for (int i = 0; i < maxMessages; i++) { NotificationInfo info = mostRecentNotifPerThread.get(i); inboxStyle.addLine(info.formatInboxMessage(context)); } notification = inboxStyle.build(); uniqueThreads.clear(); mostRecentNotifPerThread.clear(); if (DEBUG) { Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification"); } } } notifyUserIfFullScreen(context, title); nm.notify(NOTIFICATION_ID, notification); // Trigger the QuickMessage pop-up activity if enabled // But don't show the QuickMessage if the user is in a call or the phone is ringing if (qmPopupEnabled && qmIntent != null) { TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE && !ConversationList.mIsRunning && !ComposeMessageActivity.mIsRunning) { context.startActivity(qmIntent); } } }
From source file:org.apache.hadoop.hive.ql.MultiDriver.java
private int multipreoptimizetest() throws CommandNeedRetryException { int i;/*from www .j a va 2s . c o m*/ PerfLogger perfLogger = PerfLogger.getPerfLogger(); for (i = 0; i < cmds.size(); i++) { TaskFactory.resetId(); ParseContext pCtx = multiPctx.get(i); // conf=(HiveConf)confs.get(i); conf = pCtx.getConf(); ctx = pCtx.getContext(); LOG.info("Before MultidoPhase2forTest Optree:\n" + Operator.toString(pCtx.getTopOps().values())); // do Optimizer gen MR task SemanticAnalyzer sem; try { sem = new SemanticAnalyzer(conf); sem.MultidoPhase2forTest(pCtx); sem.validate(); plan = new QueryPlan(cmds.get(i), sem, perfLogger.getStartTime(PerfLogger.DRIVER_RUN)); if (false) { String queryPlanFileName = ctx.getLocalScratchDir(true) + Path.SEPARATOR_CHAR + "queryplan.xml"; LOG.info("query plan = " + queryPlanFileName); queryPlanFileName = new Path(queryPlanFileName).toUri().getPath(); // serialize the queryPlan FileOutputStream fos = new FileOutputStream(queryPlanFileName); Utilities.serializeObject(plan, fos); fos.close(); } // initialize FetchTask right here if (plan.getFetchTask() != null) { plan.getFetchTask().initialize(conf, plan, null); } // get the output schema schema = schemas.get(i); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } boolean requireLock = false; boolean ckLock = checkLockManager(); if (ckLock) { boolean lockOnlyMapred = HiveConf.getBoolVar(conf, HiveConf.ConfVars.HIVE_LOCK_MAPRED_ONLY); if (lockOnlyMapred) { Queue<Task<? extends Serializable>> taskQueue = new LinkedList<Task<? extends Serializable>>(); taskQueue.addAll(plan.getRootTasks()); while (taskQueue.peek() != null) { Task<? extends Serializable> tsk = taskQueue.remove(); requireLock = requireLock || tsk.requireLock(); if (requireLock) { break; } if (tsk instanceof ConditionalTask) { taskQueue.addAll(((ConditionalTask) tsk).getListTasks()); } if (tsk.getChildTasks() != null) { taskQueue.addAll(tsk.getChildTasks()); } // does not add back up task here, because back up task should be the same // type of the original task. } } else { requireLock = true; } } int ret; if (requireLock) { ret = acquireReadWriteLocks(); if (ret != 0) { releaseLocks(ctx.getHiveLocks()); // return new CommandProcessorResponse(ret, errorMessage, SQLState); } } ret = execute(); if (ret != 0) { //if needRequireLock is false, the release here will do nothing because there is no lock releaseLocks(ctx.getHiveLocks()); // return new CommandProcessorResponse(ret, errorMessage, SQLState); } //if needRequireLock is false, the release here will do nothing because there is no lock releaseLocks(ctx.getHiveLocks()); //test output SessionState ss = SessionState.get(); PrintStream out = ss.out; ArrayList<String> res = new ArrayList<String>(); LOG.info("Output the result of query ID(" + i + "):"); printHeader(this, out); int counter = 0; try { while (this.getResults(res)) { for (String r : res) { out.println(r); } counter += res.size(); res.clear(); if (out.checkError()) { break; } } } catch (IOException e) { console.printError("Failed with exception " + e.getClass().getName() + ":" + e.getMessage(), "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); ret = 1; } } return 0; }
From source file:com.threerings.media.tile.bundle.tools.TileSetBundler.java
/** * Creates a tileset bundle at the location specified by the * <code>targetPath</code> parameter, based on the description * provided via the <code>bundleDesc</code> parameter. * * @param idBroker the tileset id broker that will be used to map * tileset names to tileset ids./*from w w w .j a v a 2 s . c om*/ * @param bundleDesc a file object pointing to the bundle description * file. * @param target the tileset bundle file that will be created. * * @return true if the bundle was rebuilt, false if it was not because * the bundle file was newer than all involved source files. * * @exception IOException thrown if an error occurs reading, writing * or processing anything. */ public boolean createBundle(TileSetIDBroker idBroker, final File bundleDesc, File target) throws IOException { // stick an array list on the top of the stack into which we will // collect parsed tilesets ArrayList<TileSet> sets = Lists.newArrayList(); _digester.push(sets); // parse the tilesets FileInputStream fin = new FileInputStream(bundleDesc); try { _digester.parse(fin); } catch (SAXException saxe) { String errmsg = "Failure parsing bundle description file " + "[path=" + bundleDesc.getPath() + "]"; throw (IOException) new IOException(errmsg).initCause(saxe); } finally { fin.close(); } // we want to make sure that at least one of the tileset image // files or the bundle definition file is newer than the bundle // file, otherwise consider the bundle up to date long newest = bundleDesc.lastModified(); // create a tileset bundle to hold our tilesets TileSetBundle bundle = new TileSetBundle(); // add all of the parsed tilesets to the tileset bundle try { for (int ii = 0; ii < sets.size(); ii++) { TileSet set = sets.get(ii); String name = set.getName(); // let's be robust if (name == null) { log.warning("Tileset was parsed, but received no name " + "[set=" + set + "]. Skipping."); continue; } // make sure this tileset's image file exists and check its last modified date File tsfile = new File(bundleDesc.getParent(), set.getImagePath()); if (!tsfile.exists()) { System.err.println("Tile set missing image file " + "[bundle=" + bundleDesc.getPath() + ", name=" + set.getName() + ", imgpath=" + tsfile.getPath() + "]."); continue; } if (tsfile.lastModified() > newest) { newest = tsfile.lastModified(); } // assign a tilset id to the tileset and bundle it try { int tileSetId = idBroker.getTileSetID(name); bundle.addTileSet(tileSetId, set); } catch (PersistenceException pe) { String errmsg = "Failure obtaining a tileset id for " + "tileset [set=" + set + "]."; throw (IOException) new IOException(errmsg).initCause(pe); } } // clear out our array list in preparation for another go sets.clear(); } finally { // before we go, we have to commit our brokered tileset ids // back to the broker's persistent store try { idBroker.commit(); } catch (PersistenceException pe) { log.warning("Failure committing brokered tileset ids " + "back to broker's persistent store " + "[error=" + pe + "]."); } } // see if our newest file is newer than the tileset bundle if (skipIfTargetNewer() && newest < target.lastModified()) { return false; } // create an image provider for loading our tileset images SimpleCachingImageProvider improv = new SimpleCachingImageProvider() { @Override protected BufferedImage loadImage(String path) throws IOException { return ImageIO.read(new File(bundleDesc.getParent(), path)); } }; return createBundle(target, bundle, improv, bundleDesc.getParent(), newest); }
From source file:com.android.contacts.ContactSaveService.java
/** * Insert aggregation exception ContentProviderOperations between {@param rawContactIds1} * and {@param rawContactIds2} to {@param operations}. * @return false if an error occurred, true otherwise. *///from www. j a va 2 s . c o m private boolean buildSplitTwoContacts(ArrayList<ContentProviderOperation> operations, long[] rawContactIds1, long[] rawContactIds2, boolean hardSplit) { if (rawContactIds1 == null || rawContactIds2 == null) { Log.e(TAG, "Invalid arguments for splitContact request"); return false; } // For each pair of raw contacts, insert an aggregation exception final ContentResolver resolver = getContentResolver(); // The maximum number of operations per batch (aka yield point) is 500. See b/22480225 final int batchSize = MAX_CONTACTS_PROVIDER_BATCH_SIZE; for (int i = 0; i < rawContactIds1.length; i++) { for (int j = 0; j < rawContactIds2.length; j++) { buildSplitContactDiff(operations, rawContactIds1[i], rawContactIds2[j], hardSplit); // Before we get to 500 we need to flush the operations list if (operations.size() > 0 && operations.size() % batchSize == 0) { if (!applyOperations(resolver, operations)) { return false; } operations.clear(); } } } return true; }
From source file:org.apache.hadoop.hive.ql.MultiDriver.java
private void multiOutputexplain() throws CommandNeedRetryException { //test output //output the result of the multiquery // set the var:plan schema ctx SessionState ss = SessionState.get(); PrintStream out = ss.out;/*from ww w. ja va 2 s . c o m*/ ArrayList<String> res = new ArrayList<String>(); LOG.info("Output the result of Multi-query"); try { boolean isexplain = ctx.getExplain(); if (true) { LOG.info("Output explain query plan:"); printHeader(this, out); int counter = 0; while (this.getResults(res)) { for (String r : res) { out.println(r); } counter += res.size(); res.clear(); if (out.checkError()) { break; } } return; } int i; for (i = 0; i < multiPctx.size(); i++) { LOG.info("Output Multi-query ID:" + i); int counter = 0; if (!isexplain) { schema = schemas.get(i); } else { //schema=null; } printHeader(this, out); if (plan != null && ((MultiQueryPlan) plan).getfetchtasklist() != null) { plan.setFetchTask(((MultiQueryPlan) plan).getfetchtasklist().get(i)); } this.ctx = multiPctx.get(i).getContext(); while (this.getResults(res)) { for (String r : res) { out.println(r); } counter += res.size(); res.clear(); if (out.checkError()) { break; } } } } catch (IOException e) { console.printError("Failed with exception " + e.getClass().getName() + ":" + e.getMessage(), "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); // ret = 1; } }
From source file:org.apache.hadoop.hive.ql.MultiDriver.java
private void multiOutputResult() throws CommandNeedRetryException { //test output //output the result of the multiquery // set the var:plan schema ctx SessionState ss = SessionState.get(); PrintStream out = ss.out;// w ww . j a v a 2s . co m ArrayList<String> res = new ArrayList<String>(); LOG.info("Output the result of Multi-query"); try { boolean isexplain = ctx.getExplain(); if (isexplain) { LOG.info("Output explain query plan:"); printHeader(this, out); int counter = 0; while (this.getResults(res)) { for (String r : res) { out.println(r); } counter += res.size(); res.clear(); if (out.checkError()) { break; } } return; } int i; for (i = 0; i < multiPctx.size(); i++) { System.out.println("Output Multi-query ID:" + i); int counter = 0; if (!isexplain) { schema = schemas.get(i); } else { //schema=null; } printHeader(this, out); if (plan != null && ((MultiQueryPlan) plan).getfetchtasklist() != null) { plan.setFetchTask(((MultiQueryPlan) plan).getfetchtasklist().get(i)); } this.ctx = multiPctx.get(i).getContext(); while (this.getResults(res)) { for (String r : res) { out.println(r); } counter += res.size(); res.clear(); if (out.checkError()) { break; } } } } catch (IOException e) { console.printError("Failed with exception " + e.getClass().getName() + ":" + e.getMessage(), "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); // ret = 1; } }
From source file:com.yoctopuce.YoctoAPI.YModule.java
public String calibConvert(String param, String currentFuncValue, String unit_name, String sensorType) { int paramVer; int funVer;/*from ww w.ja v a2 s . co m*/ int funScale; int funOffset; int paramScale; int paramOffset; ArrayList<Integer> words = new ArrayList<Integer>(); ArrayList<String> words_str = new ArrayList<String>(); ArrayList<Double> calibData = new ArrayList<Double>(); ArrayList<Integer> iCalib = new ArrayList<Integer>(); int calibType; int i; int maxSize; double ratio; int nPoints; double wordVal; // Initial guess for parameter encoding paramVer = calibVersion(param); funVer = calibVersion(currentFuncValue); funScale = calibScale(unit_name, sensorType); funOffset = calibOffset(unit_name); paramScale = funScale; paramOffset = funOffset; if (funVer < 3) { if (funVer == 2) { words = SafeYAPI()._decodeWords(currentFuncValue); if ((words.get(0).intValue() == 1366) && (words.get(1).intValue() == 12500)) { funScale = 1; funOffset = 0; } else { funScale = words.get(1).intValue(); funOffset = words.get(0).intValue(); } } else { if (funVer == 1) { if (currentFuncValue.equals("") || (YAPI._atoi(currentFuncValue) > 10)) { funScale = 0; } } } } calibData.clear(); calibType = 0; if (paramVer < 3) { if (paramVer == 2) { words = SafeYAPI()._decodeWords(param); if ((words.get(0).intValue() == 1366) && (words.get(1).intValue() == 12500)) { paramScale = 1; paramOffset = 0; } else { paramScale = words.get(1).intValue(); paramOffset = words.get(0).intValue(); } if ((words.size() >= 3) && (words.get(2).intValue() > 0)) { maxSize = 3 + 2 * ((words.get(2).intValue()) % (10)); if (maxSize > words.size()) { maxSize = words.size(); } i = 3; while (i < maxSize) { calibData.add((double) words.get(i).intValue()); i = i + 1; } } } else { if (paramVer == 1) { words_str = new ArrayList<String>(Arrays.asList(param.split(","))); for (String ii : words_str) { words.add(YAPI._atoi(ii)); } if (param.equals("") || (words.get(0).intValue() > 10)) { paramScale = 0; } if ((words.size() > 0) && (words.get(0).intValue() > 0)) { maxSize = 1 + 2 * ((words.get(0).intValue()) % (10)); if (maxSize > words.size()) { maxSize = words.size(); } i = 1; while (i < maxSize) { calibData.add((double) words.get(i).intValue()); i = i + 1; } } } else { if (paramVer == 0) { ratio = Double.valueOf(param); if (ratio > 0) { calibData.add(0.0); calibData.add(0.0); calibData.add((double) Math.round(65535 / ratio)); calibData.add(65535.0); } } } } i = 0; while (i < calibData.size()) { if (paramScale > 0) { calibData.set(i, (calibData.get(i).doubleValue() - paramOffset) / paramScale); } else { calibData.set(i, SafeYAPI()._decimalToDouble((int) (double) Math.round(calibData.get(i).doubleValue()))); } i = i + 1; } } else { iCalib = SafeYAPI()._decodeFloats(param); calibType = (int) (double) Math.round(iCalib.get(0).doubleValue() / 1000.0); if (calibType >= 30) { calibType = calibType - 30; } i = 1; while (i < iCalib.size()) { calibData.add(iCalib.get(i).doubleValue() / 1000.0); i = i + 1; } } if (funVer >= 3) { if (calibData.size() == 0) { param = "0,"; } else { param = Integer.toString(30 + calibType); i = 0; while (i < calibData.size()) { if (((i) & (1)) > 0) { param = param + ":"; } else { param = param + " "; } param = param + Integer .toString((int) (double) Math.round(calibData.get(i).doubleValue() * 1000.0 / 1000.0)); i = i + 1; } param = param + ","; } } else { if (funVer >= 1) { nPoints = ((calibData.size()) / (2)); param = Integer.toString(nPoints); i = 0; while (i < 2 * nPoints) { if (funScale == 0) { wordVal = SafeYAPI() ._doubleToDecimal((int) (double) Math.round(calibData.get(i).doubleValue())); } else { wordVal = calibData.get(i).doubleValue() * funScale + funOffset; } param = param + "," + Double.toString((double) Math.round(wordVal)); i = i + 1; } } else { if (calibData.size() == 4) { param = Double.toString((double) Math .round(1000 * (calibData.get(3).doubleValue() - calibData.get(1).doubleValue()) / calibData.get(2).doubleValue() - calibData.get(0).doubleValue())); } } } return param; }
From source file:net.cbtltd.rest.interhome.A_Handler.java
/** * Test accommodation products.//ww w. ja va 2s . c o m * * @param sqlSession the current SQL session. */ public synchronized void readProducts1() { Date timestamp = new Date(); String message = "Interhome testProducts " + getAltpartyid(); LOG.debug(message); String fn = null; final SqlSession sqlSession = RazorServer.openSession(); try { JAXBContext jc = JAXBContext.newInstance("net.cbtltd.rest.interhome.accommodation"); Unmarshaller um = jc.createUnmarshaller(); fn = "accommodation.xml"; Accommodations accommodations = (Accommodations) um.unmarshal(ftp(fn)); LOG.debug("accommodation size " + accommodations.getAccommodation().size()); int i = 0; Date version = new Date(); ArrayList<String> attributes = new ArrayList<String>(); for (Accommodation accommodation : accommodations.getAccommodation()) { try { attributes.clear(); Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), accommodation.getCode()); if (product == null) { continue; } addType(attributes, accommodation.getType()); if (accommodation.getAttributes() != null && accommodation.getAttributes().getAttribute() != null) { for (String attribute : accommodation.getAttributes().getAttribute()) { addAttribute(attributes, attribute); } } if (accommodation.getDetails() != null) { addDetail(attributes, accommodation.getDetails()); } addQuality(attributes, String.valueOf(accommodation.getQuality())); if (accommodation.getThemes() != null && accommodation.getThemes().getTheme() != null) { for (String theme : accommodation.getThemes().getTheme()) { addTheme(attributes, theme); } } RelationService.replace(sqlSession, Relation.PRODUCT_ATTRIBUTE, product.getId(), attributes); sqlSession.commit(); LOG.debug(i++ + " " + accommodation.getCode() + " " + product.getId()); wait(getProductwait()); } catch (Throwable x) { LOG.error(accommodation + " error " + x.getMessage()); } } } catch (Throwable x) { sqlSession.rollback(); LOG.error("Product Error " + x.getMessage()); } finally { sqlSession.close(); delete(fn); } MonitorService.monitor(message, timestamp); }
From source file:com.mwebster.exchange.EasSyncService.java
private void runPingLoop() throws IOException, StaleFolderListException, IllegalHeartbeatException { int pingHeartbeat = mPingHeartbeat; userLog("runPingLoop"); // Do push for all sync services here long endTime = System.currentTimeMillis() + (30 * MINUTES); HashMap<String, Integer> pingErrorMap = new HashMap<String, Integer>(); ArrayList<String> readyMailboxes = new ArrayList<String>(); ArrayList<String> notReadyMailboxes = new ArrayList<String>(); int pingWaitCount = 0; while ((System.currentTimeMillis() < endTime) && !mStop) { // Count of pushable mailboxes int pushCount = 0; // Count of mailboxes that can be pushed right now int canPushCount = 0; // Count of uninitialized boxes int uninitCount = 0; Serializer s = new Serializer(); Cursor c = mContentResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, MailboxColumns.ACCOUNT_KEY + '=' + mAccount.mId + AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX, null, null);/*w w w . ja va 2 s. c o m*/ notReadyMailboxes.clear(); readyMailboxes.clear(); try { // Loop through our pushed boxes seeing what is available to push while (c.moveToNext()) { pushCount++; // Two requirements for push: // 1) SyncManager tells us the mailbox is syncable (not running, not stopped) // 2) The syncKey isn't "0" (i.e. it's synced at least once) long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN); int pingStatus = SyncManager.pingStatus(mailboxId); String mailboxName = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); if (pingStatus == SyncManager.PING_STATUS_OK) { String syncKey = c.getString(Mailbox.CONTENT_SYNC_KEY_COLUMN); if ((syncKey == null) || syncKey.equals("0")) { // We can't push until the initial sync is done pushCount--; uninitCount++; continue; } if (canPushCount++ == 0) { // Initialize the Ping command s.start(Tags.PING_PING) .data(Tags.PING_HEARTBEAT_INTERVAL, Integer.toString(pingHeartbeat)) .start(Tags.PING_FOLDERS); } String folderClass = getTargetCollectionClassFromCursor(c); s.start(Tags.PING_FOLDER).data(Tags.PING_ID, c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN)) .data(Tags.PING_CLASS, folderClass).end(); readyMailboxes.add(mailboxName); } else if ((pingStatus == SyncManager.PING_STATUS_RUNNING) || (pingStatus == SyncManager.PING_STATUS_WAITING)) { notReadyMailboxes.add(mailboxName); } else if (pingStatus == SyncManager.PING_STATUS_UNABLE) { pushCount--; userLog(mailboxName, " in error state; ignore"); continue; } } } finally { c.close(); } if (Eas.USER_LOG) { if (!notReadyMailboxes.isEmpty()) { userLog("Ping not ready for: " + notReadyMailboxes); } if (!readyMailboxes.isEmpty()) { userLog("Ping ready for: " + readyMailboxes); } } // If we've waited 10 seconds or more, just ping with whatever boxes are ready // But use a shorter than normal heartbeat boolean forcePing = !notReadyMailboxes.isEmpty() && (pingWaitCount > 5); if ((canPushCount > 0) && ((canPushCount == pushCount) || forcePing)) { // If all pingable boxes are ready for push, send Ping to the server s.end().end().done(); pingWaitCount = 0; mPostReset = false; mPostAborted = false; // If we've been stopped, this is a good time to return if (mStop) return; long pingTime = SystemClock.elapsedRealtime(); try { // Send the ping, wrapped by appropriate timeout/alarm if (forcePing) { userLog("Forcing ping after waiting for all boxes to be ready"); } HttpResponse res = sendPing(s.toByteArray(), forcePing ? mPingForceHeartbeat : pingHeartbeat); int code = res.getStatusLine().getStatusCode(); userLog("Ping response: ", code); // Return immediately if we've been asked to stop during the ping if (mStop) { userLog("Stopping pingLoop"); return; } if (code == HttpStatus.SC_OK) { // Make sure to clear out any pending sync errors SyncManager.removeFromSyncErrorMap(mMailboxId); HttpEntity e = res.getEntity(); int len = (int) e.getContentLength(); InputStream is = res.getEntity().getContent(); if (len != 0) { int pingResult = parsePingResult(is, mContentResolver, pingErrorMap); // If our ping completed (status = 1), and we weren't forced and we're // not at the maximum, try increasing timeout by two minutes if (pingResult == PROTOCOL_PING_STATUS_COMPLETED && !forcePing) { if (pingHeartbeat > mPingHighWaterMark) { mPingHighWaterMark = pingHeartbeat; userLog("Setting high water mark at: ", mPingHighWaterMark); } if ((pingHeartbeat < mPingMaxHeartbeat) && !mPingHeartbeatDropped) { pingHeartbeat += PING_HEARTBEAT_INCREMENT; if (pingHeartbeat > mPingMaxHeartbeat) { pingHeartbeat = mPingMaxHeartbeat; } userLog("Increasing ping heartbeat to ", pingHeartbeat, "s"); } } } else { userLog("Ping returned empty result; throwing IOException"); throw new IOException(); } } else if (isAuthError(code)) { mExitStatus = EXIT_LOGIN_FAILURE; userLog("Authorization error during Ping: ", code); throw new IOException(); } } catch (IOException e) { String message = e.getMessage(); // If we get the exception that is indicative of a NAT timeout and if we // haven't yet "fixed" the timeout, back off by two minutes and "fix" it boolean hasMessage = message != null; userLog("IOException runPingLoop: " + (hasMessage ? message : "[no message]")); if (mPostReset) { // Nothing to do in this case; this is SyncManager telling us to try another // ping. } else if (mPostAborted || isLikelyNatFailure(message)) { long pingLength = SystemClock.elapsedRealtime() - pingTime; if ((pingHeartbeat > mPingMinHeartbeat) && (pingHeartbeat > mPingHighWaterMark)) { pingHeartbeat -= PING_HEARTBEAT_INCREMENT; mPingHeartbeatDropped = true; if (pingHeartbeat < mPingMinHeartbeat) { pingHeartbeat = mPingMinHeartbeat; } userLog("Decreased ping heartbeat to ", pingHeartbeat, "s"); } else if (mPostAborted) { // There's no point in throwing here; this can happen in two cases // 1) An alarm, which indicates minutes without activity; no sense // backing off // 2) SyncManager abort, due to sync of mailbox. Again, we want to // keep on trying to ping userLog("Ping aborted; retry"); } else if (pingLength < 2000) { userLog("Abort or NAT type return < 2 seconds; throwing IOException"); throw e; } else { userLog("NAT type IOException"); } } else if (hasMessage && message.contains("roken pipe")) { // The "broken pipe" error (uppercase or lowercase "b") seems to be an // internal error, so let's not throw an exception (which leads to delays) // but rather simply run through the loop again } else { throw e; } } } else if (forcePing) { // In this case, there aren't any boxes that are pingable, but there are boxes // waiting (for IOExceptions) userLog("pingLoop waiting 60s for any pingable boxes"); sleep(60 * SECONDS, true); } else if (pushCount > 0) { // If we want to Ping, but can't just yet, wait a little bit // TODO Change sleep to wait and use notify from SyncManager when a sync ends sleep(2 * SECONDS, false); pingWaitCount++; //userLog("pingLoop waited 2s for: ", (pushCount - canPushCount), " box(es)"); } else if (uninitCount > 0) { // In this case, we're doing an initial sync of at least one mailbox. Since this // is typically a one-time case, I'm ok with trying again every 10 seconds until // we're in one of the other possible states. userLog("pingLoop waiting for initial sync of ", uninitCount, " box(es)"); sleep(10 * SECONDS, true); } else { // We've got nothing to do, so we'll check again in 30 minutes at which time // we'll update the folder list. Let the device sleep in the meantime... userLog("pingLoop sleeping for 30m"); sleep(30 * MINUTES, true); } } // Save away the current heartbeat mPingHeartbeat = pingHeartbeat; }
From source file:com.android.launcher3.CellLayout.java
private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY, View dragView, Rect boundingRect, ArrayList<View> intersectingViews) { if (boundingRect != null) { boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY); }/* www. java2 s .c o m*/ intersectingViews.clear(); Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY); Rect r1 = new Rect(); final int count = mShortcutsAndWidgets.getChildCount(); for (int i = 0; i < count; i++) { View child = mShortcutsAndWidgets.getChildAt(i); if (child == dragView) continue; LayoutParams lp = (LayoutParams) child.getLayoutParams(); r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan); if (Rect.intersects(r0, r1)) { mIntersectingViews.add(child); if (boundingRect != null) { boundingRect.union(r1); } } } }