List of usage examples for java.util HashMap remove
public V remove(Object key)
From source file:org.apache.hadoop.yarn.server.resourcemanager.TestRM.java
@Test(timeout = 40000) public void testNMToken() throws Exception { MockRM rm = new MockRM(conf); try {//w w w . ja v a 2 s .co m Assume.assumeFalse(rm.getResourceScheduler() instanceof FairScheduler); rm.start(); MockNM nm1 = rm.registerNode("h1:1234", 10000); NMTokenSecretManagerInRM nmTokenSecretManager = rm.getRMContext().getNMTokenSecretManager(); // submitting new application RMApp app = rm.submitApp(1000); // start scheduling. nm1.nodeHeartbeat(true); // Starting application attempt and launching // It should get registered with NMTokenSecretManager. RMAppAttempt attempt = app.getCurrentAppAttempt(); MockAM am = rm.sendAMLaunched(attempt.getAppAttemptId()); Assert.assertTrue(nmTokenSecretManager.isApplicationAttemptRegistered(attempt.getAppAttemptId())); // This will register application master. am.registerAppAttempt(); ArrayList<Container> containersReceivedForNM1 = new ArrayList<Container>(); List<ContainerId> releaseContainerList = new ArrayList<ContainerId>(); HashMap<String, Token> nmTokens = new HashMap<String, Token>(); // initially requesting 2 containers. AllocateResponse response = am.allocate("h1", 1000, 2, releaseContainerList); Assert.assertEquals(0, response.getAllocatedContainers().size()); allocateContainersAndValidateNMTokens(am, containersReceivedForNM1, 2, nmTokens, nm1); Assert.assertEquals(1, nmTokens.size()); // requesting 2 more containers. response = am.allocate("h1", 1000, 2, releaseContainerList); Assert.assertEquals(0, response.getAllocatedContainers().size()); allocateContainersAndValidateNMTokens(am, containersReceivedForNM1, 4, nmTokens, nm1); Assert.assertEquals(1, nmTokens.size()); // We will be simulating NM restart so restarting newly added h2:1234 // NM 2 now registers. MockNM nm2 = rm.registerNode("h2:1234", 10000); nm2.nodeHeartbeat(true); ArrayList<Container> containersReceivedForNM2 = new ArrayList<Container>(); response = am.allocate("h2", 1000, 2, releaseContainerList); Assert.assertEquals(0, response.getAllocatedContainers().size()); allocateContainersAndValidateNMTokens(am, containersReceivedForNM2, 2, nmTokens, nm2); Assert.assertEquals(2, nmTokens.size()); // Simulating NM-2 restart. nm2 = rm.registerNode("h2:1234", 10000); // Wait for reconnect to make it through the RM and create a new RMNode Map<NodeId, RMNode> nodes = rm.getRMContext().getRMNodes(); while (nodes.get(nm2.getNodeId()).getLastNodeHeartBeatResponse().getResponseId() > 0) { Thread.sleep(WAIT_SLEEP_MS); } int interval = 40; // Wait for nm Token to be cleared. while (nmTokenSecretManager.isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(), nm2.getNodeId()) && interval-- > 0) { LOG.info("waiting for nmToken to be cleared for : " + nm2.getNodeId()); Thread.sleep(WAIT_SLEEP_MS); } Assert.assertTrue(nmTokenSecretManager.isApplicationAttemptRegistered(attempt.getAppAttemptId())); // removing NMToken for h2:1234 nmTokens.remove(nm2.getNodeId().toString()); Assert.assertEquals(1, nmTokens.size()); // We should again receive the NMToken. response = am.allocate("h2", 1000, 2, releaseContainerList); Assert.assertEquals(0, response.getAllocatedContainers().size()); allocateContainersAndValidateNMTokens(am, containersReceivedForNM2, 4, nmTokens, nm2); Assert.assertEquals(2, nmTokens.size()); // Now rolling over NMToken masterKey. it should resend the NMToken in // next allocate call. Assert.assertTrue(nmTokenSecretManager.isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(), nm1.getNodeId())); Assert.assertTrue(nmTokenSecretManager.isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(), nm2.getNodeId())); nmTokenSecretManager.rollMasterKey(); nmTokenSecretManager.activateNextMasterKey(); Assert.assertFalse(nmTokenSecretManager.isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(), nm1.getNodeId())); Assert.assertFalse(nmTokenSecretManager.isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(), nm2.getNodeId())); // It should not remove application attempt entry. Assert.assertTrue(nmTokenSecretManager.isApplicationAttemptRegistered(attempt.getAppAttemptId())); nmTokens.clear(); Assert.assertEquals(0, nmTokens.size()); // We should again receive the NMToken. response = am.allocate("h2", 1000, 1, releaseContainerList); Assert.assertEquals(0, response.getAllocatedContainers().size()); allocateContainersAndValidateNMTokens(am, containersReceivedForNM2, 5, nmTokens, nm2); Assert.assertEquals(1, nmTokens.size()); Assert.assertTrue(nmTokenSecretManager.isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(), nm2.getNodeId())); // After AM is finished making sure that nmtoken entry for app Assert.assertTrue(nmTokenSecretManager.isApplicationAttemptRegistered(attempt.getAppAttemptId())); am.unregisterAppAttempt(); // marking all the containers as finished. for (Container container : containersReceivedForNM1) { nm1.nodeHeartbeat(attempt.getAppAttemptId(), container.getId().getContainerId(), ContainerState.COMPLETE); } for (Container container : containersReceivedForNM2) { nm2.nodeHeartbeat(attempt.getAppAttemptId(), container.getId().getContainerId(), ContainerState.COMPLETE); } nm1.nodeHeartbeat(am.getApplicationAttemptId(), 1, ContainerState.COMPLETE); am.waitForState(RMAppAttemptState.FINISHED); Assert.assertFalse(nmTokenSecretManager.isApplicationAttemptRegistered(attempt.getAppAttemptId())); } finally { rm.stop(); } }
From source file:org.telegraph.messenger.NotificationsController.java
@SuppressLint("InlinedApi") public void showExtraNotifications(NotificationCompat.Builder notificationBuilder, boolean notifyAboutLast) { if (Build.VERSION.SDK_INT < 18) { return;/*from ww w . j a va 2s . c o m*/ } ArrayList<Long> sortedDialogs = new ArrayList<>(); HashMap<Long, ArrayList<MessageObject>> messagesByDialogs = new HashMap<>(); for (int a = 0; a < pushMessages.size(); a++) { MessageObject messageObject = pushMessages.get(a); long dialog_id = messageObject.getDialogId(); if ((int) dialog_id == 0) { continue; } ArrayList<MessageObject> arrayList = messagesByDialogs.get(dialog_id); if (arrayList == null) { arrayList = new ArrayList<>(); messagesByDialogs.put(dialog_id, arrayList); sortedDialogs.add(0, dialog_id); } arrayList.add(messageObject); } HashMap<Long, Integer> oldIdsWear = new HashMap<>(); oldIdsWear.putAll(wearNotificationsIds); wearNotificationsIds.clear(); HashMap<Long, Integer> oldIdsAuto = new HashMap<>(); oldIdsAuto.putAll(autoNotificationsIds); autoNotificationsIds.clear(); for (int b = 0; b < sortedDialogs.size(); b++) { long dialog_id = sortedDialogs.get(b); ArrayList<MessageObject> messageObjects = messagesByDialogs.get(dialog_id); int max_id = messageObjects.get(0).getId(); int max_date = messageObjects.get(0).messageOwner.date; TLRPC.Chat chat = null; TLRPC.User user = null; String name; if (dialog_id > 0) { user = MessagesController.getInstance().getUser((int) dialog_id); if (user == null) { continue; } } else { chat = MessagesController.getInstance().getChat(-(int) dialog_id); if (chat == null) { continue; } } if (chat != null) { name = chat.title; } else { name = UserObject.getUserName(user); } Integer notificationIdWear = oldIdsWear.get(dialog_id); if (notificationIdWear == null) { notificationIdWear = wearNotificationId++; } else { oldIdsWear.remove(dialog_id); } Integer notificationIdAuto = oldIdsAuto.get(dialog_id); if (notificationIdAuto == null) { notificationIdAuto = autoNotificationId++; } else { oldIdsAuto.remove(dialog_id); } NotificationCompat.CarExtender.UnreadConversation.Builder unreadConvBuilder = new NotificationCompat.CarExtender.UnreadConversation.Builder( name).setLatestTimestamp((long) max_date * 1000); Intent msgHeardIntent = new Intent(); msgHeardIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); msgHeardIntent.setAction("org.telegraph.messenger.ACTION_MESSAGE_HEARD"); msgHeardIntent.putExtra("dialog_id", dialog_id); msgHeardIntent.putExtra("max_id", max_id); PendingIntent msgHeardPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, notificationIdAuto, msgHeardIntent, PendingIntent.FLAG_UPDATE_CURRENT); unreadConvBuilder.setReadPendingIntent(msgHeardPendingIntent); NotificationCompat.Action wearReplyAction = null; if (!ChatObject.isChannel(chat)) { Intent msgReplyIntent = new Intent(); msgReplyIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); msgReplyIntent.setAction("org.telegraph.messenger.ACTION_MESSAGE_REPLY"); msgReplyIntent.putExtra("dialog_id", dialog_id); msgReplyIntent.putExtra("max_id", max_id); PendingIntent msgReplyPendingIntent = PendingIntent.getBroadcast( ApplicationLoader.applicationContext, notificationIdAuto, msgReplyIntent, PendingIntent.FLAG_UPDATE_CURRENT); RemoteInput remoteInputAuto = new RemoteInput.Builder(NotificationsController.EXTRA_VOICE_REPLY) .setLabel(LocaleController.getString("Reply", R.string.Reply)).build(); unreadConvBuilder.setReplyAction(msgReplyPendingIntent, remoteInputAuto); Intent replyIntent = new Intent(ApplicationLoader.applicationContext, WearReplyReceiver.class); replyIntent.putExtra("dialog_id", dialog_id); replyIntent.putExtra("max_id", max_id); PendingIntent replyPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, notificationIdWear, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT); RemoteInput remoteInputWear = new RemoteInput.Builder(EXTRA_VOICE_REPLY) .setLabel(LocaleController.getString("Reply", R.string.Reply)).build(); String replyToString; if (chat != null) { replyToString = LocaleController.formatString("ReplyToGroup", R.string.ReplyToGroup, name); } else { replyToString = LocaleController.formatString("ReplyToUser", R.string.ReplyToUser, name); } wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon, replyToString, replyPendingIntent).addRemoteInput(remoteInputWear).build(); } String text = ""; for (int a = messageObjects.size() - 1; a >= 0; a--) { MessageObject messageObject = messageObjects.get(a); String message = getStringForMessage(messageObject, false); if (message == null) { continue; } if (chat != null) { message = message.replace(" @ " + name, ""); } else { message = message.replace(name + ": ", "").replace(name + " ", ""); } if (text.length() > 0) { text += "\n\n"; } text += message; unreadConvBuilder.addMessage(message); } TLRPC.FileLocation photoPath = null; if (chat != null) { if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) { photoPath = chat.photo.photo_small; } } else { if (user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) { photoPath = user.photo.photo_small; } } Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class); intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); intent.setFlags(32768); if (chat != null) { intent.putExtra("chatId", chat.id); } else if (user != null) { intent.putExtra("userId", user.id); } PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT); NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender(); if (wearReplyAction != null) { wearableExtender.addAction(wearReplyAction); } NotificationCompat.Builder builder = new NotificationCompat.Builder( ApplicationLoader.applicationContext).setContentTitle(name) .setSmallIcon(R.drawable.notification).setGroup("messages").setContentText(text) .setColor(0xff2ca5e0).setGroupSummary(false).setContentIntent(contentIntent) .extend(wearableExtender) .extend(new NotificationCompat.CarExtender() .setUnreadConversation(unreadConvBuilder.build())) .setCategory(NotificationCompat.CATEGORY_MESSAGE); if (photoPath != null) { BitmapDrawable img = ImageLoader.getInstance().getImageFromMemory(photoPath, null, "50_50"); if (img != null) { builder.setLargeIcon(img.getBitmap()); } } if (chat == null && user != null && user.phone != null && user.phone.length() > 0) { builder.addPerson("tel:+" + user.phone); } notificationManager.notify(notificationIdWear, builder.build()); wearNotificationsIds.put(dialog_id, notificationIdWear); } for (HashMap.Entry<Long, Integer> entry : oldIdsWear.entrySet()) { notificationManager.cancel(entry.getValue()); } }
From source file:org.archive.bdb.BdbModule.java
@SuppressWarnings("unchecked") protected void doRecover() throws IOException { File cpDir = new File(dir.getFile(), recoveryCheckpoint.getName()); File logfilesList = new File(cpDir, "jdbfiles.manifest"); List<String> filesAndLengths = FileUtils.readLines(logfilesList); HashMap<String, Long> retainLogfiles = new HashMap<String, Long>(); for (String line : filesAndLengths) { String[] fileAndLength = line.split(","); long expectedLength = Long.valueOf(fileAndLength[1]); retainLogfiles.put(fileAndLength[0], expectedLength); // check for files in checkpoint directory; relink to environment as necessary File cpFile = new File(cpDir, line); File destFile = new File(dir.getFile(), fileAndLength[0]); if (cpFile.exists()) { if (cpFile.length() != expectedLength) { LOGGER.warning(cpFile.getName() + " expected " + expectedLength + " actual " + cpFile.length()); // TODO: is truncation necessary? }/* w ww . jav a2s . c o m*/ if (destFile.exists()) { if (!destFile.delete()) { LOGGER.log(Level.SEVERE, "unable to delete obstructing file " + destFile); } } boolean status = FilesystemLinkMaker.makeHardLink(cpFile.getAbsolutePath(), destFile.getAbsolutePath()); if (!status) { LOGGER.log(Level.SEVERE, "unable to create required restore link " + destFile); } } } IOFileFilter filter = FileFilterUtils.orFileFilter(FileFilterUtils.suffixFileFilter(".jdb"), FileFilterUtils.suffixFileFilter(".del")); filter = FileFilterUtils.makeFileOnly(filter); // reverify environment directory is as it was at checkpoint time, // deleting any extra files for (File f : dir.getFile().listFiles((FileFilter) filter)) { if (retainLogfiles.containsKey(f.getName())) { // named file still exists under original name long expectedLength = retainLogfiles.get(f.getName()); if (f.length() != expectedLength) { LOGGER.warning(f.getName() + " expected " + expectedLength + " actual " + f.length()); // TODO: truncate? this unexpected length mismatch // probably only happens if there was already a recovery // where the affected file was the last of the set, in // which case BDB appends a small amount of (harmless?) data // to the previously-undersized file } retainLogfiles.remove(f.getName()); continue; } // file as now-named not in restore set; check if un-".DEL" renaming needed String undelName = f.getName().replace(".del", ".jdb"); if (retainLogfiles.containsKey(undelName)) { // file if renamed matches desired file name long expectedLength = retainLogfiles.get(undelName); if (f.length() != expectedLength) { LOGGER.warning(f.getName() + " expected " + expectedLength + " actual " + f.length()); // TODO: truncate to expected size? } if (!f.renameTo(new File(f.getParentFile(), undelName))) { throw new IOException("Unable to rename " + f + " to " + undelName); } retainLogfiles.remove(undelName); } // file not needed; delete/move-aside if (!f.delete()) { LOGGER.warning("unable to delete " + f); org.archive.util.FileUtils.moveAsideIfExists(f); } // TODO: log/warn of ruined later checkpoints? } if (retainLogfiles.size() > 0) { // some needed files weren't present LOGGER.severe("Checkpoint corrupt, needed log files missing: " + retainLogfiles); } }
From source file:org.sakaiproject.tool.assessment.ui.listener.author.ItemAddListener.java
private void updateAttachment(List oldList, List newList, ItemDataIfc item, boolean pendingOrPool) { if ((oldList == null || oldList.size() == 0) && (newList == null || newList.size() == 0)) return;//from w ww.j a v a2 s . c o m List list = new ArrayList(); HashMap map = getAttachmentIdHash(oldList); for (int i = 0; i < newList.size(); i++) { ItemAttachmentIfc a = (ItemAttachmentIfc) newList.get(i); if (map.get(a.getAttachmentId()) != null) { // exist already, remove it from map map.remove(a.getAttachmentId()); } else { // new attachments a.setItem(item); list.add(a); } } // save new ones AssessmentService service; if (pendingOrPool) { service = new AssessmentService(); } else { service = new PublishedAssessmentService(); } service.saveOrUpdateAttachments(list); // remove old ones Set set = map.keySet(); Iterator iter = set.iterator(); while (iter.hasNext()) { Long attachmentId = (Long) iter.next(); service.removeItemAttachment(attachmentId.toString()); } }
From source file:exm.stc.frontend.ASTWalker.java
/** * Check that app output args are not omitted from command line * Omit warning//w w w. j a v a 2 s. c om * @param context * @param outputs * @param outArgs * @param redir * @throws UserException */ private void checkAppOutputs(Context context, List<Var> outArgs, List<Var> args, Redirects<Var> redirFutures, Set<Suppression> suppressions) throws UserException { boolean deferredError = false; HashMap<String, Var> outMap = new HashMap<String, Var>(); for (Var output : outArgs) { // Check output types if (!Types.isFile(output) && !Types.isVoid(output)) { LogHelper.error(context, "Output argument " + output.name() + " has " + " invalid type for app output: " + output.type().typeName()); deferredError = true; } outMap.put(output.name(), output); } if (redirFutures.stdout != null) { // Already typechecked Var output = redirFutures.stdout; outMap.put(output.name(), output); } for (Var arg : args) { if (arg.defType() == DefType.OUTARG) { outMap.remove(arg.name()); } } for (Var redir : redirFutures.redirections(false, true)) { if (redir.defType() == DefType.OUTARG) { outMap.remove(redir.name()); } } for (Var unreferenced : outMap.values()) { if (!Types.isVoid(unreferenced.type()) && !suppressions.contains(Suppression.UNUSED_OUTPUT)) { LogHelper.warn(context, "Output argument " + unreferenced.name() + " is not referenced in app command line. This usually " + "indicates an error. However, if this is intended, for example " + "if the file location is implicit, you can suppress this warning " + "by annotating the function with @suppress=unused_output"); } } if (deferredError) { throw new UserException(context, "Compilation failed due to type " + "error in definition of function " + context.getFunctionContext().getFunctionName()); } }
From source file:de.innovationgate.wgpublisher.lucene.LuceneManager.java
private void removeFromIndexedDbs(String dbkey) { synchronized (_indexedDbs) { // copy indexed dbs HashMap newIndexedDbs = new HashMap(); newIndexedDbs.putAll(_indexedDbs); // remove in copy newIndexedDbs.remove(dbkey); // switch maps _indexedDbs = newIndexedDbs;// w w w . j a va 2 s .c om } }
From source file:edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQuery.java
/** * Parse Query/* w ww . j ava2s. co m*/ * * <P> Parses out string representation of query xml object into building blocks that will be used to generate sql statement. * In particular, this method establishes the processing order of groups, panels, and items when building the query * * @param queryXml string that contains the query definition xml object received from the query request * @throws JAXBUtilException exception thrown when errors arise from converting string to xml and vice versa * @throws I2B2Exception exception thrown when i2b2 specific error arises */ public void parseQuery() throws I2B2Exception { //get query timing out - this will be used as the default timing for all groups //and panels. Panel timing values will override this value queryTiming = queryDef.getQueryTiming(); //first step, get the constraints parsed out by groups they reference //also parse through the columns that need to be returned by each panel group constraintMapping = new TemporalQueryConstraintMapping(queryDef); HashMap<String, TemporalSubQuery> subQuerySet = new HashMap<String, TemporalSubQuery>(); //second step, treat panel object on the query level as panel group with no temporal component if (queryDef.getPanel() != null && queryDef.getPanel().size() > 0) { TemporalSubQuery mainQuery = new TemporalSubQuery(this, queryDef.getPanel()); //check to see if the main query is an "everyone" query boolean getEveryoneQuery = false; if (mainQuery != null && mainQuery.getPanelCount() == 1) { TemporalPanel mainPanel = mainQuery.getPanelList().get(0); if (mainPanel != null && mainPanel.isPanelInverted() && (mainPanel.getItemList() == null || mainPanel.getItemList().size() == 0)) { getEveryoneQuery = true; } } //if there are no subqueries or the main query is not an "everyone" query, include //the main query as a special subquery if (queryDef.getSubquery() == null || queryDef.getSubquery().size() == 0 || !getEveryoneQuery) { subQuerySet.put("**default**", mainQuery); } } //third step, check for query objects and create corresponding temporal query panel groups if (queryDef.getSubquery() != null && queryDef.getSubquery().size() > 0) { for (QueryDefinitionType query : queryDef.getSubquery()) { HashMap<String, List<QueryConstraintType>> constraints = constraintMapping .getConstraintsForQuery(query.getQueryId()); EnumSet<TemporalSubQuery.TemporalQueryReturnColumns> returnColumns = constraintMapping .getReturnColumnsForQuery(query.getQueryId()); TemporalSubQuery subQuery = new TemporalSubQuery(this, query, constraints, returnColumns); subQuerySet.put(query.getQueryId(), subQuery); } } //last step, group set object established the order of the groups. now copy objects //into straight list for easier processing subQueryList = new ArrayList<TemporalSubQuery>(); subQueryMap = new HashMap<String, Integer>(); int index = 0; for (String eventId : constraintMapping.getOrderedQueryList()) { TemporalSubQuery subQuery = subQuerySet.get(eventId); if (subQuery != null) { subQueryList.add(subQuery); subQueryMap.put(eventId, index); index++; subQuerySet.remove(eventId); } } if (subQuerySet.size() > 0) { for (TemporalSubQuery grp : subQuerySet.values()) { subQueryList.add(grp); subQueryMap.put(grp.getQueryId(), index); index++; } } }
From source file:org.telegram.messenger.NotificationsController.java
@SuppressLint("InlinedApi") private void showExtraNotifications(NotificationCompat.Builder notificationBuilder, boolean notifyAboutLast) { if (Build.VERSION.SDK_INT < 18) { return;// w ww. j a v a 2 s . c o m } ArrayList<Long> sortedDialogs = new ArrayList<>(); HashMap<Long, ArrayList<MessageObject>> messagesByDialogs = new HashMap<>(); for (int a = 0; a < pushMessages.size(); a++) { MessageObject messageObject = pushMessages.get(a); long dialog_id = messageObject.getDialogId(); if ((int) dialog_id == 0) { continue; } ArrayList<MessageObject> arrayList = messagesByDialogs.get(dialog_id); if (arrayList == null) { arrayList = new ArrayList<>(); messagesByDialogs.put(dialog_id, arrayList); sortedDialogs.add(0, dialog_id); } arrayList.add(messageObject); } HashMap<Long, Integer> oldIdsWear = new HashMap<>(); oldIdsWear.putAll(wearNotificationsIds); wearNotificationsIds.clear(); HashMap<Long, Integer> oldIdsAuto = new HashMap<>(); oldIdsAuto.putAll(autoNotificationsIds); autoNotificationsIds.clear(); for (int b = 0; b < sortedDialogs.size(); b++) { long dialog_id = sortedDialogs.get(b); ArrayList<MessageObject> messageObjects = messagesByDialogs.get(dialog_id); int max_id = messageObjects.get(0).getId(); int max_date = messageObjects.get(0).messageOwner.date; TLRPC.Chat chat = null; TLRPC.User user = null; String name; if (dialog_id > 0) { user = MessagesController.getInstance().getUser((int) dialog_id); if (user == null) { continue; } } else { chat = MessagesController.getInstance().getChat(-(int) dialog_id); if (chat == null) { continue; } } if (chat != null) { name = chat.title; } else { name = UserObject.getUserName(user); } Integer notificationIdWear = oldIdsWear.get(dialog_id); if (notificationIdWear == null) { notificationIdWear = wearNotificationId++; } else { oldIdsWear.remove(dialog_id); } Integer notificationIdAuto = oldIdsAuto.get(dialog_id); if (notificationIdAuto == null) { notificationIdAuto = autoNotificationId++; } else { oldIdsAuto.remove(dialog_id); } NotificationCompat.CarExtender.UnreadConversation.Builder unreadConvBuilder = new NotificationCompat.CarExtender.UnreadConversation.Builder( name).setLatestTimestamp((long) max_date * 1000); Intent msgHeardIntent = new Intent(); msgHeardIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); msgHeardIntent.setAction("org.telegram.messenger.ACTION_MESSAGE_HEARD"); msgHeardIntent.putExtra("dialog_id", dialog_id); msgHeardIntent.putExtra("max_id", max_id); PendingIntent msgHeardPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, notificationIdAuto, msgHeardIntent, PendingIntent.FLAG_UPDATE_CURRENT); unreadConvBuilder.setReadPendingIntent(msgHeardPendingIntent); NotificationCompat.Action wearReplyAction = null; if (!ChatObject.isChannel(chat)) { Intent msgReplyIntent = new Intent(); msgReplyIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); msgReplyIntent.setAction("org.telegram.messenger.ACTION_MESSAGE_REPLY"); msgReplyIntent.putExtra("dialog_id", dialog_id); msgReplyIntent.putExtra("max_id", max_id); PendingIntent msgReplyPendingIntent = PendingIntent.getBroadcast( ApplicationLoader.applicationContext, notificationIdAuto, msgReplyIntent, PendingIntent.FLAG_UPDATE_CURRENT); RemoteInput remoteInputAuto = new RemoteInput.Builder(NotificationsController.EXTRA_VOICE_REPLY) .setLabel(LocaleController.getString("Reply", R.string.Reply)).build(); unreadConvBuilder.setReplyAction(msgReplyPendingIntent, remoteInputAuto); Intent replyIntent = new Intent(ApplicationLoader.applicationContext, WearReplyReceiver.class); replyIntent.putExtra("dialog_id", dialog_id); replyIntent.putExtra("max_id", max_id); PendingIntent replyPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, notificationIdWear, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT); RemoteInput remoteInputWear = new RemoteInput.Builder(EXTRA_VOICE_REPLY) .setLabel(LocaleController.getString("Reply", R.string.Reply)).build(); String replyToString; if (chat != null) { replyToString = LocaleController.formatString("ReplyToGroup", R.string.ReplyToGroup, name); } else { replyToString = LocaleController.formatString("ReplyToUser", R.string.ReplyToUser, name); } wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon, replyToString, replyPendingIntent).addRemoteInput(remoteInputWear).build(); } String text = ""; for (int a = messageObjects.size() - 1; a >= 0; a--) { MessageObject messageObject = messageObjects.get(a); String message = getStringForMessage(messageObject, false); if (message == null) { continue; } if (chat != null) { message = message.replace(" @ " + name, ""); } else { message = message.replace(name + ": ", "").replace(name + " ", ""); } if (text.length() > 0) { text += "\n\n"; } text += message; unreadConvBuilder.addMessage(message); } TLRPC.FileLocation photoPath = null; if (chat != null) { if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) { photoPath = chat.photo.photo_small; } } else { if (user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) { photoPath = user.photo.photo_small; } } Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class); intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); intent.setFlags(32768); if (chat != null) { intent.putExtra("chatId", chat.id); } else if (user != null) { intent.putExtra("userId", user.id); } PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT); NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender(); if (wearReplyAction != null) { wearableExtender.addAction(wearReplyAction); } NotificationCompat.Builder builder = new NotificationCompat.Builder( ApplicationLoader.applicationContext).setContentTitle(name) .setSmallIcon(R.drawable.notification).setGroup("messages").setContentText(text) .setColor(0xff2ca5e0).setGroupSummary(false).setContentIntent(contentIntent) .extend(wearableExtender) .extend(new NotificationCompat.CarExtender() .setUnreadConversation(unreadConvBuilder.build())) .setCategory(NotificationCompat.CATEGORY_MESSAGE); if (photoPath != null) { BitmapDrawable img = ImageLoader.getInstance().getImageFromMemory(photoPath, null, "50_50"); if (img != null) { builder.setLargeIcon(img.getBitmap()); } } if (chat == null && user != null && user.phone != null && user.phone.length() > 0) { builder.addPerson("tel:+" + user.phone); } notificationManager.notify(notificationIdWear, builder.build()); wearNotificationsIds.put(dialog_id, notificationIdWear); } for (HashMap.Entry<Long, Integer> entry : oldIdsWear.entrySet()) { notificationManager.cancel(entry.getValue()); } }
From source file:ch.elexis.core.ui.views.FallDetailBlatt2.java
/** * disposes of required and optional fields on the bottom of the page.<br> * re-reads the contents for this case for the upper part<br> * recreates the required and optional fields on the bottom of the page (call to * setExtendedFields)// w w w . j av a2 s . c o m * * @param f * caseID */ @SuppressWarnings("unchecked") public void setFall(final IFall f) { if (actFall != null) { save(); } // *** dispose of currently displayed fields actFall = f; for (Control c : lReqs) { c.dispose(); } lReqs.clear(); keepEditable.clear(); // *** fill billing systems into combo, set current system cAbrechnung.setItems(Abrechnungstypen); if (f == null) { form.setText(Messages.FallDetailBlatt2_NoCaseSelected); //$NON-NLS-1$ tBezeichnung.setText(""); tBezeichnung.setMessage(Messages.FallDetailBlatt2_29); cReason.select(0); return; } String billingSystem = f.getAbrechnungsSystem(); // auto select accident if uvg is selected if ("UVG".equals(billingSystem)) { int idx = ArrayUtils.indexOf(Reasons, FallConstants.TYPE_ACCIDENT); if (idx > -1) { f.setGrund(Reasons[idx]); } } form.setText(f.getLabel()); // *** set Fallbezeichnung tBezeichnung.setText(f.getBezeichnung()); // *** set Grund (Krankheit/Unfall/...) String grund = f.getGrund(); int ix = cReason.indexOf(grund); if (ix == -1) { ix = 0; } cReason.select(ix); cAbrechnung.setText(billingSystem); // *** set startDate/EndDate TimeTool tt = new TimeTool(); if (tt.set(f.getBeginnDatum()) == true) { dpVon.setDate(tt.getTime()); } else { dpVon.setDate(null); } if (tt.set(f.getEndDatum()) == true) { dpBis.setDate(tt.getTime()); } else { dpBis.setDate(null); } // *** set copy for patient btnCopyForPatient.setSelection(f.getCopyForPatient()); // *** set Garant tGarant.setBackground(null); tGarant.setToolTipText(null); Kontakt garant = f.getGarant(); String garantLabel = garant.getLabel(); if (garant.isDeleted()) { tGarant.setBackground(UiDesk.getColor(UiDesk.COL_RED)); garantLabel = "*** " + garantLabel; tGarant.setToolTipText(Messages.Contact_is_marked_deleted); } tGarant.setText(garantLabel); // *** set cost bearer (if enabled for billing system) boolean costBearerDisabled = BillingSystem.isCostBearerDisabled(billingSystem); tCostBearer.setVisible(!costBearerDisabled); hlCostBearer.setVisible(!costBearerDisabled); tCostBearer.setBackground(null); tCostBearer.setToolTipText(null); if (!costBearerDisabled) { Kontakt costBearer = f.getCostBearer(); String label = (costBearer != null) ? costBearer.getLabel() : f.getPatient().getLabel(); if (costBearer != null && costBearer.isDeleted()) { tCostBearer.setBackground(UiDesk.getColor(UiDesk.COL_RED)); label = "*** " + label; tCostBearer.setToolTipText(Messages.Contact_is_marked_deleted); } tCostBearer.setText(label); } else { tCostBearer.setText(StringConstants.EMPTY); } // *** adding required fields defined in prefs String reqs = BillingSystem.getRequirementsBySystem(billingSystem); if ((reqs != null) && (reqs.length() > 0)) { // *** do not display a title bar since this is already displayed // above Rechnungsempfnger! setExtendedFields(f, reqs, StringTool.leer, false, false, false); } // *** adding optional fields defined in prefs String optionals = f.getOptionals(); if ((optionals != null) && (optionals.length() > 0)) { setExtendedFields(f, optionals, Messages.FallDetailBlatt2_optionalData, false, false, true); //$NON-NLS-1$ } // ****** show any other fields from extinfo - ONLY FOR ADMINS, NOT // INTENDED FOR NORMAL USERS !!! // first part fields with definition, second part without definition // *** display all unused field having a display specification String[] reqsArray = BillingSystem.getRequirementsBySystem(billingSystem).split(DEFINITIONSDELIMITER); for (int reqI = 0; reqI < reqsArray.length; reqI++) { reqsArray[reqI] = reqsArray[reqI].split(ARGUMENTSSDELIMITER)[0]; } String[] optsArray = f.getOptionals().split(DEFINITIONSDELIMITER); for (int reqI = 0; reqI < optsArray.length; reqI++) { optsArray[reqI] = optsArray[reqI].split(ARGUMENTSSDELIMITER)[0]; } // *** read field definitions for unused fields (previously required or // optional) List<String> unused = new ArrayList<String>(); LinkedHashMap<String, String> unusedHash = new LinkedHashMap<String, String>(); String strUnused = f.getUnused(); if ((strUnused != null) && (!strUnused.isEmpty())) { String[] allUnused = strUnused.split(DEFINITIONSDELIMITER); //$NON-NLS-1$ Arrays.sort(allUnused, String.CASE_INSENSITIVE_ORDER); // *** sort // alphabetically for (String unusedPart : allUnused) { int posColon = unusedPart.indexOf(ARGUMENTSSDELIMITER); String key = unusedPart.substring(0, posColon); // *** do not show if already displayed in required or optional // fields boolean alreadyDisplayed = false; for (int reqI = 0; reqI < reqsArray.length; reqI++) { if (key.equalsIgnoreCase(reqsArray[reqI])) { alreadyDisplayed = true; } } for (int reqI = 0; reqI < optsArray.length; reqI++) { if (key.equalsIgnoreCase(optsArray[reqI])) { alreadyDisplayed = true; } } if (!alreadyDisplayed) { String value = unusedPart.substring(posColon + 1); unusedHash.put(key, value); unused.add(unusedPart); } } } Map<String, String> httmp = getSelectedFall().getMap(PersistentObject.FLD_EXTINFO); HashMap<String, String> ht = new HashMap<String, String>(httmp); String[] unusedHashStringArray = {}; if (unusedHash.size() > 0) { String unusedHashString = unusedHash.toString(); unusedHashString = unusedHashString.substring(1); unusedHashString = unusedHashString.substring(0, unusedHashString.length() - 1); unusedHashStringArray = unusedHashString.split(", "); //$NON-NLS-1$ } String otherFieldsList_2 = StringTool.leer; String delim = StringTool.leer; for (int uhi = 0; uhi < unusedHashStringArray.length; uhi++) { String unusedItem = unusedHashStringArray[uhi]; String[] itemParts = unusedItem.split("="); //$NON-NLS-1$ String controlName = itemParts[0]; String[] controlDefParts = itemParts[1].split(ARGUMENTSSDELIMITER); String controlType = controlDefParts[0]; String[] itemList = { StringTool.leer }; if (controlType.equalsIgnoreCase("X")) { //$NON-NLS-1$ if (controlDefParts.length > 1) { itemList = controlDefParts[1].split(ITEMDELIMITER); } } boolean isAdded = false; // *** special handling if multiple items for (int ili = 0; ili < itemList.length; ili++) { String item = itemList[ili]; if (!item.isEmpty()) { item = "_" + item; //$NON-NLS-1$ } String combControlName = controlName + item; if (ht.containsKey(combControlName)) { ht.remove(combControlName); String values = StringTool.leer; if (controlDefParts.length > 1) { values = controlDefParts[1]; } if (!isAdded) { otherFieldsList_2 = otherFieldsList_2 + delim + controlName + ARGUMENTSSDELIMITER + controlType + ARGUMENTSSDELIMITER + values; } delim = DEFINITIONSDELIMITER; isAdded = true; } } } // *** only for admins! if (otherFieldsList_2.length() > 0) { if (CoreHub.acl.request(AccessControlDefaults.CASE_MODIFY_SPECIALS) == true) { setExtendedFields(f, otherFieldsList_2, Messages.FallDetailBlatt2_unusedFieldsWithDefinition, true, true, false); //$NON-NLS-1$ } } // *** collect all other fields that are not yet shown anywhere else, // display as text String otherFieldsList = otherFieldsList_2; otherFieldsList = StringTool.leer; Set<String> keySet = ht.keySet(); Object[] arr = keySet.toArray(); for (int i = 0; i < arr.length; i++) { String subkey = (String) arr[i]; String abrSystem = getSelectedFall().getAbrechnungsSystem(); String key = Preferences.LEISTUNGSCODES_CFG_KEY + "/" + abrSystem; //$NON-NLS-1$ String bed = CoreHub.globalCfg.get(key + "/bedingungen", StringTool.leer); //$NON-NLS-1$ boolean isAlreadyShown = false; if (subkey.equalsIgnoreCase(FallConstants.FLD_EXTINFO_BILLING)) isAlreadyShown = true; // if (subkey.equalsIgnoreCase("payment")) isAlreadyShown = true; // if (subkey.equalsIgnoreCase("Fallnummer")) isAlreadyShown = true; // if (subkey.equalsIgnoreCase("Gesetz")) isAlreadyShown = true; String[] bedArr = bed.split(DEFINITIONSDELIMITER); if (!bed.isEmpty()) { for (int ii = 0; ii < bedArr.length; ii++) { String fldParts = bedArr[ii]; String[] flds = fldParts.split(ARGUMENTSSDELIMITER); String fld = flds[0]; if ((flds[1].equalsIgnoreCase("X")) && ((flds.length > 2)) //$NON-NLS-1$ && (!flds[2].isEmpty())) { String checkBoxes = flds[2]; String[] checkBoxArray = checkBoxes.split(ITEMDELIMITER); for (int cb_i = 0; cb_i < checkBoxArray.length; cb_i++) { if ((fld + "_" + checkBoxArray[cb_i]).equalsIgnoreCase(subkey)) { //$NON-NLS-1$ isAlreadyShown = true; break; } } } else { if (fld.equalsIgnoreCase(subkey)) { isAlreadyShown = true; break; } } } } String opt = CoreHub.globalCfg.get(key + "/fakultativ", StringTool.leer); //$NON-NLS-1$ if (!isAlreadyShown) { String[] optArr = opt.split(DEFINITIONSDELIMITER); if (!opt.isEmpty()) { for (int ii = 0; ii < optArr.length; ii++) { String fld = optArr[ii].split(ARGUMENTSSDELIMITER)[0]; if (fld.equalsIgnoreCase(subkey)) { isAlreadyShown = true; break; } } } } if (!isAlreadyShown) { if (unusedHash.containsKey(subkey)) { // *** try to find def String theVal = (String) unusedHash.get(subkey); String[] vals = theVal.split(ARGUMENTSSDELIMITER); otherFieldsList = otherFieldsList + delim + subkey + ARGUMENTSSDELIMITER + vals[0]; if (vals.length > 1) { otherFieldsList = otherFieldsList + ARGUMENTSSDELIMITER + vals[1]; } } else { // *** if no spec found, then show as text otherFieldsList = otherFieldsList + delim + subkey + ":T"; //$NON-NLS-1$ } delim = DEFINITIONSDELIMITER; } } if (otherFieldsList.length() > 0) { // *** want to sort alphabetically here String[] tmpArr = otherFieldsList.split(DEFINITIONSDELIMITER); Arrays.sort(tmpArr, String.CASE_INSENSITIVE_ORDER); otherFieldsList = StringTool.leer; String tmpDel = StringTool.leer; for (int i = 0; i < tmpArr.length; i++) { otherFieldsList = otherFieldsList + tmpDel + tmpArr[i]; tmpDel = DEFINITIONSDELIMITER; } // *** only for admins! if (CoreHub.acl.request(AccessControlDefaults.CASE_MODIFY_SPECIALS) == true) { setExtendedFields(f, otherFieldsList, Messages.FallDetailBlatt2_unusedFieldsWithoutDefinition, true, true, false); //$NON-NLS-1$ } } if (lockUpdate) { setUnlocked(CoreHub.getLocalLockService().isLockedLocal(actFall)); } }
From source file:org.mindswap.swoop.renderer.entity.NLVisitor.java
private void reconcileNegativeThingNodes(NLNode node) { HashMap links = node.getLinks(); NLLink isNotALink = new NLLink("", NLVisitor.LINK_COMPLEMENT); // first: gather all the is-a links NLLink nonThingLink = null;/*from w ww . ja va2s . c o m*/ NLLink thingLink = null; boolean thingFound = false; Set isaLinks = new HashSet(); for (Iterator iter = links.keySet().iterator(); iter.hasNext();) { NLLink link = (NLLink) iter.next(); NLNode target = (NLNode) links.get(link); //System.out.println( "LINK: " + link.keyword + " (" + link.linkType + "), TARGET: " + target.keyword ); if (link.equals(isNotALink)) { isaLinks.add(link); if (target.getKeyword().equals("Thing") || target.getKeyword().equals("thing")) { //System.out.println( "thing found" ); thingFound = true; thingLink = link; } else { nonThingLink = link; } } } //System.out.println( "NEG-ISA's: " + isaLinks.size() + " " + thingFound); if (thingFound) { if (isaLinks.size() == 0) { // this should never happen } else if (isaLinks.size() == 1) { // there is only one node and it is a thing node, so we can safely pull its links up NLNode thingNode = (NLNode) links.get(thingLink); HashMap tLinks = thingNode.getLinks(); node.links.putAll(tLinks); links.remove(thingLink); } else { NLNode thingNode = (NLNode) links.get(thingLink); NLNode nonThingNode = (NLNode) links.get(nonThingLink); HashMap tLinks = thingNode.getLinks(); HashMap ntLinks = nonThingNode.getLinks(); ntLinks.putAll(tLinks); links.remove(thingLink); } } // Recurse for (Iterator iter = links.keySet().iterator(); iter.hasNext();) { NLLink link = (NLLink) iter.next(); NLNode target = (NLNode) links.get(link); //System.out.println( "NEW LINK: " + link.keyword + " (" + link.linkType + "), TARGET: " + target.keyword ); reconcileNegativeThingNodes(target); } }