/** * Implements CallListener.callEnded. Stops sounds that are playing at the moment if there're any. * Removes the call panel and disables the hangup button. */ public void callEnded(CallEvent event) { Call sourceCall = event.getSourceCall(); NotificationManager.stopSound(NotificationManager.BUSY_CALL); NotificationManager.stopSound(NotificationManager.INCOMING_CALL); NotificationManager.stopSound(NotificationManager.OUTGOING_CALL); if (activeCalls.get(sourceCall) != null) { CallPanel callPanel = (CallPanel) activeCalls.get(sourceCall); this.removeCallPanelWait(callPanel); } }
/** * Implements CallListener.incomingCallReceived. When a call is received creates a call panel and * adds it to the main tabbed pane and plays the ring phone sound to the user. */ public void incomingCallReceived(CallEvent event) { Call sourceCall = event.getSourceCall(); CallPanel callPanel = new CallPanel(this, sourceCall, GuiCallParticipantRecord.INCOMING_CALL); mainFrame.addCallPanel(callPanel); if (mainFrame.getState() == JFrame.ICONIFIED) mainFrame.setState(JFrame.NORMAL); if (!mainFrame.isVisible()) mainFrame.setVisible(true); mainFrame.toFront(); this.callButton.setEnabled(true); this.hangupButton.setEnabled(true); NotificationManager.fireNotification( NotificationManager.INCOMING_CALL, null, "Incoming call recived from: " + sourceCall.getCallParticipants().next()); activeCalls.put(sourceCall, callPanel); this.setCallPanelVisible(true); }
@Override protected void onHandleIntent(Intent intent) { if (builder == null) { cancellUpdate(); return; } long progress = Math.min(duration, System.currentTimeMillis() - start); Notification notification = builder.setProgress((int) duration, (int) progress, false).build(); if (progress == duration) { cancellUpdate(); } NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); notification.flags |= Notification.FLAG_NO_CLEAR; notificationManager.notify(TaskService.CURRENT_TASK_NOTIFICATION_ID, notification); }
public void showNotification(String title, String message) { Intent notifyIntent = new Intent(this, MainActivity.class); notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pendingIntent = PendingIntent.getActivities( this, 0, new Intent[] {notifyIntent}, PendingIntent.FLAG_UPDATE_CURRENT); Notification notification = new Notification.Builder(this) .setSmallIcon(android.R.drawable.ic_dialog_info) .setContentTitle(title) .setContentText(message) .setAutoCancel(true) .setContentIntent(pendingIntent) .build(); notification.defaults |= Notification.DEFAULT_SOUND; NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(1, notification); }
public static void displayNotification(Context context, String text) { Intent openIntent = new Intent(context, MainActivity.class); Notification notification = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.icon) .setContentTitle(context.getResources().getString(R.string.notification_title)) .setContentText(text) .setContentIntent(PendingIntent.getActivity(context, 0, openIntent, 0)) .addAction( android.R.drawable.ic_menu_close_clear_cancel, context.getResources().getString(R.string.menu_exit), PendingIntent.getBroadcast(context, 0, new ExitIntent(), 0)) .addAction( android.R.drawable.ic_menu_manage, context.getResources().getString(R.string.menu_main_screen), PendingIntent.getActivity(context, 0, openIntent, 0)) .build(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); notification.flags |= Notification.FLAG_ONGOING_EVENT; notificationManager.notify(1983, notification); }
/** * Creates a notification to a Group coordinator signaling that a user wants to join their group * * <p>- Requires a groupId request parameter for the GET * * @param req The HTTP Request * @param res The HTTP Response */ public void inviteAction(HttpServletRequest req, HttpServletResponse res) { // Ensure there is a cookie for the session user if (AccountController.redirectIfNoCookie(req, res)) return; Map<String, Object> viewData = new HashMap<String, Object>(); int groupId = Integer.parseInt(req.getParameter("groupId")); try { // Get the session user HttpSession session = req.getSession(); Session userSession = (Session) session.getAttribute("userSession"); User user = userSession.getUser(); // Get the coordinator for the group GroupManager groupMan = new GroupManager(); Group group = groupMan.get(groupId); User coordinator = groupMan.getCoordinator(groupId); // Send a notification to the coordinator for them to permit access to the group NotificationManager notificationMan = new NotificationManager(); Notification notification = new Notification( coordinator.getId(), coordinator, groupId, group, user.getFullName() + " wants to join your group " + group.getGroupName(), "/home/notifications?addUserId=" + user.getId() + "&groupId=" + group.getId()); notificationMan.createNotification(notification); redirectToLocal(req, res, "/home/dashboard"); return; } catch (Exception e) { redirectToLocal(req, res, "/home/dashboard"); } }
/** * Handles the <tt>ActionEvent</tt> generated when user presses one of the buttons in this panel. */ public void actionPerformed(ActionEvent evt) { JButton button = (JButton) evt.getSource(); String buttonName = button.getName(); if (buttonName.equals("call")) { Component selectedPanel = mainFrame.getSelectedTab(); // call button is pressed over an already open call panel if (selectedPanel != null && selectedPanel instanceof CallPanel && ((CallPanel) selectedPanel).getCall().getCallState() == CallState.CALL_INITIALIZATION) { NotificationManager.stopSound(NotificationManager.BUSY_CALL); NotificationManager.stopSound(NotificationManager.INCOMING_CALL); CallPanel callPanel = (CallPanel) selectedPanel; Iterator participantPanels = callPanel.getParticipantsPanels(); while (participantPanels.hasNext()) { CallParticipantPanel panel = (CallParticipantPanel) participantPanels.next(); panel.setState("Connecting"); } Call call = callPanel.getCall(); answerCall(call); } // call button is pressed over the call list else if (selectedPanel != null && selectedPanel instanceof CallListPanel && ((CallListPanel) selectedPanel).getCallList().getSelectedIndex() != -1) { CallListPanel callListPanel = (CallListPanel) selectedPanel; GuiCallParticipantRecord callRecord = (GuiCallParticipantRecord) callListPanel.getCallList().getSelectedValue(); String stringContact = callRecord.getParticipantName(); createCall(stringContact); } // call button is pressed over the contact list else if (selectedPanel != null && selectedPanel instanceof ContactListPanel) { // call button is pressed when a meta contact is selected if (isCallMetaContact) { Object[] selectedContacts = mainFrame.getContactListPanel().getContactList().getSelectedValues(); Vector telephonyContacts = new Vector(); for (int i = 0; i < selectedContacts.length; i++) { Object o = selectedContacts[i]; if (o instanceof MetaContact) { Contact contact = ((MetaContact) o).getDefaultContact(OperationSetBasicTelephony.class); if (contact != null) telephonyContacts.add(contact); else { new ErrorDialog( this.mainFrame, Messages.getI18NString("warning").getText(), Messages.getI18NString( "contactNotSupportingTelephony", new String[] {((MetaContact) o).getDisplayName()}) .getText()) .showDialog(); } } } if (telephonyContacts.size() > 0) createCall(telephonyContacts); } else if (!phoneNumberCombo.isComboFieldEmpty()) { // if no contact is selected checks if the user has chosen // or has // writen something in the phone combo box String stringContact = phoneNumberCombo.getEditor().getItem().toString(); createCall(stringContact); } } else if (selectedPanel != null && selectedPanel instanceof DialPanel) { String stringContact = phoneNumberCombo.getEditor().getItem().toString(); createCall(stringContact); } } else if (buttonName.equalsIgnoreCase("hangup")) { Component selectedPanel = this.mainFrame.getSelectedTab(); if (selectedPanel != null && selectedPanel instanceof CallPanel) { NotificationManager.stopSound(NotificationManager.BUSY_CALL); NotificationManager.stopSound(NotificationManager.INCOMING_CALL); NotificationManager.stopSound(NotificationManager.OUTGOING_CALL); CallPanel callPanel = (CallPanel) selectedPanel; Call call = callPanel.getCall(); if (removeCallTimers.containsKey(callPanel)) { ((Timer) removeCallTimers.get(callPanel)).stop(); removeCallTimers.remove(callPanel); } removeCallPanel(callPanel); if (call != null) { ProtocolProviderService pps = call.getProtocolProvider(); OperationSetBasicTelephony telephony = mainFrame.getTelephonyOpSet(pps); Iterator participants = call.getCallParticipants(); while (participants.hasNext()) { try { // now we hang up the first call participant in the // call telephony.hangupCallParticipant((CallParticipant) participants.next()); } catch (OperationFailedException e) { logger.error("Hang up was not successful: " + e); } } } } } else if (buttonName.equalsIgnoreCase("minimize")) { JCheckBoxMenuItem hideCallPanelItem = mainFrame.getMainMenu().getViewMenu().getHideCallPanelItem(); if (!hideCallPanelItem.isSelected()) hideCallPanelItem.setSelected(true); this.setCallPanelVisible(false); } else if (buttonName.equalsIgnoreCase("restore")) { JCheckBoxMenuItem hideCallPanelItem = mainFrame.getMainMenu().getViewMenu().getHideCallPanelItem(); if (hideCallPanelItem.isSelected()) hideCallPanelItem.setSelected(false); this.setCallPanelVisible(true); } }
public void showNotifications(List<String> contacts) { if (!(ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationsActivity)) { Conversation[] conversations = Database.getInstance(applicationContext).getConversations(preferences.getDid()); for (Conversation conversation : conversations) { if (!conversation.isUnread() || !contacts.contains(conversation.getContact()) || (ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationActivity && ((ConversationActivity) ActivityMonitor.getInstance().getCurrentActivity()) .getContact() .equals(conversation.getContact()))) { continue; } String smsContact = Utils.getContactName(applicationContext, conversation.getContact()); if (smsContact == null) { smsContact = Utils.getFormattedPhoneNumber(conversation.getContact()); } String allSmses = ""; String mostRecentSms = ""; boolean initial = true; for (Message message : conversation.getMessages()) { if (message.getType() == Message.Type.INCOMING && message.isUnread()) { if (initial) { allSmses = message.getText(); mostRecentSms = message.getText(); initial = false; } else { allSmses = message.getText() + "\n" + allSmses; } } else { break; } } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(applicationContext); notificationBuilder.setContentTitle(smsContact); notificationBuilder.setContentText(mostRecentSms); notificationBuilder.setSmallIcon(R.drawable.ic_chat_white_24dp); notificationBuilder.setPriority(Notification.PRIORITY_HIGH); notificationBuilder.setSound( Uri.parse(Preferences.getInstance(applicationContext).getNotificationSound())); notificationBuilder.setLights(0xFFAA0000, 1000, 5000); if (Preferences.getInstance(applicationContext).getNotificationVibrateEnabled()) { notificationBuilder.setVibrate(new long[] {0, 250, 250, 250}); } else { notificationBuilder.setVibrate(new long[] {0}); } notificationBuilder.setColor(0xFFAA0000); notificationBuilder.setAutoCancel(true); notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(allSmses)); Bitmap largeIconBitmap; try { largeIconBitmap = MediaStore.Images.Media.getBitmap( applicationContext.getContentResolver(), Uri.parse( Utils.getContactPhotoUri(applicationContext, conversation.getContact()))); largeIconBitmap = Bitmap.createScaledBitmap(largeIconBitmap, 256, 256, false); largeIconBitmap = Utils.applyCircularMask(largeIconBitmap); notificationBuilder.setLargeIcon(largeIconBitmap); } catch (Exception ignored) { } Intent intent = new Intent(applicationContext, ConversationActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra( applicationContext.getString(R.string.conversation_extra_contact), conversation.getContact()); TaskStackBuilder stackBuilder = TaskStackBuilder.create(applicationContext); stackBuilder.addParentStack(ConversationActivity.class); stackBuilder.addNextIntent(intent); notificationBuilder.setContentIntent( stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT)); Intent replyIntent = new Intent(applicationContext, ConversationQuickReplyActivity.class); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { replyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); } else { //noinspection deprecation replyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); } replyIntent.putExtra( applicationContext.getString(R.string.conversation_extra_contact), conversation.getContact()); PendingIntent replyPendingIntent = PendingIntent.getActivity( applicationContext, 0, replyIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationCompat.Action.Builder replyAction = new NotificationCompat.Action.Builder( R.drawable.ic_reply_white_24dp, applicationContext.getString(R.string.notifications_button_reply), replyPendingIntent); notificationBuilder.addAction(replyAction.build()); Intent markAsReadIntent = new Intent(applicationContext, MarkAsReadReceiver.class); markAsReadIntent.putExtra( applicationContext.getString(R.string.conversation_extra_contact), conversation.getContact()); PendingIntent markAsReadPendingIntent = PendingIntent.getBroadcast( applicationContext, 0, markAsReadIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationCompat.Action.Builder markAsReadAction = new NotificationCompat.Action.Builder( R.drawable.ic_drafts_white_24dp, applicationContext.getString(R.string.notifications_button_mark_read), markAsReadPendingIntent); notificationBuilder.addAction(markAsReadAction.build()); int id; if (notificationIds.get(conversation.getContact()) != null) { id = notificationIds.get(conversation.getContact()); } else { id = notificationIdCount++; notificationIds.put(conversation.getContact(), id); } NotificationManager notificationManager = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(id, notificationBuilder.build()); } } }
private void clearNotification() { NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager.cancel(1983); }
public static void testPerformance() throws Exception { setConfigurationValues(); File outfile = new File("performance.log"); CountDownLatch publiserhStartSignal = new CountDownLatch(1); CountDownLatch publisherDoneSignal = new CountDownLatch(noTopicsPublished); NotificationManager notifManagerArray[] = new NotificationManager[numberOfSubscriber]; StatCalculatorThread statCalcThread[] = new StatCalculatorThread[numberOfSubscriber]; setPayload(payLoadMultiplier); for (int j = 0; j < numberOfSubscriber; j++) { notifManagerArray[j] = new NotificationManager( configurations.getProperty(ConfigKeys.BROKER_URL), consumerPort + j, protocol, numMultiThreadsSupportPerSub); } // thread to calculate stats for notification manager // set the subscriptions depending on the topic or xpath based int arrayIndex = 0; int totalReceivers = 0; createSubscriberArray(noTopicsPublished, numberOfSubscriber, notifManagerArray, arrayIndex); System.out.println("subscribing to topics completed, creating publisher threads"); // start publishers PublisherThread[] publisher = new PublisherThread[noTopicsPublished]; createPublishers( noTopicsPublished, protocol, publiserhStartSignal, publisherDoneSignal, publisher); System.out.println("sending signal to start publishing..."); long publisherStartTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis(); publiserhStartSignal.countDown(); // let all threads proceed for (int j = 0; j < numberOfSubscriber; j++) { statCalcThread[j] = new StatCalculatorThread(notifManagerArray[j], testExpirationTime); statCalcThread[j].start(); } publisherDoneSignal.await(); // wait for all to finish for (int j = 0; j < noTopicsPublished; j++) { totalPublishRTT += publisher[j].getAvgPubTime(); } avgPublishRTTime = totalPublishRTT / noTopicsPublished; long publishersRunningTime = System.currentTimeMillis() - publisherStartTime; System.out.println("finished publishing messgaes."); for (StatCalculatorThread stats : statCalcThread) { stats.join(); } long stopTime = 0l; long totNumberOfMessagesReceived = 0; for (StatCalculatorThread stats : statCalcThread) { stopTime = stopTime < stats.getLastMsgReceivedTime() ? stats.getLastMsgReceivedTime() : stopTime; totalRoundTripTime += stats.getTotalTime(); totNumberOfMessagesReceived += stats.getNumberOfMsgReceived(); } for (NotificationManager notifMngr : notifManagerArray) { totalReceivers += notifMngr.getNoTopicsSubscribed(); } avgRountTripTime = totalRoundTripTime / totNumberOfMessagesReceived; long executionTime = stopTime - startTime; double throughtput = (totNumberOfMessagesReceived * 1000) / (executionTime); List<Stat> statistics = new ArrayList<Stat>(); statistics.add(new Stat("Payload size (bytes)", payload.getBytes("US-ASCII").length)); statistics.add(new Stat("Protocol", protocol)); statistics.add(new Stat("# total expected Msgs", totalReceivers * notifPerTopic)); statistics.add(new Stat("# total msgs received", totNumberOfMessagesReceived)); setStatList( notifPerTopic, noTopicsPublished, publishersRunningTime, executionTime, throughtput, statistics); printStatistics(statistics, outfile); for (NotificationManager notifMngr : notifManagerArray) { notifMngr.cleanup(); } System.out.println("end of test"); System.exit(0); }
/** * Displays the Create Discussion page for a HTTP Get, or creates a Discussion Thread for a HTTP * Post * * <p>- Requires a cookie for the session user - Requires a groupId request parameter for a GET - * Requires a groupId and threadName request parameter for a POST - Requires a document request * part for a POST * * @param req The HTTP Request * @param res The HTTP Response */ public void createDiscussionAction(HttpServletRequest req, HttpServletResponse res) { // Ensure there is a cookie for the session user if (AccountController.redirectIfNoCookie(req, res)) return; Map<String, Object> viewData = new HashMap<>(); if (req.getMethod() == HttpMethod.Get) { viewData.put("title", "Create Discussion"); viewData.put("groupId", req.getParameter("groupId")); view(req, res, "/views/group/CreateDiscussion.jsp", viewData); return; } else if (req.getMethod() == HttpMethod.Post) { // save discussion GroupManager groupMan = new GroupManager(); DiscussionThread thread = new DiscussionThread(); int groupId = Integer.parseInt(req.getParameter("groupId")); thread.setGroupId(groupId); thread.setGroup(groupMan.get(groupId)); thread.setThreadName(req.getParameter("threadName")); DiscussionManager dm = new DiscussionManager(); dm.createDiscussion(thread); try { Part documentPart = req.getPart("document"); // if we have a document to upload if (documentPart.getSize() > 0) { String uuid = DocumentController.saveDocument(this.getServletContext(), documentPart); Document doc = new Document(); doc.setDocumentName(getFileName(documentPart)); doc.setDocumentPath(uuid); doc.setVersionNumber(1); doc.setThreadId(thread.getId()); doc.setGroupId(thread.getGroupId()); DocumentManager docMan = new DocumentManager(); docMan.createDocument(doc); // Get uploading User HttpSession session = req.getSession(); Session userSession = (Session) session.getAttribute("userSession"); User uploader = userSession.getUser(); // Create a notification to all in the group NotificationManager notificationMan = new NotificationManager(); groupMan = new GroupManager(); List<User> groupUsers = groupMan.getGroupUsers(groupId); for (User u : groupUsers) { Notification notification = new Notification( u.getId(), u, groupId, null, "User " + uploader.getFullName() + " has uploaded a document", "/document/document?documentId=" + doc.getId()); notificationMan.createNotification(notification); } } } catch (Exception e) { logger.log(Level.SEVERE, "Document save error", e); } redirectToLocal(req, res, "/group/discussion/?threadId=" + thread.getId()); return; } httpNotFound(req, res); }
/** * Displays a given Meeting page for a HTTP Get, or creates a new Meeting for a HTTP Post * * <p>- Requires a cookie for the session user - Requires a meetingId request parameter for a GET * - Requires description, createdByUserId, datepicker, meetingTime, groupId request parameters * for a POST * * @param req The HTTP Request * @param res The HTTP Response */ public void meetingAction(HttpServletRequest req, HttpServletResponse res) { // Ensure there is a cookie for the session user if (AccountController.redirectIfNoCookie(req, res)) return; Map<String, Object> viewData = new HashMap<String, Object>(); viewData.put("title", "Meeting"); // Initialise Manager connections MeetingManager meetingMan = new MeetingManager(); GroupManager groupMan = new GroupManager(); if (req.getMethod() == HttpMethod.Get) { // Get request parameter int meetingId = Integer.parseInt(req.getParameter("meetingId")); Meeting meeting = meetingMan.get(meetingId); if (meeting != null) { List<User> meetingUsers = groupMan.getGroupUsers(meeting.getGroupId()); viewData.put("meetingUsers", meetingUsers); viewData.put("meeting", meeting); view(req, res, "/views/group/Meeting.jsp", viewData); } else { httpNotFound(req, res); } } else if (req.getMethod() == HttpMethod.Post) { // Get details from request String description = req.getParameter("description"); int createdByUserId = Integer.parseInt(req.getParameter("createdByUserId")); Date dateCreated = new Date(); String meetingDate = req.getParameter("datepicker"); String meetingTime = req.getParameter("meetingTime"); // Parse meeting date time details DateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm"); Date dateDue = new Date(); try { dateDue = format.parse(meetingDate + " " + meetingTime); } catch (ParseException e) { // Unable to parse date. This shouldn't happen since we are // performing javascript validation. } int groupId = Integer.parseInt(req.getParameter("groupId")); // Create a Meeting Meeting meeting = new Meeting(); meeting.setDescription(description); meeting.setCreatedByUserId(createdByUserId); meeting.setDateCreated(dateCreated); meeting.setDateDue(dateDue); meeting.setGroupId(groupId); meetingMan.createMeeting(meeting); int meetingId = meetingMan.getIdFor(meeting); meeting.setId(meetingId); UserManager userMan = new UserManager(); User createdByUser = userMan.get(createdByUserId); // Create a notification for all users in group NotificationManager notificationMan = new NotificationManager(); List<User> users = groupMan.getGroupUsers(groupId); for (User u : users) { Notification notification = new Notification( u.getId(), u, groupId, null, "Meeting " + description + " was created by " + createdByUser.getFullName(), "/group/meeting?meetingId=" + meetingId); notificationMan.createNotification(notification); } // Update the User Session to show new meeting HttpSession session = req.getSession(); Session userSession = (Session) session.getAttribute("userSession"); User admin = userSession.getUser(); admin.getMeetings().add(meeting); // Show meeting page viewData.put("meetingUsers", users); viewData.put("meeting", meeting); view(req, res, "/views/group/Meeting.jsp", viewData); } }
private void submitJob(CoasterChannel channel, Task task, String configId) throws ProtocolException { NotificationManager.getDefault().registerListener(task.getIdentity(), task, this); jsc = new SubmitJobCommand(task, configId); jsc.executeAsync(channel, this); }